squlearn.qnn.QNNClassifier

class squlearn.qnn.QNNClassifier(encoding_circuit: EncodingCircuitBase, operator: ObservableBase | list[ObservableBase], executor: Executor, loss: LossBase, optimizer: OptimizerBase, param_ini: ndarray = None, param_op_ini: ndarray = None, batch_size: int = None, epochs: int = None, shuffle: bool = None, opt_param_op: bool = True, variance: float | Callable = None, shot_control: ShotControlBase = None, parameter_seed: int | None = 0, caching: bool = True, pretrained: bool = False, callback: Callable | str | None = 'pbar', primitive: str | None = None, **kwargs)

Quantum Neural Network for Classification.

This class implements a quantum neural network (QNN) for classification with a scikit-learn interface. A parameterized quantum circuit and a possibly parameterized operator are used as a ML model. They are trained according to a specified loss using the specified optimizer. Mini-batch training is possible.

Parameters:
  • encoding_circuit (EncodingCircuitBase) – The parameterized quantum circuit (PQC) part of the QNN. For a list of encoding circuits, check this list of implemented Encoding Circuits.

  • operator (Union[ObservableBase, list[ObservableBase]]) – The operator that is used in the expectation value of the QNN. Can be a list for multiple outputs. For a list of operators, check this list of implemented Operators.

  • executor (Executor) – Executor instance.

  • loss (LossBase) – The loss function to be optimized. Can also be combination of multiple loss functions.

  • optimizer (OptimizerBase) – The optimizer instance that is used to minimize the loss function.

  • param_ini (np.ndarray, default=None) – Initial values of the parameters of the PQC.

  • param_op_ini (np.ndarray, default=None) – Initial values of the parameters of the operator.

  • batch_size (int, default=None) – Number of data points in each batch in mini-batch training. Will only be used if optimizer is of type SGDMixin.

  • epochs (int, default=None) – Number of epochs of SGD to perform. Will only be used if optimizer is of type SGDMixin.

  • shuffle (bool, default=None) – If True, data points get shuffled before each epoch. Will only be used if optimizer is of type SGDMixin.

  • opt_param_op (bool, default=True) – If True, the operators parameters get optimized.

  • variance (Union[float, Callable], default=None) – The variance factor to be used. If it is None, the variance regularization will not be used. Else this determines the strength of the variance regularization.

  • parameter_seed (Union[int, None], default=0) – Seed for the random number generator for the parameter initialization, if param_ini or param_op_ini is None.

  • caching (bool, default=True) – If True, the results of the QNN are cached.

  • pretrained (bool, default=False) – Set to true if the supplied parameters are already trained.

  • callback (Union[Callable, str, None], default=None) – A callback for the optimization loop. Can be either a Callable, “pbar” (which uses a tqdm.tqdm process bar) or None. If None, the optimizers (default) callback will be used.

  • primitive (Union[str,None], default=None) – The primitive that is utilized in the qnn. Default primitive is the one specified in the executor initialization, if nothing is specified, the estimator will used. Possible values are "estimator" or "sampler".

See also

squlearn.qnn.QNNRegressor

Quantum Neural Network for Regression.

Example

from squlearn import Executor
from squlearn.encoding_circuit import ChebyshevRx
from squlearn.observables import SummedPaulis
from squlearn.qnn import QNNClassifier, SquaredLoss
from squlearn.optimizers import SLSQP
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

X, y = make_blobs(60, centers=2, random_state=0)
X = MinMaxScaler((-0.9, 0.9)).fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=42
)
clf = QNNClassifier(
    ChebyshevRx(4, 2, 2),
    SummedPaulis(4),
    Executor(),
    SquaredLoss(),
    SLSQP(),
    np.random.rand(16),
    np.random.rand(5)
)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

Methods:

fit(X, y, weights: ndarray = None) None

Fit a new model to data.

This method will reinitialize the models parameters and fit it to the provided data.

Parameters:
  • X – array-like or sparse matrix of shape (n_samples, n_features) Input data

  • y – array-like of shape (n_samples,) Labels

  • weights – Weights for each data point

get_metadata_routing()

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:

routing – A MetadataRequest encapsulating routing information.

Return type:

MetadataRequest

get_params(deep: bool = True) dict

Returns a dictionary of parameters for the current object.

Parameters:

deep – If True, includes the parameters from the base class.

Returns:

A dictionary of parameters for the current object.

Return type:

dict

partial_fit(X, y, weights: ndarray = None) None

Fit a model to data.

This method will update the models parameters to fit the provided data. It won’t reinitialize the models parameters.

Parameters:
  • X – array-like or sparse matrix of shape (n_samples, n_features) Input data

  • y – array-like of shape (n_samples,) Labels

  • weights – Weights for each data point

predict(X: ndarray) ndarray

Predict using the QNN.

Parameters:

X – The input data.

Returns:

The predicted values.

Return type:

np.ndarray

predict_proba(X: ndarray) ndarray

Return probabilities using the QNN.

Parameters:

X – The input data.

Returns:

The probabilities

Return type:

np.ndarray

score(X, y, sample_weight=None)

Return the mean accuracy on the given test data and labels.

In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.

Parameters:
  • X (array-like of shape (n_samples, n_features)) – Test samples.

  • y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True labels for X.

  • sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.

Returns:

score – Mean accuracy of self.predict(X) w.r.t. y.

Return type:

float

set_fit_request(*, weights: bool | None | str = '$UNCHANGED$') QNNClassifier

Request metadata passed to the fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:

weights (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for weights parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_params(**params) BaseQNN

Sets the hyper-parameters of the BaseQNN.

Parameters:

params – Hyper-parameters of the BaseQNN.

Returns:

updated BaseQNN

set_partial_fit_request(*, weights: bool | None | str = '$UNCHANGED$') QNNClassifier

Request metadata passed to the partial_fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to partial_fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to partial_fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:

weights (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for weights parameter in partial_fit.

Returns:

self – The updated object.

Return type:

object

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') QNNClassifier

Request metadata passed to the score method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:

sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.

Returns:

self – The updated object.

Return type:

object