介绍

利用Python进行机器学习预测房价是一个经典的回归问题,广泛应用于房地产、金融和数据科学领域。本指南将详细介绍如何使用Python的scikit-learn库,从数据加载、预处理、特征工程到模型训练与评估,一步步构建一个房价预测模型。

环境设置与库导入

首先,确保已安装必要的Python库,包括pandas、numpy、scikit-learn和matplotlib。使用以下代码导入常用库:

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt

数据加载与探索

使用pandas加载数据集,例如波士顿房价数据集或自定义CSV文件。通过head()、describe()和info()方法初步探索数据,识别特征类型、缺失值和分布情况。

data = pd.read_csv('housing_data.csv')
print(data.head())
print(data.describe())

处理缺失值

检测并处理缺失值是关键步骤。使用dropna()删除缺失行,或使用fillna()填充缺失值(如均值、中位数或众数)。

data.fillna(data.mean(), inplace=True)

特征工程

特征工程能提升模型性能。包括创建新特征、编码分类变量(如使用One-Hot Encoding)和标准化数值特征。

scaler = StandardScaler()
numerical_features = ['area', 'rooms', 'age']
data[numerical_features] = scaler.fit_transform(data[numerical_features])

特征选择

使用相关性分析或特征重要性排名选择关键特征,避免过度拟合。例如,通过相关系数矩阵筛选与房价高度相关的特征。

correlation_matrix = data.corr()
print(correlation_matrix['price'].sort_values(ascending=False))

模型训练

将数据分为训练集和测试集,常用比例是80-20。使用随机森林回归模型进行训练,该模型擅长处理非线性关系。

X = data.drop('price', axis=1)
y = data['price']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

模型评估

使用均方误差(MSE)或R2分数评估模型性能。可视化预测结果与实际值的对比图。

predictions = model.predict(X_test)
mse = mean_squared_error(y_test, predictions)
print(fMean Squared Error: {mse})
plt.scatter(y_test, predictions)
plt.xlabel(Actual Prices)
plt.ylabel(Predicted Prices)
plt.title(Actual vs Predicted Housing Prices)
plt.show()

模型优化

通过超参数调优(如GridSearchCV)和改进特征工程提升模型。尝试不同算法如梯度提升或神经网络以比较性能。

from sklearn.model_selection import GridSearchCV
param_grid = {'n_estimators': [50, 100, 200], 'max_depth': [None, 10, 20]}
grid_search = GridSearchCV(RandomForestRegressor(), param_grid, cv=5)
grid_search.fit(X_train, y_train)
print(grid_search.best_params_)

部署与应用

将训练好的模型保存为pkl文件,便于后续部署到Web应用或API中。使用joblib或pickle库实现。

import joblib
joblib.dump(model, 'housing_price_model.pkl')

总结

本指南涵盖了机器学习预测房价的完整流程,从数据预处理到模型部署。通过实践这些步骤,您可以构建高效的房价预测模型,并根据实际需求进行调整和优化。

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