決策樹

決策樹是一個分類器,它使用一系列詳細的規則(如 a> 7),這些規則很容易理解。

下面的示例使用長度為 3 的三個特徵向量訓練決策樹分類器,然後預測迄今未知的第四特徵向量的結果,即所謂的測試向量。

from sklearn.tree import DecisionTreeClassifier

# Define training and target set for the classifier
train = [[1,2,3],[2,5,1],[2,1,7]]
target = [10,20,30]

# Initialize Classifier. 
# Random values are initialized with always the same random seed of value 0 
# (allows reproducible results)
dectree = DecisionTreeClassifier(random_state=0)
dectree.fit(train, target)

# Test classifier with other, unknown feature vector
test = [2,2,3]
predicted = dectree.predict(test)

print predicted

可以使用以下方式顯示輸出:

import pydot
import StringIO

dotfile = StringIO.StringIO()
tree.export_graphviz(dectree, out_file=dotfile)
(graph,)=pydot.graph_from_dot_data(dotfile.getvalue())
graph.write_png("dtree.png")
graph.write_pdf("dtree.pdf")