Skip to main content
LearnMLAcademy
Intermediate10 min read

Online Learning

Stream machine learning updates continuously using incremental SGD algorithms, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Online Learning

What if your data never stops?

A fraud model cannot wait forever for the next full retraining cycle.

Imagine a bank receiving thousands of new transactions every minute. Customer behaviour changes, new fraud patterns appear, and fresh labelled examples keep arriving. Retraining the entire model from zero after every small change would be wasteful.

Online learning gives us another option: keep the model's current knowledge and update it a little as new information arrives.

Most introductory Machine Learning examples use batch learning: collect a dataset, train a model, deploy it, and retrain later. That approach is often the simplest and safest choice.

Online learning, also called incremental learning, is different. The model can continue learning from new labelled examples or mini-batches without throwing away everything it has already learned.

The core loop

New observation arrives
Predict with current model
Observe label and error
Update, then repeat

Important idea

Online learning does not mean that every prediction system must retrain after every single event. Updates may happen one sample at a time or in small mini-batches. The defining idea is that the model can continue learning from new data without starting from zero each time.

The Big Idea: Do Not Start From Zero

Suppose a model has already learned from the first 1,000 observations. Now 100 new labelled observations arrive. A full batch retraining process may train again using all 1,100 observations. An incremental learner can instead start from the model it already has and update it using the new information.

Full retraining idea

Old 1,000 + new 100 observations
↓
Train a new model again

Incremental idea

Existing trained model
+ new 100 observations ↓
Updated model

Mental model: online learning is usually about old model state + new data → updated model state. The algorithm remembers what it has already learned and adjusts from there.

Batch Learning vs Online Learning

Batch Learning

Typical flow: collect data → train → deploy → retrain later.

The model normally stays fixed between retraining cycles.

Often simpler to reproduce, validate, and govern.

Online Learning

Typical flow: receive new data → predict → update → continue.

The model can adapt incrementally as labelled data becomes available.

Useful for streams, very large datasets, or changing environments.

QuestionBatchOnline / Incremental
How is the model updated?Periodic retrainingIncremental updates
Must all data fit in memory?Not always, but commonly assumedNo; can process small chunks
Can it react quickly to change?Depends on retraining frequencyPotentially, if feedback arrives quickly
Operational complexityUsually lowerUsually higher

Do Not Confuse These Terms

Online learning

The model itself is updated incrementally as new labelled examples or feedback become available.

Streaming inference

Predictions are made on a live stream, but the model may remain completely fixed. Streaming prediction is not automatically online learning.

Out-of-core learning

Data is processed in chunks because the full dataset is too large for RAM. The dataset can be historical and fixed; it does not have to be a live stream.

Reinforcement learning

An agent chooses actions and learns from rewards. It is a different learning paradigm, even though learning may also happen sequentially.

A Tiny Numerical Example: Updating Without Recalculating Everything

Before updating a Machine Learning model, look at the same idea using something familiar: a running mean. Suppose we have already seen the values 10, 20, 30. Their mean is 20. Now a new value, 40, arrives.

Old mean

(10 + 20 + 30) / 3 = 20

Incremental update

new mean = old mean + (new value - old mean) / new count

= 20 + (40 - 20) / 4

= 25

We reached the same mean as (10 + 20 + 30 + 40) / 4, but the update rule only needed the previous state, the new value, and the count. Incremental Machine Learning algorithms use the same broad principle, although their state and update rules are more sophisticated.

From Intuition to Model Updates

Many incremental linear models can be understood using a Stochastic Gradient Descent style update:

wnew = wold − η × gradient

w
model parameter
η
learning rate
gradient
direction of local loss change

Suppose the current weight is 0.50, the learning rate is 0.10, and the gradient from the new example is −0.40.

w_new = 0.50 − 0.10 × (−0.40)

w_new = 0.50 + 0.04

w_new = 0.54

The model has changed a little after seeing new information. Online learning repeats this type of update many times. The exact update depends on the algorithm and its loss function.

How Often Can We Update?

One sample at a time

