This quantum kernel methods tutorial gives you a reusable workflow for designing, implementing, and evaluating quantum kernel classifiers. You will learn how fidelity and projected quantum kernels work, how to structure experiments in Qiskit or PennyLane, and what to check before treating a result as meaningful.
Overview
A quantum kernel classifier uses a quantum circuit to map classical inputs into a quantum feature space, then measures similarity between examples. A classical kernel method can use that similarity matrix with an algorithm such as a support vector classifier. The quantum circuit is therefore usually part of the feature representation, while the optimization and final decision boundary remain classical. This is a form of hybrid quantum-classical computing.
For two inputs, x and z, a fidelity-style quantum kernel commonly has the form:
K(x,z) = |<phi(x)|phi(z)>|^2
Here, phi is a parameterized feature map implemented by a circuit. Similar inputs should produce larger kernel values than dissimilar inputs, but that outcome is not automatic. The encoding circuit, input scaling, entanglement pattern, measurement method, noise, and classical estimator all affect the matrix.
Projected quantum kernels take a different route. Instead of estimating a global state overlap, they measure selected observables or other circuit outputs and calculate similarity from those classical projections. This can make the representation easier to inspect and may offer a practical alternative when full fidelity estimation is expensive. Neither approach should be assumed to be superior without a controlled comparison.
A reliable experiment separates four questions:
- Representation: Does the feature map encode the available signal without creating unnecessary circuit depth?
- Kernel quality: Is the matrix numerically valid, stable, and informative for the task?
- Classifier performance: Does the quantum kernel improve or match appropriate classical alternatives?
- Operational cost: Can the matrix be generated and reused within the available simulation or hardware budget?
For broader method selection, compare this workflow with a general quantum algorithm selection guide. If the experiment is part of an organizational proof of concept, define the baseline and success criteria before running circuits by using an enterprise quantum proof of concept framework.
Checklist by scenario
Scenario 1: Establishing a small baseline
- Choose a binary classification dataset with a clearly documented target and a modest number of features.
- Split the data before fitting transformations. Fit scaling, feature selection, and other preprocessing only on the training partition.
- Reduce the feature count deliberately if the circuit maps one feature to one qubit. Document whether reduction is statistical, domain-based, or simply a development constraint.
- Scale features into the input range expected by the feature map. Keep the transformation identical for training, validation, and test data.
- Build a classical baseline, such as a linear model and a classical kernel model, using the same splits and evaluation metric.
- Construct training and test kernel matrices separately. Do not fit the classifier on a matrix that includes information from the test set.
- Record the random seed, software versions, circuit definition, shot setting if applicable, and backend or simulator configuration.
The initial goal is not to prove a quantum advantage. It is to establish that the data pipeline, kernel construction, and evaluation are correct. The quantum algorithm experiment checklist can help turn this small trial into a reproducible benchmark.
Scenario 2: Comparing fidelity and projected kernels
- Keep the dataset split, preprocessing, classifier, and scoring procedure fixed.
- Change only the kernel construction method or the feature-map configuration.
- For a fidelity kernel, specify how overlaps are estimated and whether the implementation uses exact simulation, finite shots, or hardware measurements.
- For a projected kernel, list the observables, measured qubits, aggregation rule, and distance or similarity function used to form the matrix.
- Compare matrix diagnostics, validation performance, test performance, and resource requirements rather than accuracy alone.
- Repeat the comparison across more than one reasonable circuit depth or encoding choice, without selecting configurations based only on test results.
A projected kernel may be easier to diagnose because its measured features can be inspected directly. A fidelity kernel may provide a compact global similarity, but overlap estimation can become costly as the dataset grows. Treat these as experimental design trade-offs, not universal rankings.
Scenario 3: Porting between Qiskit and PennyLane
- Write down the mathematical feature map before translating code. Include the rotation convention, feature-to-qubit assignment, data re-uploading pattern, entangling gates, and parameter scaling.
- Confirm that both implementations use the same wire order and feature order.
- Test both circuits on a few fixed inputs and compare state probabilities, expectation values, or kernel entries.
- Check whether the framework version supports the kernel class, device, differentiation method, and execution mode used by the example.
- Compare the resulting matrices with a numerical tolerance rather than expecting identical finite-shot values.
Illustrative Qiskit-style pseudocode might look like this:
feature_map = build_feature_map(num_qubits, reps=1)
quantum_kernel = build_fidelity_kernel(feature_map=feature_map)
K_train = quantum_kernel.evaluate(X_train)
K_test = quantum_kernel.evaluate(X_test, X_train)
classifier.fit(K_train, y_train)
predictions = classifier.predict(K_test)
A PennyLane-style workflow can use the same conceptual stages:
@qml.qnode(device)
def embedding(x):
encode_features(x)
apply_entanglers()
return qml.state()
def kernel(x, z):
# Define an overlap or projected similarity
return similarity(embedding(x), embedding(z))
K_train = make_matrix(X_train, X_train, kernel)
K_test = make_matrix(X_test, X_train, kernel)
These snippets are intentionally conceptual. Kernel APIs and device interfaces change, so verify the current documentation for the Qiskit or PennyLane release used in your project. Keep framework-specific code behind a small adapter so that the experiment logic remains portable.
Scenario 4: Testing on a simulator or quantum backend
- Run an exact or high-precision simulator version first to establish a reference matrix.
- Run a finite-shot simulator to estimate sampling variability.
- Only then test a hardware backend, if hardware access is relevant to the research question.
- Track circuit depth, number of evaluations, shots, queue behavior, retries, and result caching.
- Report whether the comparison measures algorithmic behavior, hardware robustness, or both.
A quantum simulator versus real hardware comparison is useful only when the execution conditions are recorded. For practical handling of repeated kernel evaluations, see the quantum job management guide.
What to double-check
Positive semidefiniteness and numerical validity
An ideal Mercer kernel is positive semidefinite. In practice, finite precision, finite shots, noise, or an inconsistent similarity definition can produce small negative eigenvalues. Inspect symmetry and the eigenvalue spectrum of the training matrix. A small numerical deviation may be handled with a documented stabilization step, but large or systematic violations require investigation rather than silent correction.
Useful checks include:
- Verify that
Kis approximately equal to its transpose. - Inspect minimum eigenvalues and condition number.
- Check diagonal values and whether they are consistent with the kernel definition.
- Compare a matrix generated twice under the same deterministic conditions.
- Document any diagonal adjustment, eigenvalue clipping, or regularization.
Scaling and computational cost
Kernel construction requires many pairwise evaluations. For n examples, a full training matrix contains roughly quadratic pair relationships before accounting for repeated shots, circuit depth, batching, and backend overhead. A method that works on a toy dataset may become impractical when the sample count grows.
Estimate the number of circuit executions before selecting a kernel. Consider subsampling, approximate methods, caching, symmetry reuse, or a smaller development set. These choices should be made before looking at test performance so that resource constraints do not become an after-the-fact explanation.
Data leakage and evaluation design
Kernel methods are vulnerable to the same leakage risks as other machine-learning pipelines. Do not fit a scaler on all observations, choose feature-map parameters using the test set, or report the best result from many untracked trials. If hyperparameters are tuned, use a validation procedure or nested evaluation appropriate to the dataset size. Compare quantum and classical models under the same protocol.
Feature-map choice
Start with a simple feature map that matches the available features. More layers and entanglement do not automatically create a better representation. Check whether the circuit produces nearly indistinguishable states, highly concentrated similarities, or unstable outputs. Compare shallow and deeper versions while recording their depth and parameter count.
Input encoding deserves its own design decision. The quantum machine learning data encoding guide provides a useful framework for comparing angle, amplitude, and basis-based approaches.
Common mistakes
- Calling any similarity matrix a quantum advantage: A quantum-generated matrix is not evidence of advantage without a fair classical comparison and a defined resource model.
- Using the test set during feature-map selection: Keep model and circuit decisions inside the training or validation process.
- Ignoring the classical kernel baseline: A classical radial basis or polynomial kernel may be a strong reference. Its omission makes conclusions difficult to interpret.
- Changing several variables at once: If encoding, depth, classifier, and split all change, you cannot identify what caused the result.
- Assuming simulator results predict hardware results: Sampling noise, device noise, connectivity, compilation, and execution overhead can change the matrix.
- Silently repairing an invalid matrix: Stabilization can be reasonable, but the reason, method, and effect on results should be reported.
- Failing to preserve provenance: Save the circuit definition, preprocessing parameters, matrix-generation settings, backend details, and evaluation outputs. Use the quantum experiment documentation template as a starting point.
When comparing model quality, use a dedicated quantum machine learning baseline benchmark rather than relying on a single accuracy value.
When to revisit
Revisit this workflow whenever the underlying inputs change. That includes a new dataset, altered feature engineering, a different class balance, a new circuit depth, a framework upgrade, or a move from simulation to hardware. A kernel matrix is tied to its feature map, preprocessing, execution model, and data distribution; it should not be treated as a permanent artifact that can be reused without checks.
Before each substantial rerun, use this short action list:
- Freeze and record the dataset version, split, preprocessing, and target definition.
- Reconfirm that the Qiskit or PennyLane implementation matches the intended feature map.
- Regenerate training and test matrices rather than mixing matrices from different configurations.
- Check symmetry, eigenvalues, diagonal behavior, conditioning, and execution variability.
- Run the same classical baselines and preserve their evaluation settings.
- Review leakage controls and confirm that tuning decisions do not use the final test set.
- Record circuit depth, evaluation count, shots, backend or simulator, runtime observations, and any stabilization.
- Update the experiment conclusion only after comparing quality, reproducibility, and cost.
This checklist keeps a quantum kernel classifier experiment useful as tools and workflows evolve. For related variational models, consult the variational quantum algorithm hyperparameter tuning guide, and use the quantum circuit testing workflow when matrix discrepancies point to an implementation problem.