squlearn.kernel.ml
.QSVR
- class squlearn.kernel.ml.QSVR(quantum_kernel: KernelMatrixBase | str | None = None, **kwargs)
Quantum Support Vector Regression
This class is a wrapper of
sklearn.svm.SVR
. It uses a quantum kernel matrix to replace the kernel matrix in thesklearn.svm.SVR
class. The parameters of the parent class can be adjusted via**kwargs
. See the documentation there for additional information about the standard SVR parameters. The scikit-learn SVR has kernel specific arguments that are omitted here because they do not apply to the quantum kernels. These arekernel
gamma
degree
coef0
- Parameters:
quantum_kernel (Union[KernelMatrixBase, str]) – The quantum kernel matrix to be used in the SVC. 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.
**kwargs – Possible arguments can be obtained by calling
get_params()
. Notable examples are parameters of thesklearn.svm.SVR
class such as the regularization parametersC
(float, default=1.0) or epsilon (float, default=0.1). Additionally, properties of the underlying encoding circuit can be adjusted via kwargs such as the number of qubits (num_qubits
), or (if supported) the number of layers (num_layers
).
See also
squlearn.kernel.ml.QSVC
Quantum Support Vector Classification
Example
import numpy as np from sklearn.model_selection import train_test_split from squlearn import Executor from squlearn.encoding_circuit import HubregtsenEncodingCircuit from squlearn.kernel.ml.qsvr import QSVR from squlearn.kernel.matrix import ProjectedQuantumKernel encoding_circuit = HubregtsenEncodingCircuit(num_qubits=2, num_features=1, num_layers=2) kernel = ProjectedQuantumKernel( encoding_circuit, executor=Executor(), initial_parameters=np.random.rand(encoding_circuit.num_parameters)) X = np.linspace(0, np.pi, 100) y = np.sin(X) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) qsvc = QSVR(quantum_kernel=kernel) qsvc.fit(X_train, y_train) print(f"The score on the test set is {qsvc.score(X_test, y_test)}")
Methods:
- fit(X, y, sample_weight=None)
Fit the QSVR model according to the given training data.
- Parameters:
X (array-like, sparse matrix) – Training data of shape (n_samples, n_features) or (n_samples, n_samples) Training vectors, where n_samples is the number of samples and n_features is the number of features. For kernel=”precomputed”, the expected shape of X is (n_samples, n_samples).
y (array-like) – Lables with shape (n_samples,)
sample_weight (array-like) – Weights of shape (n_samples,), default=None Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points.
- 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 QSVR class.
- Parameters:
deep (bool) – If True, also the parameters for contained objects are returned (default=True).
- Returns:
Dictionary with hyper-parameters and values.
- predict(X)
Perform regression on samples in X.
For an one-class model, +1 (inlier) or -1 (outlier) is returned.
- Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train).
- Returns:
y_pred – The predicted values.
- Return type:
ndarray of shape (n_samples,)
- 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_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') QSVR
Request metadata passed to the
fit
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 tofit
if 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.
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 infit
.- Returns:
self – The updated object.
- Return type:
object
- set_params(**params) None
Sets value of the QSVR hyper-parameters.
- Parameters:
params – Hyper-parameters and their values, e.g.
num_qubits=2
.
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') QSVR
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