Ride-Hailing Demand Modeling & Forecasting Questions
Techniques for modeling and forecasting ride-hailing demand, including time-series forecasting, demand drivers, feature engineering, model selection (e.g., ARIMA, Prophet, ML-based predictors), evaluation metrics (MAPE, RMSE), and deployment considerations within analytics workflows for transportation data.
MediumTechnical
63 practiced
Outline Python pseudocode to train a LightGBM model to predict the next 24 hours of ride demand using lag features and exogenous variables. Include data splitting with rolling-origin CV, feature matrix construction, categorical encoding or handling city/zone IDs, and a simple hyperparameter tuning loop (grid or random). Explain multi-step forecasting strategy if applicable.
Sample Answer
Approach: use lag features + exogenous variables to build a supervised dataset for 24-hour ahead forecasts. Use rolling-origin cross-validation to respect time order. Train LightGBM with simple hyperparameter search (grid/random). For multi-step, use direct or recursive strategy — here show direct models per horizon (0..23) for robustness.Key points:- Rolling-origin CV preserves temporal order and measures performance across time windows.- Encode city/zone with ordinal or target encoding; use categorical_feature in LightGBM for speed.- Direct multi-step modeling avoids accumulation; recursive is lighter but riskier.- Monitor MAE/RMSE and business KPIs (e.g., percentage demand coverage).
python
# pseudocode / Python-ish
import pandas as pd
import numpy as np
import lightgbm as lgb
from sklearn.model_selection import ParameterSampler
from sklearn.preprocessing import OrdinalEncoder
# 1. Prepare raw time-series data: df with ['datetime','city','zone','rides', ...exog vars...]
df = df.sort_values(['city','zone','datetime'])
# 2. Feature builder: create lags and rolling stats
def build_features(group, lags=[1,24,48], windows=[24,168]):
for l in lags:
group[f'lag_{l}'] = group['rides'].shift(l)
for w in windows:
group[f'roll_mean_{w}'] = group['rides'].shift(1).rolling(w).mean()
# add hour/day/week cyclical
group['hour_sin'] = np.sin(2*np.pi*group.datetime.dt.hour/24)
group['hour_cos'] = np.cos(2*np.pi*group.datetime.dt.hour/24)
return group
df = df.groupby(['city','zone']).apply(build_features).dropna()
# 3. Encode categorical city/zone (ordinal or target encoding)
cat_cols = ['city','zone']
enc = OrdinalEncoder()
df[cat_cols] = enc.fit_transform(df[cat_cols])
# 4. Create multi-step targets (direct method): target_h = rides shifted -h
H = 24
for h in range(1, H+1):
df[f'target_t+{h}'] = df['rides'].shift(-h)
# drop rows with NA targets
df = df.dropna()
# 5. Rolling-origin CV generator
def rolling_origin_splits(df_time, initial_window, horizon, step):
start = initial_window
while start + horizon <= len(df_time):
train_idx = np.arange(0, start)
test_idx = np.arange(start, start+horizon)
yield train_idx, test_idx
start += step
# 6. Hyperparameter search (random sample)
param_space = {'num_leaves':[31,63], 'learning_rate':[0.05,0.1], 'n_estimators':[100,300]}
search = list(ParameterSampler(param_space, n_iter=6, random_state=0))
best = {}
for h in range(1, H+1): # train separate model per horizon
best_score = np.inf
for params in search:
cv_scores = []
for train_idx, val_idx in rolling_origin_splits(df, initial_window=2000, horizon=168, step=168):
X_train = df.iloc[train_idx].drop([f'target_t+{k}' for k in range(1,H+1)], axis=1)
y_train = df.iloc[train_idx][f'target_t+{h}']
X_val = df.iloc[val_idx].drop([f'target_t+{k}' for k in range(1,H+1)], axis=1)
y_val = df.iloc[val_idx][f'target_t+{h}']
model = lgb.LGBMRegressor(**params)
model.fit(X_train, y_train, categorical_feature=cat_cols, eval_set=[(X_val,y_val)], early_stopping_rounds=50, verbose=False)
preds = model.predict(X_val)
cv_scores.append(mean_absolute_error(y_val, preds))
if np.mean(cv_scores) < best_score:
best_score = np.mean(cv_scores)
best[h] = (params, best_score)
# 7. Final training: train each horizon model on full train period using best[h]
# 8. Prediction: for a given current time, build features, predict targets 1..24 directly
# Notes:
# - Direct strategy trains one model per horizon (robust, avoids error accumulation).
# - Recursive strategy predicts t+1 then feeds it to predict t+2; simpler but error compounds.
# - Consider time-based holdout for final test, scale exogenous covariates, and use target encoding for high-cardinality zone IDs.MediumTechnical
64 practiced
You need to choose between ARIMA, Prophet, and tree-based ML models (e.g., LightGBM) to forecast hourly rides in a metro with strong weekly seasonality, many holidays, and frequent local events. Describe the selection process: which diagnostics you would run, trade-offs around exogenous regressors, automation and maintenance implications, and evaluation plan (metrics, cross-validation) to pick the best approach across multiple cities.
Sample Answer
Situation: We need a reproducible process to pick the best hourly-forecast method across many cities with strong weekly seasonality, many holidays and frequent local events.Diagnostics I’d run first- Visualize per-city time series (daily/weekly aggregates) and decompose (STL) to confirm weekly seasonality, trend, residuals.- ACF/PACF and Augmented Dickey-Fuller to check stationarity and dominant lags.- Spectral/periodogram to confirm periodicities (24h, 168h).- Inspect holiday/event impact via event-aligned averages (do events shift level or just noise?).- Check data quality: missingness, cold-start cities/hours, calendar alignment.Model trade-offs and exogenous regressors- ARIMA (seasonal SARIMA): good if series is stationary after differencing and seasonality is regular. Handles well-defined lags but struggles with many categorical exogenous events and nonlinearity. Exogenous regressors (SARIMAX) work but scale poorly with many event types.- Prophet: built-in seasonality, holiday handling via binary regressors and changepoints; fast, interpretable, robust to missing data — good baseline for business-facing reporting. Less flexible for complex interactions.- Tree-based (LightGBM/GBDT): most flexible — can use lag features, rolling stats, calendar/festival flags, weather, special-event embeddings. Usually gives best accuracy if well-featured and enough history, but needs careful feature engineering and is less interpretable.Exogenous regressor trade-offs- Include deterministic regressors: hour-of-week, day-of-week, holiday flags, event intensity, weather, special promotions.- For ARIMA/Prophet prefer low-dimensional, well-crafted regressors (one-hot holidays, binary events); for LightGBM, richer features (lags, rolling means, interaction terms, event recency/duration) boost performance.- Beware leakage: only use information available at forecast time (forecast weather separately or use expected values).- High cardinality events: consider grouping (major/minor) or embeddings for tree models.Automation & maintenance- Build a pipeline: ingestion → validation → feature engineering → model training → scoring → monitoring.- Model selection: maintain baseline (Prophet) + best-performing model (LightGBM) per city. Automate regular retraining (daily/weekly) with scheduled hyperparameter tuning on a cadence (e.g., monthly).- Monitoring: track forecast errors (MAE/MAPE), data drift, and feature distributions; alert when performance degrades.- Resource trade-offs: LightGBM needs more compute and engineering; Prophet/ARIMA faster to deploy and explain to stakeholders. For many cities, use a tiered approach: simple models where demand is low; more complex where ROI justifies it.Evaluation plan (metrics & cross-validation)- Metrics: primary business metric MAE or RMSE (absolute error matters for supply sizing); also MAPE (for relative error), and RMSLE if skewed. Use multiple metrics to capture scale and business impact.- Cross-validation: rolling-origin (time-series) CV with multiple backtest windows (e.g., rolling 28-day test windows across last 6 months) to capture seasonality and event variability. Ensure each fold respects forecast horizon (e.g., 24h, 168h).- Holdouts: preserve a final chronological holdout (e.g., last 4 weeks) for unbiased comparison.- Per-city evaluation: compute metrics per city and aggregate with weighted average by business importance (rides volume) to avoid small cities dominating.- Statistical comparison: use Diebold-Mariano or paired bootstrap to test significance across methods.Selection criteria across cities- Accuracy on holdout and stability across folds.- Operational cost: training/inference time, maintenance overhead.- Interpretability needs for stakeholders.- Robustness to holidays/events (evaluate event weeks separately).- Choose model by balancing accuracy gains vs operational complexity; implement fallback (Prophet) if complex model fails.Example practical pipeline- Feature engineering job creates calendar flags, event intensity scores, lags/rolling features, weather forecasts.- Train LightGBM with time-based CV; train Prophet per city as baseline; store model metadata and validation results.- Deploy best model per city automatically; monitor and retrain when error crosses threshold.This process yields an empirical, maintainable selection that accounts for holidays/events, operational constraints, and business impact.
MediumTechnical
62 practiced
Your production forecasting model's accuracy degraded by about 12% immediately after a new regional pricing policy was introduced. Draft an investigation plan: what data checks and visualizations to run first, how to separate policy impact from seasonality, candidate modeling remedies (retraining, new features, model revamp), and how to communicate findings and mitigation steps to stakeholders.
Sample Answer
Investigation plan — quick, structured, and stakeholder-ready.1) Immediate data checks (first 24 hours)- Confirm data integrity: counts, nulls, duplicates for key tables (transactions, prices, timestamps, region IDs).- Verify policy rollout metadata: effective date/time, affected SKUs/regions, any phased rollout flags.- Check pipeline latency: did feature/label timestamps shift (backfill or delayed ingestion)?2) First visualizations (fast dashboards)- Time series of model error (MAE/MAPE) by region, SKU, and customer segment — annotate policy change point.- Pre/post distribution plots: predicted vs actual, residual histograms, and Q-Q plots.- Rolling-window performance (7/30/90 days) to see trend vs abrupt change.- Price/time heatmap by region to visualize policy-induced price shifts.- Cohort analysis: compare cohorts exposed vs unexposed to policy.3) Separate policy impact from seasonality- Decompose historical demand into trend + seasonal + residual (STL decomposition) for affected regions.- Run difference-in-differences: select control regions or SKUs not subject to policy and compare delta in errors and demand.- Seasonal adjustment: compute seasonally adjusted series and re-evaluate model errors.- Short A/B style test if rollout partial: compare contemporaneous cohorts.4) Candidate modeling remedies- Quick fixes (hours–days): add policy flag, region-policy interaction, recent price features, or lagged price elasticities; retrain only feature-store/light models.- Medium (days–weeks): retrain full model including new features, retrain on recent window to capture new regime; update feature engineering to include promotional/policy indicators.- Revamp (weeks–months): consider regime-switching models, hierarchical models by region, or causal models estimating price elasticity; embed online learning or more robust regularization to adapt quickly.- Validation: backtest with pre/post split, use holdout control regions, check calibration and business KPIs (revenue, stockouts).5) Communication & mitigation- Immediate message (within 24h): concise note to stakeholders explaining observed 12% degradation, that investigation started, initial checks passed/failed, and short-term mitigations (e.g., freeze operational decisions based on model, use simple price-adjusted forecast or human-in-loop).- Interim report (48–72h): show visuals (error time series, control comparisons), preliminary root-cause hypothesis, proposed short-term fix and timeline.- Final report: confirm root cause (policy vs seasonality), actions taken, model performance post-mitigation, monitor plan, and recommended longer-term changes.- Stakeholder asks: impact quantification (revenue/ops), risk of further regressions, resource needs for revamp.6) Monitoring & prevention- Add policy-change detector alert to monitoring (automated annotation on dashboards).- Track post-mitigation KPIs and schedule a review after one business cycle.- Document lessons and add policy flags to feature catalog.This plan finds root cause quickly, isolates policy vs seasonality, proposes prioritized remedies, and keeps stakeholders informed with data-backed steps.
MediumTechnical
81 practiced
Marketing plans a 20% weekend discount in California. Describe how you would forecast incremental demand attributable to the campaign, how to measure lift (preferred experimental or observational approaches), and outline a dashboard layout showing realized lift, confidence intervals, and ROI for marketing and finance stakeholders.
Sample Answer
Approach summary- Clarify objective: estimate incremental weekend demand in CA caused by a 20% discount and compute incremental revenue/ROI for marketing & finance.Forecasting incremental demand1. Baseline model (pre-campaign): build a time-series model of weekend demand in CA using historical weekends, controlling for seasonality, holidays, weather, price, and trends (SARIMA / Prophet / XGBoost with date features). Use this to predict expected demand absent the campaign.2. Counterfactual via control group: preferred—use randomized or quasi-random control (see below) to create a realistic counterfactual rather than relying solely on model extrapolation.Preferred measurement (experimental)- Randomized geo-weekend experiment: randomly assign a set of CA DMAs or stores to receive the 20% discount on weekends while others remain at regular price for a test window (4–8 weekends). Measure difference-in-differences (DiD): (treated_post − treated_pre) − (control_post − control_pre). This isolates weekend lift and controls for common shocks.- Randomize at customer-level (if pricing can be personalized) for stronger causal identification.Observational alternatives- Synthetic control: construct a weighted combination of out-of-CA regions that match pre-period trends in CA weekends, then compare post-period.- Regression with controls: panel regression with store/region fixed effects, time fixed effects, interaction term for CA*post, and covariates (promotions, weather). Use robust SEs clustered at region.Statistical inference & metrics- Primary metric: incremental units sold (absolute) and incremental revenue = incremental units * (price after discount).- Secondary: margin impact = incremental revenue − incremental cost (consider lower price + variable cost), incremental AOV, repeat purchase lift.- Use bootstrap or cluster-robust standard errors to get 95% CIs on incremental demand and incremental revenue.- Compute ROI = (incremental gross profit − incremental marketing cost) / marketing cost. Report payback and breakeven discount threshold.Dashboard layout (two-sheet design: Executive + Diagnostic)Executive sheet (for Marketing & Finance)- KPI banner: Incremental units, incremental revenue, incremental gross profit, ROI, test window, sample size, p-value.- Time series chart: Actual CA weekend demand vs. counterfactual with shaded 95% CI for counterfactual; highlight test period.- Lift summary: Bar chart showing absolute and percent lift by weekend and cumulative.- ROI widget: inputs (marketing spend, cost per unit), computed ROI and breakeven discount; toggle between gross and net ROI.- Statistical summary: estimate, 95% CI, p-value, power achieved.Diagnostic sheet (for analysts)- Control balance table: pre-period metrics for treated vs control (sales, traffic, demographics).- Model diagnostics: residuals, goodness-of-fit, pre-trend test graph.- Sensitivity analysis: alternative models (synthetic control, regression), robustness table showing estimates under each method.- Segmentation: lift by region, product category, new vs returning customers.- Data quality alerts: missing data, outlier weekends.Implementation notes- Minimum test duration: 4–8 weekends; power calc beforehand using baseline variance to set sample size.- Data needs: daily sales, prices, promotions, store/region identifiers, customer segments, costs, external covariates (holidays, weather).- Automation: pipeline to refresh model & dashboard weekly; include annotation layer for anomalies.This combination gives causal estimates, uncertainty bounds, and finance-ready ROI, plus diagnostics to build stakeholder confidence.
EasyTechnical
59 practiced
List common data quality problems in ride-hailing datasets (such as duplicate trips, missing timestamps, GPS drift, incorrect status labels). For each issue propose a detection method and remediation steps suitable to implement in an automated ETL pipeline, and explain how you'd measure residual risk after remediation.
Sample Answer
Common data quality problems in ride‑hailing datasets, detection methods, remediation in ETL, and residual‑risk measurement:1) Duplicate trips- Detection: identify identical ride_id or same vehicle_id + driver_id + passenger_id + start_timestamp within short window; fuzzy match on route/times.- Remediation: deduplicate in ETL using deterministic keys (keep earliest/most complete), or merge records preserving union of non-null fields; flag soft‑duplicates for downstream review.- Residual risk metric: duplicate rate after dedupe (duplicates / total), and number of soft‑duplicates deferred to manual review.2) Missing timestamps (start/end/accept)- Detection: null checks, unrealistic order (end < start), or huge gaps between events.- Remediation: infer missing timestamps when possible (interpolate from surrounding events, use ETA offsets, or impute using average durations by route/time); otherwise mark ride as incomplete and exclude from duration KPIs but keep for volume counts.- Residual risk metric: percent of records with imputed timestamps and variance between imputed vs actual (on a holdout sample).3) GPS drift / noisy location points- Detection: detect outliers using speed thresholds (>200 km/h), sudden jumps, low HDOP/accuracy values, or unrealistic route geometry (teleportation).- Remediation: smooth routes with Kalman or moving‑median filter; remove points with poor accuracy; snap to road network using map-matching; if majority noisy, flag ride quality low and exclude from distance-based metrics.- Residual risk metric: proportion of rides with remediated points; average pre/post distance delta; percentage of map-matched points.4) Incorrect status labels (e.g., completed vs canceled)- Detection: consistency checks: status vs timestamps (completed without end_timestamp), fare >0 but status canceled, sequence violations.- Remediation: apply rules to normalize status (derive final_status from timestamps/financial events), create canonical status field and preserve raw status for audit; correct obvious mismatches automatically.- Residual risk metric: mismatch rate between canonical status and raw status; sample audit error rate.5) Inconsistent units / schema drift- Detection: schema validation: datatype checks, out‑of‑range values (negative distances), unexpected new columns.- Remediation: enforce strict schema in ETL (reject or map unknown fields), cast units to canonical (meters, seconds, USD), alert on schema changes.- Residual risk metric: number of schema‑violations per day, rejected rows rate.6) Timezone/clock skew issues- Detection: timestamps outside expected business hours for region, inconsistent timezone fields, sequence anomalies across services.- Remediation: normalize to UTC in ETL and store local_tz separately; correct known service offsets; record correction provenance.- Residual risk metric: proportion of corrected timestamps; frequency of cross-service sequence anomalies.General automation & monitoring best practices:- Implement validation rules as data quality tests in ETL (Airflow/DBT checks), write remediation actions and provenance metadata (why/how fixed).- Maintain a data quality dashboard with KPIs above, alert thresholds, SLA for human review.- Periodic sampling/audit: compare a random sample of raw vs canonical records to estimate residual error and feed error rates back to improve rules.
Unlock Full Question Bank
Get access to hundreds of Ride-Hailing Demand Modeling & Forecasting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.