【python】Scikit-learn中决策树可视化方法

本文通过实例介绍了如何使用scikit-learn库中的决策树回归模型进行数据拟合,并展示了不同最大深度参数(max_depth)对拟合效果的影响。同时,还提供了决策树可视化的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考
官方文档,决策树的介绍
官方文档,回归树使用参数介绍
官方文档,回归树小的例子
scikit-learn决策树算法类库使用小结(分类回归树参数对比介绍与可视化方法)


官方回归树的example代码如下

print(__doc__)

# Import the necessary modules and libraries
import numpy as np
from sklearn.tree import DecisionTreeRegressor
import matplotlib.pyplot as plt

# Create a random dataset
rng = np.random.RandomState(1)
X = np.sort(5 * rng.rand(80, 1), axis=0)
y = np.sin(X).ravel()
y[::5] += 3 * (0.5 - rng.rand(16))

# Fit regression model
regr_1 = DecisionTreeRegressor(max_depth=2)
regr_2 = DecisionTreeRegressor(max_depth=5)
regr_1.fit(X, y)
regr_2.fit(X, y)

# Predict
X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]
y_1 = regr_1.predict(X_test)
y_2 = regr_2.predict(X_test)

# Plot the results
plt.figure()
plt.scatter(X, y, s=20, edgecolor="black",
            c="darkorange", label="data")
plt.plot(X_test, y_1, color="cornflowerblue",
         label="max_depth=2", linewidth=2)
plt.plot(X_test, y_2, color="yellowgreen", label="max_depth=5", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()

结果如图,max_depth = 2时拟合的没有max_depth = 5好
这里写图片描述

安装graphviz
可参考scikit-learn决策树算法类库使用小结
具体步骤如下

apt-get install graphviz
pip install graphviz
pip install pydotplus

用以下代码就可以可视化决策树了

from IPython.display import Image  
from sklearn import tree
import pydotplus 

#regr_1 和regr_2
dot_data = tree.export_graphviz(regr_1, out_file=None,  #regr_1 是对应分类器
                         feature_names=['x'],   #对应特征的名字
                         class_names=['y'],    #对应类别的名字
                         filled=True, rounded=True,  
                         special_characters=True)  
graph = pydotplus.graph_from_dot_data(dot_data)  
graph.write_png('example.png')    #保存图像
Image(graph.create_png()) 

max_depth=2
这里写图片描述

max_depth=5
这里写图片描述

自己用y = x^2玩玩

X = []
y = []
for i in range (1,81):
    X.append([i]) 
    y.append(i**2)
X_test = []
for i in np.arange(1.0,81.0,0.2):
    X_test.append([i])
    
regr_1 = DecisionTreeRegressor(max_depth=2)
regr_2 = DecisionTreeRegressor(max_depth=10)
regr_1.fit(X, y)
regr_2.fit(X, y)

y_1 = regr_1.predict(X_test)
y_2 = regr_2.predict(X_test)

plt.figure()
plt.scatter(X, y, s=20, edgecolor="black",
            c="darkorange", label="data")
plt.plot(X_test, y_1, color="cornflowerblue",
         label="max_depth=2", linewidth=2)
plt.plot(X_test, y_2, color="yellowgreen", label="max_depth=10", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()

这里写图片描述

max_depth=2
这里写图片描述

max_depth=10
这里写图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值