波士顿房价预测代码jupyter
时间: 2024-12-25 22:18:29 浏览: 20
波士顿房价预测是一个经典的机器学习示例,通常用于教学目的,特别是在使用Python的数据分析库如Pandas和Scikit-learn进行回归分析时。在Jupyter Notebook中,这个例子通常是通过加载波士顿房价数据集(也称为Boston Housing Dataset),然后构建线性回归模型来预测房屋价格。
以下是基本步骤:
1. **导入所需库**:
```python
import pandas as pd
from sklearn.datasets import load_boston
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
%matplotlib inline
```
2. **加载并预处理数据**:
```python
boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['PRICE'] = boston.target
```
3. **数据探索和可视化**:
```python
df.head(), df.describe()
```
4. **分割数据集**:
```python
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)
```
5. **创建和训练模型**:
```python
model = LinearRegression()
model.fit(X_train, y_train)
```
6. **预测和评估**:
```python
predictions = model.predict(X_test)
mse = mean_squared_error(y_test, predictions)
r2 = r2_score(y_test, predictions)
```
7. **结果展示**:
```python
print(f"Mean Squared Error: {mse}")
print(f"R-squared Score: {r2}")
```
在这个过程中,你可以使用`%matplotlib inline`使得Jupyter Notebook直接显示图表,以便直观地查看特征与房价之间的关系。
阅读全文