决策树(回归树)——波士顿房价

from sklearn.tree import DecisionTreeRegressor
from sklearn.datasets import load_boston
from sklearn.model_selection import cross_val_score

#导入波士顿房价数据
boston = load_boston()

boston.data.shape
>>(506, 13)

boston.target.shape
>>(506,)

#实例化
regressor = DecisionTreeRegressor(random_state=0)

#交叉验证10次,返回MSE
cross_val_score(regressor, boston.data, boston.target, cv = 10, scoring = 'neg_mean_squared_error')
>>array([-16.41568627, -10.61843137, -18.30176471, -55.36803922,
       -16.01470588, -44.70117647, -12.2148    , -91.3888    ,
       -57.764     , -36.8134    ])

回归树实例:一维回归的图像绘制(用回归树来拟合正弦曲线,并添加一些噪声来
观察回归树的表现)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor

#创建一条含有噪声的正玄曲线
rng = np.random.RandomState(1)
x = np.sort(5*rng.rand(80,1),axis = 0)

#通过numpy正弦函数生成y,并降维(80,1)到(80,),二维到一维
y = np.sin(x).ravel()
y[::5] += 3*(0.5 - rng.rand(16))
y[::5].shape
>>(16,)

#实例化与训练模型
reg_1 = DecisionTreeRegressor(max_depth = 2)
reg_2 = DecisionTreeRegressor(max_depth = 3)

reg_1.fit(x,y)
reg_2.fit(x,y)

#测试机导入模型,预测结果
x_test = np.arange(0,5,0.01)[:,np.newaxis]
y_1 = reg_1.predict(x_test)
y_2 = reg_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=5", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()

 

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值