波士顿房价预测数据集线性回归模型python
时间: 2023-11-16 21:07:36 浏览: 120
boston 房价数据集预测 多种回归方法 python 有报告
5星 · 资源好评率100%
好的,针对波士顿房价预测数据集,我们可以使用线性回归模型进行预测。以下是使用Python实现线性回归模型的步骤:
1. 导入必要的库和数据集
```python
import pandas as pd
import numpy as np
from sklearn.datasets import load_boston
boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['target'] = boston.target
```
2. 数据预处理
```python
X = df.drop('target', axis=1)
y = df['target']
```
3. 划分训练集和测试集
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 训练模型
```python
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(X_train, y_train)
```
5. 预测结果
```python
y_pred = lr.predict(X_test)
```
6. 评估模型
```python
from sklearn.metrics import mean_squared_error, r2_score
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print('Mean Squared Error:', mse)
print('R^2 Score:', r2)
```
阅读全文