波士顿房价预测(随机森林和线性回归) 1.线性回归和随机森林建模 from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LinearRegression 2.预测房价并绘制对比图
时间: 2024-02-06 22:11:54 浏览: 164
好的,这里是波士顿房价预测的代码,包括线性回归和随机森林建模以及预测和绘制对比图:
```python
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score, mean_squared_error
import matplotlib.pyplot as plt
# 加载数据集
boston = load_boston()
# 转换为DataFrame格式
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = pd.DataFrame(boston.target, columns=['MEDV'])
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 线性回归建模
lr = LinearRegression()
lr.fit(X_train, y_train)
# 随机森林建模
rf = RandomForestRegressor(n_estimators=200, random_state=42)
rf.fit(X_train, y_train)
# 预测测试集结果
lr_pred = lr.predict(X_test)
rf_pred = rf.predict(X_test)
# 绘制对比图
plt.figure(figsize=(10, 5))
plt.plot(y_test.values, label='True Values')
plt.plot(lr_pred, label='Linear Regression')
plt.plot(rf_pred, label='Random Forest')
plt.legend()
plt.show()
# 输出评估指标
print('Linear Regression R2 Score:', r2_score(y_test, lr_pred))
print('Random Forest R2 Score:', r2_score(y_test, rf_pred))
print('Linear Regression MSE:', mean_squared_error(y_test, lr_pred))
print('Random Forest MSE:', mean_squared_error(y_test, rf_pred))
```
运行代码后,会得到预测结果对比图和模型评估指标。你可以根据需要对代码进行修改和调整。
阅读全文