python利用sklearn包编写决策树源代码

yipeiwu_com7年前Python基础

本文实例为大家分享了python编写决策树源代码,供大家参考,具体内容如下

因为最近实习的需要,所以用python里的sklearn包重新写了一次决策树。

工具:sklearn,将dot文件转化为pdf格式(是为了将形成的决策树可视化)graphviz-2.38,下载解压之后将其中的bin文件的目录添加进环境变量

源代码如下:

from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import tree
from sklearn import preprocessing
from sklearn.externals.six import StringIO
from xml.sax.handler import feature_external_ges
from numpy.distutils.fcompiler import dummy_fortran_file

# Read in the csv file and put features into list of dict and list of class label
allElectronicsData = open(r'E:/DeepLearning/resources/AllElectronics.csv', 'rt')
reader = csv.reader(allElectronicsData)
headers = next(reader)
featureList = []
lableList = []
for row in reader:
lableList.append(row[len(row)-1])
rowDict = {}
#不包括len(row)-1
for i in range(1,len(row)-1):
rowDict[headers[i]] = row[i]
featureList.append(rowDict)
print(featureList)

vec = DictVectorizer()
dummX = vec.fit_transform(featureList).toarray()
print(str(dummX))
lb = preprocessing.LabelBinarizer()
dummY = lb.fit_transform(lableList)
print(str(dummY))

#entropy=>ID3
clf = tree.DecisionTreeClassifier(criterion='entropy')
clf = clf.fit(dummX, dummY)
print("clf:"+str(clf))


#可视化tree
with open("resultTree.dot",'w')as f:
f = tree.export_graphviz(clf, feature_names=vec.get_feature_names(),out_file = f)


#对于新的数据怎样来查看它的分类
oneRowX = dummX[0,:]
print("oneRowX: "+str(oneRowX))
newRowX = oneRowX
newRowX[0] = 1
newRowX[2] = 0

predictedY = clf.predict(newRowX)
print("predictedY: "+ str(predictedY))

这里的AllElectronics.csv,形式如下图所示:

今天早上好不容易将jdk、eclipse以及pydev装进linux,但是,但是,但是,想装numpy的时候,总是报错,发现是没有gcc,然后又去装gcc,真是醉了,到现在gcc还是没有装成功,再想想方法

相关文章

Python缓存技术实现过程详解

一段非常简单代码 普通调用方式 def console1(a, b): print("进入函数") return (a, b) print(console1(3, 'a...

Python设计模式之职责链模式原理与用法实例分析

Python设计模式之职责链模式原理与用法实例分析

本文实例讲述了Python设计模式之职责链模式原理与用法。分享给大家供大家参考,具体如下: 职责链模式(Chain Of Responsibility):使多个对象都有机会处理请求,从而...

Python实现的基数排序算法原理与用法实例分析

Python实现的基数排序算法原理与用法实例分析

本文实例讲述了Python实现的基数排序算法。分享给大家供大家参考,具体如下: 基数排序(radix sort)属于“分配式排序”(distribution sort),又称“桶子法”(...

python实现dict版图遍历示例

复制代码 代码如下:#_*_coding:utf_8_import sysimport os class Graph():    def __init__(...

python实现根据指定字符截取对应的行的内容方法

工作中遇到的,在一个.c文件中有很多函数,这个.c是自动生成的,需要将所有的函数通过extern放到.h中,每个函数都是UINT32 O_开头,通过正则表达式进行字符匹配以及通过line...