python利用sklearn包編寫決策樹源代碼
本文實例為大家分享了python編寫決策樹源代碼,供大家參考,具體內(nèi)容如下
因為最近實習的需要,所以用python里的sklearn包重新寫了一次決策樹。
工具:sklearn,將dot文件轉化為pdf格式(是為了將形成的決策樹可視化)graphviz-2.38,下載解壓之后將其中的bin文件的目錄添加進環(huán)境變量
源代碼如下:
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)
#對于新的數(shù)據(jù)怎樣來查看它的分類
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的時候,總是報錯,發(fā)現(xiàn)是沒有gcc,然后又去裝gcc,真是醉了,到現(xiàn)在gcc還是沒有裝成功,再想想方法
相關文章
Python Selenium破解滑塊驗證碼最新版(GEETEST95%以上通過率)
這篇文章主要介紹了Python Selenium破解滑塊驗證碼最新版(GEETEST95%以上通過率),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01
Python torch.flatten()函數(shù)案例詳解
這篇文章主要介紹了Python torch.flatten()函數(shù)案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08
Python使用matplotlib給柱狀圖添加數(shù)據(jù)標簽bar_label()
這篇文章主要介紹了Python使用matplotlib給柱狀圖添加數(shù)據(jù)標簽bar_label(),記錄如何用使用matplotlib給柱狀圖添加數(shù)據(jù)標簽,是以matplotlib.pyplot.bar_label()為例,需要的朋友可以參考一下2022-03-03
python更新數(shù)據(jù)庫中某個字段的數(shù)據(jù)(方法詳解)
這篇文章主要介紹了python更新數(shù)據(jù)庫中某個字段的數(shù)據(jù)方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
Python實現(xiàn)帶GUI界面的手寫數(shù)字識別
這篇文章主要介紹了如何通過Python實現(xiàn)帶GUI界面的手寫數(shù)字識別,文中的示例代碼講解詳細,對我們學習Python有一定的幫助,感興趣的可以了解一下2022-01-01

