標(biāo)題: 決策樹實(shí)現(xiàn)python程序 [打印本頁]

作者: suncaixin    時間: 2018-2-1 15:54
標(biāo)題: 決策樹實(shí)現(xiàn)python程序
利用python實(shí)現(xiàn)決策時程序,最后輸出整個決策過程的pdf文件

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Nov 22 13:13:07 2017

  4. @author: suncaixin
  5. """
  6. #collect number
  7. from sklearn.feature_extraction import DictVectorizer
  8. import numpy as np
  9. import pandas as pd
  10. import csv
  11. from sklearn import tree
  12. from sklearn import preprocessing
  13. allElectrionicsData=open(r'數(shù)據(jù)地址','rt')
  14. reader=csv.reader(allElectrionicsData)
  15. headers=next(reader)
  16. print(headers)
  17. feature_list=[]
  18. label_list=[]
  19. for row in reader:
  20.     label_list.append(row[len(row)-1])
  21.     rowDict={}
  22.     for i in range(1,len(row)-1):
  23.         print(row[i])
  24.         rowDict[headers[i]]=row[i]
  25.         print('rowDict:',rowDict)
  26.     feature_list.append(rowDict)
  27. print(feature_list)
  28. #tranform feature
  29. vec=DictVectorizer()
  30. dunmyX=vec.fit_transform(feature_list).toarray()
  31. print('dunmyX:',str(dunmyX))
  32. print(vec.get_feature_names())
  33. #class label transform
  34. lb=preprocessing.LabelBinarizer()
  35. dunmyY=lb.fit_transform(label_list)
  36. print('dunmyY:',str(dunmyY))
  37. #decision tree
  38. clf=tree.DecisionTreeClassifier(criterion='entropy')
  39. clf=clf.fit(dunmyX,dunmyY)
  40. print('clf',str(clf))
  41. #visulize model
  42. with open('allElectronicInformationGain.dot','w') as f:
  43.     f=tree.export_graphviz(clf,feature_names=vec.get_feature_names(),out_file=f)
  44. #output pdf:dot -Tpdf C:\Users\suncaixin\allElectronicInformationGain.dot -o outpu.pdf

  45. #predict
  46. oneRowx=dunmyX[0,:]
  47. newRowx=oneRowx
  48. newRowx[0]=1
  49. newRowx[2]=0
  50. predictedY=clf.predict([newRowx])
  51. print('predicted:',str(predictedY))
復(fù)制代碼


decision_tree.zip

884 Bytes, 下載次數(shù): 7, 下載積分: 黑幣 -5

決策樹python程序






歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1