python头歌实训作业答案第4关:scikit-learn线性回归实践 - 波斯顿房价预测
时间: 2024-11-09 07:18:54 浏览: 105
Python机器学习(scikit-learn):线型模型(线型回归、逻辑回归)、样本生成器、方法链-谢TS的博客.pdf
波士顿房价预测是Python scikit-learn库中的经典案例,它使用了`Boston Housing`数据集来进行线性回归模型的训练。这个练习的主要目标是通过分析影响波士顿地区房价的各种因素,如犯罪率、平均房间数等,建立一个模型来预测房价。
第4关的具体步骤可能包括:
1. 导入所需的库:
```python
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
import pandas as pd
```
2. 加载并预处理数据:
```python
boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['PRICE'] = boston.target # 将标签添加到DataFrame中
X_train, X_test, y_train, y_test = train_test_split(df.drop('PRICE', axis=1), df['PRICE'], test_size=0.2, random_state=42)
```
3. 创建并训练线性回归模型:
```python
model = LinearRegression()
model.fit(X_train, y_train)
```
4. 预测并评估模型性能:
```python
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"Mean Squared Error: {mse:.2f}")
print(f"R-squared Score: {r2:.2f}")
```
阅读全文