TExcelTAD

Batch Learning

Batch learning (offline learning) is the default way models are built: collect a data set, train the model on all of it in one run, evaluate it, deploy it, and leave it unchanged until the next training run. Almost every example in this track so far has been batch learning, which is why it deserves a closer look at its strengths and its blind spot.

Note: "Batch" means two different things in ML. Batch learning is training on a fixed, collected data set (this lesson). A mini-batch is the small group of examples used for one gradient step inside a training run. A batch-learning run usually processes its data in mini-batches.

The batch workflow

  1. Snapshot the data: a fixed, versioned data set, for example all transactions up to 31 March.
  2. Train the model on it, with all preprocessing fitted on the training part.
  3. Evaluate against held-out data and against the model currently in production.
  4. Deploy the new version if it is better; the model is now frozen.
  5. Retrain later from a newer snapshot, on a schedule (nightly, weekly, monthly) or when monitoring sees drift.

Strength 1: reproducible by design

Because the data is a fixed snapshot, the same code, data and seed give the same model every time. You can rerun last month's training, compare versions fairly and explain exactly what a model learned from. The example trains a random forest three times and fingerprints its predicted probabilities.

python · try it yourself
import hashlib
import numpy as np
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)

def train(seed):
    model = RandomForestClassifier(n_estimators=100, random_state=seed).fit(X_train, y_train)
    fingerprint = hashlib.sha256(model.predict_proba(X_test).round(6).tobytes()).hexdigest()[:12]
    return model, fingerprint

for seed in [0, 0, 1]:
    model, fp = train(seed)
    print(f"seed {seed}: test accuracy {model.score(X_test, y_test):.3f}, prediction fingerprint {fp}")
seed 0: test accuracy 1.000, prediction fingerprint 45487e2e0668
seed 0: test accuracy 1.000, prediction fingerprint 45487e2e0668
seed 1: test accuracy 0.981, prediction fingerprint 043bd303d48b

Two runs with seed 0 produce identical predictions down to the sixth decimal. Seed 1 builds different random trees and a slightly different model (0.981 instead of 1.000 on 54 test wines, one mistake). Recording the seed, the data version and the code version is what lets a team reproduce a model months later; the Deployment & MLOps course shows tools that do this automatically.

Strength 2: thorough evaluation before release

A batch model can be tested at leisure before anyone relies on it: cross-validation, error analysis per group, comparison with the current model, a review by a domain expert. An online model, by contrast, changes while it is in service.

The blind spot: a frozen model ages

Between training runs, the world keeps moving. In the next example, customer behaviour shifts a little every month. One model is trained on months 0–2 and never again; another is retrained every three months by a scheduled batch job, each time on the most recent three months.

python · try it yourself
import numpy as np
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(1)
def month(m, n=300):
    # Customer behaviour shifts a little every month (the class boundary moves to the right).
    X = rng.normal(loc=[m * 0.25, 0], size=(n, 2))
    y = (X[:, 0] + 0.5 * X[:, 1] > m * 0.3).astype(int)
    return X, y

history = [month(m) for m in range(12)]
X0 = np.vstack([h[0] for h in history[:3]]); y0 = np.concatenate([h[1] for h in history[:3]])
never = LogisticRegression().fit(X0, y0)          # trained once on months 0-2, never again

print("month  trained once  retrained every 3 months")
for m in range(3, 12):
    if m % 3 == 0:                                # scheduled batch job: refit on the last 3 months
        Xr = np.vstack([h[0] for h in history[m - 3:m]]); yr = np.concatenate([h[1] for h in history[m - 3:m]])
        scheduled = LogisticRegression().fit(Xr, yr)
    X, y = history[m]
    print(f"{m:5}  {never.score(X, y):12.3f}  {scheduled.score(X, y):24.3f}")
month  trained once  retrained every 3 months
    3         0.760                     0.760
    4         0.703                     0.703
    5         0.630                     0.630
    6         0.493                     0.803
    7         0.460                     0.687
    8         0.427                     0.597
    9         0.490                     0.837
   10         0.353                     0.687
   11         0.327                     0.610

In month 3 both models are the same (the first retraining also used months 0–2). The model trained once declines steadily, to 0.327 in month 11. The scheduled one recovers after each retraining (0.803 in month 6, 0.837 in month 9) and then ages again until the next run: the sawtooth pattern typical of batch models in a changing world. The drift here is deliberately fast; how often to retrain is a trade-off between cost and how quickly your data changes, decided by monitoring, not guesswork.

Batch or online?

Choose batch learning when Choose online learning when
the data changes slowly (weeks or months) the data changes within hours or days
reproducibility and audits matter (credit, medicine) adapting fast matters more than strict reproducibility
the data set fits in storage and training is affordable the stream is too large to store
labels arrive in bulk labels arrive continuously

Many systems combine both: a solid batch model retrained regularly, with a small online component (such as recent-popularity features) that adapts between runs.

Pitfalls

  • Training once and forgetting. Every deployed batch model needs monitoring and a retraining plan.
  • Retraining blindly. A scheduled job that deploys whatever it produces can ship a worse model, for example after a broken data feed. Compare each new model with the current one before switching.
  • Unversioned snapshots. If the training data is overwritten, the model can never be reproduced or audited.

Practice

  1. In the drift example, why are the month-3 accuracies of the two models identical?
Answer

The first scheduled retraining happens at month 3 and uses months 0, 1 and 2, exactly the data the "trained once" model was fitted on. Both are the same logistic regression on the same data, so they make the same predictions.

  1. A bank retrains its credit-risk model every quarter. A new law changes which customers may apply, starting next month. What should the team do?
Answer

Not wait for the next scheduled run. The applicant population will change suddenly (data drift), so the team should monitor the inputs closely from the first day, assess how the old model behaves on the new population, and retrain as soon as enough new labelled data exists, perhaps with interim rules for the new group.

Test yourself

What is batch learning?

  1. Updating the model after every example
  2. Training on a fixed, collected data set in one run and deploying the frozen model
  3. Training with mini-batches only
  4. Learning from rewards

Why did two runs with seed 0 give the same prediction fingerprint?

  1. Random forests are not random
  2. The same data, code and seed reproduce the same model exactly
  3. The fingerprint ignores the predictions
  4. scikit-learn caches models

What is the typical accuracy pattern of a batch model retrained on a schedule in a drifting world?

  1. A flat line
  2. A sawtooth: recovery after each retraining, then decline
  3. A steady rise
  4. Random noise