python多元线性回归预测波士顿房价
时间: 2023-09-23 20:12:32 浏览: 125
好的,下面是Python实现多元线性回归预测波士顿房价的步骤:
1. 导入所需的库:
``` python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
```
2. 加载波士顿房价数据集:
``` python
boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = pd.DataFrame(boston.target, columns=['MEDV'])
```
3. 数据集划分为训练集和测试集:
``` python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 创建线性回归模型并进行训练:
``` python
reg = LinearRegression()
reg.fit(X_train, y_train)
```
5. 对测试集进行预测并计算均方误差:
``` python
y_pred = reg.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print('均方误差:', mse)
```
6. 可以输出预测结果和实际结果进行比较:
``` python
result = pd.DataFrame({'Actual': y_test['MEDV'], 'Predicted': y_pred.flatten()})
print(result)
```
7. 最后,我们可以画出实际房价和预测房价的散点图:
``` python
plt.scatter(y_test, y_pred)
plt.xlabel('实际房价')
plt.ylabel('预测房价')
plt.show()
```
以上就是Python实现多元线性回归预测波士顿房价的步骤。
阅读全文