欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Python 实现机器学习的 房价预测回归项目

Python 实现机器学习的 房价预测回归项目

2025/3/11 10:13:51 来源:https://blog.csdn.net/2302_77582029/article/details/146158709  浏览:    关键词:Python 实现机器学习的 房价预测回归项目

项目目标:

      基于房屋特征(如房间数、地理位置等)预测加州地区的房价中位数。

      使用 Python 实现机器学习的 房价预测回归项目(使用 California Housing 数据集)

环境准备

# 安装必要库(若未安装)
# pip install numpy pandas matplotlib scikit-learn seaborn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error, r2_score

完整代码实现

步骤 1: 加载数据集
# 加载加州房价数据集
california = fetch_california_housing()
X = california.data  # 特征数据
y = california.target  # 目标变量(房价中位数,单位:万美元)
feature_names = california.feature_namesprint("特征名称:", feature_names)
print("样本数量:", X.shape[0])
print("特征数量:", X.shape[1])
步骤 2: 数据探索
# 转换为DataFrame
df = pd.DataFrame(X, columns=feature_names)
df['MedHouseVal'] = y# 查看数据概览
print("\n数据前5行:")
print(df.head())# 统计信息
print("\n数据描述:")
print(df.describe())# 绘制房价分布图
plt.figure(figsize=(8,5))
sns.histplot(df['MedHouseVal'], bins=50, kde=True)
plt.title("房价中位数分布")
plt.xlabel("房价(万美元)")
plt.show()# 特征相关性热力图
plt.figure(figsize=(10,8))
corr_matrix = df.corr()
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm')
plt.title("特征相关性矩阵")
plt.show()
步骤 3: 数据预处理
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42
)# 特征标准化
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
步骤 4: 模型训练与比较
# 初始化模型
models = {"Linear Regression": LinearRegression(),"Decision Tree": DecisionTreeRegressor(max_depth=5)
}# 训练与评估
results = {}
for name, model in models.items():model.fit(X_train_scaled, y_train)y_pred = model.predict(X_test_scaled)# 计算指标mse = mean_squared_error(y_test, y_pred)r2 = r2_score(y_test, y_pred)results[name] = {"MSE": round(mse, 2),"R²": round(r2, 3)}# 展示结果
print("\n模型性能对比:")
for model_name, metrics in results.items():print(f"{model_name}:")print(f"  MSE: {metrics['MSE']}")print(f"  R²分数: {metrics['R²']}\n")
步骤 5: 结果可视化
# 获取最佳模型预测结果
best_model = LinearRegression()
best_model.fit(X_train_scaled, y_train)
y_pred = best_model.predict(X_test_scaled)# 绘制实际值与预测值对比
plt.figure(figsize=(8,6))
plt.scatter(y_test, y_pred, alpha=0.5)
plt.plot([0, 5], [0, 5], 'r--')  # 理想对角线
plt.xlabel("实际房价")
plt.ylabel("预测房价")
plt.title("实际值 vs 预测值")
plt.show()# 绘制残差图
residuals = y_test - y_pred
plt.figure(figsize=(8,6))
sns.histplot(residuals, kde=True)
plt.title("残差分布")
plt.xlabel("预测误差")
plt.show()
步骤 6: 特征重要性分析(决策树)
# 获取决策树特征重要性
dt_model = DecisionTreeRegressor(max_depth=5).fit(X_train_scaled, y_train)
importances = dt_model.feature_importances_# 可视化特征重要性
plt.figure(figsize=(10,6))
sns.barplot(x=importances, y=feature_names, palette="viridis")
plt.title("特征重要性排序(决策树模型)")
plt.xlabel("重要性分数")
plt.show()

输出示例

特征名称: ['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude']
样本数量: 20640
特征数量: 8模型性能对比:
Linear Regression:MSE: 0.56R²分数: 0.602Decision Tree:MSE: 0.68R²分数: 0.517

关键分析点

  1. 数据特征MedInc(收入中位数)与房价正相关最强

  2. 模型对比:线性回归表现优于决策树(R²分数更高)

  3. 残差分析:误差大致呈正态分布,但存在高价房低估现象

  4. 地理因素:经度(Longitude)在决策树中显示较高重要性

扩展建议

  1. 尝试其他回归模型(随机森林、梯度提升树)

  2. 添加特征交互项(如收入×房间数)

  3. 使用网格搜索优化超参数

  4. 将经纬度转换为地理位置聚类特征

  5. 部署为API服务(使用Flask/FastAPI)

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词