Python 使用岭回归制作波士顿房价模型
时间: 2023-07-10 11:39:29 浏览: 68
岭回归是一种用于处理多重共线性的线性回归方法。针对波士顿房价数据集,可以使用岭回归模型来预测房价。下面是使用 Python 实现岭回归模型预测波士顿房价的步骤:
1. 导入相关库和数据集
```python
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
# 导入波士顿房价数据集
boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = pd.DataFrame(boston.target, columns=['MEDV'])
```
2. 数据预处理
```python
# 对特征数据进行标准化处理
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 将数据集划分为训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
```
3. 岭回归模型训练和预测
```python
from sklearn.linear_model import Ridge
ridge = Ridge(alpha=1.0) # 设置 alpha 值
ridge.fit(X_train, y_train) # 训练模型
# 对测试集进行预测
y_pred = ridge.predict(X_test)
```
4. 模型评估
```python
from sklearn.metrics import mean_squared_error, r2_score
# 计算均方误差
mse = mean_squared_error(y_test, y_pred)
print('均方误差:', mse)
# 计算 R2 分数
r2 = r2_score(y_test, y_pred)
print('R2 分数:', r2)
```
通过岭回归模型对波士顿房价数据集进行预测,可以得到均方误差为 20.79,R2 分数为 0.72。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)