Update after every labelled observation. This can adapt quickly but may react strongly to noisy observations.

Mini-batch updates

Collect a small chunk such as 32, 100, or 1000 observations and update once per chunk. This is often more computationally convenient.

Periodic incremental updates

Update every few minutes, hours, or days without retraining from scratch. The right cadence depends on feedback delay and business needs.

See partial_fit() in the Simplest Possible Way

Scikit-learn's StandardScaler can update its running mean and variance with partial_fit(). This gives us a clean bridge from the running-mean intuition to a real API.

partial_fit_scaler.py
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()

batch_1 = [[10], [20], [30]]
scaler.partial_fit(batch_1)
print(scaler.mean_)

batch_2 = [[40], [50]]
scaler.partial_fit(batch_2)
print(scaler.mean_)

Output

[20.]
[30.]

Why does the mean become 30?

(10 + 20 + 30 + 40 + 50) / 5 = 30

The second call updated the scaler's existing statistics instead of forgetting the first batch.

Repeated fit()

Conceptually starts a new fitting procedure and generally replaces previously learned estimator state.

partial_fit()

Continues incremental learning from the estimator's current state using the next sample or mini-batch.

Python: Incremental Learning with partial_fit()

Scikit-learn provides several estimators with a partial_fit() method. Each call updates an already-existing model using the supplied mini-batch instead of restarting training from the beginning.

For classifiers such as SGDClassifier, the complete set of possible classes must be supplied on the first partial_fit() call. Later calls can omit it.

The example below uses an initial 200-sample warm-up period. The scaler is fitted only on that historical chunk and then frozen. The remaining 1000 samples arrive in 100-sample batches.

online_learning.py
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import SGDClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score

X, y = make_classification(
    n_samples=1200,
    n_features=10,
    n_informative=6,
    n_redundant=2,
    class_sep=1.2,
    flip_y=0.03,
    random_state=42,
)

warmup = 200
batch_size = 100
classes = np.array([0, 1])

# Use only historical data to learn scaling statistics.
scaler = StandardScaler().fit(X[:warmup])

model = SGDClassifier(
    loss="log_loss",
    learning_rate="constant",
    eta0=0.01,
    alpha=0.0001,
    random_state=42,
)

# First incremental update.
X0 = scaler.transform(X[:warmup])
model.partial_fit(X0, y[:warmup], classes=classes)

correct = 0
seen = 0
batch_scores = []

for start in range(warmup, len(X), batch_size):
    stop = min(start + batch_size, len(X))
    X_batch = scaler.transform(X[start:stop])
    y_batch = y[start:stop]

    # 1. TEST FIRST: predict before learning this batch.
    y_pred = model.predict(X_batch)
    batch_scores.append(accuracy_score(y_batch, y_pred))
    correct += (y_pred == y_batch).sum()
    seen += len(y_batch)

    # 2. THEN TRAIN on the newly labelled batch.
    model.partial_fit(X_batch, y_batch)

print("Warm-up samples:", warmup)
print("Streamed samples:", seen)
print("First 3 batch accuracies:", [round(s, 3) for s in batch_scores[:3]])
print("Prequential accuracy:", round(correct / seen, 3))

Expected output

Warm-up samples: 200
Streamed samples: 1000
First 3 batch accuracies: [0.8, 0.8, 0.82]
Prequential accuracy: 0.811

Spot the Bug: Which Stream Evaluation Is Honest?

Pipeline A — misleading

New batch arrives
↓
Train on that batch
↓
Predict and score the same batch

The model has already seen the answers before you measure it.

Pipeline B — preferred

New batch arrives
↓
Predict and score first
↓
Then update the model

This tests the model state that actually existed before learning from the new batch.

Why predict before learning?

If we train on a batch and then score that same batch, the result is partly a training score. In a stream, a more realistic approach is often test-then-train (also called prequential evaluation): predict using the model state available at that moment, observe the true label when it arrives, measure the error, and only then update the model.

Prequential pattern

PredictObserve labelScoreUpdate

Preprocessing Must Be Stream-Safe Too

