**
Python3的决策树应用及遇到的问题解决
**
根据列表训练集(用Excel存为.csv格式)
RID,age,income,student,credit_rating,Class_buys_computer
1,youth,high,no,fair,no
2,youth,high,no,excellent,no
3,middle_aged ,high,no,fair,yes
4,senior,medium,no,fair,yes
5,senior,low,yes,fair,yes
6,senior,low,yes,excellent,no
7,middle_aged ,low,yes,excellent,yes
8,youth,medium,no,fair,no
9,youth,low,yes,fair,yes
10,senior,medium,yes,fair,yes
11,youth,medium,yes,excellent,yes
12,middle_aged ,medium,no,excellent,yes
13,middle_aged ,high,yes,fair,yes
14,senior,medium,no,excellent,no
一、步骤:
1、将以上列表存为.csv格式文件,读取特征值列表和Class列表
2、将特征值列表和Class列表转换为(0,1)形式
3、运用决策树分类
4、使模型可视化
5、利用测试集进行预测测试
附源码:
from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import preprocessing
from sklearn import tree
from sklearn.externals.six import StringIO
#Read in the csv file put features in a list of dict and list of class label
allElectronicsData = open(r'C:\Users\wqs\Desktop\1.csv','rt') #路径前的'r'相当于转义
reader = csv.reader(allElectronicsData) #按行读取
headers = next(reader)
print(headers)
featureList = [] #特征值列表
labelList = [] #最后一列(Class列表)
for row in reader:
labelList.append(row[len(row) - 1]) #每一行Length固定为6,row[5]即最后一列值,遍历每一行取出最后一列值放入labelList
rowDict = {}
# print(labelList)
for i in range(1,len(row) - 1): #for i in range(1,5):1,2,3,4
# print(row[i])
rowDict[headers[i]] = row[i] #将此行的每个特征值取出给表头的每个headers
# print("rowdict:",rowDict)
featureList.append(rowDict)
print(featureList)
#Vectorize features 将特征列表转化为字符型的dummy v
vec = DictVectorizer() #实例化
dummyX = vec.fit_transform(featureList).toarray()
print("dummyX:",str(dummyX))
print(vec.get_feature_names())
print("labelList:",labelList)
#vectorize class labels 将Class转化为dummyY
lb = preprocessing.LabelBinarizer() #实例化
dummyY = lb.fit_transform(labelList)
print("dummyY:",dummyY)
#using decision tree for classification(运用决策树分类)
clf = tree.DecisionTreeClassifier(criterion = 'entropy')
clf.fit(dummyX,dummyY)
print("clf:",str(clf))
#Visulize model 使模型可视化
with open("allElectronicInformationGainOri.dot", 'w') as f:
f = tree.export_graphviz(clf, feature_names=vec.get_feature_names(), out_file=f)
#测试集
# predict a new row
oneRowX = dummyX[0, :]
print("oneRowX: " + str(oneRowX))
newRowX = oneRowX
newRowX[0] = 1
newRowX[2] = 0
print("newRowX: " + str(newRowX))
predictedY = clf.predict([newRowX])
print("predictedY: " + str(predictedY))
二、遇到的问题及解决办法
1、打开.csv文件出错的情况及解决办法
如果出现下图情况,第一列数据乱码,那就是你存为.csv文件时候的选择错了
应该选择如图所示:
下图所示选择会出现乱码:
2、中文注释乱码情况:需要更改编码方式点击projiect->Properties选择如图所示编码方式即可:
3、如果出现这样的错误提示:AttributeError: ‘_csv.reader’ object has no attribute ‘next’
需要更改headers = reader.next() 为headers = next(reader)即可,这应该是Python3和Python2的区别,如下图所示:
4、模型可视化时.dot文件转化为graphviz注意的问题
在cmd命令中输入dot -Tpdf iris.dot -o output.pdf
(1) 注意iris.dot为你的.dot文件所在路径
(2)输出文件路径为cmd命令行前面的路径
5、测试集预测出现的问题:
array=[ 1. 0. 0. 0. 1. 1. 0. 0. 1. 0.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
如图所示:
解决办法:这是因为数据集newRowX数组矩阵需要加个中括号[ ]如图所示:
最后上一张运行成功截图:
2018年1月26日于斛兵塘