custom
eigenkit.torch.estimators.custom
Estimators built from blocks and observables that you supply.
They wrap a list of Block objects and an observables specification into a
Circuit, and then add a small classical head (an nn.Linear layer that gives
the classification logits or a single regression output). When the number of
features of the data differs from the number of inputs that the circuit expects,
an nn.Linear adapter is added in front.
eigenkit.torch.estimators.custom.CustomQuantumClassifier
Bases: ModelAccessMixin, BaseQuantumClassifier
Classifier compatible with scikit-learn, built from your own list of blocks.
Give any sequence of blocks (Encoding, Variational, StrongVariational,
Reuploading, or a custom block from CircuitBuilder.to_block()) and an
observables specification, as for Circuit. The estimator connects them
into a quantum layer followed by a classical nn.Linear head, and trains the
whole model with the cross-entropy loss. When the number of features of the
data differs from the number of inputs that the circuit expects, an
nn.Linear adapter is added in front automatically.
The number of inputs of the circuit is read from the first Encoding or
Reuploading block, so blocks must contain one. A circuit whose inputs
enter through another block, such as the UnaryLoader of
eigenkit.orthogonal, is not supported yet and raises a ValueError in
fit(), even with in_features given.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
blocks
|
list[Block]
|
The list of blocks, in order. |
required |
observables
|
ObservableLike
|
The observables. It takes the same options as
|
None
|
provider
|
ProviderSpec
|
The backend. Default: |
'numpy'
|
in_features
|
int | None
|
The number of features of the data. If None, it is inferred
from the first |
None
|
n_classes
|
int | None
|
The number of output classes. If None, it is inferred from the training labels. |
None
|
lr
|
float
|
The learning rate of the optimiser. |
0.01
|
optimizer
|
str
|
The name of the optimiser. The supported names are |
'adam'
|
optimizer_kwargs
|
dict | None
|
Extra keyword arguments passed to the optimiser. |
None
|
epochs
|
int
|
The number of training epochs. |
50
|
batch_size
|
int
|
The size of each mini-batch. |
32
|
show_progress
|
bool
|
If True, a tqdm progress bar is shown. |
True
|
random_state
|
int | None
|
The seed. |
42
|
Attributes:
| Name | Type | Description |
|---|---|---|
train_losses_ |
The cross-entropy loss of each epoch, set by |
|
validation_losses_ |
The validation cross-entropy loss of each epoch, set
by |
Example
import numpy as np
from eigenkit import (
CustomQuantumClassifier, Encoding, Variational, all_z,
)
rng = np.random.default_rng(0)
X_train, X_test = rng.uniform(0, np.pi, (20, 4)), rng.uniform(0, np.pi, (5, 4))
y_train = np.array([0, 1] * 10)
blocks = [
Encoding(in_features=4, rotation="RY"),
Variational(depth=2, rotation="RY"),
]
model = CustomQuantumClassifier(
blocks=blocks, observables=all_z(4), epochs=10,
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
fit(X, y, X_val=None, y_val=None)
Fit the classifier on training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
The samples, of shape |
required |
y
|
ndarray
|
The class labels, of shape |
required |
X_val
|
ndarray | None
|
Optional validation samples, used to compute the validation loss of each epoch. |
None
|
y_val
|
ndarray | None
|
Optional validation labels, used to compute the validation loss of each epoch. |
None
|
Returns:
| Type | Description |
|---|---|
'CustomQuantumClassifier'
|
This estimator, so that calls can be chained. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
load(path, *, provider=None, trusted=False)
classmethod
Load a fitted model from a .eigenkit bundle.
Loading a bundle does not unpickle anything, unless you pass
trusted=True for a bundle saved before eigenkit 1.3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The path of the bundle. |
required |
provider
|
ProviderSpec | None
|
A provider that replaces the saved one. |
None
|
trusted
|
bool
|
Load a bundle saved before eigenkit 1.3 by |
False
|
Returns:
| Type | Description |
|---|---|
'BaseQuantumEstimator'
|
The loaded estimator. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the method is called on a subclass and the bundle holds
a different class. |
SerializationError
|
If the bundle holds joblib pickles and |
predict(X)
Predict the class labels of X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
The samples, of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
One prediction for each sample. |
predict_proba(X)
Predict the probability of each class, with a softmax over the logits.
It returns a float32 array of shape (n_samples, n_classes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
The samples, of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The probabilities, of shape |
save(path)
Save a fitted model to a .eigenkit bundle.
A bundle holds JSON, NumPy arrays without pickle, PyTorch weights and,
for models built on scikit-learn objects (QSVC, QSVR, the reservoir
classifier), those objects serialized with skops. None of them is a
pickle, so loading a bundle does not run code from it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The path of the bundle. The suffix |
required |
eigenkit.torch.estimators.custom.CustomQuantumRegressor
Bases: ModelAccessMixin, BaseQuantumRegressor
Regressor compatible with scikit-learn, built from your own list of blocks.
It is the regression counterpart of
CustomQuantumClassifier.
It wraps your quantum Circuit with an nn.Linear head of one neuron, trained
with the chosen regression loss. An nn.Linear input adapter is added when the
number of features of the data differs from the number of inputs of the
circuit.
As for the classifier, the number of inputs of the circuit is read from the
first Encoding or Reuploading block, so blocks must contain one; a
UnaryLoader is not supported yet and raises a ValueError in fit().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
blocks
|
list[Block]
|
The list of blocks, in order. |
required |
observables
|
ObservableLike
|
The observables. It takes the same options as
|
None
|
provider
|
ProviderSpec
|
The backend. Default: |
'numpy'
|
in_features
|
int | None
|
The number of features of the data. If None, it is inferred
from the first |
None
|
lr
|
float
|
The learning rate of the optimiser. |
0.01
|
optimizer
|
str
|
The name of the optimiser: |
'adam'
|
optimizer_kwargs
|
dict | None
|
Extra keyword arguments passed to the optimiser. |
None
|
epochs
|
int
|
The number of training epochs. |
50
|
batch_size
|
int
|
The size of each mini-batch. |
32
|
loss_func
|
str
|
The regression loss: |
'mse'
|
huber_delta
|
float
|
The threshold of the Huber loss. |
1.0
|
huber_reduction
|
str
|
The reduction of the Huber loss: |
'mean'
|
show_progress
|
bool
|
If True, a tqdm progress bar is shown. |
True
|
random_state
|
int | None
|
The seed. |
42
|
Attributes:
| Name | Type | Description |
|---|---|---|
train_losses_ |
The training loss of each epoch, set by |
|
validation_losses_ |
The validation loss of each epoch, set by |
fit(X, y, X_val=None, y_val=None)
Fit the regressor on training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
The samples, of shape |
required |
y
|
ndarray
|
The real-valued targets, of shape |
required |
X_val
|
ndarray | None
|
Optional validation samples, used to compute the validation loss of each epoch. |
None
|
y_val
|
ndarray | None
|
Optional validation targets, used to compute the validation loss of each epoch. |
None
|
Returns:
| Type | Description |
|---|---|
'CustomQuantumRegressor'
|
This estimator, so that calls can be chained. |
load(path, *, provider=None, trusted=False)
classmethod
Load a fitted model from a .eigenkit bundle.
Loading a bundle does not unpickle anything, unless you pass
trusted=True for a bundle saved before eigenkit 1.3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The path of the bundle. |
required |
provider
|
ProviderSpec | None
|
A provider that replaces the saved one. |
None
|
trusted
|
bool
|
Load a bundle saved before eigenkit 1.3 by |
False
|
Returns:
| Type | Description |
|---|---|
'BaseQuantumEstimator'
|
The loaded estimator. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the method is called on a subclass and the bundle holds
a different class. |
SerializationError
|
If the bundle holds joblib pickles and |
predict(X)
Predict the continuous targets of X. It returns a float32 array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
The samples, of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
One prediction for each sample. |
save(path)
Save a fitted model to a .eigenkit bundle.
A bundle holds JSON, NumPy arrays without pickle, PyTorch weights and,
for models built on scikit-learn objects (QSVC, QSVR, the reservoir
classifier), those objects serialized with skops. None of them is a
pickle, so loading a bundle does not run code from it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The path of the bundle. The suffix |
required |