This quantum kernel machine learning tutorial shows how to build, validate, and tune a quantum classifier in Python without treating a quantum circuit as a replacement for the full machine learning workflow. You will prepare a small real dataset, construct a feature-map kernel, check whether it contains useful signal, train a classical support vector machine, and plan a simulator-to-hardware validation path.
Overview
A quantum kernel method uses a quantum circuit to map a classical feature vector into a quantum state. The kernel measures similarity between two encoded states:
K(x,z) = |<φ(x)|φ(z)>|²
The resulting matrix is passed to a classical kernel algorithm, commonly a support vector classifier. This makes the workflow hybrid by design: Python and scikit-learn handle data preparation, splitting, metrics, and optimization, while a quantum SDK evaluates the similarity function.
A useful experiment has three baselines:
- A classical SVM using a linear or radial basis function kernel.
- A quantum-kernel SVM using an ideal statevector simulator.
- A quantum-kernel SVM using finite shots, a noise model, or hardware.
Without these comparisons, a quantum classifier can appear successful simply because the dataset is easy or because the classical baseline was not tuned. Treat the circuit as one candidate feature map, not as evidence of an advantage by itself.
Checklist by scenario
1. Preparing a small, reproducible dataset
- Choose a binary classification problem first. A two-class subset of Iris is suitable for a workflow demonstration, but it is not a performance claim.
- Split the data before fitting any scaler. Use a fixed random seed and retain the test set until final evaluation.
- Match the number of selected features to the number of available qubits, or define a documented feature-reduction step.
- Scale features for the chosen encoding. Rotation-based encodings often map values into an angle range such as
[0, π]; the appropriate range depends on the feature map. - Record class counts in every split. Accuracy can conceal poor performance when classes are imbalanced.
2. Building an initial PennyLane kernel
The following example is intentionally small. SDK interfaces and device names can change, so pin and record the versions used in a project and check the installed documentation before adapting it.
import pennylane as qml
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import SVC
from sklearn.metrics import balanced_accuracy_score, confusion_matrix
X, y = load_iris(return_X_y=True)
mask = y < 2
X, y = X[mask, :2], y[mask]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=7
)
scaler = MinMaxScaler(feature_range=(0, np.pi))
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
n_qubits = X_train.shape[1]
dev = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(dev)
def state(x):
qml.AngleEmbedding(x, wires=range(n_qubits), rotation="Y")
return qml.state()
def quantum_kernel(x, z):
psi_x = state(x)
psi_z = state(z)
return float(abs(np.vdot(psi_x, psi_z)) ** 2)
def kernel_matrix(A, B):
return np.array([[quantum_kernel(x, z) for z in B] for x in A])
K_train = kernel_matrix(X_train, X_train)
K_test = kernel_matrix(X_test, X_train)
model = SVC(kernel="precomputed", class_weight="balanced")
model.fit(K_train, y_train)
pred = model.predict(K_test)
print(balanced_accuracy_score(y_test, pred))
print(confusion_matrix(y_test, pred))
This statevector implementation is useful for learning and debugging. It constructs the training Gram matrix and the test-to-training matrix separately. A precomputed-kernel classifier expects exactly that orientation: rows are samples being predicted and columns correspond to training samples.
3. Comparing feature maps and classical baselines
Change one variable at a time. Compare the simple angle map with a map that adds entangling gates, if supported by your SDK and device. Keep the data split, SVM settings, and evaluation metrics fixed. For each experiment, save the feature-map description, qubit count, circuit depth, two-qubit gate count, shot count, simulator or hardware identifier, and random seeds.
Run a classical SVM with the same train/test split. Tune its regularization parameter and, for an RBF kernel, its width parameter rather than comparing against arbitrary defaults. A quantum kernel that loses to a well-tuned classical baseline may still be educational, but the result should be described accurately.
4. Moving from simulation to hardware
Hardware generally cannot provide the exact statevector used in the example. Estimate overlaps with a supported method such as a compute-uncompute circuit or a SWAP-test-style construction, then use measured probabilities to estimate each kernel entry. The exact implementation depends on the SDK, execution primitive, backend, transpilation rules, and measurement interface.
Start with a small training set. A kernel matrix requires many pairwise evaluations, so hardware cost grows quickly with the number of samples. Use the same preprocessing and circuit definition as the simulator experiment, then compare ideal, noisy-simulator, and hardware matrices before comparing classifier scores.
What to double-check
Kernel validity and alignment
A practical kernel matrix should be approximately symmetric, have values in the expected range, and be close to positive semidefinite. Small negative eigenvalues can arise from sampling noise; large violations may indicate an implementation or orientation error. Check symmetry with np.max(abs(K - K.T)) and inspect eigenvalues before training.
Kernel alignment provides a useful signal check. Compare the centered quantum kernel with a label-based target kernel, while remembering that alignment is a diagnostic rather than a generalization guarantee. If the matrix is nearly constant, the circuit is not separating examples effectively. If it is almost an identity matrix, it may be memorizing sample-specific differences rather than learning a useful similarity structure.
Noise, shots, and reproducibility
- Evaluate the same circuits with increasing shot counts to see whether metrics stabilize.
- Repeat hardware or noisy-simulator runs with several seeds where possible.
- Keep an untouched test result separate from feature-map selection and hyperparameter tuning.
- Track circuit depth and two-qubit operations after transpilation, not only before compilation.
- Decide in advance whether mitigation, matrix projection, or regularization is allowed, and apply it consistently.
For measurement interpretation, review the difference between counts, probabilities, quasi-distributions, and expectation values in this guide to quantum circuit measurement results. For hardware planning, use the backend selection matrix and estimate qubits, depth, shots, and runtime before submitting jobs.
Common mistakes
- Scaling before splitting: fitting a scaler on all data leaks test-set information. Fit preprocessing only on the training partition.
- Using too many features: encoding every column can increase qubit count and circuit complexity. Select, reduce, or encode features deliberately.
- Confusing similarity with accuracy: a visually interesting kernel matrix does not establish classification value. Always report a held-out metric and a baseline.
- Ignoring class imbalance: include balanced accuracy, precision, recall, or a confusion matrix when class frequencies differ.
- Tuning on the test set: repeated feature-map changes based on test performance turn the test set into a validation set. Use cross-validation or a separate validation split.
- Assuming ideal simulation predicts hardware: finite shots, readout error, gate noise, connectivity, and compilation can change the kernel substantially. Use noise-aware validation before hardware execution.
- Building a huge kernel matrix first: pairwise circuit execution scales with the sample count. Prototype on a subset and estimate resources before expanding.
If results are uninformative, first inspect the data scaling and kernel distribution. Then reduce circuit depth, test a simpler feature map, increase shots, and compare against a classical kernel. If results are unstable, examine matrix eigenvalues and repeat the experiment rather than selecting the most favorable run.
When to revisit
Revisit this workflow whenever the dataset, feature count, feature map, SDK, simulator, backend, or shot budget changes. A new SDK release can alter device interfaces, primitives, transpilation behavior, or supported integrations, so record the package versions and rerun a small regression test before trusting historical results.
Before each experiment, use this short action list:
- Freeze the dataset split, preprocessing configuration, and software environment.
- Run the classical baseline and ideal quantum-kernel baseline.
- Inspect symmetry, eigenvalues, alignment, class balance, and kernel-value distribution.
- Measure sensitivity to shots, noise, and at least one alternative feature map.
- Estimate pairwise executions and hardware resources before cloud submission.
- Report held-out metrics with the circuit and backend details needed to reproduce them.
For production-oriented hybrid quantum applications, connect these checks to automated tests. The hybrid quantum-classical CI/CD guide covers regression workflows, while the guides to noise simulation and error mitigation help structure the simulator-to-hardware comparison. The result is not merely a quantum classifier that runs, but an experiment whose limitations and changes remain visible over time.