Predicting Station-Level Micro-Mobility Checkout Demand
Machine LearningModel answerLast updated
Architect an end-to-end machine learning pipeline to forecast hourly bike-sharing demand, covering censoring adjustments, spatial-temporal features, model selection, and backtesting.
You are asked to design a production-grade machine learning pipeline to predict hourly bike checkout demand at individual docking stations across a major metropolitan bike-share network. Operations teams rely on these predictions to route rebalancing vans and prevent stockouts (empty docks) and oversupplies (full docks).
Available Datasets
- Trip Activity Logs:
trip_id,start_station_id,end_station_id,start_time,end_time. - Station Metadata:
station_id,capacity,latitude,longitude,elevation,install_date. - Exogenous Features: Weather forecasts and historical observations (temperature, rain, wind speed), municipal calendar (holidays, events), and public transportation service disruptions.
Expected Deliverables
- Pipeline Architecture & Demand Censoring: Explain how to process raw trip logs into a structured temporal panel. Detail how you will handle censored demand caused by stockouts where observed pickups drop due to lack of supply rather than lack of interest.
- Feature Engineering Strategy: Detail your feature matrix, focusing on cyclic seasonality, spatial proximity, and external signals. Address how to prevent target leakage when integrating weather data into a real-time system.
- Model Selection & Architecture Trade-Offs: Compare a global gradient-boosted decision tree framework against a spatio-temporal deep learning architecture (e.g., Graph Neural Networks paired with Temporal Fusion Transformers). Discuss interpretability, operational overhead, and loss formulations suitable for count data.
- Validation Framework & Metrics: Design a validation strategy that accounts for temporal dependencies. Select appropriate evaluation metrics and explain how to evaluate performance across low-volume or highly intermittent fringe stations.
Hints
Hint 1
Observed trip starts only measure realized usage, not total potential demand. Consider how to adjust for hours when inventory was zero.
Hint 2
Operational models predicting future hours must be trained on weather predictions available prior to inference time, rather than post-hoc actual weather recordings.
Hint 3
Random cross-validation breaks time order and leaks target information via lag and rolling window features. Use walk-forward backtesting splits.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Target Formulation & Pipeline Architecture
Defining the Target Variable
Predicting net flow alone is insufficient for rebalancing operations. The system must forecast two separate targets for each station $i$ and time step $t+h$:
- Pickups (Checkouts): Outflow demand.
- Dropoffs (Checkins): Inflow demand.
Net inventory change over horizon $h$ is then calculated as: $$\Delta \text{Inventory}{i, t+h} = \sum{k=1}^{h} \left( \widehat{\text{Dropoffs}}{i, t+k} - \widehat{\text{Pickups}}{i, t+k} \right) + \text{Rebalancing Interventions}$$
Data Ingestion & Panel Construction
-
Filtering Noise:
- Exclude trips shorter than 60 seconds starting and ending at the same station (accidental un-docking or system test trips).
- Filter out bulk logistics movements performed by maintenance fleets (typically identified by fleet operator IDs or non-standard travel durations).
- Standardize all timestamps to local timezone, normalizing daylight saving time shifts.
-
Dense Spatial-Temporal Panel:
- Generate a full Cartesian cross-product grid of
(station_id x hourly_timestamp). - Perform an outer join with trip aggregations. Crucially, fill unobserved station-hours with 0 pickups/dropoffs. Skipping zero-count hours creates a sparse matrix that heavily biases predictions upward.
- Generate a full Cartesian cross-product grid of
-
Handling Demand Censoring (Stockouts): When a station reaches 0 bikes, true demand $D_{i,t}$ is unobserved, and realized trips $Y_{i,t} \le D_{i,t}$. Treating $Y_{i,t} = 0$ during a stockout teaches the model that demand was zero.
- Track Station State: Maintain a minute-by-minute dock status log to compute
minutes_emptyandminutes_fullfor every station-hour. - Mitigation Techniques:
- Filtering/Weighting: Exclude or down-weight samples where
minutes_empty > 10. - Imputation: Estimate latent demand for stockout hours using unconstrained historical periods matched by station cluster, day-of-week, weather, and hour.
- Censored Likelihood Loss: Train a Tobit-style model where stockout periods contribute to the loss function using upper-tail probability $P(Y \ge y_{\text{observed}})$ rather than standard equality $P(Y = y_{\text{observed}})$.
- Filtering/Weighting: Exclude or down-weight samples where
- Track Station State: Maintain a minute-by-minute dock status log to compute
2. Feature Engineering & Leakage Prevention
+-----------------------------------------------------------------------------------+
| FEATURE MATRIX |
+------------------------------------+----------------------------------------------+
| Cyclical & Calendar Features | Horizon-Safe Temporal Lags |
| - Sine/Cosine(Hour, Day, Month) | - Lagged Checkouts: t-h, t-24, t-168 |
| - Public Holiday / Event Indicators| - Rolling 7d/28d means for hour-of-week |
| - Commute vs. Weekend Interaction | - Baseline State: Inventory at time t |
+------------------------------------+----------------------------------------------+
| Exogenous Predictors | Spatial & Network Signals |
| - Forecasted Temp, Rain, Wind | - Station capacity, elevation, land-use type |
| - Rain x Commute Hour Interaction | - Distance to transit hubs & CBD |
| - Transit Outages (Distance-decay) | - Lagged demand of k-nearest stations |
| | - Nearby station stockout flags (spillover) |
+------------------------------------+----------------------------------------------+
Cyclical & Calendar Encodes
- Continuous Transformations: Map temporal periodicities using sine and cosine components: $$\text{hour}{\sin} = \sin\left(\frac{2\pi \cdot \text{hour}}{24}\right), \quad \text{hour}{\cos} = \cos\left(\frac{2\pi \cdot \text{hour}}{24}\right)$$
- Non-Linear Domain Interactions: Create explicit composite features like
is_weekend$\times$hour_of_day. Rush-hour spikes at 08:00 and 17:00 exist on weekdays but disappear on weekends; tree models require fewer splits to isolate this behavior when provided with explicit interaction features.
Autoregressive Lags (Horizon-Restricted)
For a forecast made at time $t$ for target $t+h$:
- Feature construction must only consume data available at or prior to time $t$. Valid lags include $Y_t, Y_{t-1}, Y_{t-24}, Y_{t-168}$.
- Initial Inventory Feature: Include inventory counts and dock availability at prediction time $t$. If inventory is near zero, immediate short-term pickups ($t+1$) are physically constrained unless rebalancing occurs.
Spatial & Spillover Signals
- Static Attributes: Dock capacity, elevation (uphill stations face asymmetric one-way depletion), distance to central business district (CBD), and land-use category (residential, commercial, transit hub).
- Spatial Spillover Dynamics: Calculate the rolling average demand of the $k$-nearest neighbor stations within a 400-meter radius. If nearby Station B suffers a stockout, spillover demand transfers to target Station A.
Preventing Information Leakage
- Weather Data Integrity: Models must strictly consume historical point-in-time weather forecasts issued prior to time $t$, rather than post-hoc actual weather recordings. Using realized actuals introduces target leakage, as true future weather is unobservable at inference time.
3. Model Architecture & Selection Trade-Offs
| Aspect | Approach A: Global Gradient Boosted Trees (LightGBM / XGBoost) | Approach B: Spatio-Temporal Deep Learning (GNN + TFT) |
|---|---|---|
| Architecture | Single unified tree model across all stations utilizing station encodings and explicit spatial/lag features. | Graph Convolutional Layers (nodes = stations, edges = network flow/distance) combined with Temporal Fusion Transformers. |
| Spatial Modeling | Requires manual engineering of spatial features (k-NN aggregated lags, distance metrics). | Dynamically learns spatial spillovers and spatial-temporal interactions across the station graph. |
| Sample Efficiency & Compute | Highly efficient. Fast training on CPU/GPU panel data with modest memory footprints. | Requires large volumes of training history, extensive hyperparameter tuning, and dedicated GPU infrastructure. |
| Loss & Target Distribution | Direct support for count objectives (Poisson, Tweedie) or quantile regression losses ($\alpha \in {0.1, 0.5, 0.9}$). | Custom parametric head distributions (e.g., Negative Binomial, Zero-Inflated Poisson). |
| Explainability | High (SHAP values, split gain analysis). Straightforward to debug field anomalies. | Low to Moderate (Attention matrices provide limited insight into specific node outputs). |
| Handling New Stations | Generalizes immediately via static physical metadata and geospatial proximity features. | Requires updating spatial graph topologies and re-training structural node embeddings. |
Model Architecture Recommendation
- Baseline Model: Seasonal-naive benchmark along with a station-level Poisson Generalized Linear Model (GLM).
- Primary Production Engine: A global LightGBM model configured with a Poisson or Tweedie objective. Tabular tree ensembles consistently outpace deep learning models on structured time-series panel data while remaining easier to maintain, retrain, and explain to operational stakeholders.
- Next-Stage Exploration: Evaluate spatio-temporal GNN architectures (e.g., Spatio-Temporal Graph Convolutional Networks) if error analysis indicates that complex multi-hop neighborhood spillover dynamics are underfitted by decision trees.
4. Evaluation Strategy & Metrics
Time-Aware Validation Strategy
Standard random $K$-fold cross-validation breaks temporal sequence order and leaks future target information into lag and rolling features.
Train Window [T1 ... T_train] ----> [Gap = h] ----> Test Window [T_train + h ... T_eval]
(Slide Window Forward)
- Walk-Forward (Expanding/Rolling Window) Backtesting: Train on history up to $t$, enforce a buffer gap equal to forecast horizon $h$, and evaluate on the subsequent window $[t+h, t+h+\Delta t]$.
- Fold Construction: Execute 8–12 rolling splits covering diverse seasonal conditions (winter vs. summer, holiday weeks, rainy days, transit strike events).
Primary Metric Selection
- Poisson Deviance: $$\text{Deviance} = 2 \sum_{i,t} \left( y_{i,t} \log\left(\frac{y_{i,t}}{\hat{y}{i,t}}\right) - (y{i,t} - \hat{y}_{i,t}) \right)$$ Why: Appropriate for zero-heavy count data where variance scales with the mean. Unlike RMSE, it penalizes relative scale errors appropriately across low- and high-volume stations.
- Weighted Absolute Percentage Error (WAPE): $$\text{WAPE} = \frac{\sum_{i,t} |y_{i,t} - \hat{y}{i,t}|}{\sum{i,t} y_{i,t}}$$ Why: Solves division-by-zero issues inherent to MAPE on low-count hours while providing an intuitive, business-friendly error percentage.
Evaluating Intermittent & Low-Volume Stations
Many suburban or fringe stations register zero checkouts for consecutive hours, leading to sparse count distributions.
- Stratified Evaluation: Segment stations into volume quantiles (High, Medium, Low/Intermittent Volume) and track metrics independently per tier.
- Distributional Metric (CRPS / Pinball Loss): Evaluate probabilistic predictions across low-demand stations using Continuous Ranked Probability Score (CRPS) or Quantile Loss ($\alpha \in {0.5, 0.9}$) to ensure the model captures upper-tail demand risks without over-predicting expected counts.