1. 使用python读入数据sklearn中的波士顿房价的数据集。2. 对该数据集进行可视化(使用点图和核密度曲线直方图)3. 使用GBDT对模型进行预测,要求使用交叉验证训练,给出MSE误差曲线。
时间: 2024-02-09 17:08:42 浏览: 34
好的,我来为你提供Python的代码实现。
首先,我们需要导入相关的库和模块:numpy、pandas、matplotlib、sklearn等。然后,使用sklearn中的load_boston方法读入波士顿房价数据集。
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
boston = load_boston()
```
接下来,我们对数据集进行可视化。首先,使用散点图展示房价和房屋面积之间的关系。
```python
plt.scatter(boston.data[:, 5], boston.target)
plt.xlabel('RM')
plt.ylabel('Price')
plt.show()
```
然后,使用核密度曲线和直方图展示房屋面积和房间数目的分布情况。
```python
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.hist(boston.data[:, 5], bins=20)
plt.xlabel('RM')
plt.ylabel('Frequency')
plt.subplot(1, 2, 2)
plt.hist(boston.data[:, 6], bins=20)
plt.xlabel('LSTAT')
plt.ylabel('Frequency')
plt.show()
```
最后,我们使用GBDT模型对数据集进行预测,并使用交叉验证训练,给出MSE误差曲线。首先,我们需要将数据集分为训练集和测试集。
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.3, random_state=42)
```
然后,我们可以使用sklearn中的GradientBoostingRegressor模型进行训练和预测。
```python
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import cross_val_score
# 创建GBDT模型
gbdt = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=1, random_state=42)
# 训练模型
gbdt.fit(X_train, y_train)
# 预测模型
y_pred = gbdt.predict(X_test)
# 计算MSE
mse = mean_squared_error(y_test, y_pred)
print("MSE: %.2f" % mse)
# 使用交叉验证训练,并画出MSE误差曲线
scores = cross_val_score(gbdt, boston.data, boston.target, cv=10, scoring='neg_mean_squared_error')
plt.plot(np.arange(1, 11), -scores)
plt.xlabel('Number of folds')
plt.ylabel('MSE')
plt.show()
```
以上就是Python的代码实现,希望对你有帮助。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)