梯度下降的使用-房价预测
2026/4/27 8:22:17 网站建设 项目流程

一个小小的建议:可以安装JupyterLab来调试练习,真的很方便。

""" 房价预测示例 - 使用梯度下降求解线性回归 使用真实数据集:加州房价数据集 (California Housing Dataset) 来源:1990年加州人口普查数据 特征说明: - MedInc: 区域内家庭收入中位数 - HouseAge: 房屋年龄中位数 - AveRooms: 平均房间数 - AveBedrms: 平均卧室数 - Population: 区域人口 - AveOccup: 平均居住人数 - Latitude: 纬度 - Longitude: 经度 - Target: 房屋价格中位数 (单位:10万美元) """importnumpyasnpfromsklearn.datasetsimportfetch_california_housingtry:importmatplotlib.pyplotasplt HAS_MATPLOTLIB=TrueexceptImportError:HAS_MATPLOTLIB=False# 配置中文字体支持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("正在加载加州房价数据集...")housing=fetch_california_housing()X=housing.data# 特征矩阵y=housing.target# 目标值(房价,单位:10万美元)# 为了演示清晰,只取前1000条数据,并选择3个主要特征# 真实场景可以用全部数据X_subset=X[:1000,:3]# 只取收入、房龄、房间数y_subset=y[:1000]# 将房价单位转换为"万美元"(乘以10)y_subset=y_subset*10feature_names=['收入中位数(万$)','房龄中位数(年)','平均房间数']print(f"原始数据集:{housing.data.shape[0]}条记录")print(f"使用数据:{len(y_subset)}条记录 (示例演示)")returnX_subset,y_subset,feature_names# ============================================# 2. 数据预处理# ============================================defpreprocess_data(X):""" 特征预处理:标准化 使各特征在相近范围内,加速梯度下降收敛 """# 计算均值和标准差mu=np.mean(X,axis=0)sigma=np.std(X,axis=0)# 标准化X_scaled=(X-mu)/sigma# 添加偏置列 (x0 = 1)m=X.shape[0]X_final=np.column_stack([np.ones(m),X_scaled])returnX_final,mu,sigma# ============================================# 3. 梯度下降实现# ============================================defgradient_descent(X,y,alpha=0.01,iterations=1000,verbose=True):""" 批量梯度下降 参数: X: 特征矩阵 (m, n+1),包含偏置列 y: 目标值向量 (m,) alpha: 学习率 iterations: 最大迭代次数 verbose: 是否打印训练过程 返回: theta: 估计的参数向量 loss_history: 损失历史记录 """m,n=X.shape theta=np.zeros(n)# 参数初始化为零loss_history=[]foriinrange(iterations):# 计算预测值h=X.dot(theta)# 计算误差error=h-y# 计算损失 (MSE)loss=(1/(2*m))*np.sum(error**2)loss_history.append(loss)# 计算梯度并更新参数gradient=(1/m)*X.T.dot(error)theta=theta-alpha*gradient# 打印训练进度ifverboseand(i%100==0ori==iterations-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: 特征标准差 返回: 预测房价 (万美元) """# 构建特征向量features=np.array([med_inc,house_age,ave_rooms])# 标准化(使用训练数据的均值和标准差)features_scaled=(features-mu)/sigma# 添加偏置项features_final=np.array([1,features_scaled[0],features_scaled[1],features_scaled[2]])# 预测predicted_price=np.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-',linewidth=2)plt.xlabel('迭代次数',fontsize=12)plt.ylabel('损失 (MSE)',fontsize=12)plt.title('梯度下降收敛过程',fontsize=14)plt.grid(True,alpha=0.3)# 标记收敛点final_loss=loss_history[-1]plt.axhline(y=final_loss,color='r',linestyle='--',alpha=0.5)plt.text(len(loss_history)*0.7,final_loss,f'最终损失:{final_loss:.2f}',fontsize=10)plt.tight_layout()plt.show()plt.savefig('/Users/agilewing/house_price_loss.png',dpi=150)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_names=load_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,sigma=preprocess_data(X_raw)print(f"特征均值:{mu}")print(f"特征标准差:{sigma}")# Step 3: 设置超参数print("\n[Step 3] 设置超参数...")alpha=0.1# 学习率iterations=500# 迭代次数print(f"学习率:{alpha}")print(f"迭代次数:{iterations}")# Step 4: 训练模型print("\n[Step 4] 开始训练 (梯度下降)...")theta,loss_history=gradient_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] 模型评估...")predictions=X.dot(theta)mse=np.mean((predictions-y)**2)rmse=np.sqrt(mse)r2=1-np.sum((y-predictions)**2)/np.sum((y-np.mean(y))**2)print(f"均方误差 (MSE):{mse:.2f}")print(f"均方根误差 (RMSE):{rmse:.2f}万美元")print(f"R² 分数:{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:price=predict_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_inc=input(" 区域收入中位数 (万美元): ")ifmed_inc.lower()=='q':breakmed_inc=float(med_inc)house_age=float(input(" 房屋年龄中位数 (年): "))ave_rooms=float(input(" 平均房间数: "))price=predict_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,sigma=main()# 可选:交互式预测# interactive_predict(theta, mu, sigma)

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询