DEV Community

Sonal Shrivastav
Sonal Shrivastav

Posted on

Building an End-to-End Bike Rental Demand Forecasting Pipeline with Machine Learning and FastAPI

Accurate demand prediction is critical for urban mobility networks. If a bike-sharing network miscalculates, stations run empty or overflow, leading to lost revenue and frustrated commuters.

In my latest portfolio project, I built an end-to-end Machine Learning regression pipeline in Python that forecasts hourly bike rental demand with an R² score of 0.9546 (MAE: 22.81).

Here is a breakdown of how I designed, built, and productionized this pipeline.


1. The Dataset & Preventing Target Leakage

Working with over 17,000+ hourly records, the raw dataset included columns for casual and registered users, which together sum up to the target variable (cnt).

  • The Trap: If you leave these component counts in your feature set during training, the model essentially "cheats" by seeing components of the answer, leading to inflated, unrealistic metrics (target leakage).
  • The Fix: I explicitly reconstructed the target column (cnt = casual + registered) and dropped the component columns prior to splitting the data to ensure zero evaluation contamination.

2. Feature Engineering & Preprocessing

To capture non-linear commuter trends (like morning rush hours or weekend dips), I engineered custom domain flags:

  • is_rush_hour: Flagged peak transit windows.
  • temp_diff: Captured temperature variations.
  • is_weekend: Differentiated weekday commuter habits from weekend leisure riding.

Categorical features were handled using one-hot encoding, and missing values were systematically imputed (Median for numerical variables, Mode for categorical ones).


3. Model Benchmarking & Hyperparameter Tuning

I evaluated several regression algorithms, comparing Decision Trees, Random Forests, and Gradient Boosting.

To squeeze out maximum performance, I leveraged 5-fold RandomizedSearchCV to optimize the hyperparameters of the Gradient Boosting Regressor, successfully achieving a robust R² of 0.9546 and an MAE of 22.81.


4. Production Deployment with FastAPI

A model sitting in a Jupyter notebook doesn't solve real-world problems. To make this pipeline production-ready:

  1. I serialized the trained model and scaler using Joblib.
  2. I built a lightweight FastAPI prediction endpoint (/predict) to handle real-time inference requests.

🔗 Resources & Walkthrough

If you found this breakdown helpful or have questions about handling target leakage in regression tasks, let me know in the comments!

Top comments (0)