欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

sklearn构造决策树模型 树的可视化 pydotplus和GraphViz的安装

程序员文章站 2024-03-19 20:27:28
...

sklearn 数量级是百万级的都可以用,用的人很多
sklearn API文档:http://scikit-learn.org/stable/modules/classes.html

准备工作

1.安装pydotplus

打开Anacorda Prompt 输入 pip install pydotplus 然后等待
sklearn构造决策树模型 树的可视化 pydotplus和GraphViz的安装

2.安装GraphViz

https://graphviz.gitlab.io/_pages/Download/Download_windows.html

sklearn构造决策树模型 树的可视化 pydotplus和GraphViz的安装
下载完进行安装,一路next,记住安装路径。
sklearn构造决策树模型 树的可视化 pydotplus和GraphViz的安装
环境变量的配置:将D:\Program Files (x86)\Graphviz2.38\bin添加到path中
sklearn构造决策树模型 树的可视化 pydotplus和GraphViz的安装
如果Python IDE是打开的,那么在安装完GraphViz后重新启动**Python IDE,否则IDE无法调用GraphViz。会报错:**InvocationException: GraphViz’s executables not found

开始

1.数据

数据直接采用sklearn内部的数据集california_housing ,关于房价的数据集。
This dataset contains the average house value as target variable
and the following input variables (features): average income,
housing average age, average rooms, average bedrooms, population,
average occupation, latitude, and longitude in that order.

2.代码


import matplotlib.pyplot as plt

import pandas as pd
from sklearn import tree
import pydotplus
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor

from IPython.display import Image

from sklearn.grid_search import GridSearchCV
from sklearn.datasets.california_housing import fetch_california_housing


housing = fetch_california_housing()
print(housing.DESCR)
#自带的数据

'''


'''
print(housing.data.shape)

print(housing.data[0])


'''
树模型参数:
1.criterion gini or entropy

2.splitter best or random 前者是在所有特征中找最好的切分点 后者是在部分特征中(数据量大的时候)

3.max_features None(所有),log2,sqrt,N 特征小于50的时候一般使用所有的

4.max_depth 数据少或者特征少的时候可以不管这个值,如果模型样本量多,特征也多的情况下,可以尝试限制下

5.min_samples_split 如果某节点的样本数少于min_samples_split,则不会继续再尝试选择最优特征来进行划分如果样本量不大,不需要管这个值。如果样本量数量级非常大,则推荐增大这个值。

6.min_samples_leaf 这个值限制了叶子节点最少的样本数,如果某叶子节点数目小于样本数,则会和兄弟节点一起被剪枝,如果样本量不大,不需要管这个值,大些如10W可是尝试下5

7.min_weight_fraction_leaf 这个值限制了叶子节点所有样本权重和的最小值,如果小于这个值,则会和兄弟节点一起被剪枝默认是0,就是不考虑权重问题。一般来说,如果我们有较多样本有缺失值,或者分类树样本的分布类别偏差很大,就会引入样本权重,这时我们就要注意这个值了。

8.max_leaf_nodes 通过限制最大叶子节点数,可以防止过拟合,默认是"None”,即不限制最大的叶子节点数。如果加了限制,算法会建立在最大叶子节点数内最优的决策树。如果特征不多,可以不考虑这个值,但是如果特征分成多的话,可以加以限制具体的值可以通过交叉验证得到。

9.class_weight 指定样本各类别的的权重,主要是为了防止训练集某些类别的样本过多导致训练的决策树过于偏向这些类别。这里可以自己指定各个样本的权重如果使用“balanced”,则算法会自己计算权重,样本量少的类别所对应的样本权重会高。

10.min_impurity_split 这个值限制了决策树的增长,如果某节点的不纯度(基尼系数,信息增益,均方差,绝对差)小于这个阈值则该节点不再生成子节点。即为叶子节点 。

n_estimators:要建立树的个数
'''


dtr = tree.DecisionTreeRegressor(max_depth=2) #实例化 指定树的深度为2
#print(help(tree.DecisionTreeRegressor))
dtr.fit(housing.data[:, [6, 7]], housing.target) #构造树模型 取所有样本的第6,7列特征,target结果值

#要可视化显示 首先需要安装 graphviz   http://www.graphviz.org/Download..php
dot_data = \
    tree.export_graphviz(
        dtr,
        out_file=None,
        feature_names=housing.feature_names[6:8],  #特征名字
        filled=True,
        impurity=False,
        rounded=True
    )
#生成.dot文件

#pip install pydotplus
#import pydotplus
graph = pydotplus.graph_from_dot_data(dot_data)
graph.get_nodes()[7].set_fillcolor("#FFF2DD")  #指定颜色
#from IPython.display import Image
Image(graph.create_png()) #画出这个树
graph.write_png("dtr_white_background.png") #保存为png格式


#from sklearn.model_selection import train_test_split 切分train 和test集
data_train, data_test, target_train, target_test = \
    train_test_split(housing.data, housing.target, test_size=0.1, random_state=42)  #为了使随机的结果一致,所以指定random_state
dtr = tree.DecisionTreeRegressor(random_state=42)
dtr.fit(data_train, target_train)

dtr.score(data_test, target_test) #不同算法里的score的计算方法不一样
print(dtr.score(data_test, target_test))

#from sklearn.ensemble import RandomForestRegressor
rfr = RandomForestRegressor(random_state=42)
rfr.fit(data_train, target_train)
a = rfr.score(data_test, target_test)
print(a)

#from sklearn.grid_search import GridSearchCV
tree_param_grid = {'min_samples_split': list((3, 6, 9)), 'n_estimators': list((10, 50, 100))}
grid = GridSearchCV(RandomForestRegressor(), param_grid=tree_param_grid, cv=5) #传入算法,参数候选项,cv将训练集切分为几个来交叉验证
grid.fit(data_train, target_train)
print(grid.grid_scores_, grid.best_params_, grid.best_score_)


rfr = RandomForestRegressor(min_samples_split=3, n_estimators=100, random_state=42)
rfr.fit(data_train, target_train)
rfr.score(data_test, target_test)
print(rfr.score(data_test, target_test))




d = pd.Series(rfr.feature_importances_, index=housing.feature_names).sort_values(ascending=False)
print(d)


(20640, 8)
[ 8.3252 41. 6.98412698 1.02380952 322.
2.55555556 37.88 -122.23 ]
0.637318351331017
0.7908649228096493
[mean: 0.78684, std: 0.00517, params: {‘min_samples_split’: 3, ‘n_estimators’: 10},
mean: 0.80496, std: 0.00417, params: {‘min_samples_split’: 3, ‘n_estimators’: 50},
mean: 0.80759, std: 0.00410, params: {‘min_samples_split’: 3, ‘n_estimators’: 100},
mean: 0.78779, std: 0.00625, params: {‘min_samples_split’: 6, ‘n_estimators’: 10},
mean: 0.80427, std: 0.00501, params: {‘min_samples_split’: 6, ‘n_estimators’: 50},
mean: 0.80650, std: 0.00492, params: {‘min_samples_split’: 6, ‘n_estimators’: 100},
mean: 0.78815, std: 0.00483, params: {‘min_samples_split’: 9, ‘n_estimators’: 10},
mean: 0.80401, std: 0.00523, params: {‘min_samples_split’: 9, ‘n_estimators’: 50},
mean: 0.80531, std: 0.00480, params: {‘min_samples_split’: 9, ‘n_estimators’: 100}]
{‘min_samples_split’: 3, ‘n_estimators’: 100} 0.8075895321510531
0.8090829049653158
MedInc 0.524257
AveOccup 0.137947
Latitude 0.090622
Longitude 0.089414
HouseAge 0.053970
AveRooms 0.044443
Population 0.030263
AveBedrms 0.029084
dtype: float64
sklearn构造决策树模型 树的可视化 pydotplus和GraphViz的安装

scikit-learn决策树算法类库使用小结
https://www.cnblogs.com/pinard/p/6056319.html

完成