Tag: Forecast

  • ML0178 k-Median Facility Location

    Uber wants to cluster pickup points into k stops minimizing total walking distance. Why is this k-median not k-means, and what algorithm actually solves it?

    Three dashed panels. Panel 1, the demand: a small street-grid map with blue dots for pickup requests along the streets and white squares for legal curb points, labeled 1,200 pickup requests per hour, 300 legal curb points, and walking follows the street grid. Panel 2, the prototype: a teammate ran KMeans with 12 clusters on latitude and longitude, producing 12 centroids that minimize squared distance, 3 of which fall inside buildings or a park; the dashboard reports inertia in squared meters and riders report long walks. Panel 3, the open choices: three boxes ask whether the objective should be squared or total walking distance, whether stops can go anywhere or only at legal curb points, and which algorithm, Lloyd, swap search, or exact, has a guarantee.

    The Problem: A shared-ride team must place k = 12 pickup stops for 1,200 hourly pickup requests, choosing among 300 legal curb points so that riders’ total walking distance is as small as possible. A teammate’s KMeans prototype reports a good inertia, yet 3 of its 12 centroids sit inside buildings or a park and riders complain about long walks.

    Answer

    Total walking distance adds up plain distances, so the objective is k-median, while k-means minimizes the sum of squared distances. For a single stop on a street, the median minimizes total walking and the mean minimizes squared walking, and squaring lets a few distant riders drag the stop away from everyone else. Walking also follows sidewalks rather than straight lines, and a stop must sit at a legal curb point. That makes the real problem discrete metric k-median, also called the p-median or facility-location problem, solved over a precomputed walking-distance matrix. Like k-means it is NP-hard, so Lloyd-style alternation only reaches a local optimum with no quality bound. What actually solves it is distance-weighted seeding plus swap local search, provably within 3 + 2/t of optimal, backed by the exact p-median integer program or its LP bound at city-zone sizes.

    (1) Linear Cost, Not Squared: Walking cost grows linearly with distance, while k-means squares it. One rider 300 m away then weighs as much as nine riders 100 m away and pulls the stop toward the fringe.
    (2) Median, Not Mean: On a line, total distance is minimized by the median and squared distance by the mean. On a Manhattan grid the optimum is the coordinate-wise median, and with straight-line distance it is the geometric median, found iteratively by Weiszfeld’s algorithm.
    (3) Network Distance And Candidate Stops: Walking distance is a shortest path on the pedestrian graph, so d(i, j) is a precomputed matrix, not a formula on coordinates. A mean of graph nodes is undefined, so any update step must pick a medoid from the legal curb points.
    (4) NP-Hard, With A Floor: Discrete k-median is NP-hard even for points in the plane, and metric k-median cannot be approximated below a factor of 1 + 2/e \approx 1.736 unless P = NP. k-means is NP-hard too, so Lloyd converging is never the same as Lloyd solving.
    (5) Swap Search Carries The Guarantee: Local search that swaps up to t open stops for closed candidates ends within 3 + 2/t of optimal, which is 5 for single swaps. Seeding with probability proportional to distance (not squared distance) gives an expected O(\log k)-approximate starting point.

    Mathematical Formulation:
    \min_{S \subseteq F,\ |S| = k} \sum_{j \in D} w_j\, d(j, S)
    d(j, S) = \min_{i \in S} d(i, j)
    \min \sum_{i \in F} \sum_{j \in D} w_j d_{ij} x_{ij}
    \sum_{i \in F} x_{ij} = 1
    x_{ij} \leq y_i
    \sum_{i \in F} y_i = k
    \min_{|C| = k} \sum_{j \in D} \min_{c \in C} \|x_j - c\|_2^2
    \arg\min_{c} \sum_{j} |x_j - c| = \mathrm{median}(x)
    \arg\min_{c} \sum_{j} (x_j - c)^2 = \bar x
    \mathrm{cost}(S_{\mathrm{LS}}) \leq (3 + 2/t)\, \mathrm{OPT}

    Where:

    • S is the set of opened stops, chosen from the candidate set F of legal curb points, and k is the number of stops.
    • D is the set of demand points (pickups, or grid cells that aggregate them), indexed by j, and w_j is the number of requests at point j.
    • d(i, j) = d_{ij} is the walking distance from candidate i to demand point j along the pedestrian network, and d(j, S) is the distance to the nearest open stop.
    • x_{ij} \in \{0, 1\} assigns demand j to stop i and y_i \in \{0, 1\} opens stop i. The constraints assign every demand point once, only to an open stop, with exactly k stops open. Relaxing both to [0, 1] gives the LP lower bound.
    • C is the set of k-means centers, free to sit anywhere in the plane, x_j are pickup coordinates, and \|\cdot\|_2^2 is squared straight-line distance.
    • \mathrm{median}(x) and \bar x are the median and mean of rider positions on a single street.
    • S_{\mathrm{LS}} is any solution where no swap of up to t stops lowers the cost, and \mathrm{OPT} is the optimal k-median cost.

    Worked Example:
    Five riders wait along one street at 0, 10, 20, 30 and 400 m, and we place a single stop (k = 1). The mean is \bar x = 460/5 = 92 m and the median is 20 m. At the mean the walks are 92, 82, 72, 62 and 308 m, for a total of 616 m. At the median they are 20, 10, 0, 10 and 380 m, for a total of 420 m. The k-means stop therefore costs 47% more walking (616/420 \approx 1.47). It still wins its own objective, with a squared cost of 119,080 square meters at the mean against 145,000 at the median.

    Two-panel chart. Left: grouped bars of walking distance for riders A to E at 0, 10, 20, 30 and 400 meters; with the k-means stop at the mean of 92 meters the walks are 92, 82, 72, 62 and 308 meters, totaling 616, and with the k-median stop at the median of 20 meters they are 20, 10, 0, 10 and 380, totaling 420; a note says moving the stop 72 meters toward rider E saves E 72 meters but adds 268 meters for riders A to D. Right: total walking cost and squared-distance cost, each divided by its own minimum, plotted against stop position from minus 20 to 200 meters; total walking is minimized at 20 meters and squared cost at 92 meters, where total walking is 47 percent above its minimum, while at 20 meters the squared cost is 22 percent above its minimum.

    Figure 1: (a) Per-rider walks for the worked example. Moving the stop from the median (20 m) to the mean (92 m) saves rider E 72 m but adds 268 m for riders A to D, so total walking rises from 420 m to 616 m. (b) Each cost divided by its own minimum. Total walking bottoms out at the median and squared distance at the mean, so neither stop is optimal for the other objective.

    Which Algorithm Actually Solves It:
    Because the problem is NP-hard, “solves” means either an exact method fast enough for the instance at hand or an approximation with a proven ratio. The Lloyd analogue for k-median alternates nearest-stop assignment with a per-cluster median or medoid update. It is quick but stalls in local optima, because it never moves a stop from one neighborhood to another. Swap local search (the PAM family) tries replacing an open stop with a closed candidate and keeps any swap that lowers total walking, which is exactly the move Lloyd cannot make. Arya et al. proved every swap-local optimum is within 5 times the global optimum, and within 3 + 2/t when t stops are swapped at once. LP-rounding algorithms push the best proven ratio below 2.7, but in production the swap solution is usually certified against the LP relaxation rather than replaced by a rounding algorithm.

    PropertySwap local search (PAM, FasterPAM)Lloyd-style k-mediansk-means (Lloyd)p-median integer program
    ObjectiveTotal walking distance, any metricTotal walking distanceSum of squared straight-line distancesTotal walking distance, any distance matrix
    Where stops goOnly candidate curb pointsMedoids among candidates, or off-network geometric mediansAnywhere, often inside blocksOnly candidate curb points
    GuaranteeWithin 3 + 2/t of optimal (5 for single swaps)Local optimum, no boundLocal optimum of the wrong objectiveOptimal, or a certified gap from the LP bound
    CostAbout k times |F| swap checks per pass; FasterPAM removes a factor of kOne assignment plus one medoid update per iterationCheapest, O(nk) per iterationExponential worst case; p-median LPs are often nearly integral
    Best useDefault solver at production scaleFast warm startWhen the true cost really is varianceOffline planning and certifying heuristics

    Login to view more content
  • DL0233 Thinking-Fusion Deployment Tradeoff

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0137 Time-Series Forecasting

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0137 Serverless GPU Warm Pool

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0123 Surge Dynamic Pricing

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0058 Ride-Hailing Matching System

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0045 Theme Park Wait Prediction

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0067 Probability vs Likelihood

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0007 Demand Forecasting System for Retailer

    

    Design a demand forecasting system for a large retail company like Costco, Walmart, or Target. The system should predict future product demand across stores and time to support inventory planning, replenishment, and promotions.

    Line-art scene: store shelves with products and a sales history curve flow into a question mark, producing a replenishment plan with P10, P50, and P90 quantities

    The Problem: thousands of SKUs across hundreds of stores. Predict each one’s future demand well enough to keep shelves full and waste low, then feed those numbers to replenishment and pricing.

    Answer

    The demand forecasting system ingests diverse data (sales, inventory, weather, promotions) and predicts product demand with ML models spanning time series, tree-based, and deep learning methods. It features a scalable layered architecture (data pipelines, real-time processing, integration for inventory management) and drives decisions with probabilistic forecasts, reducing stockouts, optimizing supply chains, and improving accuracy through iterative model training.

    (1) Problem Definition & Metrics: Fix granularity (SKU-store-day), horizon (2-week operational, 3-month tactical), and objective (minimize out-of-stocks and waste); measure with WMAPE and forecast bias.
    (2) Data Strategy: A unified feature store over internal signals (sales, hierarchy, pricing, promos, inventory, clicks) and external ones (calendar, weather, events, competitor, macro).
    (3) Layered Architecture: Ingestion → processing & feature store → modeling layer → serving APIs → monitoring & feedback.
    (4) Hierarchical Ensemble Modeling: Interpretable base (Prophet/ETS) at aggregate level, global LightGBM/XGBoost as the granular workhorse, TFT/DeepAR for high-volatility items, reconciled top-down and bottom-up.
    (5) Probabilistic Forecasts: Output quantile forecasts (P10, P50, P90) so logistics can set safety stock from uncertainty, not a single number.

    Five-layer architecture diagram: batch and real-time data ingestion flows to feature store, modeling layer, forecast serving API with replenishment and pricing consumers, and monitoring with a feedback arrow returning to modeling

    Figure 1: The five-layer system: ingestion and the feature store feed a model repository; forecasts are served through APIs to replenishment and pricing, while monitoring closes the loop back into retraining.

    Clarify Before Designing:
    (1) Scale: how many SKUs, stores, and series (SKU × store) must be forecast?
    (2) Granularity & Horizon: store-day or region-week? 2-week replenishment or 3-month tactical planning?
    (3) Decision Consumers: automated replenishment, or human planners reviewing suggestions?
    (4) Data Reality: is a promotions calendar available in advance? New product launch cadence (cold-start rate)?
    (5) Cost Asymmetry: the cost of a stockout (lost sale, empty shelf) versus overstock (waste, markdowns)?


    Login to view more content