调用sklearn库实现对波士顿房价的预测,采用线性回归方法,并计算以下性能评价指标:平均绝对误差、均方误差、均方根误差、决定系数R2值。
时间: 2024-03-13 17:44:57 浏览: 59
线性回归-波士顿房价预测sklearn.ipynb
好的,针对您的问题,我可以给出以下解答:
首先,我们需要加载波士顿房价数据集和所需的库:
```python
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
boston = load_boston()
X, y = boston.data, boston.target
```
然后,我们将数据集分为训练集和测试集:
```python
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)
```
我们可以使用以下代码计算平均绝对误差、均方误差、均方根误差和R2值:
```python
# 预测
y_pred = lr.predict(X_test)
# 计算平均绝对误差MAE
mae = mean_absolute_error(y_test, y_pred)
print("MAE:", mae)
# 计算均方误差MSE
mse = mean_squared_error(y_test, y_pred)
print("MSE:", mse)
# 计算均方根误差RMSE
rmse = mean_squared_error(y_test, y_pred, squared=False)
print("RMSE:", rmse)
# 计算R2值
r2 = r2_score(y_test, y_pred)
print("R2:", r2)
```
这样,我们就完成了对波士顿房价的预测,并计算了平均绝对误差、均方误差、均方根误差和R2值。
阅读全文