rolling_regressor
¶
Classes:
Name | Description |
---|---|
RollingRegressor |
Incremental regressor with a fixed-size rolling window. |
RollingRegressor
¶
RollingRegressor(
module: Module,
loss_fn: Union[str, Callable] = "mse",
optimizer_fn: Union[str, Type[Optimizer]] = "sgd",
lr: float = 0.001,
is_feature_incremental: bool = False,
device: str = "cpu",
seed: int = 42,
window_size: int = 10,
append_predict: bool = False,
**kwargs
)
Bases: RollingDeepEstimator
, Regressor
Incremental regressor with a fixed-size rolling window.
Maintains the most recent window_size
observations in a deque and feeds
them as a (sequence_length, batch=1, n_features) tensor to the wrapped
PyTorch module. This enables simple sequence style conditioning for models
such as RNN/LSTM/GRU without storing the full historical stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
module
|
Module
|
Wrapped regression module (expects rolling tensor input shape). |
required |
loss_fn
|
str | Callable
|
Loss used for optimisation. |
'mse'
|
optimizer_fn
|
str | type
|
Optimizer specification. |
'sgd'
|
lr
|
float
|
Learning rate. |
1e-3
|
is_feature_incremental
|
bool
|
Whether to expand the first trainable layer when new feature names appear. |
False
|
device
|
str
|
Torch device. |
'cpu'
|
seed
|
int
|
Random seed. |
42
|
window_size
|
int
|
Number of most recent samples kept in the rolling buffer. |
10
|
append_predict
|
bool
|
If True, predicted samples (during prediction) are appended to the window enabling simple autoregressive rollouts. |
False
|
**kwargs
|
Forwarded to :class: |
{}
|
Examples:
Real-world regression example using the Bikes dataset from river. We keep only
the numeric features so the rolling tensor construction succeeds. A small GRU
is trained online and we track a running MAE. The exact value may vary across
library versions and hardware.
>>> import random, numpy as np
>>> from torch import nn, manual_seed
>>> from river import datasets, metrics
>>> from deep_river.regression.rolling_regressor import RollingRegressor
>>> _ = manual_seed(42)
>>> random.seed(42)
>>> np.random.seed(42)
>>> first_x, _ = next(iter(datasets.Bikes()))
>>> numeric_keys = sorted([k for k, v in first_x.items() if isinstance(v, (int, float))])
>>> class TinySeq(nn.Module):
... def __init__(self, n_features):
... super().__init__()
... self.rnn = nn.GRU(n_features, 8)
... self.head = nn.Linear(8, 1)
... def forward(self, x):
... out, _ = self.rnn(x)
... return self.head(out[-1])
>>> model = RollingRegressor(module=TinySeq(len(numeric_keys)), window_size=8)
>>> mae = metrics.MAE()
>>> window_size = 8
>>> for i, (x, y) in enumerate(datasets.Bikes().take(200)):
... x_num = {k: x[k] for k in numeric_keys}
... if i >= window_size:
... y_pred = model.predict_one(x_num)
... mae.update(y, y_pred)
... model.learn_one(x_num, y)
>>> assert 0.0 <= mae.get() < 15.0
>>> print(f"MAE: {mae.get():.4f}")
MAE: ...
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 |
Batch update with multiple samples using the rolling window. |
learn_one |
Update model using a single (x, y) and current rolling window. |
load |
Load a previously saved estimator. |
predict_many |
Predict targets for multiple samples (appends to a copy of the window). |
predict_one |
Predict a single regression target using rolling context. |
save |
Persist the estimator (architecture, weights, optimiser & runtime state). |
Source code in deep_river/regression/rolling_regressor.py
clone
¶
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
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
learn_many
¶
Batch update with multiple samples using the rolling window.
Only performs an optimisation step once the internal window has reached
window_size
length to ensure a full sequence is available.
Source code in deep_river/regression/rolling_regressor.py
learn_one
¶
Update model using a single (x, y) and current rolling window.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
dict
|
Feature mapping. |
required |
y
|
float
|
Target value. |
required |
Source code in deep_river/regression/rolling_regressor.py
load
classmethod
¶
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
predict_many
¶
Predict targets for multiple samples (appends to a copy of the window).
Returns a single-column DataFrame named 'y_pred'
.
Source code in deep_river/regression/rolling_regressor.py
predict_one
¶
Predict a single regression target using rolling context.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
dict
|
Feature mapping. |
required |
Returns:
Type | Description |
---|---|
float
|
Predicted target value. |
Source code in deep_river/regression/rolling_regressor.py
save
¶
Persist the estimator (architecture, weights, optimiser & runtime state).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
str | Path
|
Destination file. Parent directories are created automatically. |
required |