squlearn.kernel.ml
.QGPR
- class squlearn.kernel.ml.QGPR(quantum_kernel: KernelMatrixBase | str | None = None, sigma: float = 1e-06, normalize_y: bool = False, full_regularization: bool = True, **kwargs)
Quantum Gaussian Process Regression (QGPR).
This class implements the Gaussian process regression analogous to scikit-learn but is not a wrapper. The implementation is based on Algorithm 2.1 of Ref. [1]. Additional arguments can be set via
**kwargs
.- Parameters:
quantum_kernel (Optional[Union[KernelMatrixBase, str]]) – The quantum kernel matrix to be used for the Gaussian process (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 for fit() method and total Gram matrix within predict(). This is particularly useful when storing quantum kernel matrices from real backends to numpy arrays.
sigma – (float), default=1.e-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.
normalize_y – (bool), default=False: Whether to normalize the target values y by removing the mean and scaling to unit-variance. This is recommended for cases where zero-mean, unit-variance priors are used. Note that, in this implementation, the normalization is reversed before the GP predictions are reported.
full_regularization – (bool), default=True: enable full gram matrix regularization.
**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.
See also
squlearn.kernel.ml.QKRR
Quantum Gaussian Process regression.
squlearn.kernel.ml.QSVR
Quantum Support Vector regression.
References
[2]: F.Rapp, M.Roth “Quantum Gaussian Process Regression for Bayesian Optimization”, https://link.springer.com/article/10.1007/s42484-023-00138-9.
Example
from squlearn import Executor from squlearn.encoding_circuit import HubregtsenEncodingCircuit from squlearn.kernel.matrix import FidelityKernel from squlearn.kernel.ml import QGPR enc_circ = HubregtsenEncodingCircuit(num_qubits=num_qubits, num_features=num_features, num_layers=2) q_kernel = FidelityKernel(encoding_circuit=enc_circ, executor=Executor()) q_kernel.assign_parameters(np.random.rand(enc_circ.num_parameters)) qgpr_ansatz = QGPR(quantum_kernel=q_kernel) qgpr_ansatz.fit(sample_train,label_train) qgpr_ansatz.predict(sample_test)
Methods:
- calculate_cov_and_mean()
Calculates the mean and covariance of the QGPR model
- fit(X, y)
Fit Quantum Gaussian process regression model. The fit method of the QGPR class just calculates the training kernel matrix. Depending on the choice of normalize_y the target values are normalized.
- Parameters:
X – array-like or sparse matrix of shape (n_samples, n_features) The training data. 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.
- 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 hyper-parameters and their values of the QGPR method.
- Parameters:
deep (bool) – If True, also the parameters for contained objects are returned (default=True).
- Returns:
Dictionary with hyper-parameters and values.
- predict(X: ndarray, return_std=False, return_cov=False)
Predict using the Quantum Gaussian process regression model. Depending on the choice of regularization the quantum kernel matrix is regularized. The respective solution of the QKRR problem is obtained by solving the linear system using scipy’s Cholesky decomposition for providing numerical stability Optionally also returns its standard deviation (return_std=True) or covariance (return_cov=True). Note that at most one of the two can be requested.
- Parameters:
X – The test data of shape (n_samples, n_features). If quantum_kernel == “precomputed”, this is the precomputed Gram matrix instead, which has to be of shape np.block[[K_train, K_testtrain.T], [K_testtrain, K_test]]
return_std – (bool), default=True: Whether to return the standard deviation of the prediction
return_cov – (bool), default=False: Whether to return the covariance of the prediction
- Returns:
- The predicted values of shape (n_samples,)
Mean of predictive distribution at query points.
- y_std: The standard deviation of the prediction of shape (n_samples,), optional
Standard deviation of predictive distribution at query points. Only returned when return_std is True.
- y_cov: The covariance of the prediction of shape (n_samples, n_samples), optional
Covariance of joint predictive distribution a query points. Only returned when return_cov is True.
- Return type:
y_mean
- 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)
, wheren_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 usesmultioutput='uniform_average'
from version 0.23 to keep consistent with default value ofr2_score()
. This influences thescore
method of all the multioutput regressors (except forMultiOutputRegressor
).
- set_params(**params) None
Sets value of the encoding circuit hyper-parameters.
- Parameters:
params – Hyper-parameters and their values, e.g.
num_qubits=2
.
- set_predict_request(*, return_cov: bool | None | str = '$UNCHANGED$', return_std: bool | None | str = '$UNCHANGED$') QGPR
Request metadata passed to the
predict
method.Note that this method is only relevant if
enable_metadata_routing=True
(seesklearn.set_config()
). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True
: metadata is requested, and passed topredict
if provided. The request is ignored if metadata is not provided.False
: metadata is not requested and the meta-estimator will not pass it topredict
.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:
return_cov (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
return_cov
parameter inpredict
.return_std (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
return_std
parameter inpredict
.
- Returns:
self – The updated object.
- Return type:
object
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') QGPR
Request metadata passed to the
score
method.Note that this method is only relevant if
enable_metadata_routing=True
(seesklearn.set_config()
). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True
: metadata is requested, and passed toscore
if 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.
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 inscore
.- Returns:
self – The updated object.
- Return type:
object