squlearn.kernel.QSVR

class squlearn.kernel.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 the sklearn.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 are

  • kernel

  • 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 the sklearn.svm.SVR class such as the regularization parameters C (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.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.qsvr import QSVR
from squlearn.kernel.lowlevel_kernel import ProjectedQuantumKernel

encoding_circuit = HubregtsenEncodingCircuit(num_qubits=2, 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:

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, 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.

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.

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 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), 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_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') QSVR

Configure whether metadata should be requested to be passed to the fit method.

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 (see sklearn.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 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.

Parameters:

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

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

Configure whether metadata should be requested to be passed to the score method.

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 (see sklearn.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 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.

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