Lesson 42 · 120 min · advanced
End-to-End Quantum-Kernel SVM
This lesson assembles a complete quantum-kernel classifier and evaluates it honestly. It derives the soft-margin dual with a precomputed kernel, in which training sees the data only through the Gram block and prediction only through the test block , and fixes the bias from the Karush–Kuhn–Tucker conditions. It proves that the two-qubit ZZ feature map prepares , that its CNOT–phase–CNOT gadget is a rotation up to a global phase, and that building it with instead of phase gates multiplies every state by and leaves the kernel unchanged. It shows that for angle encodings the data scale is the kernel bandwidth, that finite-shot Gram matrices lose positive semidefiniteness because the exact ones are rank deficient, and that eigenvalue clipping is the Frobenius-nearest positive semidefinite repair. On the two-moons data the ZZ kernel with one repetition reaches a test accuracy of , two repetitions drop to , and the classical angle kernel reaches .
Prerequisites: The SWAP Test, The Inversion (Compute–Uncompute) Test, Hamiltonian-Evolution Encoding & Trotterisation
Objectives and key results
Split a quantum-kernel classifier into its kernel blocks and , derive the soft-margin dual with a precomputed kernel, and compute the bias and the decision function from the KKT conditions.
Write the gate-level circuit of the two-qubit ZZ feature map, prove that , and derive the closed form of the feature state and its kernel.
Prove that the and phase-gate versions of the ZZ map differ only by the global phase and therefore define the same kernel.
Explain min–max scaling to and prove that for angle encodings the scale factor plays the role of an inverse bandwidth: with equality to second order.
Bound the rank of quantum Gram matrices, show that finite-shot noise makes a rank-deficient Gram matrix indefinite with positive probability, and prove that eigenvalue clipping is the unique Frobenius-nearest positive semidefinite matrix and never moves the estimate away from the true Gram matrix.
Evaluate the pipeline on held-out data, compare it with a classical baseline, and use kernel–target alignment to discuss why a more expressive feature map can generalise worse.
- formula · Precomputed-kernel SVM
- identity · ZZ gadget
- formula · Two-qubit ZZ feature state
- theorem · R_Z and phase-gate ZZ maps give the same kernel
- theorem · Scale is bandwidth for angle encodings
- theorem · Eigenvalue clipping is the nearest PSD matrix
The quantum-kernel SVM pipeline#
The lessons of this module built every component of a quantum kernel method separately: the fidelity kernel and its positive semidefiniteness, the SWAP test and the inversion test that estimate one kernel entry, and the shot budget of a whole Gram matrix. The kernel-methods lesson of Module 3.1 built the other half, the support vector machine. This lesson connects them into one pipeline and runs it on a real classification problem, the two-moons dataset, from raw features to a test accuracy.
The pipeline has six stages. (1) Preprocess: scale every feature to an interval, here . (2) Encode: choose a feature map , here the two-qubit ZZ map. (3) Estimate the training block with kernel circuits. (4) Train a soft-margin SVM classically on . (5) Estimate the test block with further circuits. (6) Predict with the decision function and measure the accuracy on held-out labels. The quantum computer appears only in stages (3) and (5); everything else is classical convex optimisation. For our split, and , the two blocks need distinct circuits.
Definition
Training and test kernel blocks
Let be the training data with labels and the test inputs. For a kernel , the training block and the test block are Row of compares test point with every training point, in the order of the training set. For a fidelity kernel, is symmetric with unit diagonal and has no structure beyond .
The soft-margin SVM needs only the kernel blocks
Let be a feature map into a real inner-product space with , and let . The soft-margin primal problem has the dual with zero duality gap; an optimal is and the decision function is , so . For a fidelity kernel one may take = the Hermitian matrices with the Hilbert–Schmidt inner product and ; then is a Hermitian observable and .
Proof (8 steps)
- Step 1:Lagrangian with one multiplier for each margin constraint and one for each .
- Step 2:is a convex quadratic in ; its gradient vanishes at the minimiser. The normal vector is a combination of training features, as the representer theorem predicts.
- Step 3:is linear in and , so the infimum is unless these coefficients vanish; turns the second equation into the box constraint.
- Step 4:Bilinearity of the inner product and the kernel property : the feature vectors never appear on their own, only through kernel values.
- Step 5:Insert the three stationarity conditions: , the term and the terms vanish. This is the dual objective.
- Step 6:The primal is a convex quadratic program with affine constraints and a feasible point, so strong duality holds and the KKT conditions are necessary and sufficient for optimality (linear constraint qualification).
- Step 7:Insert ; at a test point the kernel values are the entries of row of , so for all test points at once.
- Step 8:The fidelity kernel is the Hilbert–Schmidt inner product of the encoded density operators (lesson Quantum Kernels & Fidelity Kernels); a real combination of Hermitian matrices is Hermitian, so the trained model is the expectation value of an observable plus a bias.
∎
The bias from the KKT conditions
At an optimum, complementary slackness gives and . Consequently: ; ; and for every free support vector (), and If the set of free support vectors is non-empty, all of them give the same , and solvers report the average .
Proof (6 steps)
- Step 1:KKT complementary slackness: a multiplier can be positive only when its constraint is active. The second form uses from the previous theorem.
- Step 2:A free support vector has , so its slack vanishes: it lies exactly on the margin.
- Step 3:The margin constraint of is active and .
- Step 4:Multiply by and insert the decision function of the previous theorem at the training point .
- Step 5:For , forces and primal feasibility gives ; for the margin constraint is active with .
- Step 6:In exact arithmetic every free support vector yields the same value; an iterative solver stops at a tolerance, and averaging the reduces the effect of the residual KKT violations. LIBSVM, behind scikit-learn's SVC, uses this average (and the midpoint of the feasible interval of when is empty).
∎
Quick check
A precomputed-kernel SVM was trained on points. Which matrix must be passed to predict to classify new points?
The two-qubit ZZ feature map#
Definition
Two-qubit ZZ feature map (one repetition)
For let . The ZZ feature map of Havlíček et al. (2019) with one repetition prepares where the rightmost operator acts first, is the phase gate on qubit , and has control and target . With qubit as the most significant bit, , and With repetitions the block is applied times. The single-qubit phases encode the features, the CNOT–phase–CNOT gadget encodes their product, and the kernel is .
Circuit · 2 qubits
The ZZ feature map at : on both qubits, , , then . All four amplitudes of the output have modulus ; only their phases carry the data.
The CNOT–phase–CNOT gadget is a ZZ rotation
For every , On basis states it multiplies by , a phase that depends only on the parity of the two bits.
Proof (6 steps)
- Step 1:The CNOT flips the target exactly when the control is ; applying it twice adds twice modulo , which is the identity.
- Step 2:for , here applied to the target bit .
- Step 3:Linearity pulls the scalar out; the second CNOT undoes the first because .
- Step 4:The operator is diagonal in the computational basis, ordered .
- Step 5:, and since only the parity of the exponent matters; the second identity checks on the two parities and .
- Step 6:Insert the parity identity. A function of a diagonal matrix acts entrywise on its eigenvalues, so has the eigenvalue on .
∎
Unitary verified: (max deviation 0.0e+0)
Closed form of the ZZ feature state and its kernel
With , equivalently , and
Proof (7 steps)
- Step 1:on each qubit; expand the tensor product.
- Step 2:Each phase gate multiplies by where is the bit of its own qubit.
- Step 3:The lemma with .
- Step 4:All gates after the Hadamards are diagonal, so their phases add on each basis state of the uniform superposition; removes the product phase from .
- Step 5:is the eigenvalue of on . Hence the diagonal phase operator equals , which acting on gives the exponential form.
- Step 6:Inner product antilinear in the first argument, computed in the orthonormal computational basis.
- Step 7:Square the modulus. The diagonal check confirms normalisation; four phases can cancel completely, so ranges over all of .
∎
The R_Z version of the map differs by a global phase only
Let be the circuit of the definition with every phase gate replaced by (this is how the platform's zzFeatureMap builds it). Then, for repetitions,
for in particular , and the two kernels are identical: for all .
Proof (6 steps)
- Step 1:Factor out of both diagonal entries.
- Step 2:The Kronecker product is bilinear, so scalar factors of the two operands multiply.
- Step 3:Same factorisation with , pulled out of the matrix product by linearity.
- Step 4:A scalar multiple of the identity commutes with every matrix, so all phases collect in front of one repetition of the phase-gate circuit, and repetitions collect copies.
- Step 5:Insert the exponential form of the closed-form proposition; the two phases cancel, leaving the Havlíček form with .
- Step 6:With : the bra conjugates its phase, and a unimodular factor drops out of the modulus. Data-dependent global phases are invisible to the fidelity kernel (lesson Quantum Kernels & Fidelity Kernels).
∎
Quick check
Using the closed form, compute the ZZ kernel (one repetition) between the opposite corners and of the data square. Give the value to three decimals.
Data scaling and kernel bandwidth#
Rotation angles are periodic, so the numerical range of the features decides which part of each rotation the data occupy. Feeding raw features into an encoding is therefore never neutral: multiplying all features by a constant changes the kernel, and with it the classifier. The raw two-moons features of the lab span ; the lab maps them to .
Definition
Min–max scaling to [0, s]
Given data with per-feature minimum and maximum , the min–max scaled features are (and for a constant feature). The lab uses and computes over all rows.
For angle encodings the scale is the bandwidth
Encode by the product encoding of , , and let . The kernel is , and: (a) if for all (always true for ), then ; (b) , the same second-order behaviour as the Gaussian kernel with , i.e. a length scale proportional to ; (c) for each factor is strictly decreasing in , whereas for the points and have identical encodings; (d) as , uniformly and the Gram matrix tends to the rank-one matrix .
Proof (8 steps)
- Step 1:Product-encoding kernel of the lesson Quantum Kernels & Fidelity Kernels, evaluated at the scaled features and .
- Step 2:on because vanishes at and has derivative . Hence is non-increasing and .
- Step 3:is even, so may replace . At the left side is and the inequality holds trivially.
- Step 4:Multiply the non-negative inequalities; this is (a).
- Step 5:Half-angle identity and the cosine series; products of two second-order terms are . The Gaussian matches for : this is (b).
- Step 6:For and we have , so similarity decreases strictly with distance in each feature: the first part of (c).
- Step 7:The rotation by returns every state up to the global phase : the two ends of the feature range are identified (aliasing), the second part of (c).
- Step 8:From and for (induction on ). With every entry near the Gram matrix approaches , the decision function tends to a constant, and the classifier cannot separate anything: (d).
∎
The heatmap starts with the angle encoding of two-circles points scaled to : every entry is close to , the matrix is nearly the rank-one all-ones matrix, and one eigenvalue dominates the spectrum, exactly as part (d) predicts. Move the scale slider to and the block structure of the two circles appears, because the effective length scale shrinks below the distance between the classes. Push it towards and points at the two ends of a feature range start to look alike again (aliasing).
For the ZZ map the scale enters twice. The single-qubit phases have period in , so is exactly one period: a smaller range uses only part of the circle, a larger one wraps around it. The product phase ranges over on , more than three full turns, and it is not a function of . This is why the opposite corners and have kernel (quick check above): the ZZ kernel imposes a notion of similarity that is unrelated to Euclidean distance, and whether that helps depends entirely on the data.
Quick check
One feature is scaled to with and encoded by . What is the kernel between the two extreme points and ?
Finite shots, lost positivity and eigenvalue clipping#
On hardware, every kernel entry is a relative frequency. With inversion-test shots per entry, with and , and entries estimated by different circuits have independent errors (lesson Quantum Kernels & Fidelity Kernels). The diagonal of is known to be and need not be measured. The estimated matrix is symmetric, but it need not be positive semidefinite, and the SVM dual is only guaranteed to be a concave problem when it is. The reason is structural: exact quantum Gram matrices of many points are singular.
Rank of a quantum Gram matrix
For -qubit pure feature states, . For the two-qubit ZZ map with one repetition the bound improves to , and for the product encoding of features to . Hence for points the ZZ Gram matrix has at least zero eigenvalues.
Proof (7 steps)
- Step 1:The Hermitian matrices form a real inner-product space of dimension ; is the coordinate vector of in an orthonormal basis (for instance the normalised Pauli strings), and has the columns .
- Step 2:, so both matrices have the same kernel and hence the same rank.
- Step 3:Outer product of the closed form with itself: every diagonal entry has modulus squared , independent of the data.
- Step 4:A Hermitian matrix with a fixed diagonal is determined by the real and imaginary parts of its entries above the diagonal; are the matrix units.
- Step 5:Every lies in the -dimensional space spanned by and .
- Step 6:has Bloch vector ; a product state is the tensor product of its one-qubit density matrices.
- Step 7:Rank–nullity for the symmetric matrix. The engine finds rank exactly for the reps-1 ZZ map, for two repetitions and for the angle encoding (TypeScript cell of the results section).
∎
Shot noise makes a singular Gram matrix indefinite with positive probability
Let have a unit null vector () with for some pair with . Let where is symmetric with zero diagonal and independent entries () of mean and variance . Then , where and ; consequently .
Proof (7 steps)
- Step 1:Spectral theorem: with and , , with equality at the eigenvector of .
- Step 2:Use the unit vector in the variational formula and .
- Step 3:The diagonal of vanishes and .
- Step 4:Linearity of expectation, and additivity of variances for independent summands.
- Step 5:All terms are non-negative and the assumed pair contributes a positive one.
- Step 6:Otherwise almost surely, and a non-negative variable with mean vanishes almost surely, contradicting .
- Step 7:By the second step, implies . With independent null directions in the ZZ Gram matrix, many eigenvalues can cross zero at once.
∎
The TypeScript cell simulates this with the platform's engine. It estimates every entry above the diagonal of the reps-1 ZZ training Gram matrix from Bernoulli shots with success probability (the inversion-test outcome ), seeded by mulberry32(42) so that the run is reproducible, diagonalises the estimate with the Hermitian Jacobi solver, clips the negative eigenvalues and measures distances in the Frobenius norm.
import { eigh, eigvalsh, matrix, mulberry32 } from '@/lib/quantum-simulator';
import { kernelMatrix, moonsSplit, zzFeatureMap } from '@/lib/qml';
// Exact 70 x 70 training Gram matrix of the reps-1 ZZ map (rank 13, so 57 eigenvalues are exactly zero).
const { Xtrain } = moonsSplit();
const K = kernelMatrix(zzFeatureMap(2, { reps: 1 }), Xtrain);
const m = K.length;
const rows = (A: Float64Array[]) => A.map((r) => Array.from(r));
// Finite-shot estimate: N inversion-test shots per entry above the diagonal; the outcome 00 has probability K_ij.
const N = 100;
const rng = mulberry32(42);
const Khat = K.map((r) => Float64Array.from(r));
for (let i = 0; i < m; i++) {
Khat[i][i] = 1; // pure states: the diagonal is known exactly
for (let j = i + 1; j < m; j++) {
let zeros = 0;
for (let s = 0; s < N; s++) if (rng() < K[i][j]) zeros++;
Khat[i][j] = Khat[j][i] = zeros / N;
}
}
const { values, vectors } = eigh(matrix.fromRows(rows(Khat)));
const lam = Array.from(values);
const neg = lam.filter((l) => l < 0);
console.log('shots per entry ' + N + ': smallest eigenvalue ' + lam[0].toFixed(4) + ', negative eigenvalues ' + neg.length + ' of ' + m);
// Eigenvalue clipping K_+ = V max(Lambda, 0) V^T.
const D = matrix.fromRows(lam.map((l, i) => lam.map((_, j) => (i === j ? Math.max(l, 0) : 0))));
const Kplus = matrix.mul(matrix.mul(vectors, D), matrix.adjoint(vectors));
const exact = matrix.fromRows(rows(K));
const noisy = matrix.fromRows(rows(Khat));
console.log('||K_hat - K_+||_F = ' + matrix.frobeniusNorm(matrix.sub(noisy, Kplus)).toFixed(6) + ', sqrt(sum of squared negative eigenvalues) = ' + Math.sqrt(neg.reduce((s, l) => s + l * l, 0)).toFixed(6));
console.log('distance to the exact K: noisy ' + matrix.frobeniusNorm(matrix.sub(noisy, exact)).toFixed(4) + ', clipped ' + matrix.frobeniusNorm(matrix.sub(Kplus, exact)).toFixed(4));
console.log('clipped matrix: smallest eigenvalue >= -1e-10: ' + (eigvalsh(matrix.scale(matrix.add(Kplus, matrix.adjoint(Kplus)), 0.5))[0] >= -1e-10));Expected output
shots per entry 100: smallest eigenvalue -0.5710, negative eigenvalues 29 of 70 ||K_hat - K_+||_F = 1.573392, sqrt(sum of squared negative eigenvalues) = 1.573392 distance to the exact K: noisy 2.6239, clipped 2.0764 clipped matrix: smallest eigenvalue >= -1e-10: true
Of the exact zero eigenvalues, have become negative, the smallest at , so the estimate is far from being a valid Gram matrix. After clipping, the distance from the estimate to the repaired matrix equals to all printed digits, and the repaired matrix is closer to the exact Gram matrix than the raw estimate ( against ). The next two results prove that both observations hold in general.
Eigenvalue clipping is the Frobenius-nearest positive semidefinite matrix
Let be symmetric with eigendecomposition , orthogonal, , and set (entrywise maximum on the diagonal). Then and for every symmetric positive semidefinite with equality if and only if .
Proof (8 steps)
- Step 1:is positive semidefinite: a diagonal matrix with non-negative entries, conjugated by an orthogonal matrix.
- Step 2:, and the cyclicity of the trace: the Frobenius norm is invariant under orthogonal conjugation.
- Step 3:Write and apply the invariance; is symmetric and positive semidefinite because is.
- Step 4:The diagonal entries of a positive semidefinite matrix are values of its quadratic form at the unit vectors.
- Step 5:is diagonal, so the off-diagonal part of is that of ; then drop the non-negative off-diagonal terms and the diagonal terms with .
- Step 6:Squaring preserves the order of non-negative numbers. Summing, for every admissible .
- Step 7:The bound is attained by the clipped matrix, so it is the minimum and .
- Step 8:Equality in the three inequalities forces each dropped term to vanish and with , i.e. . Hence the minimiser is unique (Higham 1988).
∎
Clipping never moves the estimate away from the true Gram matrix
For every symmetric positive semidefinite , in particular the exact Gram matrix, ; hence .
Proof (6 steps)
- Step 1:Split every eigenvalue as ; collects the negative parts with a plus sign.
- Step 2:, cyclicity of the trace, and for every real .
- Step 3:is positive semidefinite, so its trace, the sum of its eigenvalues, is non-negative.
- Step 4:Expand the squared norm with the Frobenius inner product.
- Step 5:The previous two steps.
- Step 6:Drop the non-negative cross term. In the experiment: .
∎
Quick check
A noisy estimate of a three-point Gram matrix is . What is its smallest eigenvalue? (Four decimals.)
Results on the two-moons data, reported honestly#
The experiment uses the two-moons sample make_moons(n_samples=100, noise=0.1, random_state=0) of scikit-learn, two interleaved half circles with points each, scaled to , with rows – for training and rows – ( of class , of class ) for testing. Every classifier is a soft-margin SVM with on a precomputed, exactly simulated kernel. Three kernels are compared: the ZZ map with one repetition, the ZZ map with two repetitions, and the angle encoding, whose kernel is a classical function of two cosines.
| kernel | rank of | alignment | train accuracy | test accuracy |
|---|---|---|---|---|
| ZZ, one repetition | () | |||
| ZZ, two repetitions | () | |||
| angle (classical) | () |
The Python cell reproduces the table with scikit-learn, from make_moons to the accuracies, and adds one more run, the reps-1 ZZ kernel with . It also confirms the closed form of the feature state and the global phase on the first training point.
import numpy as np
from sklearn.datasets import make_moons
from sklearn.svm import SVC
# 1. Data: the fixed two-moons sample, each feature min-max scaled to [0, pi]; rows 0-69 train, 70-99 test.
X, y = make_moons(n_samples=100, noise=0.1, random_state=0)
X = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) * np.pi
X_train, y_train, X_test, y_test = X[:70], y[:70], X[70:], y[70:]
# 2. Gates; qubit 0 is the most significant bit, i.e. the LEFT factor of np.kron.
H = np.array([[1.0, 1.0], [1.0, -1.0]]) / np.sqrt(2.0)
I2 = np.eye(2)
CNOT01 = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex)
P = lambda lam: np.diag([1.0, np.exp(1j * lam)])
RZ = lambda lam: np.diag([np.exp(-0.5j * lam), np.exp(0.5j * lam)])
def zz_state(x, reps=1, gate=P):
"""(CNOT_01 G_1(2 phi01) CNOT_01 G_0(2 x0) G_1(2 x1) (H x H))^reps |00>, G = P or RZ."""
x0, x1 = x
phi01 = (np.pi - x0) * (np.pi - x1)
psi = np.array([1, 0, 0, 0], dtype=complex)
for _ in range(reps):
psi = np.kron(H, H) @ psi
psi = np.kron(gate(2 * x0), gate(2 * x1)) @ psi
psi = CNOT01 @ np.kron(I2, gate(2 * phi01)) @ CNOT01 @ psi
return psi
def zz_kernel(A, B, reps=1):
SA = np.array([zz_state(a, reps) for a in A])
SB = np.array([zz_state(b, reps) for b in B])
return np.abs(SA.conj() @ SB.T) ** 2
def angle_kernel(A, B):
"""Classical cos^2 product kernel of the R_X angle encoding: prod_j cos^2((a_j - b_j) / 2)."""
return np.prod(np.cos((A[:, None, :] - B[None, :, :]) / 2) ** 2, axis=2)
# 3. Closed form of the state and the R_Z global phase e^{-i(x0 + x1 + phi01)}, on the first training point.
x0, x1 = X_train[0]
phi01 = (np.pi - x0) * (np.pi - x1)
closed = 0.5 * np.exp(1j * np.array([0, 2 * x1 + 2 * phi01, 2 * x0 + 2 * phi01, 2 * x0 + 2 * x1]))
print("closed form = circuit:", np.allclose(zz_state(X_train[0]), closed, atol=1e-12))
ratio = zz_state(X_train[0], gate=RZ) / zz_state(X_train[0])
print("R_Z state / P state = e^{-i(x0+x1+phi01)}:", np.allclose(ratio, np.exp(-1j * (x0 + x1 + phi01)), atol=1e-12))
# 4. Precomputed-kernel SVMs: accuracies and kernel-target alignment on the training Gram matrix.
def evaluate(name, kernel, C=1.0):
K_train, K_test = kernel(X_train, X_train), kernel(X_test, X_train) # (70, 70) and (30, 70)
model = SVC(kernel="precomputed", C=C).fit(K_train, y_train)
s = 2 * y_train - 1 # labels as +-1
alignment = s @ K_train @ s / (np.linalg.norm(K_train) * len(s))
print(f"{name:<12} C = {C:<6g} train {model.score(K_train, y_train):.4f} test {model.score(K_test, y_test):.4f} alignment {alignment:.4f}")
evaluate("ZZ reps 1", zz_kernel)
evaluate("ZZ reps 2", lambda A, B: zz_kernel(A, B, reps=2))
evaluate("angle cos^2", angle_kernel)
evaluate("ZZ reps 1", zz_kernel, C=1000.0)Expected output
closed form = circuit: True
R_Z state / P state = e^{-i(x0+x1+phi01)}: True
ZZ reps 1 C = 1 train 0.8714 test 0.9333 alignment 0.1987
ZZ reps 2 C = 1 train 0.8143 test 0.7667 alignment 0.1092
angle cos^2 C = 1 train 0.8571 test 1.0000 alignment 0.2156
ZZ reps 1 C = 1000 train 1.0000 test 0.9000 alignment 0.1987The TypeScript cell runs the same pipeline on the platform's engine: the statevector simulator for the kernels and its own SMO solver of the dual (a different implementation from LIBSVM) for training. It reaches the same accuracies, and additionally prints the ranks proved above and the average kernel value over pairs of training points that are close together (distance below ) or far apart (distance above ).
import { eigvalsh, matrix } from '@/lib/quantum-simulator';
import { angleEncoding, kernelMatrix, kernelTargetAlignment, moonsSplit, svmPredict, trainSvm, zzFeatureMap, type FeatureMap } from '@/lib/qml';
// Two moons, scaled to [0, pi], rows 0-69 train / 70-99 test; labels 0/1 mapped to -1/+1 for the SVM.
const { Xtrain, ytrain, Xtest, ytest } = moonsSplit();
const yTrain = ytrain.map((v) => (v === 1 ? 1 : -1));
const yTest = ytest.map((v) => (v === 1 ? 1 : -1));
const rows = (K: Float64Array[]) => K.map((r) => Array.from(r));
const accuracy = (pred: Int8Array, y: number[]) => pred.filter((p, i) => p === y[i]).length / y.length;
const dist = (a: number[], b: number[]) => Math.hypot(a[0] - b[0], a[1] - b[1]);
const maps: [string, FeatureMap][] = [
['ZZ reps 1 ', zzFeatureMap(2, { reps: 1 })],
['ZZ reps 2 ', zzFeatureMap(2, { reps: 2 })],
['angle (R_X)', angleEncoding(2, { rotation: 'RX' })],
];
for (const [name, map] of maps) {
const Ktrain = kernelMatrix(map, Xtrain); // 70 x 70 Gram matrix
const Ktest = kernelMatrix(map, Xtest, Xtrain); // 30 x 70 test block
const model = trainSvm(Ktrain, yTrain, { C: 1 }); // SMO on the soft-margin dual
const train = accuracy(svmPredict(model, rows(Ktrain)), yTrain);
const test = accuracy(svmPredict(model, rows(Ktest)), yTest);
const ev = eigvalsh(matrix.fromRows(rows(Ktrain)));
const rank = Array.from(ev).filter((l) => l > 1e-9 * ev[ev.length - 1]).length;
// mean kernel value over training pairs that are close (distance < 0.5) and far apart (distance > 2)
let nearSum = 0, nearCount = 0, farSum = 0, farCount = 0;
for (let i = 0; i < Xtrain.length; i++) {
for (let j = i + 1; j < Xtrain.length; j++) {
const d = dist(Xtrain[i], Xtrain[j]);
if (d < 0.5) { nearSum += Ktrain[i][j]; nearCount++; }
if (d > 2) { farSum += Ktrain[i][j]; farCount++; }
}
}
console.log(name + ': rank ' + rank + ', alignment ' + kernelTargetAlignment(Ktrain, yTrain).toFixed(4) + ', mean K near ' + (nearSum / nearCount).toFixed(3) + ' / far ' + (farSum / farCount).toFixed(3) + ', train ' + train.toFixed(4) + ', test ' + test.toFixed(4));
}Expected output
ZZ reps 1 : rank 13, alignment 0.1987, mean K near 0.700 / far 0.275, train 0.8714, test 0.9333 ZZ reps 2 : rank 16, alignment 0.1092, mean K near 0.584 / far 0.275, train 0.8143, test 0.7667 angle (R_X): rank 9, alignment 0.2156, mean K near 0.974 / far 0.145, train 0.8571, test 1.0000
Definition
Kernel–target alignment
For a Gram matrix and labels , the kernel–target alignment (Cristianini et al. 2002) is the cosine of the angle between and the ideal kernel in the Frobenius inner product, It is large when same-class pairs have large kernel values and different-class pairs small ones; it is computed from the training data alone.
Range of the alignment
, with if and only if for some . If , then .
Proof (5 steps)
- Step 1:Definition of the Frobenius inner product .
- Step 2:Every .
- Step 3:Cauchy–Schwarz inequality in the inner-product space of real matrices.
- Step 4:Equality in Cauchy–Schwarz holds exactly for parallel vectors, and the sign of the inner product must be positive.
- Step 5:The numerator is a value of the quadratic form of .
∎
What the numbers say. One repetition of the ZZ map yields a good classifier, of test points. A second repetition lowers the test accuracy to . A common explanation for such a drop is over-expressivity leading to memorisation: in the lesson on quantum kernels we proved that for wide or deep feature maps the off-diagonal kernel values concentrate around , the Gram matrix approaches the identity, the SVM can fit any labelling of the training set, and its predictions on new points degenerate. With only two qubits this regime is out of reach, and the data show a different, more modest mechanism.
- The second repetition makes the kernel less aligned with the labels: instead of . The extra layer of Hadamards and phases mixes the single-qubit and product phases, so the similarity of two points depends less on whether they belong to the same moon.
- The kernel becomes less local. Training pairs closer than have mean kernel under one repetition but only under two, while pairs farther apart than stay at in both cases, close to the value that unrelated two-qubit states have on average. Neighbours look less alike, and distant points look as alike as before.
- At the reps-2 model does not memorise: its training accuracy, , is lower than that of the reps-1 model, . It fits the training set worse and generalises worse, which is the signature of a kernel whose inductive bias does not match the data, not of overfitting. Memorisation does appear when the margin penalty is large: the reps-1 kernel with classifies every training point correctly and drops to on the test set.
- The classical angle kernel is the best of the three, , with the largest alignment (), the smallest rank () and the strongest locality (near pairs , far pairs ). By the bandwidth theorem it behaves like a Gaussian kernel with in the scaled coordinates, a smooth similarity that suits two curved, well separated classes.
Alignment computed on the training set ranked the three kernels in the same order as their test accuracies, before any test label was used, which is why it is a useful diagnostic for choosing a feature map. It is not a guarantee: alignment ignores the regularisation parameter and the margin, and on other data the ranking can change.
The workbench runs the whole pipeline in the browser on the same split: it prepares one feature state per point, builds and , trains the SVM and draws the decision function over the scaled feature square with its zero contour, the training and test points, and a table with the accuracies, the number of support vectors, the smallest eigenvalue and the alignment. It starts from the ZZ kernel with one repetition (two misclassified test points); the second instance below starts from two repetitions (seven misclassified). Compare where the zero contour runs relative to the gap between the moons in the two cases, switch the kernel to the angle encoding (implemented with rotations, which give the same kernel as ) to see the classical baseline, and vary and the feature scale to connect the picture with the bandwidth theorem.
Quick check
At , the ZZ kernel with two repetitions has training accuracy and test accuracy ; with one repetition, and . Which conclusion do these numbers support?
References
- V. Havlíček, A. D. Córcoles, K. Temme, A. W. Harrow, A. Kandala, J. M. Chow and J. M. Gambetta, Supervised learning with quantum-enhanced feature spaces, Nature 567, 209–212 (2019).doi:10.1038/s41586-019-0980-2
- M. Schuld and N. Killoran, Quantum machine learning in feature Hilbert spaces, Physical Review Letters 122, 040504 (2019).doi:10.1103/PhysRevLett.122.040504
- C. Cortes and V. Vapnik, Support-vector networks, Machine Learning 20, 273–297 (1995).doi:10.1007/BF00994018
- C.-C. Chang and C.-J. Lin, LIBSVM: A library for support vector machines, ACM Transactions on Intelligent Systems and Technology 2(3), 27 (2011).doi:10.1145/1961189.1961199
- F. Pedregosa et al., Scikit-learn: Machine learning in Python, Journal of Machine Learning Research 12, 2825–2830 (2011).jmlr.org
- N. Cristianini, J. Shawe-Taylor, A. Elisseeff and J. Kandola, On kernel-target alignment, Advances in Neural Information Processing Systems 14 (NIPS 2001), MIT Press (2002).proceedings.neurips.cc
- N. J. Higham, Computing a nearest symmetric positive semidefinite matrix, Linear Algebra and its Applications 103, 103–118 (1988).doi:10.1016/0024-3795(88)90223-6
- H.-Y. Huang, M. Broughton, M. Mohseni, R. Babbush, S. Boixo, H. Neven and J. R. McClean, Power of data in quantum machine learning, Nature Communications 12, 2631 (2021).doi:10.1038/s41467-021-22539-9
- R. Shaydulin and S. M. Wild, Importance of kernel bandwidth in quantum machine learning, Physical Review A 106, 042407 (2022).doi:10.1103/PhysRevA.106.042407
- M. Schuld, R. Sweke and J. J. Meyer, Effect of data encoding on the expressive power of variational quantum machine-learning models, Physical Review A 103, 032430 (2021).doi:10.1103/PhysRevA.103.032430
Hands-on labs
Quantum-kernel SVM on two moons
2 steps · auto-gradedOpen labBuild the complete quantum-kernel classifier of the lesson in Python. First implement the fidelity kernel of the two-qubit ZZ feature map with one repetition by simulating its circuit with NumPy; the grader compares your matrices with the platform's statevector engine and checks symmetry and positive semidefiniteness. Then train scikit-learn's
SVC(kernel="precomputed", C=1.0)on the training Gram matrix of the two-moons data scaled to and predict the held-out points; the grader computes the test accuracy from your predictions and requires at least (the reference pipeline reaches ).