鸢尾花数据分类:sklearn包中决策树算法类库的使用

这是《西瓜书带学训练营·实战任务》系列的第二篇笔记

1. DecisionTreeClassifier实例

from itertools import product

import numpy as np
import matplotlib.pyplot as plt

from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.decomposition import PCA


# 使用自带的iris数据
iris = datasets.load_iris()
X = iris.data[:, np.arange(0,4)]
y = iris.target

# 划分训练集与测试集
x_train, x_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=14)
print("训练数据集样本总数:%d;测试数据集样本总数:%d" %(x_train.shape[0],x_test.shape[0]))

# 对数据集进行标准化
ss = MinMaxScaler()
x_train = ss.fit_transform(x_train,y_train)
x_test = ss.transform(x_test)

# 特征选择:从已有的特征属性中选择出影响目标最大的特征属性
# 常用方法:
#   离散属性:F统计量、卡方系数、互信息mutual_info_classif
#   连续属性:皮尔逊相关系数、F统计量、互信息mutual_info_classif}
# 这里使用离散属性的卡方系数,实现函数为SelectKBest,用SelectKBest方法从四个原始特征属性中选择出最能影响目标的3个特征属性
ch2 = SelectKBest(chi2,k=3) # k默认为10,指定后会返回想要的特征个数
ch2.fit(x_train,y_train)
x_train = ch2.transform(x_train)
x_test = ch2.transform(x_test)

# 特征降维,这里使用PCA方法
pca = PCA(n_components=2)   # 构建一个PCA对象,设置最终维度为2维。这里为了后边画图方便,将数据维度设置为 2,一般用默认不设置就可以
x_train = pca.fit_transform(x_train) # 训练与转换,也可以拆分成两步
x_test = pca.transform(x_test)

# 训练模型
#   criterion:指定特征选择标准,可以使用"gini"或者"entropy",前者代表基尼系数,后者代表信息增益
#   max_depth:限制树的最大深度4
clf = DecisionTreeClassifier(criterion="entropy",max_depth=4)
clf.fit(X, y) # 拟合模型


# 画图
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
# 生成网格采样点
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
                     np.arange(y_min, y_max, 0.1))

Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.contourf(xx, yy, Z, alpha=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.8)
plt.show()
15455040-fff687eb6c1ff536.png

2. 可视化决策树

scikit-learn中决策树的可视化一般需要安装graphviz,主要包括graphviz的安装和python的graphviz插件的安装

    1. 安装graphviz。下载地址在:http://www.graphviz.org/。如果你是linux,可以用apt-get或者yum的方法安装。如果是windows,就在官网下载msi文件安装。无论是linux还是windows,装完后都要设置环境变量,将graphviz的bin目录加到PATH,比如我是windows,将C:/Program Files (x86)/Graphviz2.38/bin/加入了PATH
    1. 安装python插件graphviz: pip install graphviz
    1. 安装python插件pydotplus: pip install pydotplus

这样环境就搭好了,有时候python会很笨,仍然找不到graphviz,这时,可以在代码里面加入这一行:

os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'

可视化决策树的代码:

from IPython.display import Image  
from sklearn import tree
import pydotplus 
dot_data = tree.export_graphviz(clf, out_file=None, 
                         feature_names=iris.feature_names,  
                         class_names=iris.target_names,  
                         filled=True, rounded=True,  
                         special_characters=True)  
graph = pydotplus.graph_from_dot_data(dot_data)  
Image(graph.create_png())
15455040-93da93d2135ed7b9.png

参考资料:

(1) 刘建平Pinard《scikit-learn决策树算法类库使用小结》

(2) loveliuzz《机器学习sklearn19.0——决策树算法》

猜你喜欢

转载自blog.csdn.net/weixin_34268843/article/details/86909852