Skip to content

classifier

Classes:

Name Description
Classifier

Incremental PyTorch classifier with optional dynamic feature & class growth.

Classifier

Classifier(
    module: Module,
    loss_fn: Union[str, Callable],
    optimizer_fn: Union[str, type],
    lr: float = 0.001,
    output_is_logit: bool = True,
    is_class_incremental: bool = False,
    is_feature_incremental: bool = False,
    device: str = "cpu",
    seed: int = 42,
    gradient_clip_value: float | None = None,
    **kwargs
)

Bases: DeepEstimator, MiniBatchClassifier

Incremental PyTorch classifier with optional dynamic feature & class growth.

This wrapper turns an arbitrary torch.nn.Module into an incremental classifier that follows the :mod:river API. It can optionally expand its input dimensionality when previously unseen feature names occur (is_feature_incremental=True) and expand the output layer when new class labels appear (is_class_incremental=True).

When loss_fn='cross_entropy' targets are handled as integer class indices; otherwise they are converted to one-hot vectors to match the output dimension.

Parameters:

Name Type Description Default
module Module

The underlying PyTorch model producing (logit) outputs.

required
loss_fn str | Callable

Loss identifier (e.g. 'cross_entropy', 'mse') or a callable.

required
optimizer_fn str | type

Optimizer identifier ('adam', 'sgd', etc.) or an optimizer class.

required
lr float

Learning rate passed to the optimizer.

1e-3
output_is_logit bool

If True, predict_proba_* will apply a softmax (multi-class) or sigmoid (binary) as needed using :func:output2proba.

True
is_class_incremental bool

Whether to expand the output layer when new class labels appear.

False
is_feature_incremental bool

Whether to expand the input layer when new feature names are observed.

False
device str

Runtime device.

'cpu'
seed int

Random seed.

42
gradient_clip_value float | None

Norm to clip gradients to (disabled if None).

None
**kwargs

Extra parameters retained for reconstruction.

{}

Examples:

Online binary classification on the Phishing dataset from :mod:`river`.
We build a tiny MLP and maintain an online Accuracy metric. The exact value
may vary depending on library version and hardware::

>>> import random, numpy as np
>>> import torch
>>> from torch import nn, manual_seed
>>> from river import datasets, metrics
>>> from deep_river.classification import Classifier
>>> _ = manual_seed(42); random.seed(42); np.random.seed(42)
>>> first_x, _ = next(iter(datasets.Phishing()))
>>> n_features = len(first_x)
>>> class SmallMLP(nn.Module):
...     def __init__(self, n_features):
...         super().__init__()
...         self.net = nn.Sequential(
...             nn.Linear(n_features, 16),
...             nn.ReLU(),
...             nn.Linear(16, 2)
...         )
...     def forward(self, x):
...         return self.net(x)  # raw logits
>>> clf = Classifier(
...     module=SmallMLP(n_features),
...     loss_fn='cross_entropy',
...     optimizer_fn='sgd',
...     lr=1e-2,
...     is_class_incremental=True
... )
>>> acc = metrics.Accuracy()
>>> for i, (x, y) in enumerate(datasets.Phishing().take(200)):
...     if i > 0:  # only predict after first sample is seen
...         y_pred = clf.predict_one(x)
...         acc.update(y, y_pred)
...     clf.learn_one(x, y)
>>> print(f"Accuracy: {acc.get():.4f}")  # doctest: +ELLIPSIS
Accuracy: ...

Methods:

Name Description
clone

Return a fresh estimator instance with (optionally) copied state.

draw

Render a (partial) computational graph of the wrapped model.

learn_many

Learn from a batch of instances.

learn_one

Learn from a single instance.

load

Load a previously saved estimator.

predict_proba_many

Predict probabilities for a batch of instances.

predict_proba_one

Predict class membership probabilities for one instance.

save

Persist the estimator (architecture, weights, optimiser & runtime state).

Source code in deep_river/classification/classifier.py
def __init__(
    self,
    module: torch.nn.Module,
    loss_fn: Union[str, Callable],
    optimizer_fn: Union[str, type],
    lr: float = 0.001,
    output_is_logit: bool = True,
    is_class_incremental: bool = False,
    is_feature_incremental: bool = False,
    device: str = "cpu",
    seed: int = 42,
    gradient_clip_value: float | None = None,
    **kwargs,
):
    super().__init__(
        module=module,
        loss_fn=loss_fn,
        optimizer_fn=optimizer_fn,
        lr=lr,
        device=device,
        seed=seed,
        is_feature_incremental=is_feature_incremental,
        gradient_clip_value=gradient_clip_value,
        **kwargs,
    )
    self.output_is_logit = output_is_logit
    self.is_class_incremental = is_class_incremental
    self.observed_classes: SortedSet = SortedSet()