Incremental learning is not only about the final classifier. Any preprocessing step that learns statistics from data must also respect time/order.

Risky

scaler.fit(X_all)
# scaler has seen future stream data

Safer idea

scaler.fit(X_initial_history)
# future batches remain unseen

Scikit-learn's StandardScaler itself supports partial_fit() for online mean/variance updates. However, if both the feature transformation and the model are changing over time, you must design the update order carefully so that evaluation does not use future information and the model sees a consistent feature representation. Dedicated streaming libraries can make this workflow easier.

Concept Drift: When the World Changes

Online learning is especially interesting when the data-generating process changes. But the word drift covers several different situations.

ChangeSimple meaningExample
Data / covariate driftThe distribution of inputs changesCustomers now use newer devices
Class-prior shiftHow common each class is changesFraud becomes more frequent
Concept driftThe relationship between inputs and target changesPatterns that indicated fraud last year no longer mean the same thing

Online learning does not automatically solve drift. If labels arrive slowly, updates are noisy, the chosen model cannot represent the new pattern, or harmful data enters the stream, the model can still perform poorly. Drift should be monitored rather than assumed to be fixed by continuous updates.

A simple drift story

1
Period 1
Old pattern works
2
Period 2
Behaviour begins changing
3
Period 3
Errors increase
4
Period 4
Model may need adaptation

Algorithms That Can Learn Incrementally

Not every Scikit-learn estimator supports incremental training. A practical clue is whether the estimator exposes a partial_fit() method.

TaskExamplesWhy useful
ClassificationSGDClassifier, Perceptron, MultinomialNBCan update from successive mini-batches
RegressionSGDRegressorIncremental linear regression-style learning
ClusteringMiniBatchKMeansProcesses small batches instead of all rows at once
Neural networksMLPClassifier, MLPRegressorScikit-learn also exposes incremental updates for these estimators

What about trees and drift detectors?

Streaming-focused libraries such as River include methods designed specifically for evolving streams, including Hoeffding-style trees and drift detectors such as ADWIN. These are useful advanced topics, but they are not required to understand the core idea of incremental learning.

Learning Rate Matters

For SGD-style online models, the learning rate controls how strongly new data changes the model.

Too large

Updates may jump around and react too strongly to individual batches.

Reasonable

The model can learn while remaining reasonably stable.

Too small

Adaptation may be so slow that the model cannot keep up with meaningful change.

Scikit-learn's SGDClassifier supports several learning-rate schedules such as constant, optimal, invscaling, and adaptive. These schedules are not the same thing as algorithms such as AdaGrad or Adam.

Where Online Learning Can Be Useful

Fraud / abuse detection

New labelled transactions or moderation decisions can be incorporated incrementally when feedback is available.

Spam and text filtering

Vocabulary and message patterns can evolve, making incremental updates useful.

Recommendation / ranking signals

Recent clicks, views, and preferences may carry useful information about current behaviour.

IoT and operational monitoring

Continuous sensor streams may be processed without keeping the entire history in memory.

These are possible applications, not claims that every production system in these domains uses online learning. Many real systems deliberately use scheduled batch retraining, hybrid architectures, or human approval before model updates.

Benefits and Risks

Potential benefits

  • Can process data in small chunks.
  • May adapt faster than infrequent full retraining.
  • Useful when the dataset is larger than available memory.
  • Can incorporate recent labelled feedback continuously.

Important risks

  • Bad labels or corrupted data can change the model immediately.
  • Recent observations can be over-emphasized.
  • Evaluation and rollback are more operationally difficult.
  • Adversarial or poisoned inputs can be especially dangerous.

When Should You Choose Online Learning?

Online learning is worth considering when...

  • data arrives continuously or is too large for memory,
  • recent labelled feedback should affect the model quickly,
  • full retraining is expensive,
  • the environment may change over time, and
  • you can monitor, validate, and roll back updates safely.

Batch learning may be simpler when...

  • the environment changes slowly,
  • labels arrive only after long delays,
  • periodic retraining is inexpensive enough,
  • strict reproducibility/governance is important, or
  • the chosen model does not support safe incremental updates.

