scikit-learn estimator¶
hqnn_forge.sklearn ¶
hqnn_forge.sklearn¶
A scikit-learn estimator around the hybrid classifiers.
QuantumKernelClassifier is the quantum-kernel SVM (QSVM) as an estimator:
the same bookkeeping around SVC(kernel="precomputed") that
hqnn_forge.kernels otherwise leaves to the caller.
HybridClassifierEstimator implements fit / predict /
predict_proba / get_params / set_params, so a hybrid model can be
dropped into cross_val_score, GridSearchCV and Pipeline like any
other classifier. Training is delegated to
hqnn_forge.training.train_model.
scikit-learn (>= 1.6) is an optional dependency, declared by the sklearn
extra; importing this module without it raises an ImportError saying how to
install it.
Example
::
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from hqnn_forge.sklearn import HybridClassifierEstimator
clf = make_pipeline(
StandardScaler(),
HybridClassifierEstimator(n_qubits=4, n_layers=2, max_epochs=20),
)
scores = cross_val_score(clf, X, y, cv=5, scoring="matthews_corrcoef")
CALIBRATORS
module-attribute
¶
CALIBRATORS: dict[str, type[TemperatureScaler | PlattScaler]] = {'temperature': TemperatureScaler, 'platt': PlattScaler}
KernelEncoding
module-attribute
¶
KernelEncoding = Literal['angle', 'iqp', 'reuploading', 'amplitude']
HybridClassifierEstimator ¶
Bases: ClassifierMixin, BaseEstimator
scikit-learn classifier training a hybrid quantum-classical model.
Binary or multiclass, decided by y in fit, like any scikit-learn
classifier: two classes train a HybridBinaryClassifier (or the parallel
model), three or more a MulticlassHybridClassifier with the same
circuit options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelName
|
|
'serial'
|
n_qubits
|
int
|
|
8
|
n_layers
|
int
|
|
8
|
encoding_type
|
int
|
|
8
|
init_strategy
|
int
|
|
8
|
use_classical_encoder
|
int
|
|
8
|
dropout_p
|
float
|
Passed to the model constructor. |
0.0
|
device_name
|
float
|
Passed to the model constructor. |
0.0
|
diff_method
|
float
|
Passed to the model constructor. |
0.0
|
classical_hidden_dim
|
int
|
MLP width; used by the parallel model only. |
16
|
loss
|
LossName
|
|
'focal'
|
lr
|
float
|
Adam learning rate. |
0.01
|
max_epochs
|
int
|
Passed to |
20
|
batch_size
|
int
|
Passed to |
20
|
patience
|
int
|
Passed to |
20
|
monitor
|
int
|
Passed to |
20
|
validation_fraction
|
float
|
Share of the training data held out (stratified) for early stopping
and threshold selection. |
0.0
|
strategy
|
StrategyName
|
More than two classes only: |
'softmax'
|
threshold
|
float | Literal['optimal']
|
Binary only. |
'optimal'
|
calibration
|
CalibrationName | None
|
Binary only. |
None
|
random_state
|
int | None
|
Seeds weight initialisation, dropout, the validation split and batch
order. The initial weights are the model's |
None
|
noise_level
|
float
|
Noise-aware training, passed to the model: depolarizing noise of
probability |
0.0
|
noise_position
|
float
|
Noise-aware training, passed to the model: depolarizing noise of
probability |
0.0
|
noise_method
|
float
|
Noise-aware training, passed to the model: depolarizing noise of
probability |
0.0
|
noise_trajectories
|
float
|
Noise-aware training, passed to the model: depolarizing noise of
probability |
0.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
classes_ |
ndarray of shape (n_classes,)
|
The labels, sorted; with two, |
n_features_in_ |
int
|
|
model_ |
Module
|
The trained model. |
history_ |
TrainingHistory
|
|
threshold_ |
float or None
|
Decision threshold used by |
calibrator_ |
(TemperatureScaler, PlattScaler or None)
|
The fitted calibration; |
fit ¶
fit(X: ArrayLike, y: ArrayLike) -> HybridClassifierEstimator
Build the model for X's width and train it on (X, y).
predict_proba ¶
predict_proba(X: ArrayLike) -> npt.NDArray[np.float64]
Class probabilities, shape (n_samples, n_classes), columns in classes_ order.
predict ¶
predict(X: ArrayLike) -> npt.NDArray[Any]
Labels from classes_: the positive probability thresholded at
threshold_ for two classes, the argmax of the logits for more.
QuantumKernelClassifier ¶
Bases: ClassifierMixin, BaseEstimator
Support vector classifier on a quantum fidelity kernel (QSVM).
fit builds an encoding layer for the width of X, optionally trains
it by kernel-target alignment, computes the Gram matrix
K[i, j] = |⟨Φ(x_i)|Φ(x_j)⟩|² with hqnn_forge.kernels.quantum_kernel_matrix
and fits SVC(kernel="precomputed") on it. predict and friends
compute the kernel between new samples and the training set -- rows new,
columns training, the orientation SVC needs -- from the training
states cached at fit, so only the new samples are simulated. So the
estimator works in cross_val_score, GridSearchCV and Pipeline
like any other.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoding
|
KernelEncoding
|
|
'angle'
|
n_qubits
|
int | None
|
Default: one qubit per feature, or |
None
|
n_layers
|
int
|
Variational layers of the encoding layer. For the single-upload
encoders the ansatz cancels in the fidelity kernel (see
|
2
|
trainable_input_scaling
|
bool
|
|
False
|
align_steps
|
int
|
With |
0
|
align_lr
|
int
|
With |
0
|
align_subset_size
|
int
|
With |
0
|
noise_level
|
float
|
Estimate the kernel under depolarising noise from density matrices;
|
0.0
|
noise_position
|
float
|
Estimate the kernel under depolarising noise from density matrices;
|
0.0
|
C
|
float
|
Passed to |
1.0
|
class_weight
|
float
|
Passed to |
1.0
|
probability
|
bool
|
Enable |
False
|
batch_size
|
int | None
|
Samples simulated at a time, to bound memory. Default: all. |
None
|
random_state
|
int | None
|
Seeds the layer's initialisation, the alignment subsets and |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
classes_ |
ndarray
|
|
n_features_in_ |
int
|
|
layer_ |
Module
|
The (possibly aligned) encoding layer. |
svc_ |
SVC
|
|
calibrator_ |
CalibratedClassifierCV or None
|
The probability model, with |
alignment_history_ |
list of float
|
The alignment at each training step; empty without alignment. |
fit ¶
fit(X: ArrayLike, y: ArrayLike) -> QuantumKernelClassifier
Build (and optionally align) the layer, then fit the SVM on the Gram matrix.
decision_function ¶
decision_function(X: ArrayLike) -> npt.NDArray[np.float64]
SVC.decision_function on the kernel between X and the training set.
predict_proba ¶
predict_proba(X: ArrayLike) -> npt.NDArray[np.float64]
Platt-scaled probabilities; only present with probability=True, as in SVC.