TExcelTAD

Online and Incremental Learning with partial_fit

Every strategy so far trained on a fixed data set: load it, fit, evaluate, ship. Many systems never have a fixed data set. Card transactions, sensor readings, clicks and log lines arrive continuously; the data may be too large to keep; and the world that produces it changes. Online learning updates the model one example or one small batch at a time, as the data arrives, and then forgets the data. Incremental learning is the looser term for the same idea with mini-batches: the model is improved with new data without retraining from scratch.

ML Foundations contrasted online with batch learning. This lesson implements an online learner, evaluates it the way streams are evaluated, and uses scikit-learn's partial_fit. The next two lessons handle what makes streams hard: concept drift and replay and rollback.

Online SGD and prequential evaluation

The online learner is stochastic gradient descent with a batch size of one, where each example is seen once. At time tt the example (xt,yt)(\mathbf{x}_t, y_t) arrives, and

wt+1=wt−ηt ∇wℓ(wt;xt,yt),∇wℓ=(σ(wt⊤xt+bt)−yt) xt\mathbf{w}_{t+1} = \mathbf{w}_t - \eta_t \, \nabla_{\mathbf{w}} \ell(\mathbf{w}_t; \mathbf{x}_t, y_t), \qquad \nabla_{\mathbf{w}} \ell = \big(\sigma(\mathbf{w}_t^\top \mathbf{x}_t + b_t) - y_t\big) \, \mathbf{x}_t

for the logistic loss (mini-batch SGD). The step size ηt\eta_t usually decays, for example ηt=η0/t\eta_t = \eta_0 / \sqrt{t}, so that the weights settle down; a constant η\eta keeps the model able to follow change, at the price of noise.

There is no separate test set in a stream, but there is something better: every new example is unseen when it arrives. Prequential (predictive-sequential) evaluation, or test-then-train, predicts each example first and learns from it afterwards:

prequential accuracy after T=1T∑t=1T1[ft−1(xt)=yt]\text{prequential accuracy after } T = \frac{1}{T} \sum_{t=1}^{T} \mathbb{1}\big[f_{t-1}(\mathbf{x}_t) = y_t\big]

where ft−1f_{t-1} is the model before it has seen example tt. No example is ever predicted by a model that trained on it, and every example is used for both evaluation and training.

stream x_1 x_2 ... x_t x_t+1 time 1 predict with f_t-1score it: right or wrong 2 learnone step: f_t 3 discard x_tmemory stays fixed accuracy = share of examples predicted right before the model learned from them

From scratch: one example at a time

A stream of 5,000 examples with 5 features, labelled by a fixed logistic rule with weights (2,−1,0.5,0,1.5)(2, -1, 0.5, 0, 1.5) and noise. The learner holds only w\mathbf{w} and bb: each example is predicted, used for one gradient step with ηt=0.5/t\eta_t = 0.5/\sqrt{t}, and dropped.

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

# A stream of 5000 examples, 5 features, label from a fixed logistic rule (no drift yet)
rng = np.random.default_rng(0)
w_true, b_true = np.array([2.0, -1.0, 0.5, 0.0, 1.5]), -0.5
X = rng.normal(size=(5000, 5))
y = (rng.random(5000) < 1 / (1 + np.exp(-(X @ w_true + b_true)))).astype(int)

w, b = np.zeros(5), 0.0
correct = 0
for t in range(len(y)):                       # one example at a time, never stored
    x_t, y_t = X[t], y[t]
    p = 1 / (1 + np.exp(-(x_t @ w + b)))
    correct += int((p > 0.5) == y_t)          # 1. test on the new example (prequential)
    eta = 0.5 / np.sqrt(t + 1)                # decaying learning rate
    w -= eta * (p - y_t) * x_t                # 2. then train on it: one SGD step on the log-loss
    b -= eta * (p - y_t)
    if (t + 1) in (100, 500, 1000, 5000):
        print(f"after {t + 1:4d} examples: prequential accuracy {correct / (t + 1):.3f}, w = {np.round(w, 2)}")
batch = LogisticRegression(C=1e6, max_iter=1000).fit(X, y)    # all data at once, for comparison
print(f"batch logistic regression:                   w = {np.round(batch.coef_[0], 2)}")
print(f"true rule:                                   w = {w_true}")
after  100 examples: prequential accuracy 0.730, w = [ 0.83 -0.65  0.28 -0.31  0.84]
after  500 examples: prequential accuracy 0.780, w = [ 1.48 -0.77  0.29 -0.15  0.99]
after 1000 examples: prequential accuracy 0.799, w = [ 1.64 -0.82  0.45 -0.09  1.05]
after 5000 examples: prequential accuracy 0.818, w = [ 1.96 -0.87  0.48 -0.04  1.41]
batch logistic regression:                   w = [ 2.02 -0.96  0.51 -0.04  1.44]
true rule:                                   w = [ 2.  -1.   0.5  0.   1.5]

