波士顿房价预测 python实现
时间: 2024-11-19 12:14:18 浏览: 4
波士顿房价预测是一个经典的机器学习案例,通常用于入门数据分析和线性回归模型的应用。Python中,可以使用sklearn库中的`Boston Housing`数据集来实现这个任务。以下是基本步骤:
1. **导入所需的库**:
```python
import numpy as np
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
```
2. **加载数据**:
```python
boston = load_boston()
X = boston.data
y = boston.target
```
3. **数据预处理**:
```python
# 分割特征(X)和目标变量(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. **创建并训练模型**:
```python
model = LinearRegression() # 或者其他回归模型如RandomForestRegressor
model.fit(X_train, y_train)
```
5. **预测和评估**:
```python
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("均方误差(MSE):", mse)
```
阅读全文