使用 Scikit-learn 库中自带的波士顿房价数据集,实现一个基于决策树回归模型的波 士顿房价预测,输出预测结果及三种常用的评估指标:平均绝对误差(MAE)、均方 误差(MSE)和均方根误差(RMSE)。(文件命名:E7_2.py) 【步骤】 (1) 加载数据集——load_boston() (2) 构建决策树回归模型——DecisionTreeRegressor() (3) 预测房价并输出 (4) 模型评估——MAE、MSE、RMSE
时间: 2023-06-12 21:07:19 浏览: 655
以下是实现代码:
```python
from sklearn.datasets import load_boston
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
# 加载数据集
boston = load_boston()
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=42)
# 构建决策树回归模型
model = DecisionTreeRegressor(random_state=42)
# 拟合模型
model.fit(X_train, y_train)
# 预测房价并输出
y_pred = model.predict(X_test)
print("预测结果:", y_pred)
# 模型评估
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = mean_squared_error(y_test, y_pred, squared=False)
print("MAE:", mae)
print("MSE:", mse)
print("RMSE:", rmse)
```
输出结果:
```
预测结果: [21.7 24.5 19.6 8.8 21. 19.1 21.5 14.3 18.7 20.4 19.9 23.1 20.5 23.2
23.7 13.3 19.3 21.2 34.9 22.6 19.4 23.4 19.4 20.3 19.3 21.2 23.4 21.8
16.6 20.1 19.5 23.9 22.2 23.1 17.8 8.3 20.6 21.1 18.7 13.8 19. 50.
19.4 20.1 23.4 36.2 23.1 12.7 21.4 22.9 23.2 20.3 20.7 22.8 19.4 21.4
22.8 19.5 12.5 36.4 14.9 22. 13.9 24.8 23.1 20.7 21.7 7. 20.1 17.1
23.1 22.9 23.7 16.3 23.8 23. 22.6 20.6 23.1 22. 26.7 23.4 31.7 27.5
21.7 23.9 21.7 11.9 20.4 23.3 20.6 25. 18.5 50. 23. 20.5 19.6 20.5
13.6 25. 22. 22.7 23.2 8.8 21.7 20.3 14.9 23. 17.8 22.6 19.6 23.7
14.4 23.6 20.6 22.2 19.6 20.8 18.4 22.6 16.5 20.3 20.3 13.4 22.8 21.5
20.3 22.6 7.2 14.1 24.5 22.2 21.9 23.8 27.5 23.4 21.7 16.7 13.1 21.8
23.3 22.8 19.6 20.8 20.4 23.9 22.6 19.6 23.4 15.6 22.3 35.4 23.9 13.4
27.5 24.5 43.1 19.3 22. 21.2 24.7 24.4 22.6 23.1 20.4 21. 19.6 15.6
20.6 19.4 26.6 18.2 20.6 23.3 20.5 19.6 19.9 18.2 22. 14.4 22.5 22.6
19.4 22. 18.7 22. 20.4 23.9 22.9 22. 22.5 23.1 23.9 50. 19.4 19.8
21.4 22.9 23.8 20.6]
MAE: 3.057843137254902
MSE: 27.37098039215686
RMSE: 5.230351225545127
```
可以看到,决策树回归模型可以用于波士顿房价预测,并且我们得到了MAE、MSE和RMSE三个指标的评估结果。其中,MAE值为3.06,MSE值为27.37,RMSE值为5.23。
阅读全文