Online Learning and Batch Learning: When Models Update as Data Arrives
Compare batch retraining with online updates, work through the update rule by hand and learn the safeguards a self-updating model needs.
Key takeaways
- Batch models are fixed between training runs, while online models change continuously with each new example or small group.
- Serving predictions in real time is a separate matter from learning in real time.
- Test an online learner by scoring each new batch before training on it.
- The learning rate controls the trade between adapting quickly and being thrown off by noise.
- Automatic updates need input checks, a frozen reference model, versioned snapshots and a way to roll back.
Batch learning fits a model on a fixed dataset, then freezes it until someone trains a new one. Online learning updates the model as examples arrive, one at a time or in small groups. Batch training is easier to test and reproduce. Online learning adapts faster and never needs the whole history in memory.
Most production systems sit between the two. They retrain in batches on a schedule, and reserve true online updates for places where the world changes quickly and feedback arrives soon.
Two different meanings of "online"
A model can answer requests instantly through an API and still be trained once a month. That is online inference with batch learning, and it is very common. Online learning refers to how parameters change.
There is also a third pattern, often called incremental or warm-started training: on a schedule, you continue training the previous model on recent data. It behaves like batch learning with a head start. Serving modes deserve their own decision, separate from this one.
| Property | Batch retraining | Online updates |
|---|---|---|
| Data needed at once | A full training window | The current example or group |
| Speed of adapting | Until the next retrain | Almost immediate |
| Testing before release | Straightforward | Needs continuous checks |
| Reproducing a past model | Rerun on saved data | Needs snapshots or an ordered event log |
| Damage from bad data | Caught at validation, if you look | Absorbed at once |
The update, worked by hand
Online learning usually means stochastic gradient descent applied to a stream. For a linear model ŷ = w × x with loss ½(y − ŷ)², the update is w ← w + η(y − ŷ)x, where η is the learning rate.
Start with w = 0 and η = 0.1.
example 1: x = 2, y = 4
ŷ = 0, error = 4, w = 0 + 0.1 × 4 × 2 = 0.80
example 2: x = 1, y = 2
ŷ = 0.80, error = 1.20, w = 0.80 + 0.1 × 1.20 × 1 = 0.92 The data follow y = 2x, and w moves toward 2 with each step. No earlier example has to be stored. Note that a large x produces a large step, which is why feature scaling matters even more on a stream. Scaling statistics must also be computed from past data only.
Remembering and forgetting
A running average shows the central choice. To track the mean of all values so far, update μ ← μ + (x − μ)/n. Each new point counts less as n grows, which suits a stable world.
To follow a moving world, use a constant weight instead: μ ← μ + α(x − μ). With α = 0.01, the average behaves roughly like a memory of the most recent hundred or so points, with older ones fading geometrically. A larger α adapts faster and jitters more. The learning rate in an online model plays the same role.
Mini-batches and sliding windows
Updating on single examples is noisy. Collecting a small mini-batch, perhaps a few dozen or a few hundred examples, averages out some of that noise and uses hardware better, at the price of a short delay. Most systems described as online work this way.
A related design is the sliding window: keep the most recent stretch of data and refit on it frequently. A short window tracks change closely but has little data, while a long window is stable but slow to notice that old examples no longer apply. Weighting examples so that influence fades with age is a smoother version of the same idea.
You can also keep a small replay buffer, a stored sample of older or rare examples mixed into each update. It reduces forgetting, for instance of seasonal behavior that disappears for most of the year. Storing past data brings back questions of retention and privacy, so check what you are allowed to keep and for how long.
Because the final weights depend on the order of updates, record that order if you need to reconstruct a model. An append-only event log plus periodic weight snapshots usually suffices to answer the question "what did the model look like last Tuesday?"
Score first, then learn
A natural evaluation for streams is test-then-train, also called prequential evaluation. Every new group is first predicted, then used for an update. Each score therefore comes from data the model had not seen.
import numpy as np
from sklearn.linear_model import SGDClassifier
rng = np.random.default_rng(0)
model = SGDClassifier(loss="log_loss", learning_rate="constant",
eta0=0.05, random_state=0)
w = np.array([2.0, -1.0, 0.0])
for step in range(60):
if step == 30:
w = np.array([-1.0, 2.0, 0.0]) # the world changes
X = rng.normal(size=(100, 3)) # rows are examples
y = (X @ w + rng.normal(0, 0.5, 100) > 0).astype(int)
if step > 0 and (step % 5 == 0 or step in (31, 59)):
print(step, model.score(X, y)) # score first
model.partial_fit(X, y, classes=[0, 1]) # then learn In one run, accuracy sat around 0.9 before the change, fell to about 0.2 at step 30, and recovered to around 0.9 within a few more groups. A frozen model would have stayed broken. Try a much smaller eta0 and watch recovery slow.
When labels arrive late
You can only learn from an example once you know its answer. A click may arrive within seconds. A loan default may take months. If labels are slow, an "online" model is always learning about the past.
Delays also bias the stream. If positives are reported quickly while negatives are only confirmed after a waiting period, the most recent data looks more positive than it is. Use a fixed waiting window, or a method designed for delayed feedback.
What can go wrong
- Bad data is learned immediately. A broken sensor or a unit change can corrupt weights within minutes.
- Deliberate manipulation. If outsiders can influence the training stream, they can try to steer the model. Limit the weight of any one source and monitor sudden shifts.
- Feedback loops. A model that decides what users see also decides what it learns about. See how models change their own data.
- Forgetting. A model chasing recent traffic can lose rare but important cases, a problem related to catastrophic forgetting.
Reasonable safeguards include bounds on feature values and on update size, a frozen model scored alongside the live one, fixed test slices checked after updates, and automatic rollback when metrics cross a limit.
Drift: what you are adapting to
Change comes in several shapes. The inputs may shift, as when a new group of users arrives. The class proportions may shift, as with a surge in fraud attempts. Or the relationship between inputs and outcome may change, which is concept drift, the kind that makes old training data actively misleading.
The shape suggests the remedy. A sudden break calls for detection and possibly a reset or heavy reweighting toward new data. Gradual movement suits steady updates. Recurring patterns, such as weekends or holidays, are better handled with calendar features than by forcing the model to relearn them every week.
Do not assume every drop in performance is drift. A renamed field, a changed unit or a logging bug looks similar on a dashboard, and an online learner will obligingly adapt to the bug. Inspect raw inputs before you celebrate fast recovery.
Which should you choose?
Start with batch learning and ask how fast performance decays. Train on data up to some date, then score each later week. If the curve stays flat for months, occasional retraining is enough. If it sags within days, retrain more often before building anything online.
Consider true online updates when all of these hold: the relationship between inputs and outcome moves quickly, trustworthy labels arrive soon, the model type supports cheap updates, and your team can monitor it around the clock. News recommendation and bidding are typical candidates.
Linear models, naive Bayes and neural networks can all be updated incrementally. Many tree ensembles are normally trained in batches, although streaming tree algorithms exist. Check your library's documentation for which estimators support incremental fitting.
A hypothetical decision
Say you maintain a model that predicts demand for bike rentals at each station. Backtesting shows that a model trained once loses accuracy slowly over a season, and a weekly retrain removes nearly all of that loss. Sharp errors cluster around storms and street closures.
Online weight updates would add little here. A weather forecast and a closure flag as input features address the sharp errors directly, because the model can respond the moment the input changes without any new learning. The weekly retrain handles the slow movement, and you keep a release process that a small team can test.
A related theory
Researchers also study online learning as a game: predictions are made one by one, and performance is measured by regret, the extra loss compared with the best fixed choice in hindsight. The guarantees need no assumption that data is independent and identically distributed, as long as the comparison is against that fixed choice. The idea of regret introduces it, and retraining triggers covers the practical scheduling side.