Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 16 steps

End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing
  1. 1
    Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
  2. 2
    Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
  3. 3
    Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
  4. 4
    Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
  5. 5
    Recommendations, Part 1: Two Stages, Candidates Then Ranking
  6. 6
    Recommendations, Part 2: Candidate Generation With Embeddings
  7. 7
    Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
  8. 8
    Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
  9. 9
    Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
  10. 10
    Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
  11. 11
    Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
  12. 12
    Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule
  13. 13
    Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
  14. 14
    Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
  15. 15
    Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
  16. 16
    Ticket Routing, Part 4: Canary, Automatic Rollback and "Does Your Small Model Reason?"
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. End-to-End Use Cases

Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 10 of 16

Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides

Walk forward through four 28-day folds of synthetic shop demand. Ridge beats the same-weekday baseline in all 12 product-fold cells (MAE 5.81 vs 6.91), default gradient boosting lands at 6.07, a new product is short for weeks, and a leaky rolling mean fakes a drop to 5.19.

Chaand Sheikh

·27 November 2026End-to-End Use Cases

What you will learn

  • Build lag features that only use what was known before the day
  • Score a forecast with a four-fold walk-forward backtest against the same-weekday baseline
  • Compare Ridge with a gradient boosting model on the same folds and features
  • Find what the average hides: a new product and a leaky feature

Before you start

  • Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
  • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting

In Part 1 we set the line to beat for our shop: same weekday last week, with a short unit costing 3 and an extra unit costing 1 (assumed). Now we train forecast models and test them the way they'd actually be used: one stretch of days at a time, with the future covered. We'll put a simple model against a boosted one, and then look at where a good average hides a bad forecast.

The demand is still synthetic (milk, bread and rice, seed 7). Please don't expect results this clean on a real shop.

Past seasons, one at a time

Say you've got a new stocking plan and five years of records. How do you test it? You open the records up to the end of one season and cover everything after that with your hand. You decide using only what's showing, then uncover the next season and score yourself. Then you move your hand forward one season and do it again. You get many honest exams, and in every one the future stays covered. That's a walk-forward backtest.

Features from the past: features.py

You've built lags before (Time Series Basics covers them), so here we just apply them:

def add_lags(df, leak=False):
    out = df.copy()
    g = out.groupby("product")["units"]
    out["lag_7"] = g.shift(7)
    out["lag_14"] = g.shift(14)
    out["mean_7"] = g.transform(
        lambda s: s.shift(1).rolling(7).mean())
    if leak:
        out["mean_7"] = g.transform(
            lambda s: s.rolling(2).mean())
    out["dow"] = out["date"].dt.dayofweek
    return out.dropna().reset_index(drop=True)

Fill in the row for milk on 15 January 2025:

FeatureMeaningValue
lag_7Same weekday last week175
lag_14Same weekday two weeks back161
mean_7Mean of the 7 days ending yesterday (note the shift(1) before rolling)121.1
dowDay of the week2 (a Wednesday)

The first 14 days of each product have no lag_14, so they drop out. 1,260 rows become 1,218. Ignore the leak flag for now; we'll switch it on at the end.

Walk forward through time: backtest.py

A random split would let the model train on the future, so we walk forward instead:

"""Walk-forward backtest, one model for all products."""
import pandas as pd
from sklearn.linear_model import Ridge

from cost import business_cost, mae
from data import make_demand
from features import add_lags

COLS = ["lag_7", "lag_14", "mean_7", "dow"]


def walk_forward(df, folds=4, horizon=28):
    rows = []
    last = df["date"].max()
    for k in range(folds, 0, -1):
        cut = last - pd.Timedelta(days=horizon * k)
        end = cut + pd.Timedelta(days=horizon)
        train = df[df["date"] <= cut]
        test = df[df["date"].between(cut, end)]
        test = test[test["date"] > cut]
        model = Ridge().fit(train[COLS], train["units"])
        pred = model.predict(test[COLS])
        test = test.assign(pred=pred)
        for name, part in test.groupby("product"):
            rows.append({
                "fold": folds - k + 1, "product": name,
                "naive_mae": mae(part.units, part.lag_7),
                "model_mae": mae(part.units, part.pred),
                "model_cost": business_cost(part["units"],
                                            part["pred"]),
            })
    return pd.DataFrame(rows)
  • Four folds of 28 days, so the first cut sits four windows before the end of the data.
  • Everything up to the cut is training; the 28 days after it are the test.
  • One Ridge model is fitted across all products, then each product is scored on its own.
  • Every test row carries features from just before its day, so each one is a next-day forecast.
  • Then the cut moves forward 28 days. Training grows, the test slides, and we do it again.
Four walk-forward folds of 28 days Fold 1 Fold 2 Fold 3 Fold 4 train: every day up to the cut test: the next 28 days
Four exams, and the future is never in the training rows. Lengths are schematic.

What Ridge scored

Three products times four folds gives twelve cells. Here is the mean absolute error of each:

