Most machine learning tutorials assume you have a fixed dataset, train once and deploy. Real data often arrives as a stream: clicks, sensor readings, transactions, log lines. River is the Python library built for that world, where a model learns one example at a time and never needs the whole dataset in memory. River 0.27.0, released on 13 November 2026, adds a new categorical Naive Bayes classifier, a cleaner way to get prediction distributions, backend-agnostic mini-batches and a long list of streaming fixes, along with a few breaking changes. This tutorial walks through the most useful parts with runnable code.
Install River 0.27
River 0.27 now requires pandas 3.1 or newer; support for pandas 2.x and older has been removed. Upgrade both together:
pip install --upgrade "river==0.27.0" "pandas>=3.1"
All changes below come from the official 0.27.0 release notes and the GitHub release.
A 30-second refresher on online learning
In River, every model has the same small API:
learn_one(x, y)updates the model with one example,predict_one(x)predicts for one example,predict_proba_one(x)returns class probabilities (for classifiers).
Features are plain Python dictionaries, so there’s no need to build a fixed feature matrix up front.
New: CategoricalNB for categorical features
The headline addition is naive_bayes.CategoricalNB, a Naive Bayes classifier for categorical features. For each class it keeps a frequency count for every value of every feature, with additive (Laplace) smoothing controlled by alpha, and it supports both online and mini-batch modes.
Here’s the example from its docstring, a tiny “should we play outside?” dataset:
from river import naive_bayes
X = [
{"outlook": "sunny", "temp": "hot"},
{"outlook": "sunny", "temp": "hot"},
{"outlook": "sunny", "temp": "mild"},
{"outlook": "sunny", "temp": "cool"},
{"outlook": "rainy", "temp": "cool"},
{"outlook": "rainy", "temp": "cool"},
{"outlook": "rainy", "temp": "mild"},
{"outlook": "rainy", "temp": "hot"},
{"outlook": "overcast", "temp": "cool"},
{"outlook": "overcast", "temp": "mild"},
{"outlook": "overcast", "temp": "mild"},
{"outlook": "overcast", "temp": "hot"},
]
y = ["no", "no", "no", "no", "yes", "yes", "yes", "yes",
"yes", "yes", "yes", "yes"]
model = naive_bayes.CategoricalNB(alpha=1)
for x, yi in zip(X, y):
model.learn_one(x, yi)
print(model.predict_one({"outlook": "sunny", "temp": "mild"}))
# 'no'
print(model.predict_proba_one({"outlook": "sunny", "temp": "mild"}))
# {'no': 0.755..., 'yes': 0.244...}
Why use it instead of MultinomialNB?
MultinomialNB is designed for counts, like word frequencies in text. CategoricalNB treats each feature as a set of labels (country, browser, device type, plan tier), which is a better fit for typical tabular event data. It’s also handy as a fast, explainable baseline: you can inspect model.class_counts and model.feature_counts to see exactly what it has learned.
Mini-batch mode
The same model can learn from a DataFrame:
import pandas as pd
from river import naive_bayes
df = pd.DataFrame(X)
labels = pd.Series(y)
batch_model = naive_bayes.CategoricalNB(alpha=1)
batch_model.learn_many(df, labels)
unseen = pd.DataFrame([{"outlook": "rainy", "temp": "cool"}])
print(batch_model.predict_many(unseen).tolist()) # ['yes']
print(batch_model.predict_proba_many(unseen))
Mini-batches beyond pandas
MultinomialNB.learn_many, predict_many and predict_proba_many now accept any eager backend supported by narwhals, such as pandas, Polars or PyArrow, instead of pandas only. The output keeps the input backend, including the pandas index. A shared, backend-agnostic BaseNB.predict_many was added so all Naive Bayes variants use the same logic.
That means a Polars pipeline no longer needs a pandas round trip:
import polars as pl
from river import naive_bayes
# Word counts per document, as a Polars DataFrame
counts = pl.DataFrame({"cheap": [3, 0, 2], "meeting": [0, 2, 0], "offer": [2, 0, 1]})
labels = pl.Series(["spam", "ham", "spam"])
nb = naive_bayes.MultinomialNB()
nb.learn_many(counts, labels)
print(nb.predict_many(pl.DataFrame({"cheap": [1], "meeting": [0], "offer": [1]})))
Predicting distributions with BayesianLinearRegression
BayesianLinearRegression can return a full predictive distribution, not just a point estimate. In 0.27 that moved to a dedicated method, predict_dist_one, replacing predict_one(..., with_dist=True), so predict_one follows the normal regressor interface again.
from river import datasets, evaluate, linear_model, metrics
dataset = datasets.TrumpApproval()
model = linear_model.BayesianLinearRegression()
print(evaluate.progressive_val_score(dataset, model, metrics.MAE()))
x, _ = next(iter(dataset))
print(model.predict_one(x)) # a single number
print(model.predict_dist_one(x)) # a normal distribution with mean and sigma
If your code calls predict_one(x, with_dist=True), switch to predict_dist_one(x). The distribution is useful for alerting: flag a reading when it falls far outside the predicted range, instead of using a fixed threshold.
Streaming I/O fixes you’ll feel
The stream module received many fixes. The ones most likely to affect real pipelines:
stream.Cacheis now safe to interrupt. It writes a pass to a temporary file and renames it into place only when the stream is exhausted. Previously, abreak, exception or abandoned generator during the first pass could leave a truncated cache that later passes read as the full dataset. If you’ve ever wondered why a cached run “lost” data, this was a likely cause.iter_csvcloses its file and restorescsv.field_size_limiteven if you break out of the loop early, and it no longer yields an emptyxfor a blank line mid-file.- New
encodingparameter oniter_csv,iter_arffanditer_libsvm, defaulting to UTF-8. iter_sqlreleases its cursor once the stream ends or is abandoned.- ZIP inputs must contain exactly one file; empty or multi-file archives raise
ValueError.
from river import stream
for x, y in stream.iter_csv(
"events.csv",
target="label",
converters={"amount": float},
encoding="utf-8",
):
model.learn_one(x, y)
Clustering and other fixes
cluster.DenStream got several correctness fixes: the micro-cluster radius was computed wrongly (and was 0 away from the origin), predict_one now expands clusters through neighbours of neighbours, and new micro-clusters no longer reuse a deleted one’s key. If you use DenStream, expect different (more correct) clusters after upgrading. cluster.TextClust is described as roughly 3x faster, and two new datasets were added: datasets.TwitchChat and datasets.NewsT.
Breaking changes checklist
Before upgrading production code, check these:
- pandas 3.1+ is required.
OneHotEncoder(drop_first=True)no longer drops missing values, and the dropped value is now stable across observations.stream.iter_arffcasts sparse numeric values to floats, uses the first declared category for omitted nominal targets, and returnsNonefor explicitly missing targets.BayesianLinearRegression: usepredict_dist_oneinstead ofwith_dist=True.sketch.Counter @ Counternow returns a Pythonint, so remove any.item()calls on the result.sketch.Histogramcounts stay integers after merging.
Takeaway
River 0.27 is a solid release for anyone doing online learning in Python: CategoricalNB fills a real gap for categorical event data, predict_dist_one makes uncertainty a first-class output, mini-batches work with Polars and PyArrow, and the stream readers are much more robust. Upgrade with pandas 3.1, walk through the breaking changes list, and read the full release notes.