clone

clone(
    new_params=None,
    include_attributes: bool = False,
    copy_weights: bool = False,
)

Return a fresh estimator instance with (optionally) copied state.

Parameters:

Name Type Description Default
new_params dict | None

Parameter overrides for the cloned instance.

None
include_attributes bool

If True, runtime state (observed features, buffers) is also copied.

False
copy_weights bool

If True, model weights are copied (otherwise the module is re‑initialised).

False
Source code in deep_river/base.py
def clone(
    self,
    new_params=None,
    include_attributes: bool = False,
    copy_weights: bool = False,
):
    """Return a fresh estimator instance with (optionally) copied state.

    Parameters
    ----------
    new_params : dict | None
        Parameter overrides for the cloned instance.
    include_attributes : bool, default=False
        If True, runtime state (observed features, buffers) is also copied.
    copy_weights : bool, default=False
        If True, model weights are copied (otherwise the module is re‑initialised).
    """
    new_params = new_params or {}
    copy_weights = new_params.pop("copy_weights", copy_weights)

    params = {**self._get_all_init_params(), **new_params}

    if "module" not in new_params:
        params["module"] = self._rebuild_module()

    new_est = self.__class__(**self._filter_kwargs(self.__class__.__init__, params))

    if copy_weights and hasattr(self.module, "state_dict"):
        new_est.module.load_state_dict(self.module.state_dict())

    if include_attributes:
        new_est._restore_runtime_state(self._get_runtime_state())

    return new_est

draw

draw()

Render a (partial) computational graph of the wrapped model.

Imports graphviz and torchviz lazily. Raises an informative ImportError if the optional dependencies are not installed.

Source code in deep_river/base.py
def draw(self):  # type: ignore[override]
    """Render a (partial) computational graph of the wrapped model.

    Imports ``graphviz`` and ``torchviz`` lazily. Raises an informative
    ImportError if the optional dependencies are not installed.
    """
    try:  # pragma: no cover
        from torchviz import make_dot  # type: ignore
    except Exception as err:  # noqa: BLE001
        raise ImportError(
            "graphviz and torchviz must be installed to draw the model."
        ) from err

    first_parameter = next(self.module.parameters())
    input_shape = first_parameter.size()
    y_pred = self.module(torch.rand(input_shape))
    return make_dot(y_pred.mean(), params=dict(self.module.named_parameters()))

learn_many

learn_many(X: DataFrame, y: Series) -> None

Learn from a batch of instances.

Parameters:

Name Type Description Default
X DataFrame

Batch of feature rows.

required
y Series

Corresponding labels.

required
Source code in deep_river/classification/classifier.py
def learn_many(self, X: pd.DataFrame, y: pd.Series) -> None:
    """Learn from a batch of instances.

    Parameters
    ----------
    X : pandas.DataFrame
        Batch of feature rows.
    y : pandas.Series
        Corresponding labels.
    """
    self._update_observed_features(X)
    self._update_observed_targets(y)
    x_t = self._df2tensor(X)
    if self.loss_fn == "cross_entropy":
        self._classification_step_cross_entropy(x_t, y)
    else:
        self._learn(x_t, y)

learn_one

learn_one(x: dict, y: ClfTarget) -> None

Learn from a single instance.

Parameters:

Name Type Description Default
x dict

Feature dictionary.

required
y hashable

Class label.

required
Source code in deep_river/classification/classifier.py
def learn_one(self, x: dict, y: base.typing.ClfTarget) -> None:
    """Learn from a single instance.

    Parameters
    ----------
    x : dict
        Feature dictionary.
    y : hashable
        Class label.
    """
    self._update_observed_features(x)
    self._update_observed_targets(y)
    x_t = self._dict2tensor(x)
    if self.loss_fn == "cross_entropy":
        self._classification_step_cross_entropy(x_t, y)
    else:
        # One-hot pathway / other losses
        self._learn(x_t, y)

load classmethod

load(filepath: Union[str, Path])

