使用scikit-learn实现决策树的算法模板


给出AllElectronics.csv文件,其原始训练数据如下:


RIDageincomestudentcredit_ratingclass_buy_computer
1youth high no fair no 
2youth high no excellent no 
3middle_agedhigh no fair yes 
4senior medium no fair yes 
5senior low yes fair yes 
6senior low yes excellent no 
7middle_agedlow yes excellent yes 
8youth medium no fair no 
9youth low yes fair yes 
10senior medium yes fair yes 
11youth medium yes excellent yes 
12middle_agedmedium no excellent yes 
13middle_agedhigh yes fair yes 
14senior medium no excellent no 


通过scikit-learn实现决策树,对上述数据进行训练,并进行预测。

模板如下

from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import preprocessing
from sklearn import tree
from sklearn.externals.six import StringIO
from __builtin__ import str
from _csv import reader
from docutils.nodes import header
#open the csv file
allElectronicsData=open(r'E:\eclipse-jee-neon-3-win32\workspace\DeepLearningBasicsMachineLearning\DecisionTree\data\AllElectronics.csv','rb')
reader=csv.reader(allElectronicsData)
headers=reader.next()
print(headers)

featureList=[]
labelList=[]

for row in reader:
    labelList.append(row[len(row)-1])
    rowDict={}
    for i in range(1,len(row)-1):
        rowDict[headers[i]]=row[i]
    featureList.append(rowDict)
print(featureList)

vec=DictVectorizer()
dummyX=vec.fit_transform(featureList).toarray()
print("dummyX:"+str(dummyX))
print(vec.get_feature_names())
print("labelList:"+str(labelList))

lb=preprocessing.LabelBinarizer()
dummyY=lb.fit_transform(labelList)
print("dummyY:"+str(dummyY))

clf=tree.DecisionTreeClassifier(criterion='entropy')
clf=clf.fit(dummyX, dummyY)
print("clf:"+str(clf))

with open("AllElectronics.dot",'w')as f:
    f=tree.export_graphviz(clf, feature_names=vec.get_feature_names(), out_file=f)

#predict
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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林下的码路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值