梯度下降的使用-房价预测
一个小小的建议可以安装JupyterLab来调试练习真的很方便。 房价预测示例 - 使用梯度下降求解线性回归 使用真实数据集加州房价数据集 (California Housing Dataset) 来源1990年加州人口普查数据 特征说明 - MedInc: 区域内家庭收入中位数 - HouseAge: 房屋年龄中位数 - AveRooms: 平均房间数 - AveBedrms: 平均卧室数 - Population: 区域人口 - AveOccup: 平均居住人数 - Latitude: 纬度 - Longitude: 经度 - Target: 房屋价格中位数 (单位10万美元) importnumpyasnpfromsklearn.datasetsimportfetch_california_housingtry:importmatplotlib.pyplotasplt HAS_MATPLOTLIBTrueexceptImportError:HAS_MATPLOTLIBFalse# 配置中文字体支持plt.rcParams[font.sans-serif][Arial Unicode MS,SimHei,STHeiti,Heiti TC]plt.rcParams[axes.unicode_minus]False# 解决负号显示问题# # 1. 加载真实房价数据集# defload_house_price_data(): 加载加州房价数据集 (真实数据) 来源sklearn.datasets基于1990年加州人口普查 真实场景中数据通常从 CSV 文件或数据库加载 df pd.read_csv(house_prices.csv) X df[[MedInc, HouseAge, ...]].values y df[Target].values print(正在加载加州房价数据集...)housingfetch_california_housing()Xhousing.data# 特征矩阵yhousing.target# 目标值房价单位10万美元# 为了演示清晰只取前1000条数据并选择3个主要特征# 真实场景可以用全部数据X_subsetX[:1000,:3]# 只取收入、房龄、房间数y_subsety[:1000]# 将房价单位转换为万美元乘以10y_subsety_subset*10feature_names[收入中位数(万$),房龄中位数(年),平均房间数]print(f原始数据集:{housing.data.shape[0]}条记录)print(f使用数据:{len(y_subset)}条记录 (示例演示))returnX_subset,y_subset,feature_names# # 2. 数据预处理# defpreprocess_data(X): 特征预处理标准化 使各特征在相近范围内加速梯度下降收敛 # 计算均值和标准差munp.mean(X,axis0)sigmanp.std(X,axis0)# 标准化X_scaled(X-mu)/sigma# 添加偏置列 (x0 1)mX.shape[0]X_finalnp.column_stack([np.ones(m),X_scaled])returnX_final,mu,sigma# # 3. 梯度下降实现# defgradient_descent(X,y,alpha0.01,iterations1000,verboseTrue): 批量梯度下降 参数 X: 特征矩阵 (m, n1)包含偏置列 y: 目标值向量 (m,) alpha: 学习率 iterations: 最大迭代次数 verbose: 是否打印训练过程 返回 theta: 估计的参数向量 loss_history: 损失历史记录 m,nX.shape thetanp.zeros(n)# 参数初始化为零loss_history[]foriinrange(iterations):# 计算预测值hX.dot(theta)# 计算误差errorh-y# 计算损失 (MSE)loss(1/(2*m))*np.sum(error**2)loss_history.append(loss)# 计算梯度并更新参数gradient(1/m)*X.T.dot(error)thetatheta-alpha*gradient# 打印训练进度ifverboseand(i%1000oriiterations-1):print(f迭代{i:4d}: 损失 {loss:.4f})returntheta,loss_history# # 4. 模型预测# defpredict_price(med_inc,house_age,ave_rooms,theta,mu,sigma): 使用训练好的模型预测房价 参数 med_inc: 区域收入中位数 (万美元) house_age: 房屋年龄中位数 (年) ave_rooms: 平均房间数 theta: 训练得到的参数 mu: 特征均值 (用于标准化) sigma: 特征标准差 返回 预测房价 (万美元) # 构建特征向量featuresnp.array([med_inc,house_age,ave_rooms])# 标准化使用训练数据的均值和标准差features_scaled(features-mu)/sigma# 添加偏置项features_finalnp.array([1,features_scaled[0],features_scaled[1],features_scaled[2]])# 预测predicted_pricenp.dot(features_final,theta)returnpredicted_price# # 5. 训练过程可视化# defplot_loss_history(loss_history): 绘制损失下降曲线 ifnotHAS_MATPLOTLIB:print(\n提示: 安装 matplotlib 后可生成损失曲线图)print( pip install matplotlib)returnplt.figure(figsize(10,6))plt.plot(loss_history,b-,linewidth2)plt.xlabel(迭代次数,fontsize12)plt.ylabel(损失 (MSE),fontsize12)plt.title(梯度下降收敛过程,fontsize14)plt.grid(True,alpha0.3)# 标记收敛点final_lossloss_history[-1]plt.axhline(yfinal_loss,colorr,linestyle--,alpha0.5)plt.text(len(loss_history)*0.7,final_loss,f最终损失:{final_loss:.2f},fontsize10)plt.tight_layout()plt.show()plt.savefig(/Users/agilewing/house_price_loss.png,dpi150)plt.close()print(\n损失曲线已保存到: /Users/agilewing/house_price_loss.png)# # 6. 主程序# defmain():print(*50)print(房价预测模型训练)print(*50)# Step 1: 加载数据print(\n[Step 1] 加载房价数据...)X_raw,y,feature_namesload_house_price_data()print(f数据规模:{X_raw.shape[0]}条记录,{X_raw.shape[1]}个特征)print(f特征:{feature_names})print(f房价范围:{y.min():.1f}-{y.max():.1f}万美元)# Step 2: 数据预处理print(\n[Step 2] 数据预处理 (标准化)...)X,mu,sigmapreprocess_data(X_raw)print(f特征均值:{mu})print(f特征标准差:{sigma})# Step 3: 设置超参数print(\n[Step 3] 设置超参数...)alpha0.1# 学习率iterations500# 迭代次数print(f学习率:{alpha})print(f迭代次数:{iterations})# Step 4: 训练模型print(\n[Step 4] 开始训练 (梯度下降)...)theta,loss_historygradient_descent(X,y,alpha,iterations)# Step 5: 显示训练结果print(\n[Step 5] 训练完成!)print(-*40)print(估计的参数:)print(f θ₀ (基准价):{theta[0]:.2f}万美元)print(f θ₁ (收入系数):{theta[1]:.2f})print(f θ₂ (房龄系数):{theta[2]:.2f})print(f θ₃ (房间数系数):{theta[3]:.2f})print(-*40)# 注由于数据已标准化系数反映的是标准化特征的影响# 要得到原始特征的系数需要转换# Step 6: 模型评估print(\n[Step 6] 模型评估...)predictionsX.dot(theta)msenp.mean((predictions-y)**2)rmsenp.sqrt(mse)r21-np.sum((y-predictions)**2)/np.sum((y-np.mean(y))**2)print(f均方误差 (MSE):{mse:.2f})print(f均方根误差 (RMSE):{rmse:.2f}万美元)print(fR² 分数:{r2:.4f})# Step 7: 预测示例print(\n[Step 7] 使用模型预测房价...)print(-*40)# 预测几个区域使用真实合理的特征值# 加州房价数据集的特征收入中位数、房龄中位数、平均房间数test_cases[(8.0,30,6),# 高收入区老房子大房间(4.0,10,4),# 中收入区新房中等房间(2.0,40,3),# 低收入区很老房子小房间(6.0,20,5),# 中高收入区中等房龄]formed_inc,house_age,ave_roomsintest_cases:pricepredict_price(med_inc,house_age,ave_rooms,theta,mu,sigma)print(f 收入{med_inc:.1f}万$, 房龄{house_age}年,{ave_rooms}房间 → 预测房价:{price:.1f}万美元)print(-*40)# Step 8: 可视化print(\n[Step 8] 生成可视化图表...)plot_loss_history(loss_history)print(\n*50)print(训练完成模型可用于预测新房屋价格。)print(*50)returntheta,mu,sigma# # 7. 交互式预测函数# definteractive_predict(theta,mu,sigma): 交互式预测房价 用户输入区域信息模型返回预测价格 print(\n*50)print(房价预测系统 (加州房价))print(*50)whileTrue:try:print(\n请输入区域信息输入 q 退出:)med_incinput( 区域收入中位数 (万美元): )ifmed_inc.lower()q:breakmed_incfloat(med_inc)house_agefloat(input( 房屋年龄中位数 (年): ))ave_roomsfloat(input( 平均房间数: ))pricepredict_price(med_inc,house_age,ave_rooms,theta,mu,sigma)print(f\n 预测房价中位数:{price:.1f}万美元)exceptValueError:print( 输入格式错误请重新输入)exceptKeyboardInterrupt:breakprint(\n感谢使用)# # 运行主程序# if__name____main__:# 训练模型theta,mu,sigmamain()# 可选交互式预测# interactive_predict(theta, mu, sigma)
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2558883.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!