新聞中心
這里有您想知道的互聯網營銷解決方案
創(chuàng)新互聯AI教程:AI人工智能決策樹分類器
決策樹基本上是一個二叉樹流程圖,其中每個節(jié)點根據某個特征變量分割一組觀察值。

在這里,我們正在構建一個用于預測男性或女性的決策樹分類器。這里將采取一個非常小的數據集,有 19 個樣本。 這些樣本將包含兩個特征 - “身高”和“頭發(fā)長度”。
前提條件
為了構建以下分類器,我們需要安裝 pydotplus和 graphviz。 基本上,graphviz 是使用點文件繪制圖形的工具,pydotplus 是 Graphviz 的 Dot 語言模塊。 它可以與包管理器或使用pip來安裝。
現在,可以在以下 Python 代碼的幫助下構建決策樹分類器 -
首先,導入一些重要的庫如下 -
import pydotplus
from sklearn import tree
from sklearn.datasets import load_iris
from sklearn.metrics import classification_report
from sklearn import cross_validation
import collections現在,提供如下數據集 -
X = [[165,19],[175,32],[136,35],[174,65],[141,28],[176,15],[131,32],
[166,6],[128,32],[179,10],[136,34],[186,2],[126,25],[176,28],[112,38],
[169,9],[171,36],[116,25],[196,25]]
Y = ['Man','Woman','Woman','Man','Woman','Man','Woman','Man','Woman',
'Man','Woman','Man','Woman','Woman','Woman','Man','Woman','Woman','Man']
data_feature_names = ['height','length of hair']
X_train, X_test, Y_train, Y_test = cross_validation.train_test_split
(X, Y, test_size=0.40, random_state=5)在提供數據集之后,需要擬合可以如下完成的模型 -
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X,Y)預測可以使用以下 Python 代碼來完成 -
prediction = clf.predict([[133,37]])
print(prediction)使用以下 Python 代碼來實現可視化決策樹 -
dot_data = tree.export_graphviz(clf,feature_names = data_feature_names,
out_file = None,filled = True,rounded = True)
graph = pydotplus.graph_from_dot_data(dot_data)
colors = ('orange', 'yellow')
edges = collections.defaultdict(list)
for edge in graph.get_edge_list():
edges[edge.get_source()].append(int(edge.get_destination()))
for edge in edges: edges[edge].sort()
for i in range(2):dest = graph.get_node(str(edges[edge][i]))[0]
dest.set_fillcolor(colors[i])
graph.write_png('Decisiontree16.png')它會將上述代碼的預測作為[‘Woman’]并創(chuàng)建以下決策樹 -
可以改變預測中的特征值來測試它。
名稱欄目:創(chuàng)新互聯AI教程:AI人工智能決策樹分類器
網頁路徑:http://m.5511xx.com/article/dhehjcd.html


咨詢
建站咨詢
