This practical quantum kernel machine learning workflow shows how to build a quantum support-vector classifier in Python, evaluate it against classical baselines, and check whether scaling, feature-map choices, simulator shots, or hardware noise are changing the result. Use it as a reusable checklist whenever you test a new dataset or update your quantum software stack.
Overview
A quantum kernel method uses a quantum circuit to map classical input data into a feature space. The similarity between two examples is then estimated from the circuits' output states and stored in a kernel matrix. A classical support-vector machine (SVM) uses that matrix to learn a decision boundary.
The workflow is hybrid rather than fully quantum: Python and a classical machine-learning library prepare the data, a quantum simulator or device evaluates pairwise similarities, and a classical optimizer trains and evaluates the SVM. This separation is useful because it lets you inspect each stage independently.
- Choose a small, clearly defined binary classification dataset.
- Split the data before fitting transformations or calculating kernels.
- Scale features to a range that matches the circuit's rotation angles.
- Define a quantum feature map and a kernel based on state overlap.
- Construct training and test kernel matrices without data leakage.
- Train an SVM with the quantum kernel.
- Compare accuracy and stability with classical kernels.
- Repeat the experiment with finite shots or a hardware backend before making stronger claims.
For a first experiment, use two features and a modest number of samples. Small circuits make it easier to compare exact simulation, shot-based simulation, and hardware execution. If you need a broader hybrid workflow, see the hybrid quantum machine learning pipeline guide.
Checklist by scenario
Scenario 1: Build a reproducible simulator prototype
Start with a fixed train-test split and record the Python, PennyLane, scikit-learn, and backend versions. Pin compatible package versions in a virtual environment rather than assuming that examples written for one release will use identical APIs in another.
A minimal PennyLane-style implementation can look like this:
import pennylane as qml
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
X, y = make_moons(n_samples=160, noise=0.15, random_state=7)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=7
)
scaler = StandardScaler()
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)
def feature_map(x):
for wire, value in enumerate(x):
qml.RY(value, wires=wire)
if n_qubits > 1:
for wire in range(n_qubits - 1):
qml.CNOT(wires=[wire, wire + 1])
@qml.qnode(dev)
def kernel_circuit(x1, x2):
feature_map(x1)
qml.adjoint(feature_map)(x2)
return qml.probs(wires=range(n_qubits))[0]
def quantum_kernel(x1, x2):
return float(kernel_circuit(x1, x2))
def kernel_matrix(A, B):
return np.array([[quantum_kernel(a, b) for b in B] for a in A])
K_train = kernel_matrix(X_train, X_train)
K_test = kernel_matrix(X_test, X_train)
model = SVC(kernel="precomputed")
model.fit(K_train, y_train)
predictions = model.predict(K_test)
print(accuracy_score(y_test, predictions))
The circuit prepares one encoded state, applies the inverse of the second encoded state, and reads the probability of the all-zero result. That probability estimates the squared state overlap. The SVM receives a matrix, not the circuit itself.
Scenario 2: Compare quantum and classical kernels
Do not evaluate the quantum model in isolation. Train at least a linear SVM and an RBF SVM using the same split and the same training data. Compare accuracy, balanced accuracy when classes are uneven, confusion matrices, and—when the dataset is large enough—results across several random splits.
A quantum kernel that performs better on one split may not generalize. Conversely, similar predictive performance can still teach you about circuit depth, kernel geometry, or runtime. Record the classical baseline before changing the feature map.
Scenario 3: Test finite shots or hardware execution
Replace exact probabilities with shot-based measurements and recompute the same matrix. Keep the shot count, random seed where supported, transpilation settings, backend name, and execution date in your experiment metadata. Expect the matrix to become noisy and check whether it remains approximately symmetric and positive semidefinite.
Before sending circuits to hardware, review how to choose a quantum computing backend and how to optimize circuits before hardware execution.
What to double-check
- Scaling: Fit the scaler on training data only. Confirm that transformed values are suitable for the chosen rotation gates; extreme angles can make examples difficult to distinguish.
- Feature count: A simple angle-encoding circuit commonly assigns one feature to one qubit. Reduce dimensions deliberately if the dataset has more features, and document the reduction method.
- Kernel dimensions: For a precomputed SVM, the training matrix must be square, while the test matrix must have one column for every training example.
- Matrix quality: Check symmetry, diagonal values, missing values, and eigenvalues. Small negative eigenvalues can arise from numerical or shot noise; large violations may indicate an implementation problem.
- Evaluation: Keep the test set untouched until the kernel and model settings are selected. Never use test examples when choosing a feature map.
- Cost: Kernel construction requires many pairwise circuit evaluations. Estimate the number of circuits before moving to a larger dataset or a remote backend.
For simulator selection and noise-model trade-offs, consult the quantum circuit simulator comparison. If noisy results are central to the experiment, separate error mitigation from ordinary model tuning and document both versions.
Common mistakes
Calling every quantum-kernel experiment a QSVM: The SVM optimization is classical. “Quantum-kernel SVM” is more precise because the quantum circuit supplies the kernel evaluations.
Using a large dataset too early: Pairwise kernel computation grows quickly with the number of examples. Begin with a small benchmark and profile circuit execution before scaling.
Changing several variables at once: If you change scaling, circuit depth, entanglement, shots, and the SVM hyperparameters together, you cannot identify what caused the result.
Skipping a classical baseline: A quantum kernel is not useful evidence merely because it produces predictions. Compare it with simple kernels under the same evaluation protocol.
Ignoring reproducibility: Save the dataset preparation code, split seed, feature-map definition, backend configuration, kernel matrices, and metrics. The reproducible quantum experiments template provides a practical structure.
Assuming simulator accuracy predicts hardware performance: Exact statevector results are a useful reference, not a guarantee. Use shot-based simulation and hardware tests to expose sensitivity to sampling and noise. For debugging unexpected outputs, follow the quantum circuit debugging workflow.
When to revisit
Return to this checklist whenever you change the dataset, preprocessing pipeline, feature map, number of qubits, entanglement pattern, SVM settings, shot count, simulator, or execution backend. Revisit it before a seasonal planning cycle if your team is deciding whether a quantum machine-learning prototype is ready for a new experiment.
Also review the workflow after upgrading PennyLane, Qiskit, scikit-learn, or a backend plugin. Confirm imports, device behavior, measurement semantics, and precomputed-kernel conventions with a small regression test before rerunning the full study. Keep a known dataset and expected matrix properties as a smoke test.
Your next action should be modest: run the two-feature simulator example, save the quantum and classical baseline metrics, inspect the kernel matrix, and then repeat with finite shots. Only after those checks should you add features, deepen the circuit, or test hardware. This sequence makes the quantum contribution measurable rather than assumed.