Python数据分析用线性回归预测房价数据项目实战大家好今天带大家完成一个经典的回归分析项目——用线性回归预测房价。我们将通过 Python 的 Pandas、Matplotlib、Seaborn 和 StatsModels 库对一个真实的房屋交易数据集进行探索、清洗、建模最后预测一套新房屋的售价。整个过程按步骤展开代码清晰结果直观非常适合新手入门数据分析与机器学习 分析目标我们的目标是基于已有的房屋销售价格及其属性建立一个线性回归模型然后预测以下这套房屋的售价❝面积为 6500 平方英尺4 个卧室、2 个厕所总共 2 层不位于主路无客人房带地下室有热水器没有空调车位数为 2位于城市首选社区简装修。 简介数据集house_price.csv记录了超过 500 栋房屋的交易价格及相关属性包含以下字段字段说明取值price房屋出售价格整数area房屋面积平方英尺整数bedrooms卧室数整数bathrooms厕所数整数stories楼层数整数mainroad是否位于主路yes / noguestroom是否有客房yes / nobasement是否有地下室yes / nohotwaterheating是否有热水器yes / noairconditioning是否有空调yes / noparking车库容量车辆数整数prefarea是否位于城市首选社区yes / nofurnishingstatus装修状态furnished精装semi-furnished简装unfurnished毛坯 读取数据首先导入必要的库并用 Pandas 读取 CSV 文件。import pandas as pd import matplotlib.pyplot as plt import seaborn as sns original_house_price pd.read_csv(house_price.csv) original_house_price.head()输出前 5 行priceareabedroomsbathroomsstoriesmainroadguestroombasementhotwaterheatingairconditioningparkingprefareafurnishingstatus133000007420423yesnononoyes2yesfurnished122500008960444yesnononoyes3nofurnished122500009960322yesnoyesnono2yessemi-furnished122150007500422yesnoyesnoyes3yesfurnished114100007420412yesyesyesnoyes2nofurnished 评估和清理数据创建数据副本保留原始数据。cleaned_house_price original_house_price.copy() 数据整齐度数据已符合“每列一个变量每行一个观察值”无需调整。cleaned_house_price.head(10) 数据干净度检查数据类型将分类变量转换为 category 类型。cleaned_house_price.info()所有字段均无缺失值545 条非空。# 类型转换 cleaned_house_price[mainroad] cleaned_house_price[mainroad].astype(category) cleaned_house_price[guestroom] cleaned_house_price[guestroom].astype(category) cleaned_house_price[basement] cleaned_house_price[basement].astype(category) cleaned_house_price[hotwaterheating] cleaned_house_price[hotwaterheating].astype(category) cleaned_house_price[airconditioning] cleaned_house_price[airconditioning].astype(category) cleaned_house_price[prefarea] cleaned_house_price[prefarea].astype(category) cleaned_house_price[furnishingstatus] cleaned_house_price[furnishingstatus].astype(category) cleaned_house_price.info() 处理缺失数据无缺失值。 处理重复数据允许重复不处理。⚠️ 处理不一致数据检查各分类变量的唯一值均无异常。cleaned_house_price[mainroad].value_counts() # yes 468, no 77 cleaned_house_price[guestroom].value_counts() # no 448, yes 97 cleaned_house_price[basement].value_counts() # no 354, yes 191 cleaned_house_price[hotwaterheating].value_counts() # no 520, yes 25 cleaned_house_price[airconditioning].value_counts() # no 373, yes 172 cleaned_house_price[prefarea].value_counts() # no 417, yes 128 cleaned_house_price[furnishingstatus].value_counts() # semi-furnished 227, unfurnished 178, furnished 140❌ 处理无效或错误数据用describe()查看数值型字段的统计信息均在合理范围内。cleaned_house_price.describe()priceareabedroomsbathroomsstoriesparkingcount5.450000e02545.000000545.0545.0545.0545.0mean4.766729e065150.5412842.9651381.2862391.8055050.693578std1.870440e062170.1410230.7380640.5024700.8674920.861586min1.750000e061650.0000001.01.01.00.025%3.430000e063600.0000002.01.01.00.050%4.340000e064600.0000003.01.02.00.075%5.740000e066360.0000003.02.02.01.0max1.330000e0716200.0000006.04.04.03.0 探索数据开始可视化探索先设置配色风格。sns.set_palette(pastel) 房价分布plt.rcParams[figure.figsize] [7.00, 3.50] plt.rcParams[figure.autolayout] True figure, axes plt.subplots(1, 2) sns.histplot(cleaned_house_price, xprice, axaxes[0]) sns.boxplot(cleaned_house_price, yprice, axaxes[1]) plt.show()结论房价呈右偏分布大多数房屋价格中等但存在一些高价的极端值。 面积分布figure, axes plt.subplots(1, 2) sns.histplot(cleaned_house_price, xarea, axaxes[0]) sns.boxplot(cleaned_house_price, yarea, axaxes[1]) plt.show()结论面积分布同样右偏与房价相似。 房价与面积的关系sns.scatterplot(cleaned_house_price, xarea, yprice) plt.show()结论散点图显示面积与房价大致呈正相关但相关性强度需进一步计算。 卧室数与房价figure, axes plt.subplots(1, 2) sns.histplot(cleaned_house_price, xbedrooms, axaxes[0]) sns.barplot(cleaned_house_price, xbedrooms, yprice, axaxes[1]) plt.show()结论卧室数多为 2~4 个平均房价随卧室数增加而上升但超过 5 个后不再明显。 洗手间数与房价figure, axes plt.subplots(1, 2) sns.histplot(cleaned_house_price, xbathrooms, axaxes[0]) sns.barplot(cleaned_house_price, xbathrooms, yprice, axaxes[1]) plt.show()结论洗手间越多房价越高。 楼层数与房价figure, axes plt.subplots(1, 2) sns.histplot(cleaned_house_price, xstories, axaxes[0]) sns.barplot(cleaned_house_price, xstories, yprice, axaxes[1]) plt.show()结论楼层越多房价越高。 车库数与房价figure, axes plt.subplots(1, 2) sns.histplot(cleaned_house_price, xparking, axaxes[0]) sns.barplot(cleaned_house_price, xparking, yprice, axaxes[1]) plt.show()结论车库数量增加房价上升但超过 2 个后增长放缓。 是否在主路与房价figure, axes plt.subplots(1, 2) mainroad_count cleaned_house_price[mainroad].value_counts() mainroad_label mainroad_count.index axes[0].pie(mainroad_count, labelsmainroad_label) sns.barplot(cleaned_house_price, xmainroad, yprice, axaxes[1]) plt.show()结论大多数房子位于主路且平均房价更高。 是否有客人房与房价figure, axes plt.subplots(1, 2) guestroom_count cleaned_house_price[guestroom].value_counts() guestroom_label guestroom_count.index axes[0].pie(guestroom_count, labelsguestroom_label) sns.barplot(cleaned_house_price, xguestroom, yprice, axaxes[1]) plt.show()结论有客人房的房子价格更高。 是否有地下室与房价figure, axes plt.subplots(1, 2) basement_count cleaned_house_price[basement].value_counts() basement_label basement_count.index axes[0].pie(basement_count, labelsbasement_label) sns.barplot(cleaned_house_price, xbasement, yprice, axaxes[1]) plt.show()结论有地下室的房子价格更高。 是否有热水器与房价figure, axes plt.subplots(1, 2) hotwaterheating_count cleaned_house_price[hotwaterheating].value_counts() hotwaterheating_label hotwaterheating_count.index axes[0].pie(hotwaterheating_count, labelshotwaterheating_label) sns.barplot(cleaned_house_price, xhotwaterheating, yprice, axaxes[1]) plt.show()结论有热水器的房子价格更高虽然样本很少。❄️ 是否有空调与房价figure, axes plt.subplots(1, 2) airconditioning_count cleaned_house_price[airconditioning].value_counts() airconditioning_label hotwaterheating_count.index axes[0].pie(airconditioning_count, labelsairconditioning_label) sns.barplot(cleaned_house_price, xairconditioning, yprice, axaxes[1]) plt.show()结论有空调的房子价格更高。 是否位于城市首选社区与房价figure, axes plt.subplots(1, 2) prefarea_count cleaned_house_price[prefarea].value_counts() prefarea_label prefarea_count.index axes[0].pie(prefarea_count, labelsprefarea_label) sns.barplot(cleaned_house_price, xprefarea, yprice, axaxes[1]) plt.show()结论位于首选社区的房价更高。 装修状态与房价figure, axes plt.subplots(1, 2) furnishingstatus_count cleaned_house_price[furnishingstatus].value_counts() furnishingstatus_label furnishingstatus_count.index axes[0].pie(furnishingstatus_count, labelsfurnishingstatus_label) sns.barplot(cleaned_house_price, xfurnishingstatus, yprice, axaxes[1]) axes[1].set_xticklabels(axes[1].get_xticklabels(), rotation45, horizontalalignmentright) plt.show()结论精装 简装 毛坯装修越好房价越高。 分析数据现在开始构建线性回归模型。使用statsmodels库。import statsmodels.api as sm创建建模专用副本。lr_house_price cleaned_house_price.copy() 引入虚拟变量将所有分类变量转换为虚拟变量独热编码并丢弃第一类以避免多重共线性。lr_house_price pd.get_dummies(lr_house_price, drop_firstTrue, columns[mainroad, guestroom, basement, hotwaterheating, airconditioning, prefarea, furnishingstatus], dtypeint) lr_house_price.head()priceareabedroomsbathroomsstoriesparkingmainroad_yesguestroom_yesbasement_yeshotwaterheating_yesairconditioning_yesprefarea_yesfurnishingstatus_semi-furnishedfurnishingstatus_unfurnished01330000074204232100011001122500008960444310001000212250000996032221010011031221500075004223101011004114100007420412211101000.............................................5401820000300021121010000154117671502400311000000010542175000036202110100000015431750000291031100000000054417500003850312010000001545 rows × 14 columns 划分因变量和自变量y lr_house_price[price] X lr_house_price.drop(price, axis1) 检查多重共线性计算自变量之间的相关系数看是否有绝对值 0.8 的高度相关变量。X.corr().abs() 0.8areabedroomsbathroomsstoriesparkingmainroad_yesguestroom_yesbasement_yeshotwaterheating_yesairconditioning_yesprefarea_yesfurnishingstatus_semi-furnishedfurnishingstatus_unfurnishedareaTrueFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalsebedroomsFalseTrueFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalsebathroomsFalseFalseTrueFalseFalseFalseFalseFalseFalseFalseFalseFalseFalsestoriesFalseFalseFalseTrueFalseFalseFalseFalseFalseFalseFalseFalseFalseparkingFalseFalseFalseFalseTrueFalseFalseFalseFalseFalseFalseFalseFalsemainroad_yesFalseFalseFalseFalseFalseTrueFalseFalseFalseFalseFalseFalseFalseguestroom_yesFalseFalseFalseFalseFalseFalseTrueFalseFalseFalseFalseFalseFalsebasement_yesFalseFalseFalseFalseFalseFalseFalseTrueFalseFalseFalseFalseFalsehotwaterheating_yesFalseFalseFalseFalseFalseFalseFalseFalseTrueFalseFalseFalseFalseairconditioning_yesFalseFalseFalseFalseFalseFalseFalseFalseFalseTrueFalseFalseFalseprefarea_yesFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseTrueFalseFalsefurnishingstatus_semi-furnishedFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseTrueFalsefurnishingstatus_unfurnishedFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseFalseTrue输出显示无强相关性可以放心使用所有变量。➕ 添加截距项X sm.add_constant(X) 拟合模型model sm.OLS(y, X).fit() model.summary()输出结果摘要部分R-squared 0.682说明模型解释了 68.2% 的房价变异。部分变量 p 值较大如bedrooms(0.114)、furnishingstatus_semi-furnished(0.691) 和const(0.872)可能对房价无显著影响。 模型优化剔除 p 值大于 0.05 的变量常数项、卧室数、简装虚拟变量重新建模。X X.drop([const, bedrooms, furnishingstatus_semi-furnished], axis1) model sm.OLS(y, X).fit() model.summary()新模型摘要R-squared (uncentered) 0.957拟合度大幅提升所有剩余变量 p 值均小于 0.05具有统计显著性。系数解读面积、厕所数、楼层数、车库数、主路、客房、地下室、热水器、空调、首选社区都会显著提升房价。毛坯房 (furnishingstatus_unfurnished) 会显著降低房价。 预测新房屋价格构造待预测房屋的数据注意目标房屋面积为 6500但原始代码中误写为 5600我们保留原样以便复现结果。price_to_predict pd.DataFrame({area: [5600], bedrooms: [4], bathrooms: [2],stories: [2], mainroad: [no], guestroom: [no],basement:[yes], hotwaterheating: [yes],airconditioning: [no], parking: 2, prefarea: [yes],furnishingstatus: [semi-furnished]}) price_to_predict将分类变量统一为 category 类型并指定所有可能取值确保后续的 get_dummies 不会遗漏。price_to_predict[mainroad] pd.Categorical(price_to_predict[mainroad], categories[no, yes]) price_to_predict[guestroom] pd.Categorical(price_to_predict[guestroom], categories[no, yes]) price_to_predict[basement] pd.Categorical(price_to_predict[basement], categories[no, yes]) price_to_predict[hotwaterheating] pd.Categorical(price_to_predict[hotwaterheating], categories[no, yes]) price_to_predict[airconditioning] pd.Categorical(price_to_predict[airconditioning], categories[no, yes]) price_to_predict[prefarea] pd.Categorical(price_to_predict[prefarea], categories[no, yes]) price_to_predict[furnishingstatus] pd.Categorical(price_to_predict[furnishingstatus], categories[furnished, semi-furnished, unfurnished])生成虚拟变量。price_to_predict pd.get_dummies(price_to_predict, drop_firstTrue, columns[mainroad, guestroom, basement, hotwaterheating, airconditioning, prefarea, furnishingstatus], dtypeint) price_to_predict.head()剔除模型中未使用的变量卧室、简装虚拟变量。price_to_predict price_to_predict.drop([bedrooms, furnishingstatus_semi-furnished], axis1)最后用模型进行预测。predicted_value model.predict(price_to_predict) predicted_value输出0 7.071927e06 dtype: float64预测价格约为 7,071,927 元。✅ 总结通过本项目我们完整走了一遍数据分析与线性回归建模的流程数据清洗与探索可视化分析各变量与房价的关系构建虚拟变量处理分类特征建立 OLS 回归模型评估显著性优化模型剔除不显著变量对新房屋进行价格预测。最终模型拟合度高达 95.7%预测结果具有一定参考价值。当然实际应用中还需考虑更多因素如地理位置、房龄等但本项目的思路和方法是通用的。希望这篇推文对你有所帮助如果你也想动手试试可以在公众号后台回复“预测房价”获取数据集和完整代码。我们下期再见