The prequential accuracy rises from 0.730 after 100 examples to 0.818 after 5,000, and the weights move towards the true rule. Because the prequential score averages over the whole stream, it includes the early mistakes and lags behind the model's current quality. After one pass, the online weights are close to those of a batch logistic regression that saw all 5,000 rows at once and could iterate over them as often as it liked; the last weight (1.41 against 1.44) is still catching up. The online learner used constant memory: five weights and a bias, whatever the length of the stream.

With scikit-learn: partial_fit

In scikit-learn, estimators that can learn incrementally have a partial_fit method. Each call updates the model with one batch and keeps everything learned before; fit would start again from zero. The classes must be declared on the first call (classes=[0, 1]), because a batch may not contain every class. Preprocessing must be incremental too: StandardScaler.partial_fit keeps a running mean and variance.

The stream below has 10,000 rows with 20 features on very different scales, arriving in chunks of 500; 2,000 more rows are a held-out set that is only used for reporting. Two online learners run side by side: plain SGDClassifier with the logistic loss, and the same with average=True.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import SGDClassifier, LogisticRegression
from sklearn.preprocessing import StandardScaler

X, y = make_classification(n_samples=12000, n_features=20, n_informative=8, class_sep=0.8, random_state=0)
X = X * np.linspace(1, 100, 20)                            # features on very different scales
X_stream, y_stream, X_test, y_test = X[:10000], y[:10000], X[10000:], y[10000:]

scaler = StandardScaler()
models = {"SGD": SGDClassifier(loss="log_loss", alpha=1e-4, random_state=0),
          "averaged SGD": SGDClassifier(loss="log_loss", alpha=1e-4, average=True, random_state=0)}
correct = {name: 0 for name in models}
seen = 0
for start in range(0, 10000, 500):                         # chunks of 500 arrive one after another
    Xc, yc = X_stream[start:start + 500], y_stream[start:start + 500]
    scaler.partial_fit(Xc)                                 # update the running mean and variance
    Xs = scaler.transform(Xc)
    for name, clf in models.items():
        if seen:                                           # test on the chunk first ...
            correct[name] += (clf.predict(Xs) == yc).sum()
        clf.partial_fit(Xs, yc, classes=[0, 1])            # ... then train on it (classes: first call)
    seen += len(yc)
    if seen in (1000, 5000, 10000):
        print(f"{seen:5d} seen: " + " | ".join(
            f"{name} prequential {correct[name] / (seen - 500):.3f}, held-out {clf.score(scaler.transform(X_test), y_test):.3f}"
            for name, clf in models.items()))
print(f"running mean of feature 20: {scaler.mean_[-1]:.2f} (mean of all 10000 rows: {X_stream[:, -1].mean():.2f})")
full = StandardScaler().fit(X_stream)
batch = LogisticRegression(max_iter=1000).fit(full.transform(X_stream), y_stream)
print(f"batch logistic regression on all 10000 rows: held-out {batch.score(full.transform(X_test), y_test):.3f}")
 1000 seen: SGD prequential 0.830, held-out 0.792 | averaged SGD prequential 0.838, held-out 0.857
 5000 seen: SGD prequential 0.826, held-out 0.796 | averaged SGD prequential 0.872, held-out 0.869
10000 seen: SGD prequential 0.818, held-out 0.814 | averaged SGD prequential 0.873, held-out 0.870
running mean of feature 20: -0.80 (mean of all 10000 rows: -0.80)
batch logistic regression on all 10000 rows: held-out 0.873

Plain SGD stays between 0.79 and 0.81 on the held-out rows, well below the batch logistic regression trained on all 10,000 rows at once (0.873). Its weights keep jumping with each noisy single-example step. Averaged SGD reports the average of the weights along the path instead of the last value (Polyak-Ruppert averaging, wˉT=1T∑twt\bar{\mathbf{w}}_T = \frac{1}{T} \sum_t \mathbf{w}_t), which cancels much of the noise: 0.857 after 1,000 rows and 0.870 after 10,000, within 0.003 of the batch model, from a single pass and constant memory. The running scaler ends with exactly the mean of all the rows it has seen (−0.80-0.80 for feature 20), so incremental standardisation costs nothing in accuracy when the stream is stationary.

Note how the chunks are used: each chunk is first predicted by the model trained on the previous chunks (test), then learned (train). The first chunk is not scored, because there is no model yet.

Which estimators can learn incrementally

python · try it yourself
import numpy as np
from sklearn.utils import all_estimators
from sklearn.decomposition import PCA, IncrementalPCA
from sklearn.datasets import load_digits

names = sorted(name for name, cls in all_estimators() if hasattr(cls, "partial_fit"))
print(len(names), "scikit-learn estimators have partial_fit:")
print(", ".join(names))

X = load_digits().data
ipca = IncrementalPCA(n_components=5)
for start in range(0, len(X), 300):                        # 6 batches of up to 300 images
    ipca.partial_fit(X[start:start + 300])
