Hourly Demand Forecasting for Shared Mobility Systems
Machine LearningModel answerLast updated
Build a model to forecast hourly demand at individual stations in a bike-sharing network, handling time-series structure, censored observations, and overfitting risks.
You're building a forecasting system for a bike-sharing network operating across a city. The dataset contains historical records with these attributes: station identifier, hourly timestamps, counts of bikes picked up and returned, total dock capacity, snapshot of bikes present at each hour, weather conditions, holiday indicators, and signals from nearby transit hubs or local events.
Your task is to build a model that forecasts how many bikes will be picked up from a given station in the upcoming hour.
Address these aspects in your response:
- How you'll formulate the prediction target and prevent information leakage from future data
- Which features you'll construct from time patterns, station characteristics, weather data, and location attributes
- What temporal splitting strategy you'll apply for training, validation, and testing
- Which evaluation metric(s) you'll select (such as MAE, RMSE, Poisson loss, or metrics tied to operational outcomes like empty docks) and why
- Your approach to identifying and mitigating overfitting
Provide concrete examples and explain your reasoning.
Hints
Hint 1
Observed pickups may be constrained by available inventory—consider whether you're predicting observed demand or latent demand
Hint 2
Time-based data requires forward-only validation; random splits will leak future information into training
Hint 3
Features computed from historical data must be recalculated separately within each training fold to avoid leakage
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Hourly Demand Forecasting for Shared Mobility
Understanding the Problem Structure
This is a time-series forecasting task with operational constraints. The key insight is that recorded pickups represent observed demand capped by supply, not true underlying demand. When a station runs out of bikes, unmet demand goes unrecorded.
1. Target Definition and Preventing Leakage
Formulating the target: At timestamp t (start of hour h), we predict y = number of pickups at station s during the interval [t, t+1).
Handling censored observations:
- If the goal is forecasting observable pickups (for capacity planning), predict the censored outcome and include
bikes_available_at_tas a feature. The model learns the inventory constraint naturally. - If the goal is estimating true latent demand (for network expansion decisions), either exclude hours when stations were empty for significant periods, or use a survival/censored regression approach treating these as lower bounds.
Be explicit about which formulation you're using—conflating them undermines model validity.
Leakage prevention checklist:
Critical leakage sources and fixes:
- Temporal aggregations: Lag features must use
shift(1)or greater. "Last hour" means hourh-1, noth. - Concurrent events: Returns happening during hour
hare not known att—exclude them. - Weather data: At serving time, you only have forecasts. Either train on forecast data (not actuals), or explicitly account for forecast error.
- Availability snapshots: Use only the state captured exactly at time
t, not later updates. - Historical encodings: When computing station-level averages or target encodings, calculate them using only data before each validation fold's boundary.
- Preprocessing parameters: Fit normalization, imputation, and encoders separately within each training fold.
2. Feature Engineering Strategy
Temporal patterns:
- Cyclical time features: hour-of-day and day-of-week encoded with sine/cosine transforms (preserves cyclical continuity)
- Hour × day-of-week interactions (Tuesday 8am behaves differently than Saturday 8am)
- Holiday flags, including day-before and day-after indicators
- Lag features: pickups at hours
h-1,h-2,h-24(yesterday same hour), andh-168(last week same hour) - Rolling statistics: mean and standard deviation over 3-hour, 24-hour, and 7-day windows
- Same-hour-last-week average over the past 4 weeks
Station-specific features:
- Static: capacity, geographic coordinates, age since station opened
- Dynamic: current
bikes_available, fill percentage (bikes/capacity) - Historical profile (computed out-of-fold): mean demand by hour × weekday, net flow direction (morning gainer vs. drainer identifies residential vs. commercial areas)
- Recent stockout frequency: fraction of last 24 hours the station was empty or full
Weather and environmental:
- Forecast temperature, precipitation probability/amount, wind speed
- Weather × time interactions (rain at rush hour has different impact than midday rain)
- Day-over-day temperature change (first warm day triggers spike in recreational use)
Spatial and contextual:
- Proximity to transit stations (distance to nearest subway/bus stop)
- Point-of-interest density in 500m radius (offices, parks, universities)
- Terrain: elevation and slope
- Neighbor station signals: recent pickup rates and current availability at stations within 500m (captures demand spillover)
- Scheduled events within 1km: time-until-start and time-since-end for concerts, games, festivals
Model architecture: Use a gradient boosted tree model (LightGBM or XGBoost) with Poisson objective function trained globally across all stations.
Rationale:
- Handles nonlinear interactions and mixed feature types naturally
- Pooling across stations improves estimates for low-volume docks
- Poisson loss respects non-negativity and variance-mean relationship of count data
- Include station_id as a categorical feature to learn station-specific effects
Always compare against simple baselines: last-week-same-hour value and historical station × hour × weekday average.
3. Temporal Validation Strategy
Random cross-validation is invalid for time series—it leaks future information. Use forward-only splitting:
Test set: Reserve final 2-3 months. Never touch until final evaluation. Should include at least one holiday period and varied weather.
Validation: Implement expanding-window cross-validation:
- Fold 1: Train on months 1-3, validate on month 4
- Fold 2: Train on months 1-4, validate on month 5
- Fold 3: Train on months 1-5, validate on month 6
- Continue this pattern
Critical: Add an embargo period. Insert a gap between training and validation equal to your longest lookback window (e.g., 7 days). This prevents near-duplicate windows from appearing in both sets.
Additional considerations:
- If you have multi-year data, ensure validation folds span different seasons
- For cold-start evaluation, hold out 10-15% of stations entirely to test geographic generalization
- Recompute all historical aggregates within each fold using only that fold's training data
4. Evaluation Metrics
| Metric | When to Use | Limitations |
|---|---|---|
| MAE | Stakeholder reporting ("average error of 1.2 bikes") | Optimizes median, biased low for skewed counts |
| RMSE | When large errors are disproportionately costly | Dominated by high-volume stations and outliers |
| Poisson deviance | Model selection when training with Poisson objective | Less interpretable; requires clipping predictions away from zero |
| Quantile loss | When you need prediction intervals for uncertainty | Requires separate models per quantile |
Recommendation: Use Poisson deviance for model selection (aligns with training objective) and report MAE for interpretability.
Operational metrics: The business cares about stockouts. Using the predicted Poisson mean λ, compute P(demand > bikes_available) to forecast stockout probability. Evaluate these probabilities with:
- Brier score or log-loss on actual stockout events
- Precision/recall curves for stockout alerts at different thresholds
- Cost-weighted metric if rebalancing costs and lost-ride costs are known
Slice metrics by: station volume tier, time of day, day of week, weather conditions, and station age.
5. Detecting and Preventing Overfitting
Detection methods:
- Validation curve divergence: Plot training vs. validation Poisson deviance across boosting rounds. Stop when validation begins degrading.
- Feature importance instability: If top features change dramatically across CV folds, the model is fitting noise.
- Temporal degradation: Track validation error across folds. If it increases in later folds, the model doesn't generalize forward in time.
- Per-station analysis: If error distribution has extreme outliers, the model is overfitting to quirks of specific stations.
- Residual patterns: Plot residuals against time, predicted values, and key features. Systematic patterns indicate undermodeling; random noise everywhere suggests overfit.
Prevention strategies:
- Early stopping: Use validation deviance with patience of 50-100 rounds
- Regularization: Tune
min_child_weight(minimum samples per leaf),max_depth,lambda(L2), andalpha(L1) - Subsampling: Use 0.7-0.8 row and column subsampling per tree
- Learning rate: Lower rate (0.01-0.05) with more trees generalizes better
- Feature selection: Drop features with near-zero importance or high cardinality categorical features causing sparsity
- Ensemble: Average predictions across CV folds rather than retraining on all data
- Minimum station volume: Exclude or down-weight stations with very sparse history in the loss function
Common mistakes to avoid:
- Training one model per station (poor generalization for low-volume docks)
- Using categorical encoding with high-cardinality features without regularization
- Tuning on test set
- Ignoring the censoring mechanism
- Not checking if the model beats a naive baseline
The strongest solutions acknowledge uncertainty explicitly—predicting both mean and variance or outputting prediction intervals—and tie model performance directly to downstream operational decisions.