merlin.models.reservoir_classifier module
Reservoir classifier built on top of a frozen Merlin QuantumLayer.
- class merlin.models.reservoir_classifier.ReservoirClassifier(*, in_features, out_features, n_photons, reduction=None, concatenate=True, cache=True, seed=None, device=None, dtype=None)
Bases:
MerlinModuleFrozen photonic reservoir with a trainable linear readout.
The quantum reservoir is initialized once from a Haar-random interferometer and kept frozen afterwards. Training is therefore split in two stages:
fit_reservoir()fits the reservoir preprocessing, andtransform_reservoir()computes standardized quantum embeddings. Downstream optimization only updates the classical readout returned byparameters().- fit_reservoir(X, *, processor=None)
Fit the frozen reservoir preprocessing on an input feature matrix.
- Parameters:
X (numpy.ndarray|torch.Tensor|list[Any]) – Two-dimensional feature matrix used to fit the optional reduction, learn the min-max input scaling, and initialize the readout input width. When
cache=True, this method also computes and stores the fitted training-set reservoir features and their standardization statistics. Whencache=False, the quantum pass is deferred until the fitted training data is transformed.processor (merlin.core.merlin_processor.MerlinProcessor|None) – Optional processor used to evaluate the frozen quantum reservoir through Merlin’s local or remote execution path when
cache=True. If omitted,reservoir.layer.processoris used when configured. If both are set, this argument wins and emits aUserWarning. If neither is set, the quantum layer is executed locally. This argument is not used whencache=False.
- Returns:
The fitted classifier instance.
- Return type:
- Raises:
RuntimeError – If
Xcannot be interpreted as a two-dimensional feature matrix within_featurescolumns.
- forward(x)
Apply the trainable linear readout to precomputed feature vectors.
- Parameters:
x (torch.Tensor) – Batch of readout input features. This tensor must already contain the reservoir features, with optional raw-feature concatenation applied if needed.
- Returns:
Output logits produced by the linear readout.
- Return type:
- classmethod load(path, *, map_location=None, device=None)
Restore a serialized classifier from disk.
- Parameters:
path (str|pathlib.Path) – Checkpoint file previously generated with
save().map_location (str|torch.device|None) – Optional map-location argument forwarded to
torch.load().device (str|torch.device|None) – Optional device override applied to the restored classifier after loading the checkpoint configuration.
- Returns:
Restored classifier with the frozen reservoir state, preprocessing statistics, and readout parameters loaded from
path.- Return type:
- Raises:
FileNotFoundError – If
pathdoes not exist.RuntimeError – If the checkpoint cannot be deserialized by
torch.load().
Notes
This method calls
torch.load()withweights_only=False, which allows arbitrary Python objects to be unpickled. Only load checkpoints from trusted sources. Loading a malicious file can execute arbitrary code on your machine.
- make_dataset(X, y, *, processor=None)
Build a readout-ready dataset from raw inputs and classification targets.
- Parameters:
X (numpy.ndarray|torch.Tensor|list[Any]) – Two-dimensional feature matrix to transform into readout features.
y (numpy.ndarray|torch.Tensor|list[Any]) – One-dimensional classification targets aligned with
X.processor (merlin.core.merlin_processor.MerlinProcessor|None) – Optional processor used to evaluate the frozen quantum reservoir. If omitted,
reservoir.layer.processoris used when configured. If both are set, this argument wins and emits aUserWarning. If neither is set, the quantum layer is executed locally.
- Returns:
Dataset containing the transformed readout features on CPU and the integer classification targets.
- Return type:
- Raises:
RuntimeError – If
fit_reservoir()was not called first, ifXdoes not have the expected shape, or ifXandydo not contain the same number of samples.
- named_parameters(prefix='', recurse=True, remove_duplicate=True)
Yield named trainable parameters of the classifier.
- Parameters:
prefix (str) – Optional prefix prepended to the yielded parameter names.
recurse (bool) – Forwarded to
torch.nn.Module.named_parameters().remove_duplicate (bool) – Forwarded to
torch.nn.Module.named_parameters().
- Returns:
Iterator over the named readout parameters only.
- Return type:
- parameters(recurse=True)
Yield the trainable parameters of the classifier.
- Parameters:
recurse (bool) – Forwarded to
torch.nn.Module.parameters().- Returns:
Iterator over the readout parameters only. The reservoir parameters are frozen and therefore excluded.
- Return type:
- predict(X, *, processor=None)
Run the frozen reservoir and readout on a batch of raw inputs.
- Parameters:
X (numpy.ndarray|torch.Tensor|list[Any]) – Two-dimensional feature matrix to encode through the reservoir.
processor (merlin.core.merlin_processor.MerlinProcessor|None) – Optional processor used to evaluate the frozen quantum reservoir. If omitted,
reservoir.layer.processoris used when configured. If both are set, this argument wins and emits aUserWarning. If neither is set, the quantum layer is executed locally.
- Returns:
Output logits on CPU for each input sample.
- Return type:
- Raises:
RuntimeError – If
fit_reservoir()was not called first or ifXdoes not have the expected shape.
- sample(X, *, processor=None)
Alias for
fit_reservoir()provided for API consistency with scikit-learn pipeline conventions (estimator.sample(X)↔estimator.fit_reservoir(X)).- Return type:
- save(path)
Serialize the classifier state to disk.
- Parameters:
path (str|pathlib.Path) – Destination file used to store the configuration, frozen reservoir state, preprocessing statistics, cache, and readout parameters.
- Returns:
This method writes the checkpoint to disk in-place.
- Return type:
None
- to(*args, **kwargs)
Move the classifier and quantum-layer runtime state.
- Parameters:
*args (tuple[Any, ...]) – Positional arguments forwarded to
torch.nn.Module.to()andmerlin.algorithms.layer.QuantumLayer.to().**kwargs (dict[str, Any]) – Keyword arguments forwarded to
torch.nn.Module.to()andmerlin.algorithms.layer.QuantumLayer.to().
- Returns:
Updated classifier instance.
- Return type:
- Raises:
ValueError – If the requested dtype is not supported by Merlin modules.
- transform_reservoir(X, *, processor=None)
Transform raw inputs into standardized reservoir embeddings.
- Parameters:
X (numpy.ndarray|torch.Tensor|list[Any]) – Two-dimensional feature matrix to transform through the fitted reservoir preprocessing and frozen quantum layer.
processor (merlin.core.merlin_processor.MerlinProcessor|None) – Optional processor used to evaluate the frozen quantum reservoir. If omitted,
reservoir.layer.processoris used when configured. If both are set, this argument wins and emits aUserWarning. If neither is set, the quantum layer is executed locally.
- Returns:
Standardized quantum reservoir embeddings on CPU. The returned tensor does not include raw input features, even when
concatenate=True.- Return type:
- Raises:
RuntimeError – If
fit_reservoir()was not called first, ifXdoes not have the expected shape, or ifcache=Falseand quantum normalization has not yet been initialized from the fitted training data.