实现预测房价的python代码
时间: 2024-01-25 22:03:13 浏览: 67
以下是一个基本的房价预测模型的 Python 代码,使用了线性回归模型:
```python
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# 读取数据集
data = pd.read_csv('housing.csv')
# 分离特征和目标变量
X = data.drop('MEDV', axis=1)
y = data['MEDV']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建线性回归模型并训练
model = LinearRegression()
model.fit(X_train, y_train)
# 预测测试集的房价
y_pred = model.predict(X_test)
# 评估模型性能
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
print("Root Mean Squared Error: ", rmse)
print("R2 Score: ", r2)
```
这段代码假定数据集的目标变量为 'MEDV',特征变量存储在其他列中。
阅读全文