既然我们掌握了ID3的决策树算法,但是直接看那个树形结构可能对于很多人来说,很抽象,这里我就简单照着机器学习实战的书上一起来学习下,如何利用python进行绘图操作,我们引用pyplot这个库,这个库来自于matplotlib;记得前面好像我也将结果如何使用这个库来进行简单的绘图,连接是http://blog.csdn.net/xueyunf/article/details/9091719,
这里讲解下如何进行决策树图的绘制,首先我们需要绘制箭头,标注框等东西。这些可以使用annotate函数进行完成,具体参数可以查阅:
http://matplotlib.org/api/axes_api.html?highlight=annotate#matplotlib.axes.Axes.annotate
下面给出代码:
import matplotlib.pyplot as plt decisionNode = dict(boxstyle="sawtooth", fc="0.8") leafNode = dict(boxstyle="round4", fc="0.8") arrow_args = dict(arrowstyle="<-") def plotNode(nodeTxt, centerPt, parentPt, nodeType): createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args) def createPlot(): fig = plt.figure(1, facecolor='white') fig.clf() createPlot.ax1 = plt.subplot(111, frameon=False) plotNode('a decision node', (0.5, 0.1), (0.1, 0.5), decisionNode) plotNode('a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode) plt.show() createPlot()
第一个函数完成 产生节点,第二个函数调用第一个函数来完成绘图。
下面继续程序截图:
O(∩_∩)O~,这个貌似和书中的截图不一样,可以确定书中的图经过了翻译,但是代码却忘了翻译,也许是译者的疏忽吧,或者是翻译过来大家好理解,但是为了尊重原作者,所以代码没有修改,怎么理解都好,这不重要,重点是如何完成绘图。