使用线性回归算法对波士顿房价进行预测
时间: 2023-09-17 08:09:59 浏览: 85
好的,下面是一个简单的Python代码示例,演示如何使用线性回归算法对波士顿房价进行预测。首先,我们需要导入必要的库,包括NumPy、Pandas和sklearn:
```python
import numpy as np
import pandas as pd
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, r2_score
```
接下来,我们将加载波士顿房价数据集,并将其拆分为训练集和测试集:
```python
# 加载波士顿房价数据集
boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = pd.DataFrame(boston.target, columns=['MEDV'])
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
然后,我们可以使用LinearRegression类来训练线性回归模型:
```python
# 训练线性回归模型
lr = LinearRegression()
lr.fit(X_train, y_train)
```
最后,我们可以使用训练好的模型对测试集进行预测,并计算模型的均方误差和R²分数:
```python
# 对测试集进行预测并计算均方误差和R²分数
y_pred = lr.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("Mean Squared Error:", mse)
print("R2 Score:", r2)
```
完整的代码如下:
```python
import numpy as np
import pandas as pd
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, r2_score
# 加载波士顿房价数据集
boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = pd.DataFrame(boston.target, columns=['MEDV'])
# 将数据集拆分为训练集和测试集
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)
# 对测试集进行预测并计算均方误差和R²分数
y_pred = lr.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("Mean Squared Error:", mse)
print("R2 Score:", r2)
```
希望这个示例对您有所帮助!
阅读全文