squlearn.qnn.QNNRegressor
- class squlearn.qnn.QNNRegressor(encoding_circuit: EncodingCircuitBase, operator: ObservableBase | list[ObservableBase], executor: Executor, loss: QNNLossBase, 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', **kwargs)
Quantum Neural Network for Regression.
This class implements a quantum neural network (QNN) for regression 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 (QNNLossBase) – 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.tqdmprocess bar) or None. If None, the optimizers (default) callback will be used.
See also
squlearn.qnn.QNNClassifier : Quantum Neural Network for Classification.
Example
import numpy as np from squlearn import Executor from squlearn.encoding_circuit import ChebyshevRx from squlearn.observables import IsingHamiltonian from squlearn.qnn import QNNRegressor, SquaredLoss from squlearn.optimizers import SLSQP from sklearn.model_selection import train_test_split X, y = np.arange(0.1, 0.9, 0.01), np.log(np.arange(0.1, 0.9, 0.01)) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42 ) reg = QNNRegressor( ChebyshevRx(4, 1), IsingHamiltonian(4, I="S", Z="S", ZZ="S"), Executor(), SquaredLoss(), SLSQP(), np.random.rand(16), np.random.rand(5) ) reg.fit(X_train, y_train) y_pred = reg.predict(X_test[:5])
Differential Evolution Solver Example
import numpy as np import sympy as sp import matplotlib.pyplot as plt from squlearn import Executor from squlearn.encoding_circuit import KyriienkoEncodingCircuit from squlearn.observables import SummedPaulis from squlearn.qnn import QNNRegressor, ODELoss from squlearn.qnn.util import get_lr_decay from squlearn.optimizers import Adam t, y, dydt, = sp.symbols("t y dydt") eq = 20 * sp.exp(-20 * t * 0.1) * sp.sin(20 * t) + 20 * 0.1 * y + dydt initial_values = [1.0] loss_ODE = ODELoss( eq, symbols_involved_in_ODE=[t, y, dydt], initial_values=initial_values, boundary_handling="pinned", ) circuit = KyriienkoEncodingCircuit( num_qubits=6, encoding_style="chebyshev_tower", variational_arrangement="HEA", num_encoding_layers=1, num_variational_layers=5, ) observable = SummedPaulis(6, include_identity=False) param_observable = observable.generate_initial_parameters(seed=1) param_initial = circuit.generate_initial_parameters(seed=1, num_features=1) ode_regressor = QNNRegressor( circuit, observable, Executor("pennylane"), loss_ODE, Adam(options={"maxiter": 150, "tol": 0.00009, "lr": get_lr_decay(0.05, 0.02, 150)}), param_initial, param_observable, opt_param_op=False, )
Methods:
- dump(target: str | IO[bytes]) None
Serializes the model object to a file or file-like object. :param target: The target file path or file-like object where the model will be serialized. :type target: Union[str, IO[bytes]]
- 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
MetadataRequestencapsulating 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
- classmethod load(source: str | IO[bytes], executor: Executor) T
Deserializes the model object from a file or file-like object, injecting the provided Executor. :param source: The source file path or file-like object from which the model will be deserialized. :type source: Union[str, IO[bytes]] :param executor: The Executor instance to be injected into the deserialized model. :type executor: Executor
- Returns:
The deserialized model object with the injected Executor.
- 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 or sparse matrix 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
- score(X, y, sample_weight=None)
Return coefficient of determination on test data.
The coefficient of determination, \(R^2\), is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares
((y_true - y_pred)** 2).sum()and \(v\) is the total sum of squares((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.- Parameters:
X (array-like of shape (n_samples, n_features)) – Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape
(n_samples, n_samples_fitted), wheren_samples_fittedis the number of samples used in the fitting for the estimator.y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True values for X.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
- Returns:
score – \(R^2\) of
self.predict(X)w.r.t. y.- Return type:
float
Notes
The \(R^2\) score used when calling
scoreon a regressor usesmultioutput='uniform_average'from version 0.23 to keep consistent with default value ofr2_score(). This influences thescoremethod of all the multioutput regressors (except forMultiOutputRegressor).
- set_fit_request(*, weights: bool | None | str = '$UNCHANGED$') QNNRegressor
Configure whether metadata should be requested to be passed to the
fitmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- Parameters:
weights (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
weightsparameter infit.- 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$') QNNRegressor
Configure whether metadata should be requested to be passed to the
partial_fitmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topartial_fitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topartial_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.
- Parameters:
weights (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
weightsparameter inpartial_fit.- Returns:
self – The updated object.
- Return type:
object
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') QNNRegressor
Configure whether metadata should be requested to be passed to the
scoremethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed toscoreif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it toscore.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.
- Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
sample_weightparameter inscore.- Returns:
self – The updated object.
- Return type:
object