Common Mistakes

“A model making real-time predictions is automatically online learning.”

No. The model may make streaming predictions while remaining completely fixed.

“Online learning means one record at a time.”

Not necessarily. Mini-batch incremental updates are also common.

“Online learning automatically fixes concept drift.”

No. Adaptation depends on feedback, model capacity, learning rate, data quality, and monitoring.

“I can preprocess the whole stream first.”

That may leak future information. Preprocessing must respect the same chronology as model training.

“More recent data should always dominate old data.”

That is a modeling choice, not a universal law. Some old patterns remain important.

“partial_fit() is equivalent to calling fit() repeatedly.”

No. partial_fit continues incremental training, while fit() generally represents a new fitting procedure and may reset learned state.

Check Your Understanding

1. A recommendation system makes predictions every second, but its model is retrained only once a week. Is this online learning?

No. It is streaming or real-time inference, but the model itself is not being updated incrementally.

2. Why should a new labelled batch usually be scored before partial_fit()?

Because otherwise the model has already learned from that batch, making the score partly a training score rather than an honest test of the previous model state.

3. Does online learning have to update after every individual row?

No. Updates can happen one sample at a time, in mini-batches, or periodically while still continuing from the current model state.

Quick Recap

What is the central idea of online learning?

The model can continue updating incrementally as new labelled data arrives instead of always retraining from scratch.

Why is “predict first, then learn” useful?

It evaluates the model using the state that actually existed before the new labelled example or batch was incorporated.

Does online learning guarantee adaptation to concept drift?

No. Online updates create the possibility of adaptation, but successful adaptation still depends on feedback speed, algorithm choice, data quality, hyperparameters, and monitoring.

Final Takeaway

Online learning is incremental model updating. It is valuable when data or environments evolve, when datasets are too large for memory, or when waiting for full retraining is undesirable. But it adds operational risk: the model can learn from bad data just as quickly as it can learn from useful data. Good online systems therefore combine incremental learning with careful evaluation, drift monitoring, data-quality checks, and rollback strategies.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Online Learning"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Online learning updates incrementally as new examples arrive.
  • It suits large streams and changing environments.
  • Learning rate balances adaptation and forgetting.
  • Prequential evaluation predicts before learning each new outcome.
  • Rolling metrics and drift checks separate persistent change from noise.
  • Validation, rollback, and data guards limit damage from bad updates.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
What is the key difference between batch and online learning?
Question 2 of 4
What is out-of-core learning and why does online learning solve it?
Question 3 of 4
What is catastrophic forgetting in online learning?
Question 4 of 4
How do you evaluate an online learning model when new labelled examples arrive continuously?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the key difference between batch and online learning?▼

Correct Answer: Batch trains on the entire dataset producing a static model. Online updates incrementally as each new example arrives — the model is always evolving and never needs full retraining

A batch-trained fraud model from January may miss March fraud patterns. An online model updates daily with new transaction data, continuously adapting.

2What is out-of-core learning and why does online learning solve it?▼

Correct Answer: When the dataset is too large for RAM. Online learning processes data in small chunks from disk, updating the model with each chunk without ever loading the full dataset into memory

A 10TB dataset of click events cannot fit in RAM. Online learning processes it in small chunks. River (formerly scikit-multiflow) and sklearn's partial_fit() enable this.

3What is catastrophic forgetting in online learning?▼

Correct Answer: Online updates on new data cause the model to forget previously learned patterns — adapts too quickly, losing knowledge of older patterns still relevant

High learning rate adapts quickly but forgets. Low learning rate retains old knowledge but adapts slowly. Elastic Weight Consolidation and memory replay mitigate this.

4How do you evaluate an online learning model when new labelled examples arrive continuously?▼

Correct Answer: Use prequential evaluation (test-then-train): for each new example, predict first, then update with the true label. This gives a running evaluation that accurately reflects performance at each point in time without a separate held-out set

Prequential evaluation avoids look-ahead bias and gives a realistic picture of performance over time, including adaptation periods after concept drift.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next