您好,登錄后才能下訂單哦!
1. 基本環境
安裝 anaconda 環境, 由于國內登陸不了他的官網 https://www.continuum.io/downloads, 不過可以使用國內的鏡像站點: https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/
添加繪圖工具 Graphviz http://www.graphviz.org/Download_windows.php
安裝后, 將bin 目錄內容添加到環境變量path 即可
參考blog : https://www.jb51.net/article/169878.htm
官網技術文檔 : http://scikit-learn.org/stable/modules/tree.html#tree-algorithms-id3-c4-5-c5-0-and-cart
2. 遇到的一些問題
csv 文件讀取 https://docs.python.org/3.5/library/csv.html?highlight=csv#module-csv
https://docs.python.org/2/library/csv.html?highlight=csv#module-csv
3. 實現
數據文件:
這是一個給定 4 個屬性, age, income, student, credit_rating 以及 一個 標記屬性 class_buys_computer 的數據集, 我們需要根據這個數據集進行分析并構建一顆決策樹
代碼實現:
核心就是調用 tree 的 DecisionTreeClassifier 方法對數據進行 訓練得到一顆決策樹
# -*- coding: utf-8 -*- """ Created on Sun Dec 25 11:25:40 2016 @author: Administrator """ from sklearn.feature_extraction import DictVectorizer import csv from sklearn import tree from sklearn import preprocessing from sklearn.externals.six import StringIO import pydotplus from IPython.display import Image # Read in the csv file and put features into list of dict and list of class label allElectornicsData = open('AllElectronics.csv', 'r') reader = csv.reader(allElectornicsData) # headers = reader.next() python2.7 supported 本質獲取csv 文件的第一行數據 #headers = reader.__next__() python 3.5.2 headers = next(reader) 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) print(labelList) # Vetorize features vec = DictVectorizer() dummyX = vec.fit_transform(featureList).toarray() print("dummyX: " + str(dummyX)) print(vec.get_feature_names()) print("labelList: " + str(labelList)) # vectorize class labels lb = preprocessing.LabelBinarizer() dummyY = lb.fit_transform(labelList) print("dummyY: ", str(dummyY)) # Using decision tree for classification ===========【此處調用為算法核心】============ #clf = tree.DecisionTreeClassifier(criterion='entropy') clf = tree.DecisionTreeClassifier(criterion='gini') clf = clf.fit(dummyX, dummyY) print("clf: ", str(clf)) # Visualize model # dot -Tpdf iris.dot -o ouput.pdf with open("allElectronicInformationGainOri.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))
輸出結果:
ID3 算法
CART 算法
4. 決策樹的優缺點
決策樹的優勢
決策樹的劣勢
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。