FoldProductBaseline MAERidge MAE
1bread7.896.65
1milk7.507.04
1rice3.323.02
2bread6.755.95
2milk10.648.49
2rice3.933.10
3bread7.935.29
3milk10.218.49
3rice3.293.00
4bread6.826.36
4milk11.149.36
4rice3.502.99

Ridge beats the same-weekday baseline in all twelve. Running python backtest.py prints the per-product means:

         naive_mae  model_mae
product
bread         7.35       6.06
milk          9.88       8.35
rice          3.51       3.03

Over all the test days, the baseline misses by 6.91 and Ridge by 5.81. On the 3-to-1 cost rule, the baseline comes to 4,722 and Ridge to 3,806. (These are the backtest test days only, so they're not comparable with the 6.78 and 17,365 from Part 1, which were measured on all 1,239 rows.)

Now look at milk across the folds: 7.04 in fold 1, 9.36 in fold 4. A single split would have shown you one of those and hidden the spread.

A boosted model: same folds, one line changed

Ridge is simple, so let's try something stronger. boosted_slices.py uses GradientBoostingRegressor with default settings and random_state=7, on the same features and the same folds. Only the model changes:

def ridge():
    return Ridge()


def boosted():
    return GradientBoostingRegressor(random_state=7)

Running python boosted_slices.py prints:

simulated demand, 4 folds
naive    mae  6.91   cost  4722
ridge    mae  5.81   cost  3806
boosted  mae  6.07   cost  4348
boosted beats ridge in 4 of 12

The boosted model beats the baseline but not Ridge, on error (6.07 against 5.81) and on cost (4,348 against 3,806). It wins only 4 of the 12 cells. Tuning might close the gap, but that's the result we got with defaults. So the backtest gets the final say, not the name of the model. (For how boosting works, see Boosting.)

Slice 1: a new product

A good average can hide a bad forecast. So the script adds a simulated new product, oats, launched 70 days before the end and ramping up over its first 28 days. The rest of the output:

oats, first forecast at age 14 days
milk, bread, rice mae 5.83
age 14-27  days 14  units  44.9  naive  9.29  model 12.47  bias -12.47
age 28-41  days 14  units  59.1  naive  6.07  model  8.51  bias  -8.36
age 42-69  days 28  units  60.2  naive   5.0  model  4.75  bias   1.02
  • No forecast at all for 14 days. lag_14 needs two weeks of history, so oats has no row until it's 14 days old.
  • Days 14 to 27: the model misses by 12.47 and the plain guess by 9.29. The model loses. The bias is also -12.47, the same size as the error, so it's short every single day, and short is the expensive side.
  • Days 28 to 41: still behind, 8.51 against 6.07.
  • From day 42: the climb is over and oats is in the training data. Now it's 4.75 against 5.0.

Meanwhile milk, bread and rice average 5.83 in this same backtest. That number never showed you any of this. Scoring group by group is the idea behind Slice Evaluation.

Oats: model vs baseline by age days 14-27 baseline 9.29 model 12.47 days 28-41 baseline 6.07 model 8.51 days 42-69 baseline 5.0 model 4.75
MAE on the simulated new product by age band, from boosted_slices.py. Bars are to scale.

Slice 2: a score that's too good

One more failure, and this one flatters you. With leak=True, mean_7 becomes s.rolling(2).mean() with no shift. That window covers yesterday and today, and today is the answer we're trying to predict. Half of the feature is the answer itself.

         naive_mae  model_mae
product
bread         7.35       5.35
milk          9.88       7.46
rice          3.51       2.76

The overall error drops from 5.81 to 5.19, and the cost from 3,806 to about 3,430. Nothing warns you. So ask one question of every feature: would I know this value when I place the order? If not, that gain won't show up in the shop. The general version of this trap is in Train-Test Split and Data Leakage.

Common mistakes

  • A random split on time data. The model trains on days after the ones it's tested on.
  • One test window. Milk ranged from 7.04 to 9.36 across folds; one window shows you one number.
  • Trusting a stronger model's name. Default boosting lost to Ridge here.
  • Reading only the average. The new product was short for weeks while the average looked fine.
  • A rolling window without a shift. It quietly includes the target.

Recap

RunMAECost
Same-weekday baseline (4 folds)6.914,722
Ridge5.813,806
Gradient boosting, defaults6.074,348
Ridge with the leak (not real)5.19about 3,430

Try it yourself: change shift(1) to shift(3) in mean_7, run python backtest.py again, and see whether Ridge still beats 6.91.

In Part 3, the forecast becomes a job that runs every night on its own.

Keep going in the learning path End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · step 10 of 16

Previous
Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
Next post
Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Related posts

Project: Car Price Predictor End to End, from CSV to a FastAPI Price API

The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.

Fraud Scoring, Part 1: The Problem, the Metric and the Baseline

Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.

Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold

Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.

Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget

A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.

On this page

  • Past seasons, one at a time
  • Features from the past: features.py
  • Walk forward through time: backtest.py
  • What Ridge scored
  • A boosted model: same folds, one line changed
  • Slice 1: a new product
  • Slice 2: a score that's too good
  • Common mistakes
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.