机器学习实战

3-5节 决策树|使用文本注解绘制树节点|机器学习实战-学习笔记

2018-08-17  本文已影响45人  努力奋斗的durian

文章原创,最近更新:2018-08-17

学习参考链接:
1.机器学习(9)之ID3算法详解及python实现
2.机器学习实战-第3章《决策树》

本章节的主要内容是:
重点介绍项目案例1:判定鱼类和非鱼类使用文本注解绘制树节点的函数代码

1.决策树项目案例介绍:

项目案例1:

判定鱼类和非鱼类

项目概述:
开发流程:
数据集介绍

2.使用文本注解绘制树节点的函数代码

《机器学习实战》书中,该部分的代码有些混乱。重新构造了代码,创建一个类。其中,绘制最基本的树节点是如下代码:

#导入matplotlib的pyplot绘图模块并命名为plt
import matplotlib.pyplot as plt

# boxstyle是文本框类型,fc是边框粗细,sawtooth是锯齿形
decisionNode = dict(boxstyle="sawtooth",fc="0.8")
leafNode = dict(boxstyle="round4",fc="0.8")

# arrowprops: 通过arrowstyle表明箭头的风格或种类。
arrow_args=dict(arrowstyle="<-")

# annotate 注释的意思
#plotNode()函数绘制带箭头的注解,sub_ax:使用figure命令来产生子图, node_text:节点的文字标注,start_pt:箭头起点位置(上一节点位置),end_pt:箭头结束位置, node_type:节点属性   
def plot_node(sub_ax, node_text, start_pt, end_pt, node_type):
    sub_ax.annotate(node_text,
        xy = end_pt, xycoords='axes fraction', 
        xytext = start_pt, textcoords='axes fraction',
        va='center', ha='center', bbox=node_type, arrowprops=arrow_args)

if __name__ == '__main__':
    fig = plt.figure(1, facecolor='white')
    #清空绘图区
    fig.clf()
    axprops = dict(xticks=[], yticks=[]) #去掉坐标轴
    sub_ax = plt.subplot(111, frameon=False, **axprops)
    #绘制节点
    plot_node(sub_ax, 'a decision node', (0.5, 0.1), (0.1, 0.5), decisionNode)
    plot_node(sub_ax, 'a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode)
    plt.show()

输出的结果如下:


3.相关知识介绍

3.1annotate介绍

在数据可视化的过程中,图片中的文字经常被用来注释图中的一些特征。使用annotate()方法可以很方便地添加此类注释。在使用annotate时,要考虑两个点的坐标:被注释的地方xy(x, y)和插入文本的地方xytext(x, y)。

annotate语法说明 :annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,..)

xycoords 参数如下:

extcoords 设置注释文字偏移量

参数 坐标系
'figure points' 距离图形左下角的点数量
'figure pixels' 距离图形左下角的像素数量
'figure fraction' 0,0 是图形左下角,1,1 是右上角
'axes points' 距离轴域左下角的点数量
'axes pixels' 距离轴域左下角的像素数量
'axes fraction' 0,0 是轴域左下角,1,1 是右上角
'data' 使用轴域数据坐标系

arrowprops #箭头参数,参数类型为字典dict

bbox给标题增加外框 ,常用参数如下:

bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5) #fc为facecolor,ec为edgecolor,lw为lineweight

案例1

from pylab import *
annotate(s="Nothing",  xytext=(0.8, 0.8),xy=(0.2, 0.2), \
         arrowprops=dict(arrowstyle="->"))#,
show()

这是实现annotate的最简单的版本,大家注意参数的含义。

案例2

import numpy as np
import matplotlib.pyplot as plt
 
ax = plt.subplot(111)
 
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
 
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )
 
plt.ylim(-2,2)
plt.show()

输出结果如下:


上一篇 下一篇

猜你喜欢

热点阅读