squlearn.kernel.ml
.QSVC
- class squlearn.kernel.ml.QSVC(quantum_kernel: KernelMatrixBase | str | None = None, **kwargs)
Quantum Support Vector Classification
This class is a wrapper of
sklearn.svm.SVC
. It uses a quantum kernel matrix to replace the kernel matrix in thesklearn.svm.SVC
class. The parameters of the parent class can be adjusted via**kwargs
. See the documentation there for additional information about the standard SVC parameters. The scikit-learn SVC 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.SVC
class such as the regularization parametersC
(float, default=1.0). 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.QSVR
Quantum Support Vector Regression
Example
import numpy as np from sklearn.datasets import make_moons from sklearn.model_selection import train_test_split from squlearn import Executor from squlearn.encoding_circuit import HubregtsenEncodingCircuit from squlearn.kernel.ml.qsvc import QSVC from squlearn.kernel.matrix import ProjectedQuantumKernel encoding_circuit = HubregtsenEncodingCircuit(num_qubits=2, num_features=2, num_layers=2) kernel = ProjectedQuantumKernel( encoding_circuit, executor=Executor(), initial_parameters=np.random.rand(encoding_circuit.num_parameters) ) X, y = make_moons(n_samples=100, noise=0.3, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) qsvc = QSVC(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:
- decision_function(X)
Evaluate the decision function for the samples in X.
- Parameters:
X (array-like of shape (n_samples, n_features)) – The input samples.
- Returns:
X – Returns the decision function of the sample for each class in the model. If decision_function_shape=’ovr’, the shape is (n_samples, n_classes).
- Return type:
ndarray of shape (n_samples, n_classes * (n_classes-1) / 2)
Notes
If decision_function_shape=’ovo’, the function values are proportional to the distance of the samples X to the separating hyperplane. If the exact distances are required, divide the function values by the norm of the weight vector (
coef_
). See also this question for further details. If decision_function_shape=’ovr’, the decision function is a monotonic transformation of ovo decision function.
- fit(X, y)
Fit the QSVC 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 QSVC 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 classification on samples in X.
For an one-class model, +1 or -1 is returned.
- Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples_test, n_samples_train)) – For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train).
- Returns:
y_pred – Class labels for samples in X.
- Return type:
ndarray of shape (n_samples,)
- predict_log_proba(X)
Compute log probabilities of possible outcomes for samples in X.
The model need to have probability information computed at training time: fit with attribute probability set to True.
- Parameters:
X (array-like of shape (n_samples, n_features) or (n_samples_test, n_samples_train)) – For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train).
- Returns:
T – Returns the log-probabilities of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
- Return type:
ndarray of shape (n_samples, n_classes)
Notes
The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets.
- predict_proba(X)
Compute probabilities of possible outcomes for samples in X.
The model needs to have probability information computed at training time: fit with attribute probability set to True.
- Parameters:
X (array-like of shape (n_samples, n_features)) – For kernel=”precomputed”, the expected shape of X is (n_samples_test, n_samples_train).
- Returns:
T – Returns the probability of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.
- Return type:
ndarray of shape (n_samples, n_classes)
Notes
The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets.
- score(X, y, sample_weight=None)
Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Test samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True labels for X.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
- Returns:
score – Mean accuracy of
self.predict(X)
w.r.t. y.- Return type:
float
- set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') QSVC
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 QSVC hyper-parameters.
- Parameters:
params – Hyper-parameters and their values, e.g.
num_qubits=2
.
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') QSVC
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