Load a previously saved estimator.

The method reconstructs the estimator class, its wrapped module, optimiser state and runtime information (feature names, buffers, etc.).

Source code in deep_river/base.py
@classmethod
def load(cls, filepath: Union[str, Path]):
    """Load a previously saved estimator.

    The method reconstructs the estimator class, its wrapped module, optimiser
    state and runtime information (feature names, buffers, etc.).
    """
    with open(filepath, "rb") as f:
        state = pickle.load(f)

    estimator_cls = cls._import_from_path(state["estimator_class"])
    init_params = state["init_params"]

    # Rebuild module if needed
    if "module" in init_params and isinstance(init_params["module"], dict):
        module_info = init_params.pop("module")
        module_cls = cls._import_from_path(module_info["class"])
        module = module_cls(
            **cls._filter_kwargs(module_cls.__init__, module_info["kwargs"])
        )
        if state.get("model_state_dict"):
            module.load_state_dict(state["model_state_dict"])
        init_params["module"] = module

    estimator = estimator_cls(
        **cls._filter_kwargs(estimator_cls.__init__, init_params)
    )

    if state.get("optimizer_state_dict") and hasattr(estimator, "optimizer"):
        try:
            estimator.optimizer.load_state_dict(
                state["optimizer_state_dict"]  # type: ignore[arg-type]
            )
        except Exception:  # noqa: E722
            pass

    estimator._restore_runtime_state(state.get("runtime_state", {}))
    return estimator

predict_proba_many

predict_proba_many(X: DataFrame) -> DataFrame

Predict probabilities for a batch of instances.

Parameters:

Name Type Description Default
X DataFrame

Feature matrix.

required

Returns:

Type Description
DataFrame

Each row sums to 1 (multi-class) or has two columns for binary.

Source code in deep_river/classification/classifier.py
def predict_proba_many(self, X: pd.DataFrame) -> pd.DataFrame:
    """Predict probabilities for a batch of instances.

    Parameters
    ----------
    X : pandas.DataFrame
        Feature matrix.

    Returns
    -------
    pandas.DataFrame
        Each row sums to 1 (multi-class) or has two columns for binary.
    """
    self._update_observed_features(X)
    x_t = self._df2tensor(X)
    self.module.eval()
    with torch.inference_mode():
        y_preds = self.module(x_t)
    return pd.DataFrame(
        output2proba(y_preds, self.observed_classes, self.output_is_logit)
    )

predict_proba_one

predict_proba_one(x: dict) -> dict[ClfTarget, float]

Predict class membership probabilities for one instance.

Parameters:

Name Type Description Default
x dict

Feature dictionary.

required

Returns:

Type Description
dict

Mapping from label -> probability.

Source code in deep_river/classification/classifier.py
def predict_proba_one(self, x: dict) -> dict[base.typing.ClfTarget, float]:
    """Predict class membership probabilities for one instance.

    Parameters
    ----------
    x : dict
        Feature dictionary.

    Returns
    -------
    dict
        Mapping from label -> probability.
    """
    self._update_observed_features(x)
    x_t = self._dict2tensor(x)
    self.module.eval()
    with torch.inference_mode():
        y_pred = self.module(x_t)
    raw = output2proba(y_pred, self.observed_classes, self.output_is_logit)[0]
    return cast(dict[base.typing.ClfTarget, float], raw)

save

save(filepath: Union[str, Path]) -> None

Persist the estimator (architecture, weights, optimiser & runtime state).

Parameters:

Name Type Description Default
filepath str | Path

Destination file. Parent directories are created automatically.

required
Source code in deep_river/base.py
def save(self, filepath: Union[str, Path]) -> None:
    """Persist the estimator (architecture, weights, optimiser & runtime state).

    Parameters
    ----------
    filepath : str | Path
        Destination file. Parent directories are created automatically.
    """
    filepath = Path(filepath)
    filepath.parent.mkdir(parents=True, exist_ok=True)

    state = {
        "estimator_class": f"{type(self).__module__}.{type(self).__name__}",
        "init_params": self._get_all_init_params(),
        "model_state_dict": getattr(self.module, "state_dict", lambda: {})(),
        "optimizer_state_dict": getattr(self.optimizer, "state_dict", lambda: {})(),
        "runtime_state": self._get_runtime_state(),
    }

    with open(filepath, "wb") as f:
        pickle.dump(state, f)