【PythonAI】5.2.4 技能实训:使用线性回归进行房价预测

发布时间:2026/7/17 19:31:57

【PythonAI】5.2.4 技能实训:使用线性回归进行房价预测 #predict_house_price.py#!/usr/bin/env python3# -*- coding: utf-8 -*- 线性回归实战房价预测模型 基于新疆某城市房产数据模拟数据 importpandasaspdimportnumpyasnpfromsklearn.model_selectionimporttrain_test_splitfromsklearn.linear_modelimportLinearRegressionfromsklearn.preprocessingimportStandardScalerfromsklearn.metricsimportmean_squared_error,r2_score,mean_absolute_errorimportmatplotlib.pyplotasplt# 设置中文字体plt.rcParams[font.sans-serif][WenQuanYi Zen Hei]plt.rcParams[axes.unicode_minus]Falsedefgenerate_house_data(n_samples500): 生成模拟房产数据 特征面积、卧室数、楼层、房龄、距市中心距离、学区评分 np.random.seed(42)data{面积_sqm:np.random.normal(100,30,n_samples).clip(30,300),卧室数:np.random.randint(1,6,n_samples),楼层:np.random.randint(1,33,n_samples),房龄:np.random.randint(0,30,n_samples),距市中心_km:np.random.exponential(8,n_samples).clip(0.5,50),学区评分:np.random.randint(1,11,n_samples)}dfpd.DataFrame(data)# 生成房价基于特征的非线性组合噪声base_price5000# 基础单价元/平米price(df[面积_sqm]*base_price*(10.3*(df[学区评分]/10))# 面积和学区影响df[卧室数]*50000# 卧室溢价(30-df[房龄])*2000*df[面积_sqm]/100# 房龄折旧(20-df[距市中心_km])*10000# 地段溢价np.random.normal(0,50000,n_samples)# 噪声).clip(200000,5000000)# 限制价格范围df[房价_万元](price/10000).round(2)returndfdefexplore_data(df):数据探索print(*60)print(房产数据探索)print(*60)print(f样本数量:{len(df)})print(f\n数据预览:\n{df.head()})print(f\n统计摘要:\n{df.describe()})# 相关性分析print(f\n与房价的相关性:\n{df.corr()[房价_万元].sort_values(ascendingFalse)})returndf.corr()defvisualize_house_data(df):可视化房产数据fig,axesplt.subplots(2,3,figsize(16,10))# 房价分布axes[0,0].hist(df[房价_万元],bins30,colorskyblue,edgecolorblack,alpha0.7)axes[0,0].set_xlabel(房价万元)axes[0,0].set_ylabel(频数)axes[0,0].set_title(房价分布直方图)axes[0,0].axvline(df[房价_万元].mean(),colorred,linestyle--,labelf均值:{df[房价_万元].mean():.1f}万)axes[0,0].legend()# 面积 vs 房价axes[0,1].scatter(df[面积_sqm],df[房价_万元],alpha0.5,colorgreen)axes[0,1].set_xlabel(面积平方米)axes[0,1].set_ylabel(房价万元)axes[0,1].set_title(面积与房价关系)# 学区评分 vs 房价箱线图df.boxplot(column房价_万元,by学区评分,axaxes[0,2])axes[0,2].set_title(学区评分与房价关系)axes[0,2].set_xlabel(学区评分)# 房龄 vs 房价axes[1,0].scatter(df[房龄],df[房价_万元],alpha0.5,colororange)axes[1,0].set_xlabel(房龄年)axes[1,0].set_ylabel(房价万元)axes[1,0].set_title(房龄与房价关系)# 距市中心距离 vs 房价axes[1,1].scatter(df[距市中心_km],df[房价_万元],alpha0.5,colorpurple)axes[1,1].set_xlabel(距市中心距离km)axes[1,1].set_ylabel(房价万元)axes[1,1].set_title(地段与房价关系)# 特征相关性热力图corr_matrixdf.corr()imaxes[1,2].imshow(corr_matrix,cmapcoolwarm,aspectauto,vmin-1,vmax1)axes[1,2].set_xticks(range(len(corr_matrix.columns)))axes[1,2].set_yticks(range(len(corr_matrix.columns)))axes[1,2].set_xticklabels(corr_matrix.columns,rotation45,haright)axes[1,2].set_yticklabels(corr_matrix.columns)axes[1,2].set_title(特征相关性热力图)# 添加颜色条plt.colorbar(im,axaxes[1,2])# 添加相关系数标注foriinrange(len(corr_matrix.columns)):forjinrange(len(corr_matrix.columns)):textaxes[1,2].text(j,i,f{corr_matrix.iloc[i,j]:.2f},hacenter,vacenter,colorblack,fontsize8)plt.tight_layout()plt.savefig(house_price_exploration.png,dpi150,bbox_inchestight)plt.show()print(\n✓ 可视化结果已保存)deftrain_linear_regression(X_train,X_test,y_train,y_test,feature_names):训练线性回归模型print(\n*60)print(线性回归模型训练)print(*60)# 标准化特征scalerStandardScaler()X_train_scaledscaler.fit_transform(X_train)X_test_scaledscaler.transform(X_test)# 训练模型modelLinearRegression()model.fit(X_train_scaled,y_train)# 预测y_pred_trainmodel.predict(X_train_scaled)y_pred_testmodel.predict(X_test_scaled)# 评估train_r2r2_score(y_train,y_pred_train)test_r2r2_score(y_test,y_pred_test)msemean_squared_error(y_test,y_pred_test)maemean_absolute_error(y_test,y_pred_test)rmsenp.sqrt(mse)print(f训练集 R²:{train_r2:.4f})print(f测试集 R²:{test_r2:.4f})print(f均方误差(MSE):{mse:.4f})print(f均方根误差(RMSE):{rmse:.4f}万元)print(f平均绝对误差(MAE):{mae:.4f}万元)# 特征重要性系数print(f\n特征系数标准化后:)forname,coefinzip(feature_names,model.coef_):print(f{name}:{coef:.4f})print(f截距:{model.intercept_:.4f})returnmodel,scaler,y_pred_testdefvisualize_predictions(y_test,y_pred):可视化预测结果fig,axesplt.subplots(1,2,figsize(14,5))# 预测值 vs 真实值axes[0].scatter(y_test,y_pred,alpha0.6,colorblue)axes[0].plot([y_test.min(),y_test.max()],[y_test.min(),y_test.max()],r--,lw2,label完美预测线)axes[0].set_xlabel(真实房价万元)axes[0].set_ylabel(预测房价万元)axes[0].set_title(预测值 vs 真实值)axes[0].legend()axes[0].grid(True,alpha0.3)# 残差分布residualsy_test-y_pred axes[1].hist(residuals,bins30,colorgreen,edgecolorblack,alpha0.7)axes[1].axvline(x0,colorred,linestyle--,label零误差线)axes[1].set_xlabel(残差万元)axes[1].set_ylabel(频数)axes[1].set_title(预测残差分布)axes[1].legend()plt.tight_layout()plt.savefig(house_price_predictions.png,dpi150,bbox_inchestight)plt.show()defpredict_house_price(model,scaler,features,feature_names):预测单套房价features_dfpd.DataFrame([features],columnsfeature_names)features_scaledscaler.transform(features_df)predictionmodel.predict(features_scaled)[0]print(f\n房屋特征:)forname,valueinzip(feature_names,features):print(f{name}:{value})print(f预测房价:{prediction:.2f}万元)returnpredictiondefmain():主函数# 1. 生成数据print(生成模拟房产数据...)dfgenerate_house_data(n_samples1000)# 2. 探索数据explore_data(df)visualize_house_data(df)# 3. 准备数据feature_names[面积_sqm,卧室数,楼层,房龄,距市中心_km,学区评分]Xdf[feature_names]ydf[房价_万元]X_train,X_test,y_train,y_testtrain_test_split(X,y,test_size0.2,random_state42)print(f\n训练集大小:{len(X_train)})print(f测试集大小:{len(X_test)})# 4. 训练模型model,scaler,y_predtrain_linear_regression(X_train,X_test,y_train,y_test,feature_names)# 5. 可视化预测结果visualize_predictions(y_test,y_pred)# 6. 实际预测示例print(\n*60)print(房价预测演示)print(*60)# 示例1市中心学区房house1[120,3,15,5,2,9]# 面积大、新房、近市中心、学区好predict_house_price(model,scaler,house1,feature_names)# 示例2郊区老房house2[80,2,6,25,25,4]# 面积小、老房、远郊、学区一般predict_house_price(model,scaler,house2,feature_names)print(\n*60)print( 房价预测模型实战完成)print(*60)if__name____main__:main()运行结果(ai_env)$ python3 predict_house_price.py 生成模拟房产数据... 房产数据探索 样本数量: 1000 数据预览: 面积_sqm 卧室数 楼层 房龄 距市中心_km 学区评分 房价_万元 0 114.901425 4 11 13 1.777855 2 101.80 1 95.852071 1 19 19 16.795198 8 72.72 2 119.430656 3 5 20 10.737398 2 96.58 3 145.690896 5 19 23 0.500000 10 137.97 4 92.975399 3 11 14 2.284155 6 92.45 统计摘要: 面积_sqm 卧室数 楼层 房龄 距市中心_km 学区评分 房价_万元 count 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000 mean 100.643093 3.045000 16.368000 14.713000 7.748706 5.520000 89.206330 std 29.206193 1.424431 9.301349 8.608643 7.709968 2.854777 21.714165 min 30.000000 1.000000 1.000000 0.000000 0.500000 1.000000 25.870000 25% 80.572291 2.000000 8.000000 7.000000 2.174257 3.000000 74.407500 50% 100.759018 3.000000 16.500000 15.000000 5.348416 6.000000 88.965000 75% 119.438316 4.000000 24.000000 22.000000 10.898660 8.000000 104.375000 max 215.581945 5.000000 32.000000 29.000000 50.000000 10.000000 161.870000 与房价的相关性: 房价_万元 1.000000 面积_sqm 0.809533 卧室数 0.310149 学区评分 0.222888 楼层 0.066000 房龄-0.108994 距市中心_km-0.379451 Name: 房价_万元,dtype: float64 predict_house_price.py:123: UserWarning: Matplotlib is currentlyusingagg,which is a non-GUI backend,so cannot show the figure.plt.show()✓ 可视化结果已保存 训练集大小: 800 测试集大小: 200 线性回归模型训练 训练集 R²: 0.9443 测试集 R²: 0.9432 均方误差(MSE): 26.0623 均方根误差(RMSE): 5.1051万元 平均绝对误差(MAE): 4.0973万元 特征系数标准化后: 面积_sqm: 17.4734 卧室数: 7.2183 楼层: 0.0787 房龄:-1.6967 距市中心_km:-7.6313 学区评分: 4.4412 截距: 89.3039 房价预测演示 房屋特征: 面积_sqm: 120 卧室数: 3 楼层: 15 房龄: 5 距市中心_km: 2 学区评分: 9 预测房价: 113.36万元 房屋特征: 面积_sqm: 80 卧室数: 2 楼层: 6 房龄: 25 距市中心_km: 25 学区评分: 4 预测房价: 50.03万元 房价预测模型实战完成 (ai_env)$

相关新闻