squlearn.kernel.ml.QKRR

class squlearn.kernel.ml.QKRR(quantum_kernel: KernelMatrixBase | str | None = None, alpha: float | ndarray = 1e-06, **kwargs)

Quantum Kernel Ridge Regression.

This class implements the Quantum Kernel Ridge Regression analogous to KRR [1] in scikit-learn but is not a wrapper. Read more about the theoretical background of KRR in, e.g., the scikit-learn user guide. Additional arguments can be set via **kwargs.

Parameters:
  • quantum_kernel (Optional[Union[KernelMatrixBase, str]]) – The quantum kernel matrix to be used in the KRR pipeline (either a fidelity quantum kernel (FQK) or projected quantum kernel (PQK) must be provided). By setting quantum_kernel=”precomputed”, X is assumed to be a kernel matrix (train and test-train). This is particularly useful when storing quantum kernel matrices from real backends to numpy arrays.

  • alpha (Union[float, np.ndarray], default=1.0e-6) – Hyperparameter for the regularization strength; must be a positive float. This regularization improves the conditioning of the problem and assure the solvability of the resulting linear system. Larger values specify stronger regularization, cf., e.g., Ref. [2]

  • **kwargs – Keyword arguments for the quantum kernel matrix, possible arguments can be obtained by calling get_params(). Can be used to set for example the number of qubits (num_qubits=), or (if supported) the number of layers (num_layers=) of the underlying encoding circuit.

Attributes:

dual_coeff_(np.ndarray) :

Array containing the weight vector in kernel space

k_train (np.ndarray) :

Training kernel matrix of shape (n_train, n_train) which is available after calling the fit procedure

k_testtrain (np.ndarray) :

Kernel matrix of shape (n_test, n_train) which is evaluated at the predict step

See also

squlearn.kernel.ml.QGPR

Quantum Gaussian Process regression.

squlearn.kernel.ml.QSVR

Quantum Support Vector regression.

References

[1] Kevin P. Murphy “Machine Learning: A Probabilistic Perspective”, The MIT Press chapter 14.4.3, pp. 493-493

[2] https://en.wikipedia.org/wiki/Ridge_regression

Example

from squlearn import Executor
from squlearn.encoding_circuit import ChebyshevPQC
from squlearn.kernel.matrix import ProjectedQuantumKernel
from squlearn.kernel.ml import QKRR

enc_circ = ChebyshevPQC(num_qubits=4, num_features=1, num_layers=2)
q_kernel_pqk = ProjectedQuantumKernel(
    encoding_circuit=enc_circ,
    executor=Executor(),
    measurement="XYZ",
    outer_kernel="gaussian",
    initial_parameters=param,
    gamma=2.0
)
qkrr_pqk = QKRR(quantum_kernel=q_kernel_pqk, alpha=1e-5)
qkrr_pqk.fit(x_train.reshape(-1, 1), y_train)
y_pred_pqk = qkrr_pqk.predict(x.reshape(-1, 1))

Methods:

fit(X, y)

Fit the Quantum Kernel Ridge regression model.

Depending on whether regularization is set, the training kernel matrix is pre-processed accordingly prior to the actual fitting step is performed. The respective solution of the QKRR problem is obtained by solving the linear system using scipy’s Cholesky decomposition for providing numerical stability.

Parameters:
  • X – array-like or sparse matrix of shape (n_samples, n_features) If quantum_kernel == “precomputed” this is instead a precomputed training kernel matrix of shape (n_samples, n_samples).

  • y – array-like of shape (n_samples,) Target values or labels

Returns:

Returns an instance of self.

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 hyperparameters and their values of the QKRR method.

Parameters:

deep (bool) – If True, also the parameters for contained objects are returned (default=True).

Returns:

Dictionary with hyperparameters and values.

predict(X: ndarray) ndarray

Predict using the Quantum Kernel Ridge model.

Parameters:

X (np.ndarray) – Samples of data of shape (n_samples, n_features) on which QKRR model makes predictions. If quantum_kernel == “precomputed” this is instead a precomputed (test-train) kernel matrix of shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting.

Returns:

Returns predicted labels (at X) of shape (n_samples,)

Return type:

np.ndarray

score(X, y, sample_weight=None)

Return the coefficient of determination of the prediction.

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), where n_samples_fitted is 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 score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score(). This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params) None

Sets value of the encoding circuit hyperparameters.

Parameters:

params – Hyperparameters and their values, e.g. num_qubits=2.

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

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