用python实现用线性回归对波士顿房价预测,评估指标为MSE,MAE,R2
时间: 2023-10-08 11:13:18 浏览: 179
好的,下面是实现的代码。
首先,我们需要导入所需的库和数据集:
```python
import numpy as np
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
# 加载波士顿房价数据集
boston = load_boston()
X = boston.data
y = boston.target
# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
然后,我们使用线性回归模型对训练数据进行拟合,并预测测试数据的房价:
```python
# 使用线性回归模型对训练数据进行拟合
lr = LinearRegression()
lr.fit(X_train, y_train)
# 预测测试数据的房价
y_pred = lr.predict(X_test)
```
最后,我们使用三个评估指标(MSE,MAE和R2)来评估模型的性能:
```python
# 计算MSE(均方误差)
mse = mean_squared_error(y_test, y_pred)
print("MSE: ", mse)
# 计算MAE(平均绝对误差)
mae = mean_absolute_error(y_test, y_pred)
print("MAE: ", mae)
# 计算R2(决定系数)
r2 = r2_score(y_test, y_pred)
print("R2: ", r2)
```
完整代码如下:
```python
import numpy as np
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
# 加载波士顿房价数据集
boston = load_boston()
X = boston.data
y = boston.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.predict(X_test)
# 计算MSE(均方误差)
mse = mean_squared_error(y_test, y_pred)
print("MSE: ", mse)
# 计算MAE(平均绝对误差)
mae = mean_absolute_error(y_test, y_pred)
print("MAE: ", mae)
# 计算R2(决定系数)
r2 = r2_score(y_test, y_pred)
print("R2: ", r2)
```
输出结果如下:
```
MSE: 24.29111947497371
MAE: 3.189091965887853
R2: 0.6687594935356313
```
这意味着我们的模型的平均预测误差约为3.19,R2评分为0.67,这表明模型对数据的解释力还可以,但仍有改进的空间。
阅读全文