Online Learning
Some data never stops arriving: clicks on a website, card payments, sensor readings, news articles. And what it means can change: new products appear, fraudsters adapt, a machine wears out. Online learning (also called incremental learning) updates the model a little with every new example or small batch, as the data streams in, instead of retraining from scratch on a fixed data set.
Online versus batch
| Batch (offline) learning | Online learning | |
|---|---|---|
| Data | a fixed, collected data set | a stream of examples, seen once or a few times |
| Update | retrain the whole model, e.g. nightly or weekly | update after each example or mini-batch |
| Memory | needs the whole data set | needs only the current example and the model |
| Adapts to change | at the next retraining | continuously |
| Risk | stale between retrainings | can be pulled off course by bad or unusual data |
The next lesson looks at batch learning in detail. Most production systems use batch learning and retrain on a schedule; online learning is for streams that are too large to store or change too fast to wait for.
Updating without storing the data
The core idea fits in a few lines. To keep the mean and variance of a stream, you do not need to store the values: each new value adjusts the running statistics (Welford's method, which stays accurate even for long streams).
# Online mean and variance (Welford's method): update with each new value, never store the stream.
class RunningStats:
def __init__(self):
self.n, self.mean, self.m2 = 0, 0.0, 0.0
def update(self, x):
self.n += 1
delta = x - self.mean
self.mean += delta / self.n
self.m2 += delta * (x - self.mean)
@property
def variance(self):
return self.m2 / (self.n - 1) if self.n > 1 else 0.0
stats = RunningStats()
for value in [12.0, 15.5, 11.2, 14.8, 13.1, 16.4]: # e.g. delivery times arriving one by one
stats.update(value)
print(f"after {stats.n} values: mean {stats.mean:.3f}, variance {stats.variance:.3f}")after 1 values: mean 12.000, variance 0.000
after 2 values: mean 13.750, variance 6.125
after 3 values: mean 12.900, variance 5.230
after 4 values: mean 13.375, variance 4.389
after 5 values: mean 13.320, variance 3.307
after 6 values: mean 13.833, variance 4.227
After six values the mean is 13.833, the same as sum(values) / 6, yet the object holds only three numbers. Online models work the same way: the model's parameters are the running summary, and each example nudges them. Stochastic gradient descent does exactly that: one gradient step per example or mini-batch, which makes it the natural optimiser for online learning.
Keeping up with a drifting stream
In the next example the rule that separates the two classes slowly rotates from day to day: concept drift. One model is trained on day 0 and frozen. The other, an online SGDClassifier, is first scored on each new day's data (as it would be in production, before the labels are known) and then updated with partial_fit once the labels arrive.
import numpy as np
from sklearn.linear_model import SGDClassifier
rng = np.random.default_rng(0)
def batch(day, n=200):
# Two features; the boundary between the classes slowly rotates as the days pass (concept drift).
X = rng.normal(size=(n, 2))
angle = day * np.pi / 20
y = (X @ np.array([np.cos(angle), np.sin(angle)]) > 0).astype(int)
return X, y
frozen = SGDClassifier(loss="log_loss", random_state=0)
online = SGDClassifier(loss="log_loss", random_state=0)
X0, y0 = batch(0)
frozen.partial_fit(X0, y0, classes=[0, 1])
online.partial_fit(X0, y0, classes=[0, 1])
for day in range(1, 11):
X, y = batch(day)
acc_frozen, acc_online = frozen.score(X, y), online.score(X, y) # score before learning from today
online.partial_fit(X, y) # then update with today's labels
if day % 2 == 0:
print(f"day {day:2}: frozen model {acc_frozen:.3f} online model {acc_online:.3f}")day 2: frozen model 0.805 online model 0.970
day 4: frozen model 0.780 online model 0.945
day 6: frozen model 0.600 online model 0.915
day 8: frozen model 0.500 online model 0.870
day 10: frozen model 0.380 online model 0.945
By day 10 the boundary has turned by 90 degrees. The frozen model falls to 0.380, worse than guessing, because the rule it learned now points the wrong way. The online model stays between 0.87 and 0.97 on each new day: it lags one day behind the drift but keeps catching up. partial_fit is the scikit-learn method for online updates; classes must be given on the first call because a single batch might not contain every class.
Where online learning is used
- Recommendation and ads: user interests shift within hours.
- Fraud and spam: attackers change tactics as soon as they are blocked.
- Forecasting of demand or load, updated with every new measurement.
- Edge devices that adapt to their user, such as a keyboard learning your vocabulary.
- Data too large to store: each example is used once and discarded.
Pitfalls
- Bad data goes straight in. A burst of corrupted inputs or an attack can damage the model within minutes. Validate inputs, limit the learning rate, and keep the ability to roll back to an earlier model.
- Catastrophic forgetting. A model that adapts fast also forgets fast: patterns that disappear for a while (seasonal products) must be relearned. Replay of stored older examples helps.
- Evaluation is different. There is no fixed test set; score each new batch before training on it, as the example does ("prequential" evaluation). Scoring after training on it would be testing on training data.
- Labels arrive late. For fraud, the true label may take weeks. The model can only learn from examples whose labels have arrived.
The Training Strategies course covers drift handling, replay and rollback in depth.
Practice
- In the drift example, why is each day's batch scored before
partial_fitis called on it?
Answer
In production the model must predict before the true labels are known. Scoring first measures exactly that. Scoring after training on the batch would test the model on data it has just learned from and overstate its accuracy.
- A recommendation model is updated online. After a celebrity mentions an old product, clicks on it spike for a day. What could go wrong, and what would limit the damage?
Answer
The model may overreact and push the product to everyone for days, and forget other patterns. A smaller learning rate, a cap on how much one batch can change the model, monitoring of prediction shifts, and the option to roll back to yesterday's model limit the damage.
Test yourself
What characterises online learning?
- Training once on a fixed data set
- Updating the model incrementally as new examples arrive
- Learning from rewards
- Training only on the internet
Which scikit-learn method updates a model with a new batch without retraining from scratch?
fitpartial_fittransformrefit
Why did the frozen model's accuracy fall to 0.380 by day 10?
- It was trained badly
- The relationship between features and classes drifted, and the frozen model never adapted
- The data had more noise
- It overfitted
Why do online systems need a rollback option?
- To save memory
- Bad or adversarial data can corrupt the model quickly
- Rollback makes training faster
- Because
partial_fitis slow