数据挖掘入门与实战 公众号: datadw
二元决策树就是基于属性做一系列的二元(是/否)决策。每次决策对应于从两种可能性中选择一个。每次决策后,要么引出另外一个决策,要么生成最终的结果。一个实际训练决策树的例子有助于加强对这个概念的理解。了解了训练后的决策树是什么样的,就学会了决策树的训练过程。
代码清单6-1为使用Scikitlearn的DecisionTreeRegressor工具包针对红酒口感数据构建二元决策树的代码。图6-1为代码清单6-1生成的决策树。
代码清单6-1 构建一个决策树预测红酒口感-winTree.py
import urllib2 import numpy from sklearn import tree from sklearn.tree import DecisionTreeRegressor from sklearn.externals.six import StringIO from math import sqrt import matplotlib.pyplot as plot
#read data into iterable target_url = ("http://archive.ics.uci.edu/ml/machine-learning-" "databases/wine-quality/winequality-red.csv") data = urllib2.urlopen(target_url)
xList = [] labels = [] names = [] firstLine = True for line in data: if firstLine: names = line.strip().split(";") firstLine = False else: #split on semi-colon row = line.strip().split(";") #put labels in separate array labels.append(float(row[-1])) #remove label from row row.pop() #convert row to floats floatRow = [float(num) for num in row] xList.append(floatRow)
nrows = len(xList) ncols = len(xList[0])
wineTree = DecisionTreeRegressor(max_depth=3)
wineTree.fit(xList, labels)
with open("wineTree.dot", 'w') as f: f = tree.export_graphviz(wineTree, out_file=f) #Note: The code above exports the trained tree info to a #Graphviz "dot" file. #Drawing the graph requires installing GraphViz and the running the #following on the command line #dot -Tpng wineTree.dot -o wineTree.png # In Windows, you can also open the .dot file in the GraphViz #gui (GVedit.EⅩE)]
图6-1为针对红酒数据的训练结果,即一系列的决策。决策树框图显示了一系列的方框,这些方框称作节点(nodes)。有两类节点,一种针对问题输出“是”或者“否”,另外一种是终止节点,输出针对样本的预测结果,并终止整个决策的过程。终止节点也叫作叶子节点(leaf)。在图6-1中,终止节点处在框图底部,它们下面没有分支或者进一步的决策节点。
图6-1 确定红酒口感的决策树
1.1 如何利用二元决策树进行预测
当一个观察(或一行数据)被传送到一个非终止节点时,此行数据要回答此节点的问题。如果回答“是”,则该行数据进入节点下面的左侧节点。如果回答”否“,则此行数据进入节点下面的右侧节点。该过程持续进行,直到到达一个终止节点(即叶子节点),叶子节点给该行数据分配预测值。叶子节点分配的预测值是所有到达此节点的训练数据结果的均值。
尽管此决策树的第二个决策层在两个分支中都考虑了变量X[9],这两个决策也可以是针对不同属性所做的判断(可以参看第三个决策层的例子)。
最上面的节点又叫根节点(root
node)。这个节点提出的问题是“X[10] |