Multi-Horizon Dock Availability Prediction System
Machine LearningModel answerLast updated
Design a real-time forecasting system to predict bike-share dock availability 24 hours ahead, handling temporal dependencies and asymmetric costs.
You're building a predictive system for a bike-sharing network. The system must forecast how many docks will be available at each station over the coming 24 hours, using historical snapshots captured every 15 minutes.
Available Data
Each observation includes:
timestamp: When the measurement was takenstation_id: Station identifieravailable_docks: Count of empty docking spots at that momenttemp,humidity,precipitation: Weather conditionsis_holiday: Whether the day is a public holiday
Your Task
Design a forecasting solution that addresses:
-
Feature design: How would you encode temporal patterns (daily cycles, weekly rhythms) and incorporate historical trends to improve predictions? What features capture the sequential nature of the problem?
-
Data splitting: Explain your approach to creating train/validation splits that respect the temporal ordering and prevent information leakage from future data.
-
Cost-sensitive prediction: The system should be more conservative about running out of capacity. Design a loss function that reflects higher penalties when the model underestimates availability (leading to full stations).
-
Model selection: Recommend a modeling approach suited to this scenario. Consider that predictions must be generated quickly, stations influence each other geographically, and usage patterns evolve over time.
Operational Constraints
- Predictions must be produced fast enough for real-time decision support
- Station activity is correlated with nearby stations
- Historical patterns shift due to seasonal changes and city growth
Hints
Hint 1
Start with a simple baseline like last-week-same-time before building complex models
Hint 2
All features must be knowable at prediction time—don't accidentally use future weather observations
Hint 3
Consider whether you're predicting each future step independently or recursively
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Multi-Horizon Dock Availability Forecasting
Understanding the Problem
This is a multi-step-ahead time-series forecasting challenge with three key considerations:
- Temporal leakage risk: Standard validation approaches will overestimate performance
- Asymmetric costs: Underestimating availability (causing users to find full stations) is worse than overestimating
- Operational requirements: Fast inference, spatial dependencies, and evolving patterns
Start by establishing a naive baseline: predict the same value observed exactly one week ago at this time slot. Any sophisticated model must demonstrate improvement over this simple heuristic.
1. Feature Engineering Strategy
Prediction Framework: At any moment t, generate forecasts for times t+1, t+2, ..., t+96 (next 24 hours in 15-min intervals). Use a direct multi-output approach where each forecast horizon gets its own prediction, rather than feeding predictions recursively—this prevents error accumulation across 96 steps.
Temporal Encoding
Capture cyclical patterns using trigonometric transformations of the target timestamp (not the current time):
Intraday cycles (slot within day, 0-95):
slot = (hour * 4 + minute / 15)
hour_sin = sin(2π × slot / 96)
hour_cos = cos(2π × slot / 96)
Weekly cycles (day 0-6):
day_sin = sin(2π × weekday / 7)
day_cos = cos(2π × weekday / 7)
Annual seasonality:
doy_sin = sin(2π × day_of_year / 365.25)
doy_cos = cos(2π × day_of_year / 365.25)
Why sine/cosine pairs? Single sine values create ambiguities (3am and 9pm might map to the same value), while the paired encoding creates unique positions on a circle and correctly places midnight next to 11:59pm.
Also include binary calendar features: is_weekend, is_holiday, day_before_holiday, and local event indicators if available.
Historical Lag Features
All computed at forecast origin t:
Recent state:
- Immediate lags:
docks[t],docks[t-1], ...,docks[t-4] - Change velocity:
docks[t] - docks[t-1] - Rolling windows: mean and std over past 1h, 3h, 24h
Seasonal alignment:
- Yesterday same slot:
docks[t + h - 96] - Last week same slot:
docks[t + h - 672] - These become the strongest predictors for distant horizons
Station context:
- Total capacity (constant per station)
- Current occupancy ratio:
docks[t] / capacity - Exponentially weighted moving average
Weather Features
Critical: use only forecasted weather as it would be known at time t for the target horizon. Never use actual observed future weather—this is the most common leakage mistake in this problem type.
Include temperature-hour interactions naturally if using tree models, as commute patterns change dramatically between hot afternoons and cold mornings.
Spatial Dependencies
Neighbor station features:
- Weighted average occupancy at 3-5 nearest stations (by physical distance or historical trip flows)
- Whether any neighbor is currently at zero or full capacity (spillover indicator)
- Net flow trend:
∑(neighbor_docks[t] - neighbor_docks[t-1])
Handling Non-Stationarity
Rather than predicting raw counts:
- Predict deviations from seasonal baseline:
y[t+h] - y[t+h-672] - Or predict occupancy ratio which normalizes across station sizes
- Include a slow trend feature like 28-day trailing average to adapt to growth
2. Temporal Validation Approach
Never use random k-fold splitting. It causes two forms of leakage:
- Adjacent 15-minute observations are nearly identical
- Rolling window features computed in one fold incorporate target values from other folds
Walk-Forward Validation
Training data: ════════════════════════╗
║ gap
Validation origin: ║→ T₁ ──→ [forecast 96 steps]
Next fold:
Training data: ══════════════════════════════╗
║ gap
Validation origin: ║→ T₂ ──→ [forecast 96 steps]
Procedure:
- Select validation origins T₁, T₂, ..., Tₖ spread across different seasons and weekdays
- For each origin Tᵢ, train on data up to some cutoff before Tᵢ
- Insert a gap: Training labels must end before
Tᵢ - 96steps to ensure no training target falls within the validation forecast window - Generate 96-step forecasts starting from Tᵢ
- Fit any preprocessing (scalers, encoders) only on training portion
Use an expanding window (all data up to cutoff) for stable stations, or a rolling window (last N months) if drift is strong.
Reserve the most recent 4-8 weeks as a final hold-out test set never touched during development.
3. Asymmetric Loss Function
Use quantile loss (also called pinball loss) with τ > 0.5:
L(y, ŷ, τ) = {
τ × (y - ŷ) if y ≥ ŷ (underprediction)
(τ - 1) × (y - ŷ) if y < ŷ (overprediction)
}
The optimal prediction under this loss is the τ-quantile of the conditional distribution.
Setting τ from business costs:
If the cost of underestimation is cᵤ and overestimation is cₒ, then:
τ = cᵤ / (cᵤ + cₒ)
Example: If running out of docks is 4× worse than having excess capacity, use τ = 4/(4+1) = 0.8.
Implementation:
def quantile_loss(y_true, y_pred, tau=0.8):
error = y_true - y_pred
return np.mean(np.where(error >= 0, tau * error, (tau - 1) * error))
Clarify with interviewer: Since the target is "available docks," underestimation means predicting too few available spots, causing users to arrive at full stations. This matches τ > 0.5. If the business concern is actually about empty stations (no bikes), the logic inverts.
Extensions:
- Train multiple quantiles (0.1, 0.5, 0.9) to provide prediction intervals
- Clip outputs to [0, capacity]
- Optionally upweight errors when true values approach boundaries (0 or capacity)
4. Model Architecture
Recommended: Gradient Boosted Decision Trees (LightGBM or XGBoost) trained globally across all stations.
Why This Approach Works
Global modeling: Rather than training separate models per station, include station_id as a categorical feature and train one model on pooled data. Benefits:
- Shares learned patterns across stations (morning outflow, evening inflow)
- Addresses data sparsity for individual stations
- Allows specialization through station-specific splits in the trees
Handles tabular heterogeneity: Seamlessly combines weather, calendar flags, lag features, and spatial signals. Learns complex interactions like "rain × evening commute" automatically.
Real-time feasibility:
- Feature computation is incremental (update rolling stats each 15-min tick)
- Tree inference for 96 horizons takes milliseconds
- No GPU required
Native quantile support: Both frameworks support quantile regression objectives directly via objective='quantile' and alpha=tau.
Configuration:
import lightgbm as lgb
model = lgb.LGBMRegressor(
objective='quantile',
alpha=0.8, # tau parameter
n_estimators=500,
learning_rate=0.05,
max_depth=8,
num_leaves=64,
feature_fraction=0.8
)
Include horizon (1-96) as a feature so the model learns different patterns for near vs. distant forecasts.
Alternative Approaches (Trade-offs)
Per-station ARIMA/SARIMAX:
- Pros: Interpretable, uncertainty quantification
- Cons: Struggles with capacity constraints, exogenous features, and scaling to hundreds of stations
Deep sequence models (DeepAR, Temporal Fusion Transformer):
- Pros: Native probabilistic multi-horizon predictions, learns complex temporal dependencies
- Cons: Requires more training data, slower inference, harder to debug, needs GPUs
Graph Neural Networks (DCRNN, ST-GCN):
- Pros: Explicitly models spatial station network
- Cons: Significant engineering overhead, inference latency, only justified when spatial effects dominate
Evaluation Metrics
- Primary: Quantile loss at chosen τ and MAE, both broken down by horizon
- Calibration: Does the 0.9 quantile actually cover 90% of observed values?
- Operational: Precision/recall for critical events (station empty or full)
- Baseline comparison: Beat last-week-same-time and yesterday-same-time benchmarks
Common Pitfalls
- Future leakage: Using actual observed weather at t+h instead of weather forecasts available at t
- Random splits: Allowing validation samples to appear before training samples chronologically
- Recursive forecasting: Feeding predictions back as inputs, compounding errors over 96 steps
- Ignoring baseline: Building complex models without checking if they beat naive seasonal persistence
- Static models: Not planning for retraining cadence as patterns shift
Implementation Path
- Build naive baselines first (last week, last day)
- Start with simple features (time encoding, recent lags, weather)
- Add spatial and seasonal features incrementally
- Validate rigorously with walk-forward splits
- Tune quantile parameter based on observed stockout costs
- Monitor calibration and retrain monthly or quarterly