Forecasting Hourly Dock Demand for a Bike-Share Station
Machine LearningModel answerLast updated
Design an ML pipeline that forecasts 24 hours of bike demand per station, covering target framing, leakage-safe features, validation, and model choice.
Context
A bike-share operator wants a forecast of how many bikes each station will need over the next 24 hours. Operations staff use it to decide when and where to truck bikes between stations. The forecast must be produced per station and per hour.
You have three data sources:
- Station logs (
hourly_logs): timestamp, station ID, bikes currently available, and docks currently free, covering roughly the past two years. - Weather history: hourly temperature, precipitation, and wind speed.
- Calendar data: flags for weekends, public holidays, and local events such as concerts and sports games.
What you should answer
- Target definition. The logs record inventory, not rentals. Explain how you would turn them into a supervised learning target. The ops team needs a bike count, so say how that connects to your target.
- Features. Propose five features that capture seasonality, trend, and external influences on usage. For each, say what could leak future information.
- Validation. Describe how you would cross-validate on this time series without leaking information from the future.
- Models. Pick a baseline and a more complex model, and justify both.
Constraints
- Predictions must be granular: one per station, per hour.
- Training samples must not contain look-ahead information.
- The system must stay reasonable when usage suddenly spikes or drops, for example during a storm or while a station is under maintenance.
Hints
Hint 1
Start by asking what the logs actually measure. Inventory at one moment is different from rentals during an hour, and the difference between consecutive snapshots is a useful place to start.
Hint 2
For any feature, ask whether its value would be known at the moment you make the forecast. Lags that are shorter than the forecast horizon are a common trap.
Hint 3
A random shuffle of rows is the wrong way to split time series data. Think about an expanding window with a gap between train and test.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The main insight is that the raw table measures inventory, not demand. A strong answer converts inventory snapshots into a flow target, cleans out periods where the data is distorted (empty or full stations, and manual rebalancing), and then forecasts with features that are all knowable at the forecast origin. Validation has to respect time order and include a gap. The model should be a simple seasonal baseline plus a global gradient-boosted model.
1. Target definition
Let b[s,t] be the bikes available at station s at hour t. The net flow over the next hour is:
flow[s,t] = b[s,t+1] - b[s,t]
A positive flow means more returns than rentals, so the station is filling and docks are needed. A negative flow means bikes are leaving faster than they return, so the station needs bikes. Predicting the flow rather than the absolute level removes the dependence on station capacity, so one model can serve stations of different sizes.
Three things need cleaning before training:
- Censoring. When a station is empty, some would-be renters walk away, so the observed drop understates true demand. The same happens when a station is full and returns fail. Flag these hours. Either drop them from the loss or treat them as censored observations, for example with a Tobit-style likelihood.
- Rebalancing. Trucks move bikes in batches of 10 to 20. Those jumps are operator actions, not rider demand. Detect them as large deviations from the station's typical hourly variation, or remove them using dispatch logs if you have them. Otherwise the model learns to predict the team's own interventions.
- Choice of loss. If sub-hourly snapshots let you separate rentals from returns, model each as a count with a Poisson or Tweedie objective and a log link. Counts are non-negative, skewed, and have variance that grows with the mean. Net flow is a difference of two counts and can be negative, so MSE or Huber loss is a reasonable fallback.
Structure the forecast as direct multi-horizon prediction. Each training row has a station, a forecast origin T, and a horizon h from 1 to 24, and the target is the flow at T+h. Horizon is a feature. This avoids the error compounding that recursive forecasting produces, and it forces every feature to be computed as of T. The operations quantity is then the current bike count plus the cumulative predicted flow.
2. Five features
| # | Feature | What it captures | Leakage check |
|---|---|---|---|
| 1 | Hour-of-week (168-level categorical, or sin/cos of hour plus day-of-week) | Daily and weekly rhythm, such as commute peaks | Deterministic, safe |
| 2 | Same-hour flow from 7 days earlier, and 1 day earlier when h ≤ 24 | Station-specific recurring pattern | A lag shorter than h would be in the future relative to the target, so keep only lags that are already observed at T |
| 3 | Rolling 7-day and 28-day mean and std of flow at that hour-of-week, plus a 90-day level | Trend and volatility, including popularity changes | Compute with a shift so the window ends at T |
| 4 | Weather at the target hour, plus "rain started within the last hour" | Storms and other external shocks | At inference you only have forecasts. Train on archived forecasts if available, otherwise on actuals with added noise to simulate forecast error |
| 5 | Holiday, weekend, and nearby-event indicators with hours until event start or end | Spikes from stadium crowds and concerts | Event schedules are published in advance, so they are safe |
Useful extras: station capacity, distance to transit, current fill ratio at T, and an outage or maintenance flag.
3. Validation without leakage
Random K-fold is wrong here. It trains on Tuesday to predict Monday, and lag and rolling features overlap across folds, which inflates scores.
Use rolling-origin (expanding-window) validation:
Fold 1: train Jan Y1 .. Mar Y2 | gap 24h | test next 2 weeks
Fold 2: train Jan Y1 .. May Y2 | gap 24h | test next 2 weeks
Fold 3: train Jan Y1 .. Jul Y2 | gap 24h | test next 2 weeks
Rules to follow:
- Mimic production timing. If the model runs at midnight, every test row may use only data available at midnight.
- Leave a gap at least as long as the maximum horizon between the end of training and the start of testing, so no target window straddles the boundary.
- Cover the seasons. With two years of data, test folds should include winter, summer, and holiday periods. Report results per fold, not only the average.
- Fit preprocessing on training data only. This covers scalers, any target encoding of station IDs, and outlier thresholds.
- Keep a final holdout of the most recent two months, untouched until the model is chosen.
Metrics should match the use. Use Poisson deviance or MAE on flow, MAE on cumulative inventory at each horizon, and precision and recall for stockout and full-dock events, since those drive truck dispatch.
4. Model choice
Baseline: seasonal naive. Predict the flow at the same hour last week, or the trailing four-week average for that hour-of-week. It has no leakage risk and is hard to beat for commute-driven stations. A Poisson GLM on hour-of-week, weather, and calendar features makes a good interpretable second baseline.
Main model: a global gradient-boosted tree (LightGBM or XGBoost) trained across all stations, with station metadata as features and a Poisson/Tweedie or Huber objective. Reasons:
- It captures interactions, such as rain mattering at 8am on a weekday but not at 3am.
- It handles a mix of categorical and continuous features without much preprocessing.
- It retrains quickly enough to refresh daily.
- A global model shares information across stations, which helps sparse stations and makes cold-start forecasts for new stations possible.
- Quantile objectives produce P10 and P90 bands, which let ops judge whether a 20% stockout risk justifies a truck trip.
Deep sequence models such as DeepAR or the Temporal Fusion Transformer are reasonable next steps if the data grows large or the team has the infrastructure. For tabular, feature-rich data of this size, boosted trees are usually the pragmatic choice.
5. Handling spikes and drops
- Exclude maintenance and outage periods from training. At inference, use the outage flag to override predictions for affected stations.
- Use Huber or quantile losses so rare extremes do not dominate the fit.
- Refresh the forecast intraday with the latest observed inventory and updated weather forecasts, so the 24-hour horizon rolls forward as new information arrives.
- Monitor residuals by station and by event type, and alert when errors drift, which often signals a changed station layout or a new nearby venue.
Common mistakes
- Forecasting raw bike counts instead of flow, which ties the model to capacity.
- Using random splits or no gap, which overstates accuracy.
- Using a lag or rolling window that includes the target hour.
- Training on censored hours and rebalancing trucks without cleaning them out.
- Assuming weather forecasts will be as accurate at inference as observed weather was in training.