尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

机器学习入门:用Ridge回归预测共享单车需求(手把手教程)

机器学习入门:用Ridge回归预测共享单车需求(手把手教程) 机器学习实战用Ridge回归预测共享单车需求的完整指南共享单车系统作为城市短途出行的解决方案其需求预测直接影响运营效率。本文将带你从零开始构建一个Ridge回归模型完整覆盖数据探索、特征工程到模型优化的全流程。不同于传统教程我们会深入每个环节的技术细节并分享实际项目中的经验技巧。1. 数据探索与可视化理解业务逻辑在动手建模前我们需要先理解数据背后的业务逻辑。共享单车需求受多种因素影响时间维度小时、星期、月份、季节天气条件温度、湿度、风速、降水特殊事件节假日、促销活动地理位置站点分布、周边设施加载数据后我们首先检查数据质量import pandas as pd import matplotlib.pyplot as plt # 加载数据集 train_df pd.read_csv(./bike_train.csv) print(f数据集形状: {train_df.shape}) print(train_df.info()) print(train_df.describe())提示使用.info()查看数据类型和缺失值.describe()获取统计摘要可视化是发现数据规律的关键。我们绘制每小时平均租车量# 提取小时特征 train_df[hour] train_df.datetime.apply(lambda x: x.split()[1].split(:)[0]).astype(int) # 按小时分组计算均值 hourly_mean train_df.groupby(hour)[[count]].mean() # 可视化 plt.figure(figsize(12,6)) plt.plot(hourly_mean.index, hourly_mean[count], markero) plt.title(每小时平均租车量趋势) plt.xlabel(小时) plt.ylabel(平均租车量) plt.grid(True) plt.savefig(./hourly_trend.png)图租车量呈现明显的早晚高峰模式与通勤需求高度相关2. 深度特征工程从原始数据到模型输入优秀的特征工程往往比模型选择更重要。我们需要从原始数据中提取有预测力的特征2.1 时间特征分解datetime字段包含丰富信息我们可以分解为from datetime import datetime def extract_time_features(df): 从datetime字段提取多维时间特征 df[date] df.datetime.apply(lambda x: x.split()[0]) df[year] df.date.apply(lambda x: x.split(-)[0]).astype(int) df[month] df.date.apply(lambda x: x.split(-)[1]).astype(int) df[day] df.date.apply(lambda x: x.split(-)[2]).astype(int) df[hour] df.datetime.apply(lambda x: x.split()[1].split(:)[0]).astype(int) df[weekday] df.date.apply(lambda x: datetime.strptime(x, %Y-%m-%d).isoweekday()) df[is_weekend] df[weekday].apply(lambda x: 1 if x 6 else 0) return df2.2 天气特征处理天气数据通常需要特殊处理原始天气编码含义处理建议1晴/少云合并为好天气2雾/多云保留原分类3小雪/雨合并为坏天气4暴雨/极端天气考虑剔除或合并def process_weather(df): 天气数据预处理 # 合并相似天气类别 df[weather_simple] df[weather].apply( lambda x: 1 if x 1 else (2 if x 2 else 3) ) return df2.3 特征编码策略对于分类变量我们采用独热编码# 对月份、季节等分类变量进行独热编码 dummies_month pd.get_dummies(train_df[month], prefixmonth) dummies_season pd.get_dummies(train_df[season], prefixseason) dummies_weather pd.get_dummies(train_df[weather_simple], prefixweather) # 合并所有特征 train_df pd.concat([train_df, dummies_month, dummies_season, dummies_weather], axis1)3. Ridge回归模型构建与优化Ridge回归通过L2正则化解决线性回归的过拟合问题特别适合特征较多的场景。3.1 基础模型实现from sklearn.linear_model import Ridge from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split # 准备数据 features train_df.drop([datetime, date, count, casual, registered], axis1) target train_df[count] # 划分训练集和验证集 X_train, X_val, y_train, y_val train_test_split( features, target, test_size0.2, random_state42 ) # 初始化模型 ridge Ridge(alpha1.0) # 训练 ridge.fit(X_train, y_train) # 评估 train_pred ridge.predict(X_train) val_pred ridge.predict(X_val) print(f训练集RMSE: {mean_squared_error(y_train, train_pred, squaredFalse):.2f}) print(f验证集RMSE: {mean_squared_error(y_val, val_pred, squaredFalse):.2f})3.2 超参数调优alpha参数控制正则化强度我们需要通过交叉验证找到最优值from sklearn.model_selection import GridSearchCV # 定义参数网格 param_grid {alpha: [0.01, 0.1, 1, 10, 100, 1000]} # 网格搜索 grid_search GridSearchCV( Ridge(), param_grid, cv5, scoringneg_mean_squared_error ) grid_search.fit(X_train, y_train) # 最佳参数 print(f最佳alpha值: {grid_search.best_params_[alpha]}) print(f最佳分数: {-grid_search.best_score_:.2f})3.3 特征重要性分析理解哪些特征对预测最重要# 获取特征重要性 importance pd.DataFrame({ feature: X_train.columns, coef: ridge.coef_ }).sort_values(coef, ascendingFalse) # 可视化 plt.figure(figsize(10,8)) plt.barh(importance[feature][:15], importance[coef][:15]) plt.title(Top 15重要特征) plt.xlabel(系数大小) plt.tight_layout()4. 高级技巧与实战经验4.1 处理异常值共享单车数据常包含异常值# 基于3σ原则处理异常值 mean train_df[count].mean() std train_df[count].std() train_df train_df[(train_df[count] mean - 3*std) (train_df[count] mean 3*std)]4.2 目标变量变换当目标变量呈现偏态分布时对数变换可能提升性能# 对数变换 train_df[log_count] np.log1p(train_df[count]) # 建模时使用变换后的目标变量 ridge.fit(X_train, np.log1p(y_train)) pred np.expm1(ridge.predict(X_val)) # 预测时反向变换4.3 部署与监控模型上线后需要持续监控性能衰减定期评估模型在新数据上的表现特征漂移监控输入特征的统计特性变化业务指标将预测误差转化为业务影响评估# 模型保存与加载示例 import joblib # 保存 joblib.dump(ridge, bike_demand_model.pkl) # 加载 model joblib.load(bike_demand_model.pkl)在实际项目中我们发现温度特征的处理方式会显著影响模型性能。将原始温度与体感温度(atemp)的差值作为新特征可以捕捉天气舒适度对骑行意愿的影响。此外节假日特征需要特别处理因为它们的租车模式与工作日完全不同。
返回列表