|
- # -*- coding:UTF-8 -*-
- from sklearn.feature_extraction import DictVectorizer
- from sklearn import preprocessing
- from sklearn import tree
- import csv
- import pydotplus
- # -*- coding:utf-8 -*-
- #以只讀的方式打開指定的擴展名為csv的文件,其編碼格式為UTF-8-sig,注意這個位置的編碼格式不能是utf-8
- file = open(r'E:\python\a.csv','r',encoding='utf-8-sig')
- #讀取文件的內容并將其賦給變量data
- data = csv.reader(file)
- #讀取變量data中的第一行(表頭)
- header = next(data)
- #print('header = ' + str(header))
- #創(chuàng)建一個列表attributeList,專門存放數(shù)據(jù)源的屬性值
- attributeList = []
- #創(chuàng)建一個列表resultList,專門存放對應各行記錄的結果值
- resultList = []
- for row in data:
- resultList.append(row[len(row) - 1]) #將每行記錄的結果值存入resultList中
- rowDictionary = {} #定義一個詞典rowDictionary,用來存放每行的屬性名稱及其對應的屬性值
- for i in range(1,len(row) - 1):
- rowDictionary[header[i]] = row[i] #向詞典rowDictionary添加屬性名稱及其對應的屬性值
- attributeList.append(rowDictionary) #將每次內層循環(huán)產(chǎn)生的詞典添加到列表attributeList中
- # print(resultList)
- vec = DictVectorizer() #創(chuàng)建一個DictVectorizer的實例,DictVectorizer是字典特征提取器,用來將數(shù)據(jù)的數(shù)據(jù)類型轉化為整型
- attributeArray = vec.fit_transform(attributeList).toarray() #利用vec實例將列表attributeList轉化成“01”矩陣,函數(shù)fit_transform是先擬合數(shù)據(jù),再標準化,函數(shù)toarray是將轉化后的數(shù)據(jù)轉變?yōu)閿?shù)組
- title = vec.get_feature_names() #獲取vec中所有特征向量的名稱和及其能取到的值
- #print(title)
- #print(array)
- lb = preprocessing.LabelBinarizer() #初始化變量lb,preprocessing.LabelBinarizer()的作用是可將分類數(shù)據(jù)轉化為“01”數(shù)據(jù),例如可以把yes和no轉化為0和1,或是把incident和normal轉化為0和1
- resultArray = lb.fit_transform(resultList) #將結果值列表resultList轉化為“01”矩陣
- #print(resultArray)
- transformArray = tree.DecisionTreeClassifier(criterion='entropy') #利用分類決策樹tree(已引入)模塊創(chuàng)建決策樹分類器DecisionTreeClassifier,其實現(xiàn)算法是ID3算法(criterion=entropy)
- transformArray = transformArray.fit(attributeArray, resultArray) #根據(jù)attributeArray和resultArray生成決策樹
- #利用pip安裝graphviz包和pydotplus包
- dotData = tree.export_graphviz(transformArray,feature_names=title,out_file=None)#根據(jù)transformArray和title生成判定樹的節(jié)點,同時讓輸出文件為None(out_file=None)
- graph = pydotplus.graph_from_dot_data(dotData) #根據(jù)上條語句生成的決策樹結點dotData生成判定樹的圖形結構
- graph.write_pdf('E:/python/a.pdf') #將樹形結構寫入到指定的文件中
復制代碼
|
-
51hei.png
(3.49 KB, 下載次數(shù): 148)
下載附件
2020-6-10 04:41 上傳
-
-
171004119郭文磊.rar
2020-6-9 11:00 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
27.59 KB, 下載次數(shù): 23, 下載積分: 黑幣 -5
|