pca = PCA(n_components=5).fit(X)
print("explained variance, IncrementalPCA:", np.round(ipca.explained_variance_, 1))
print("explained variance, PCA:           ", np.round(pca.explained_variance_, 1))
cos = np.abs((ipca.components_ * pca.components_).sum(1))
print("|cosine| between matching components:", np.round(cos, 4))
29 scikit-learn estimators have partial_fit:
BernoulliNB, BernoulliRBM, Birch, CategoricalNB, ComplementNB, GaussianNB, HashingVectorizer, IncrementalPCA, LatentDirichletAllocation, MLPClassifier, MLPRegressor, MaxAbsScaler, MinMaxScaler, MiniBatchDictionaryLearning, MiniBatchKMeans, MiniBatchNMF, MultiOutputClassifier, MultiOutputRegressor, MultinomialNB, OneVsOneClassifier, OneVsRestClassifier, PassiveAggressiveClassifier, PassiveAggressiveRegressor, Perceptron, SGDClassifier, SGDOneClassSVM, SGDRegressor, SelectFromModel, StandardScaler
explained variance, IncrementalPCA: [178.6 163.2 141.4 100.8  68.4]
explained variance, PCA:            [179.  163.7 141.8 101.1  69.5]
|cosine| between matching components: [0.9998 0.9996 0.9998 0.9993 0.9862]

The list covers linear models trained by SGD (SGDClassifier, SGDRegressor, Perceptron, PassiveAggressiveClassifier), naive Bayes (whose counts and means simply accumulate), MLPClassifier, mini-batch clustering and matrix factorisation, and the incremental preprocessing steps (StandardScaler, MinMaxScaler, MaxAbsScaler, HashingVectorizer, which is stateless and needs no vocabulary). Trees, forests, gradient boosting and SVMs with kernels are missing: their training needs all the data at once. IncrementalPCA processes six batches of up to 300 images and recovers almost the same components as PCA on all 1,797 (cosines above 0.98, explained variances within 2 %).

warm_start=True is not the same thing: it reuses the previous solution as the starting point for a new fit on the data you pass, which helps when re-fitting on a growing data set, but each fit still needs that whole data set.

Online, mini-batch retraining, or both

Online (partial_fit per example or chunk) Periodic batch retraining
Memory constant: the model only the training window must be stored
Freshness updates within seconds as old as the last retraining (hours to weeks)
Model families linear, naive Bayes, neural networks any
Evaluation prequential, continuous classic held-out sets per retraining
Risk one bad batch changes the model immediately a bad batch affects the next retraining, which can be checked first
Typical use ads, recommendations, fraud scoring, sensors most production models

Many systems combine them: a nightly batch model plus online updates during the day, or a batch-trained backbone with an online-trained last layer.

Pitfalls

  • Scalers fitted once, on the first chunk. The first chunk's statistics are noisy and go stale; use partial_fit on the scaler, or features that need no fitting (hashing, fixed bins).
  • Calling fit instead of partial_fit. fit throws away everything learned before.
  • Forgetting classes= on the first call, or a class appearing for the first time later: scikit-learn raises an error, because the output layer was sized on the first call.
  • Ordered streams. SGD assumes examples arrive in a random order. A stream sorted by class or by customer makes the model swing; shuffle within a buffer if the order is artificial.
  • Trusting the last weights. Plain SGD's final weights are noisy; average them (average=True) or decay the learning rate.
  • A decaying learning rate in a changing world. ηt→0\eta_t \to 0 means the model eventually stops adapting. If the data drifts, keep a floor on the learning rate or detect drift and react (next lesson).

Practice

  1. Why does prequential accuracy usually underestimate the current model's accuracy on a stationary stream?
  2. In the scikit-learn example, what would go wrong if the scaler were fitted with fit on the first chunk only?
  3. Name one model you could not train with partial_fit, and one way to update it as new data arrives.
Answers
  1. It averages over the whole stream, including the early examples predicted by a model that had seen little data. The current model is better than the average of all past models. A sliding-window or exponentially weighted prequential accuracy tracks the current quality more closely.
  2. Its mean and variance would come from 500 rows only, and would never be updated. On this stationary stream that adds a little noise to every input; if the features drift, the standardised values move away from mean 0 and variance 1 and the model's inputs shift.
  3. A random forest or gradient-boosted trees (also kernel SVMs). Retrain periodically on a sliding window of recent data, or add trees fitted to the new data (some boosting libraries support continuing training), or use a streaming tree such as a Hoeffding tree from a streaming library.

Test yourself

What is the difference between fit and partial_fit in scikit-learn?

  1. None
  2. fit trains from scratch on the data given; partial_fit updates the existing model with one more batch
  3. partial_fit uses only part of the features
  4. partial_fit is for regression only

In prequential (test-then-train) evaluation, each example is…

  1. used only for testing
  2. predicted by the current model first, then used for one training update
  3. used for training twice
  4. held out until the end of the stream

Why did average=True bring the online SGD model close to the batch model?

  1. It trains several epochs
  2. It reports the average of the weights along the SGD path, which cancels much of the step-to-step noise
  3. It uses a larger learning rate
  4. It stores all the data

Why must classes= be passed on the first partial_fit call of a classifier?

  1. For speed
  2. The model must size its output for all classes, and the first batch may not contain every class
  3. It sets the class weights
  4. It is optional and ignored