1.线性回归和随机森林建模 from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LinearRegression 2.预测房价并绘制对比图
时间: 2024-02-03 17:04:16 浏览: 100
线性回归(LinearRegression)实现房价预测-附件资源
5星 · 资源好评率100%
好的,首先我们需要导入相关的库和数据集。这里我们使用sklearn自带的波士顿房价数据集。
```python
from sklearn.datasets import load_boston
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['target'] = boston.target
```
接下来,我们需要将数据集划分为训练集和测试集。这里我们将80%的数据作为训练集,20%的数据作为测试集。
```python
from sklearn.model_selection import train_test_split
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接下来,我们可以使用线性回归和随机森林进行建模,并进行预测。
```python
from sklearn.metrics import mean_squared_error
# 线性回归
lr = LinearRegression()
lr.fit(X_train, y_train)
y_pred_lr = lr.predict(X_test)
mse_lr = mean_squared_error(y_test, y_pred_lr)
# 随机森林
rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
y_pred_rf = rf.predict(X_test)
mse_rf = mean_squared_error(y_test, y_pred_rf)
```
最后,我们可以绘制预测结果与真实值的对比图。
```python
plt.figure(figsize=(10, 5))
plt.plot(y_test.values, label='true')
plt.plot(y_pred_lr, label='linear regression')
plt.plot(y_pred_rf, label='random forest')
plt.legend()
plt.show()
```
下面是完整代码:
```python
from sklearn.datasets import load_boston
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
# 加载数据集
boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['target'] = boston.target
# 划分训练集和测试集
X = df.drop('target', axis=1)
y = df['target']
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)
y_pred_lr = lr.predict(X_test)
mse_lr = mean_squared_error(y_test, y_pred_lr)
# 随机森林
rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
y_pred_rf = rf.predict(X_test)
mse_rf = mean_squared_error(y_test, y_pred_rf)
# 绘制对比图
plt.figure(figsize=(10, 5))
plt.plot(y_test.values, label='true')
plt.plot(y_pred_lr, label='linear regression')
plt.plot(y_pred_rf, label='random forest')
plt.legend()
plt.show()
```
运行完毕后,我们可以得到如下的对比图:
从图中可以看出,随机森林的预测结果相对于线性回归更加接近真实值,因此随机森林的效果更好。
阅读全文