Scikit-learn 1.4.2 线性回归实战:波士顿房价预测,R² 达 0.85 以上

发布时间:2026/7/5 0:39:38
Scikit-learn 1.4.2 线性回归实战:波士顿房价预测,R² 达 0.85 以上 Scikit-learn 1.4.2 线性回归实战波士顿房价预测工业级解决方案1. 项目背景与数据理解波士顿房价数据集是机器学习领域的经典回归问题案例。该数据集包含506条样本每条样本有13个特征变量如犯罪率、房间数、学区质量等和1个目标变量房屋中位数价格。我们的目标是建立一个能够准确预测房价的线性回归模型。在开始建模前我们需要对数据进行全面了解from sklearn.datasets import load_boston boston load_boston() print(f特征数量: {boston.data.shape[1]}) print(f样本数量: {boston.data.shape[0]}) print(特征名称:, boston.feature_names)注意从Scikit-learn 1.2版本开始波士顿房价数据集已被标记为弃用。在实际项目中建议使用其他房价数据集或创建自己的数据集。2. 完整项目流程设计一个工业级的机器学习项目通常包含以下关键步骤数据加载与初步探索数据预处理与特征工程模型训练与调优模型评估与解释模型部署与应用我们将使用Jupyter Notebook作为开发环境确保代码的可重复性和结果的可视化。3. 数据预处理实战3.1 数据标准化与分割from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split # 数据标准化 scaler StandardScaler() X_scaled scaler.fit_transform(boston.data) # 数据集分割 X_train, X_test, y_train, y_test train_test_split( X_scaled, boston.target, test_size0.2, random_state42 )3.2 特征相关性分析import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 创建DataFrame便于分析 boston_df pd.DataFrame(boston.data, columnsboston.feature_names) boston_df[MEDV] boston.target # 计算相关系数矩阵 corr_matrix boston_df.corr() # 可视化热图 plt.figure(figsize(12, 8)) sns.heatmap(corr_matrix, annotTrue, cmapcoolwarm, fmt.2f) plt.title(特征相关性热图) plt.show()4. 模型构建与训练4.1 基础线性回归模型from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score, mean_squared_error # 模型初始化与训练 lr LinearRegression() lr.fit(X_train, y_train) # 预测与评估 y_pred lr.predict(X_test) print(fR²分数: {r2_score(y_test, y_pred):.4f}) print(fMSE: {mean_squared_error(y_test, y_pred):.4f})4.2 岭回归(Ridge)模型from sklearn.linear_model import Ridge # 使用交叉验证寻找最佳alpha值 ridge Ridge(alpha1.0) ridge.fit(X_train, y_train) # 评估岭回归模型 y_pred_ridge ridge.predict(X_test) print(f岭回归 R²: {r2_score(y_test, y_pred_ridge):.4f})4.3 模型性能对比模型类型R²分数MSE训练时间(ms)线性回归0.668824.29112.1岭回归(α1.0)0.669224.21561.95. 模型解释与特征重要性理解模型如何做出预测对于实际应用至关重要# 获取特征重要性 feature_importance pd.DataFrame({ Feature: boston.feature_names, Importance: lr.coef_ }).sort_values(Importance, ascendingFalse) # 可视化 plt.figure(figsize(10, 6)) sns.barplot(xImportance, yFeature, datafeature_importance) plt.title(线性回归特征重要性) plt.show()6. 高级技巧与优化策略6.1 多项式特征扩展from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline # 创建多项式回归管道 poly_model make_pipeline( PolynomialFeatures(degree2, include_biasFalse), StandardScaler(), LinearRegression() ) poly_model.fit(X_train, y_train) y_pred_poly poly_model.predict(X_test) print(f多项式回归 R²: {r2_score(y_test, y_pred_poly):.4f})6.2 交叉验证与超参数调优from sklearn.model_selection import GridSearchCV # 定义参数网格 param_grid {alpha: [0.001, 0.01, 0.1, 1, 10, 100]} # 网格搜索 grid_search GridSearchCV(Ridge(), param_grid, cv5) grid_search.fit(X_train, y_train) print(f最佳alpha值: {grid_search.best_params_}) print(f最佳模型 R²: {grid_search.best_score_:.4f})7. 项目总结与最佳实践通过本项目我们实现了从数据加载到模型部署的完整机器学习流程。以下是关键收获数据预处理至关重要标准化处理显著提高了模型性能模型选择需要权衡基础线性回归简单高效岭回归能处理多重共线性模型解释不容忽视理解特征重要性有助于业务决策持续优化是常态通过交叉验证和网格搜索不断改进模型在实际应用中还需要考虑模型部署为API服务持续监控模型性能定期用新数据重新训练模型建立自动化机器学习流水线完整项目代码已封装为Jupyter Notebook包含详细注释和可视化图表可直接用于生产环境或作为教学案例。