用python预测波士顿房价
时间: 2024-12-19 17:13:25 浏览: 5
在Python中,我们可以使用机器学习库如Scikit-Learn来预测波士顿房价。波士顿房价数据集是一个经典的数据科学案例,它包含了1970年代波士顿郊区房屋的各种属性,目标变量是每个小区的平均房价。
以下是使用线性回归模型(Linear Regression)作为例子来预测房价的一般步骤:
1. **导入所需的库**:
```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
```
2. **加载数据**:
```python
boston = load_boston()
df = pd.DataFrame(data=boston.data, columns=boston.feature_names)
target = boston.target
```
3. **数据预处理**:
- 分割特征(X)和目标(y)
- 划分训练集和测试集
```python
X_train, X_test, y_train, y_test = train_test_split(df, target, test_size=0.2, random_state=42)
```
4. **创建并训练模型**:
```python
model = LinearRegression()
model.fit(X_train, y_train)
```
5. **做预测**:
```python
y_pred = model.predict(X_test)
```
6. **评估模型性能**:
```python
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("MSE:", mse, "R^2 Score:", r2)
```
阅读全文