决策树回归

本文通过使用决策树回归模型,探讨了不同深度设置下模型预测性能的变化。通过对正弦波数据集进行拟合,展示了随着决策树深度增加,模型复杂度及过拟合风险的变化趋势。

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

import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor

if __name__ == "__main__":
    N = 50
    x = np.linspace(-3, 3, N)
    y = np.sin(x) + np.random.randn(N) * 0.05
#     print(x.shape, x) #  (50,) [-3.         -2.87755102 -2.75510204 ...]
    x = x.reshape(-1, 1)  # 转置后,得到N个样本,每个样本都是1维的
#     print(x.shape, x) # (50, 1) [[-3.        ] [-2.87755102]  [-2.75510204] ...]
    
    # 比较决策树的深度影响
    depth = [1, 2, 3, 4, 5, 6]
    dtr = DecisionTreeRegressor(criterion='mse')
    x_test = np.linspace(-3, 3, 50).reshape(-1, 1)
    plt.figure(figsize=(20, 12))
    for i,d in enumerate(depth):
        ax = plt.subplot(2,3,i+1)
        ax.plot(x, y, 'ro', ms=6, label='Actual')
        dtr.set_params(max_depth=d)
        dtr.fit(x, y)
        y_hat = dtr.predict(x_test)
        ax.plot(x_test, y_hat, '-', color='b', linewidth=2, label='Depth=%d' % d)
        ax.legend()
    plt.legend(loc='upper left')
    plt.grid(b=True)
    plt.show()

深度不同的结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值