# 导入决策树回归器和其他必要库from sklearn.tree import DecisionTreeRegressorfrom sklearn.datasets import make_regression # 注意下划线import matplotlib.pyplot as pltimport numpy as npimport pandas as pd# 生成一个回归任务数据集,样本数量 100X, y = make_regression( n_samples=100, # 样本数 n_features=1, # 只有一个特征 noise=60, # 噪声参数 random_state=18 # 设定随机状态,便于复现)# 用散点图可视化样本plt.scatter( X, y, s=80, # 点大小 c=y, # 颜色映射 edgecolor='grey', alpha=0.6)plt.colorbar(label='y') # 添加颜色条,便于观察 y 值分布plt.grid()plt.title('Generated Regression Dataset')plt.xlabel('X')plt.ylabel('y')plt.show()
运行结果:
【结果分析】从图中可以看到,当我们把样本的噪声参数增加到60时,样本不再呈现为一条线的分布状况,而是更加“零散”地散布在二维空间中。在这种情况下,使用线性模型进行拟合显然有些不合理。
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.tree import DecisionTreeRegressorfrom sklearn.datasets import make_regression# 1. 生成数据X, y = make_regression(n_samples=100, n_features=1, noise=60, random_state=18)# 2. 创建决策树回归器(不限制 max_depth)reg = DecisionTreeRegressor(max_depth=None, random_state=18)reg.fit(X, y)# 3. 生成用于绘图的连续横坐标X_new = np.linspace(-2.5, 3.5, 300).reshape(-1, 1)y_new = reg.predict(X_new)# 4. 绘图plt.figure(figsize=(7, 5))plt.scatter(X, y, s=80, c=y, edgecolor='grey', alpha=0.4, label='Samples')plt.plot(X_new, y_new, lw=2, color='darkorange', label='Decision Tree (no depth limit)')plt.title('DecisionTreeRegressor (max_depth=None)')plt.xlabel('X')plt.ylabel('y')plt.grid(True)plt.legend()plt.show()代码展示:import numpy as npimport matplotlib.pyplot as pltfrom sklearn.tree import DecisionTreeRegressorfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.datasets import make_regression# 1. 生成数据X, y = make_regression(n_samples=100, n_features=1, noise=60, random_state=18)# 2. 单棵决策树(无深度限制)tree = DecisionTreeRegressor(max_depth=None, random_state=18)tree.fit(X, y)# 3. 随机森林(100 棵树)forest = RandomForestRegressor(n_estimators=100, random_state=18)forest.fit(X, y)# 4. 用于绘图的连续横坐标X_plot = np.linspace(-2.5, 3.5, 300).reshape(-1, 1)y_tree = tree.predict(X_plot)y_forest = forest.predict(X_plot)# 5. 画图plt.figure(figsize=(7, 5))plt.scatter(X, y, s=80, c=y, edgecolor='grey', alpha=0.4, label='Samples')plt.plot(X_plot, y_tree, lw=1.5, ls='-', c='grey', label='Single Tree (no depth limit)')plt.plot(X_plot, y_forest, lw=1.5, ls='--', c='darkgreen', label='Random Forest (n=100)')plt.title('Decision Tree vs Random Forest')plt.xlabel('X')plt.ylabel('y')plt.grid(True)plt.legend()plt.show()
【结果分析】在图中,实线部分是决策树模型,虚线部分是随机森林模型。认真观察载们不难发现,随机森林模型“波动”的幅度没有决策树模型大。这说明,随机森林模型相比决策树模型更简单,相对不容易受到噪声的干扰,也就更不容易出现过拟合的现象。
再次提示:仅供理解,思路可以用于实盘,但是不可直接用于实盘。
Copyright © 2024-2025 成都宁时科技有限公司 版权所有