Quantum Kernels#

FidelityQuantumKernel#

class FidelityQuantumKernel(encoder: BaseEncoder | None = None, n_qubits: int = 4, device: str = 'default.qubit', batch_size: int | None = None)[source]#

Bases: BaseEstimator

Fidelity-based quantum kernel matrix calculator.

Computes the Gram matrix where each entry is the fidelity (squared inner product) between quantum-encoded data points:

\(K[i, j] = |\langle \phi(x_i) | \phi(x_j) \rangle|^2\)

The quantum state \(|\phi(x)\rangle\) is prepared by the given encoder circuit.

This implements the quantum kernel approach from:

  • Havlíček et al. (2019), “Supervised learning with quantum-enhanced feature spaces” (Nature 567, 209-212).

  • Schuld & Killoran (2019), “Quantum machine learning in feature Hilbert spaces” (PRL 122, 040504).

  • Schuld, Bocharov, Svore & Wiebe (2018), “Circuit-centric quantum classifiers” (arXiv:1804.00633).

Mathematically, the quantum kernel is defined as:

\[K(x_i, x_j) = |\langle \phi(x_i) | \phi(x_j) \rangle|^2\]

where \(|\phi(x)\rangle = U_{\text{enc}}(x)|0^{\otimes n}\rangle\).

Parameters:
  • encoder (BaseEncoder, optional) – The quantum encoding circuit. If None, defaults to AngleEncoder().

  • n_qubits (int, default=4) – Number of qubits (only used if encoder is None).

  • device (str, default="default.qubit") – PennyLane device to use for simulation.

  • batch_size (int, optional) – Number of circuits to evaluate in parallel. If None, evaluates all.

encoder_#

Fitted encoder.

Type:

BaseEncoder

n_qubits_#

Number of qubits used.

Type:

int

Examples

>>> from psipose import FidelityQuantumKernel, AngleEncoder
>>> kernel = FidelityQuantumKernel(encoder=AngleEncoder(n_qubits=4))
>>> K = kernel.compute_matrix(X_train)
>>> # Use with sklearn SVC:
>>> from sklearn.svm import SVC
>>> svc = SVC(kernel="precomputed")
>>> svc.fit(K, y_train)
fit(X)[source]#

Fit the kernel by determining the encoder parameters.

Parameters:

X (array-like, shape (n_samples, n_features)) – Training data.

Returns:

self

Return type:

FidelityQuantumKernel

compute_matrix(X, Y=None)[source]#

Compute the kernel matrix.

Parameters:
  • X (array-like, shape (n_samples_X, n_features)) – First set of vectors.

  • Y (array-like, shape (n_samples_Y, n_features), optional) – Second set of vectors. If None, uses X.

Returns:

K – Kernel matrix.

Return type:

ndarray, shape (n_samples_X, n_samples_Y)

QSVC#

class QSVC(*, n_qubits: int = 4, encoder: BaseEncoder | None = None, device: str = 'default.qubit', C: float = 1.0, kernel: str = 'precomputed', degree: int = 3, gamma: float | str = 'scale', coef0: float = 0.0, shrinking: bool = True, probability: bool = False, tol: float = 0.001, cache_size: float = 200, class_weight: str | dict | None = None, verbose: bool = False, max_iter: int = -1, decision_function_shape: str = 'ovr', break_ties: bool = False, random_state: int | None = None)[source]#

Bases: BaseEstimator, ClassifierMixin

Quantum Support Vector Classifier using a fidelity quantum kernel.

Combines a quantum feature map (encoder) with a classical SVM. The quantum kernel computes similarity as \(K(x_i, x_j) = |\langle \phi(x_i)|\phi(x_j)\rangle|^2\).

This implements the quantum kernel approach from:

  • Havlíček et al. (2019), “Supervised learning with quantum-enhanced feature spaces” (Nature 567, 209-212). Introduces quantum kernels via the fidelity between quantum-encoded feature maps, combined with classical SVM.

  • Schuld & Killoran (2019), “Quantum machine learning in feature Hilbert spaces” (PRL 122, 040504). Frames quantum input encoding as a nonlinear map to Hilbert space and shows how quantum kernels can be used with classical ML methods.

  • Yang, Awan & Vall-Llosera (2019), “Support Vector Machines on Noisy Intermediate Scale Quantum Computers” (arXiv:1909.11988). Adapts SVM for NISQ devices using quantum kernel matrices.

Mathematically, the quantum kernel is defined as:

\[K(x_i, x_j) = |\langle \phi(x_i)|\phi(x_j)\rangle|^2 = |\langle 0^{\otimes n}| U_{\text{enc}}^\dagger(x_j) U_{\text{enc}}(x_i) |0^{\otimes n}\rangle|^2\]

where \(|\phi(x)\rangle = U_{\text{enc}}(x)|0^{\otimes n}\rangle\) is the quantum feature map implemented by the encoder.

The training kernel matrix \(K_{\text{train}}\) is computed and passed to sklearn.svm.SVC with kernel="precomputed".

Parameters:
  • n_qubits (int, default=4) – Number of qubits for the quantum feature map.

  • encoder (BaseEncoder, optional) – Data encoding circuit. If None, defaults to AngleEncoder().

  • device (str, default="default.qubit") – PennyLane device name for simulation.

  • C (float, default=1.0) – Regularization parameter for SVC.

  • kernel ({"precomputed"}, default="precomputed") – Kernel type. Must be “precomputed” (always uses quantum kernel).

  • degree (int, default=3) – Degree for polynomial kernel (ignored for precomputed).

  • gamma (float or {"scale", "auto"}, default="scale") – Kernel coefficient for RBF/poly/sigmoid (ignored for precomputed).

  • coef0 (float, default=0.0) – Independent term in poly/sigmoid kernel (ignored for precomputed).

  • shrinking (bool, default=True) – Whether to use shrinking heuristic in SVC.

  • probability (bool, default=False) – Whether to enable probability estimates.

  • tol (float, default=1e-3) – Tolerance for stopping criterion.

  • cache_size (float, default=200) – Kernel cache size in MB.

  • class_weight (dict or "balanced", optional) – Class weights for handling imbalanced datasets.

  • verbose (bool, default=False) – Enable verbose output.

  • max_iter (int, default=-1) – Maximum iterations for SVC solver (-1 = no limit).

  • decision_function_shape ({"ovr", "ovo"}, default="ovr") – Shape of decision function for multi-class.

  • break_ties (bool, default=False) – Break ties in multi-class classification.

  • random_state (int, optional) – Random seed for reproducibility.

classes_#

Class labels.

Type:

ndarray

n_features_in_#

Number of features seen during fit.

Type:

int

n_classes_#

Number of classes.

Type:

int

kernel_#

Fitted quantum kernel instance.

Type:

FidelityQuantumKernel

K_train_#

Training kernel matrix.

Type:

ndarray, shape (n_samples, n_samples)

svc_#

Fitted sklearn SVC instance.

Type:

SVC

support_vectors_#

Support vectors (from SVC).

Type:

ndarray

dual_coef_#

Coefficients of support vectors in decision function (from SVC).

Type:

ndarray

intercept_#

Constants in decision function (from SVC).

Type:

ndarray

X_train_#

Training data (stored for prediction).

Type:

ndarray

Examples

>>> from psipose import QSVC
>>> from sklearn.datasets import make_moons
>>> X, y = make_moons(n_samples=100, noise=0.1, random_state=42)
>>> clf = QSVC(n_qubits=2, random_state=42)
>>> clf.fit(X, y)
QSVC(n_qubits=2, random_state=42)
>>> y_pred = clf.predict(X)
fit(X, y, sample_weight=None)[source]#

Fit the quantum SVM classifier.

Parameters:
  • X (array-like, shape (n_samples, n_features)) – Training data.

  • y (array-like, shape (n_samples,)) – Target labels.

  • sample_weight (array-like, shape (n_samples,), optional) – Sample weights.

Returns:

self – Fitted estimator.

Return type:

QSVC

predict(X)[source]#

Predict class labels for samples.

Parameters:

X (array-like, shape (n_samples, n_features)) – Input samples.

Returns:

y – Predicted class labels.

Return type:

ndarray, shape (n_samples,)

predict_proba(X)[source]#

Predict class probabilities.

Requires probability=True during initialization.

Parameters:

X (array-like, shape (n_samples, n_features)) – Input samples.

Returns:

proba – Class probabilities.

Return type:

ndarray, shape (n_samples, n_classes)

decision_function(X)[source]#

Compute decision function for samples.

Parameters:

X (array-like, shape (n_samples, n_features)) – Input samples.

Returns:

decision – Decision function values.

Return type:

ndarray, shape (n_samples,) or (n_samples, n_classes)

set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') QSVC#

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

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

The QSVC uses a quantum kernel matrix computed via fidelity between encoded quantum states, then delegates to sklearn.svm.SVC.