Estimators#
VQC Classifier#
- class VQCClassifier(n_qubits: int = 4, encoder: BaseEncoder | None = None, ansatz: BaseAnsatz | None = None, optimizer: str | Callable = 'adam', learning_rate: float = 0.01, n_iter: int = 100, batch_size: int | None = None, random_state: int | None = None, device: str = 'default.qubit')[source]#
Bases:
QuantumEstimator,ClassifierMixinVariational Quantum Classifier.
A quantum classifier that uses a parameterized quantum circuit to make predictions. Follows the scikit-learn API.
For binary classification, a single quantum circuit is trained. For multi-class classification (3+ classes), uses a one-vs-rest strategy: trains one binary classifier per class.
This implements the variational quantum classifier from:
Farhi & Neven (2018), “Classification with Quantum Neural Networks on Near Term Processors” (arXiv:1802.06002). Introduces QNNs with parametrized unitaries and Pauli-Z measurements for binary classification.
Schuld, Bocharov, Svore & Wiebe (2018), “Circuit-centric quantum classifiers” (arXiv:1804.00633). Uses amplitude encoding and variational circuits with analytical gradient estimation for near-term hardware.
Mathematically, for binary classification:
\[f(\mathbf{x}) = \langle 0^{\otimes n} | U_{\text{ansatz}}^{\dagger}(\mathbf{w}) U_{\text{enc}}(\mathbf{x})^{\dagger} Z_0 U_{\text{enc}}(\mathbf{x}) U_{\text{ansatz}}(\mathbf{w}) |0^{\otimes n} \rangle\]The prediction probability for class 1 is \((f(\mathbf{x}) + 1)/2\). Training minimizes the binary cross-entropy loss:
\[\mathcal{L} = -\frac{1}{N} \sum_{i=1}^N [y_i \log(p_i) + (1-y_i) \log(1-p_i)]\]- Parameters:
n_qubits (int, default=4) – Number of qubits in the quantum circuit.
encoder (BaseEncoder, optional) – Data encoding circuit. If None, defaults to AngleEncoder().
ansatz (BaseAnsatz, optional) – Parameterized circuit. If None, defaults to StronglyEntanglingAnsatz(layers=2).
optimizer ({"adam", "sgd"} or callable, default="adam") – Optimization algorithm. If a string, uses PennyLane’s built-in optimizer. If callable, should return an optimizer instance with step() and reset() methods.
learning_rate (float, default=0.01) – Learning rate for the optimizer.
n_iter (int, default=100) – Number of optimization iterations.
batch_size (int, optional) – Batch size for training. If None, uses full batch.
random_state (int, optional) – Random seed for reproducibility.
device (str, default="default.qubit") – PennyLane device to use.
- classes_#
Class labels.
- Type:
ndarray
- n_features_in_#
Number of features seen during fit.
- Type:
int
- n_classes_#
Number of classes (binary: 2, multi-class: >2).
- Type:
int
- weights_#
Trained circuit parameters (binary classification only).
- Type:
ndarray
- encoder_#
Fitted encoder (binary classification only).
- Type:
- ansatz_#
Fitted ansatz (binary classification only).
- Type:
- estimators_#
List of fitted binary classifiers for multi-class classification. Each is a trained VQCClassifier for one class vs rest.
- Type:
list[VQCClassifier]
- loss_history_#
Training loss at each iteration. For binary: direct loss history. For multi-class: average loss across all binary classifiers.
- Type:
list[float]
- qnode_#
Cached QNode for inference (binary classification only). Set after
fit(). Advanced users can call this directly for debugging or custom measurements.- Type:
callable
- fit(X, y)[source]#
Fit the quantum classifier.
Supports both binary and multi-class classification using one-vs-rest strategy.
- Parameters:
X (array-like, shape (n_samples, n_features)) – Training data.
y (array-like, shape (n_samples,)) – Target labels.
- Returns:
self – Returns the fitted estimator.
- Return type:
- 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.
For binary classification, returns probabilities for both classes. For multi-class, returns normalized probabilities across all classes from the one-vs-rest classifiers.
- Parameters:
X (array-like, shape (n_samples, n_features)) – Input samples.
- Returns:
proba – Class probabilities.
- Return type:
ndarray, shape (n_samples, n_classes)
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,ClassifierMixinQuantum 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.SVCwithkernel="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:
- 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:
- 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
fitmethod.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(seesklearn.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 tofitif 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.
- Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
sample_weightparameter infit.- 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
scoremethod.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(seesklearn.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 toscoreif 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.
- Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
sample_weightparameter inscore.- Returns:
self – The updated object.
- Return type:
object
VQC Regressor#
- class VQCRegressor(n_qubits: int = 4, encoder: BaseEncoder | None = None, ansatz: BaseAnsatz | None = None, optimizer: str | Callable = 'adam', learning_rate: float = 0.01, n_iter: int = 100, batch_size: int | None = None, random_state: int | None = None, device: str = 'default.qubit')[source]#
Bases:
QuantumEstimator,RegressorMixinVariational Quantum Regressor.
A quantum regressor that uses a parameterized quantum circuit to make continuous predictions. Follows the scikit-learn API.
This implements the variational quantum regressor from:
Mitarai et al. (2018), “Quantum circuit learning” (arXiv:1803.00745). Introduces parameterized quantum circuits for continuous prediction using Pauli expectation values and MSE loss.
Farhi & Neven (2018), “Classification with Quantum Neural Networks on Near Term Processors” (arXiv:1802.06002). Framework for variational quantum circuits with Pauli-Z measurements.
Schuld, Bocharov, Svore & Wiebe (2018), “Circuit-centric quantum classifiers” (arXiv:1804.00633). Circuit-centric approach applicable to regression with MSE loss.
Mathematically, for input \(\mathbf{x}\):
\[f(\mathbf{x}) = \langle \phi(\mathbf{x}) | U_{\text{ansatz}}^{\dagger}(\mathbf{w}) Z_0 U_{\text{ansatz}}(\mathbf{w}) |\phi(\mathbf{x}) \rangle\]The target values are scaled to [-1, 1] and training minimizes MSE:
\[\mathcal{L} = \frac{1}{N} \sum_{i=1}^N (y_i^{\text{scaled}} - f(\mathbf{x}_i))^2\]- Parameters:
n_qubits (int, default=4) – Number of qubits in the quantum circuit.
encoder (BaseEncoder, optional) – Data encoding circuit. If None, defaults to AngleEncoder().
ansatz (BaseAnsatz, optional) – Parameterized circuit. If None, defaults to StronglyEntanglingAnsatz(layers=2).
optimizer ({"adam", "sgd"} or callable, default="adam") – Optimization algorithm.
learning_rate (float, default=0.01) – Learning rate for the optimizer.
n_iter (int, default=100) – Number of optimization iterations.
batch_size (int, optional) – Batch size for training. If None, uses full batch.
random_state (int, optional) – Random seed for reproducibility.
device (str, default="default.qubit") – PennyLane device to use.
- n_features_in_#
Number of features seen during fit.
- Type:
int
- weights_#
Trained circuit parameters.
- Type:
ndarray
- encoder_#
Fitted encoder.
- Type:
- ansatz_#
Fitted ansatz.
- Type:
- scaler_#
Fitted scaler for y values.
- Type:
StandardScaler
- loss_history_#
Training MSE at each iteration.
- Type:
list[float]
- qnode_#
Cached QNode for inference, set after
fit(). Advanced users can call this directly for debugging or custom measurements.- Type:
callable
- fit(X, y)[source]#
Fit the quantum regressor.
- Parameters:
X (array-like, shape (n_samples, n_features)) – Training data.
y (array-like, shape (n_samples,)) – Target values.
- Returns:
self – Returns the fitted estimator.
- Return type:
- predict(X)[source]#
Predict continuous target values for samples.
- Parameters:
X (array-like, shape (n_samples, n_features)) – Input samples.
- Returns:
y – Predicted target values.
- Return type:
ndarray, shape (n_samples,)
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') VQCRegressor#
Configure whether metadata should be requested to be passed to the
scoremethod.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(seesklearn.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 toscoreif 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.
- Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
sample_weightparameter inscore.- Returns:
self – The updated object.
- Return type:
object