本專案使用多種機器學習模型(Linear Regression、Random Forest、XGBoost)預測台北市 Youbike 各站點的借閱量。結合時間特徵、氣候數據與站點周邊靜態地理資訊,並提供批次實驗、殘差分析與模型儲存功能,方便比較與部署。
.
├── FINAL_MODEL_DATA_WITH_FEATURES.csv # 主要資料 (時間、氣候、地理、滯後特徵)
├── main.py # 單次訓練與比較,並儲存模型到 model/
├── run_experiments.py # 批次測試多種特徵組合與模型
├── rf_residual_analysis.py # 使用指定特徵進行 RF 殘差分析與時間平均圖
├── batch_experiment_results.csv # 批次實驗結果 (MAE, RMSE, R2)
├── results/ # 產出圖表與指標
│ └── rf_residual_analysis/
│ ├── residuals_by_hour.png
│ ├── residuals_vs_predicted.png
│ ├── residual_distribution.png
│ └── time_average_comparison.png
└── model/ # 儲存訓練完成的模型 (.joblib)
├── linear_regression_model.joblib
├── random_forest_model.joblib
└── xgboost_model.joblib
建議使用 Conda 或 venv。以下以 pip 為例(Windows PowerShell):
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -U pip
pip install pandas numpy seaborn matplotlib scikit-learn xgboost joblib若使用 Conda:
conda create -n ubike python=3.10 -y; conda activate ubike
pip install pandas numpy seaborn matplotlib scikit-learn xgboost joblib使用完整資料的預處理(數值補中位數+標準化、類別補眾數+OneHot),訓練 Linear/RandomForest/XGBoost 並儲存模型:
python main.py產出:
results/baseline_model_metrics.csv與baseline_model_comparison.pngmodel/linear_regression_model.joblibmodel/random_forest_model.joblibmodel/xgboost_model.joblib
測試多組特徵與模型,並可自動載入 main.py 儲存的模型設定:
python run_experiments.py說明:
- 以 3 月資料為測試集,其餘月份為訓練集。
- 每組特徵都會訓練並評估三種模型,結果寫入
batch_experiment_results.csv。 - 若
model/xxx_model.joblib存在,會載入並使用該模型的設定(確保一致性)。
使用固定特徵:['hour','weekday','is_weekend','is_peak','rent_count_lag_3','rent_count_lag_24'] 進行 RF 預測之殘差分析,並繪製每小時的實際 vs 預測平均折線圖。
python rf_residual_analysis.py說明:
- 若
model/rf_model.joblib存在則載入;否則會重新訓練並儲存。 residuals_by_hour.png使用紅藍漸層(RdBu)。
- 安裝環境並啟用虛擬環境(見上方「如何安裝環境」)。
- 確保
FINAL_MODEL_DATA_WITH_FEATURES.csv位於專案根目錄,且包含必要欄位(如hour,weekday,is_weekend,is_peak,rent_count_lag_3,rent_count_lag_24等)。 - 執行單次訓練以產生與儲存模型與基準指標:
python main.py
- 執行批次實驗,生成各特徵組合下的模型表現:
產出
python run_experiments.py
batch_experiment_results.csv,可用於報告與比較。 - 進行 RF 殘差分析與時間平均折線圖,驗證模型在時間維度的行為:
圖表位於
python rf_residual_analysis.py
results/rf_residual_analysis/。
常見注意事項:
- 若儲存 CSV 時出現
Permission denied,請關閉該檔案(例如 Excel)。 - 若缺少套件,請重新執行安裝指令。
- 批次實驗會以 3 月為測試集,其餘為訓練集;確保資料時間欄位
rent_time可正確解析。
-
資料切割 (Data Splitting):
- 採用 Time-based Split 而非 Random Split。
- 測試集:3 月份完整資料。
- 訓練集:其餘月份資料。
- 目的:模擬真實預測情境,避免 Data Leakage。
-
特徵工程 (Feature Engineering):
- 動態特徵:
hour,weekday,temperature,rainfall,wind_speed,is_weekend,is_peak - 滯後特徵:
rent_count_lag_3,rent_count_lag_24 - 靜態特徵:
mrt_dist_nearest_m,school_dist_nearest_m,park_dist_nearest_m,population_count,Quantity,latitude,longitude
- 動態特徵: