Lesson 39 · 110 min · advanced
Quantum Kernels & Fidelity Kernels
A quantum feature map defines the fidelity kernel . This lesson proves via the cyclicity of the trace that , proves that every quantum kernel matrix is positive semidefinite because , identifies as the linear kernel of the Hilbert–Schmidt feature space of density operators and its RKHS as the expectation values , derives the closed form for product encodings, proves exponential concentration (, ), shows that the projected quantum kernel is positive definite and keeps an -independent scale, and counts the shots needed to estimate a whole Gram matrix.
Prerequisites: RKHS, Representer & Mercer's Theorem, Angle & Phase Encoding
Objectives and key results
Derive from the cyclicity of the trace and relate it to the inversion test.
Prove that every quantum kernel matrix is positive semidefinite and that it is the Gram matrix of the vectors , i.e. the linear kernel in the Hilbert–Schmidt feature space.
Describe the RKHS of a fidelity kernel as the functions and connect it to the representer theorem of the previous module.
Compute the fidelity kernel of , and phase product encodings in closed form, .
Prove and for uniformly distributed data, and explain why exponentially many shots are then needed.
Prove that the projected quantum kernel is positive definite and compute its mean, , for product encodings.
Bound the number of shots per kernel entry () and the number of circuits for a Gram matrix ().
- identity · Fidelity kernel as a Hilbert–Schmidt inner product
- theorem · Quantum kernel matrices are positive semidefinite
- formula · Product-encoding kernel
- theorem · Exponential concentration
- definition · Projected quantum kernel
- formula · Shot cost of a Gram matrix
Quantum feature maps and the fidelity kernel#
The previous module ended with a proposition: if data are encoded into quantum states , the fidelity is a positive-definite kernel whose feature vectors are the density matrices . The encoding lessons of Module 3.2 built the circuits that produce such states. This lesson turns the observation into a learning method. A quantum kernel method splits the work between two machines: a quantum computer estimates the entries of the Gram matrix, and a classical computer solves the convex training problem of a support vector machine or of kernel ridge regression exactly as in the kernel-methods lesson, with a model of the form guaranteed by the representer theorem. We first make the kernel precise and prove its basic identities, then describe its feature space and RKHS, compute it in closed form for product encodings, and finally confront the two quantities that decide whether the method is usable at scale: the typical size of the kernel values and the number of measurements needed to estimate them.
Definition
Quantum feature map and encoded density operator
Let be the data domain. A quantum feature map on qubits is a map from to the unitary matrices, realised by a parameter-free circuit for each . It produces the feature state and the encoded density operator Since is unitary, , so is a rank-one orthogonal projector: , , . Multiplying by a global phase leaves unchanged.
Definition
Fidelity kernel and quantum kernel matrix
The fidelity (quantum) kernel of a quantum feature map is For training inputs the quantum kernel matrix (Gram matrix) is the real matrix . For test inputs the test kernel is the matrix .
The fidelity kernel is a trace of a product of density operators
For all , Moreover , , , with if and only if for some ; and does not change when the feature states are multiplied by data-dependent global phases.
Proof (7 steps)
- Step 1:Cyclicity of the trace, valid also for rectangular factors: write out the diagonal entries of , exchange the two finite sums, and recognise the diagonal entries of .
- Step 2:Abbreviate , . Matrix multiplication is associative, and the middle factor is a matrix, i.e. a scalar that can be moved to the front.
- Step 3:Cyclicity with the column and the row : is the matrix , whose trace is its only entry.
- Step 4:Linearity of the trace pulls out the scalar; conjugate symmetry of the inner product gives , and .
- Step 5:Symmetry is cyclicity once more (or ).
- Step 6:Cauchy–Schwarz inequality for the unit vectors ; equality holds exactly when is a scalar multiple , and forces , i.e. . In particular .
- Step 7:The bra conjugates its phase; a unimodular factor drops out of the modulus. Equivalently, itself is phase-free, so the right-hand side cannot depend on the phases.
∎
Reading a kernel entry off a circuit
- Step 1:Inversion (compute–uncompute) test: prepare , apply the inverse circuit of , measure all qubits; the Born rule gives the probability of the all-zero outcome.
- Step 2:; the all-zero probability is the kernel entry. It uses qubits and twice the depth of (lesson The Inversion Test).
- Step 3:The SWAP test (lesson The SWAP Test) needs qubits and controlled-SWAP gates but no inverse circuit; it also works for states whose preparation is unknown.
Result
Quick check
The inversion-test circuit is run times and the outcome appears times. Which quantity does estimate?
Positive semidefiniteness and the Hilbert–Schmidt feature space#
Definition
Hilbert–Schmidt inner product on Hermitian matrices
Let , a real vector space of dimension ( real diagonal entries and a real and an imaginary part for each of the entries above the diagonal). The Hilbert–Schmidt inner product and norm are The RKHS lesson showed that is real for Hermitian and that it is a real inner product on . For qubits and .
Every quantum kernel matrix is positive semidefinite
For every , all inputs and all , Hence every quantum kernel matrix is symmetric positive semidefinite, is a positive-definite (Mercer) kernel, and is the linear kernel of the feature space with feature map .
Proof (7 steps)
- Step 1:The coefficients are real and every is Hermitian, so is Hermitian.
- Step 2:Replace every kernel value by the trace identity of the previous theorem.
- Step 3:The trace is linear and the matrix product is bilinear, so the double sum can be moved inside as a product of two finite sums.
- Step 4:Use ; the diagonal entry is a sum of squared moduli, and so is the trace. It vanishes only for .
- Step 5:Symmetry was proved before; together with the nonnegative quadratic form this is the definition of a positive-definite kernel from the RKHS lesson.
- Step 6:By the Moore–Aronszajn construction has a unique RKHS, and the representer theorem reduces training in it to coefficients .
- Step 7:The proof used only that each is Hermitian, so remains a valid kernel when noise turns the encoded states into mixed states (it is then no longer equal to the fidelity, and ).
∎
The quantum kernel matrix is a Gram matrix of vectorised density operators
Let list the entries of . Then , so In real coordinates: with the Pauli strings and , the Euclidean Gram matrix of the real feature vectors . For one qubit this reads with the Bloch vectors .
Proof (7 steps)
- Step 1:The standard inner product of the vectorised matrices is the Hilbert–Schmidt inner product: .
- Step 2:Insert , and use the trace identity; entry of is the inner product of columns and .
- Step 3:A second proof of positive semidefiniteness (for real , ). implies , so and have the same kernel and the same rank; has columns and rows.
- Step 4:Pauli strings with , . The mixed-product rule and reduce the trace to one qubit, where (, and is traceless for distinct non-identity indices, as is each with ).
- Step 5:The Hermitian Pauli strings are pairwise orthogonal, hence linearly independent, hence a basis of . Multiplying the expansion by and taking the trace isolates one coefficient, so . Each is real (an inner product of Hermitian matrices) and because it is the expectation value of an observable with eigenvalues .
- Step 6:Insert both expansions and use .
- Step 7:and is the Bloch vector, so the single-qubit fidelity kernel is an affine function of the Euclidean inner product of Bloch vectors.
∎
The RKHS of a fidelity kernel consists of expectation values
Let and . Then , and every Hermitian observable defines a function . The trained kernel model is the expectation value of the observable .
Proof (7 steps)
- Step 1:Every kernel section is the expectation value of the observable .
- Step 2:Linearity of . Conversely every is a finite real combination of encoded states, so the pre-Hilbert space of finite kernel combinations from the RKHS lesson is exactly .
- Step 3:The Moore–Aronszajn inner product with the trace identity and bilinearity, where .
- Step 4:is injective on , so the norm is well defined and is an isometric isomorphism .
- Step 5:A finite-dimensional inner-product space is complete, so the completion step of the construction adds nothing.
- Step 6:Orthogonal decomposition in the finite-dimensional space ; is orthogonal to . So any measured observable gives a function in , with norm .
- Step 7:The representer form is the expectation value of one optimal observable, and the regulariser of kernel ridge regression or the SVM is its squared Hilbert–Schmidt norm. A variational classifier that measures after the same encoding searches a subset of these functions (Stage 4).
∎
Quick check
A quantum kernel matrix is estimated on hardware with shots per entry, and its smallest eigenvalue comes out as . What is the correct conclusion?
Closed form for product encodings#
For a general entangling feature map the kernel has no simple formula and must be simulated or measured. For the product (angle) encodings of the lesson Angle & Phase Encoding, in which feature is written into qubit by one rotation, the kernel factorises and can be computed exactly. The closed form is the basis of the lab and of the concentration analysis in the next section.
Fidelity kernel of a product encoding
Let with and a scale (qubit carries feature ). Then The same kernel is obtained for the phase encoding . It has the explicit real feature map , so every product-encoding Gram matrix has rank at most , below the general bound .
Proof (9 steps)
- Step 1:Exponential series; since , the even powers are and the odd powers are , which sum to the cosine and sine series.
- Step 2:Exponentials of multiples of the same operator commute, so their exponents add; .
- Step 3:and are orthogonal to , so .
- Step 4:, the mixed-product rule , and the factorisation of inner products of product vectors.
- Step 5:The second and third steps, factor by factor.
- Step 6:The overlap is real, so its squared modulus is its square; cosine is even; .
- Step 7:Phase encoding: the same argument with replaced by and , since .
- Step 8:Addition theorem: each one-qubit factor is the inner product of three-dimensional real feature vectors.
- Step 9:; the Gram matrix is with , whose rank is at most its number of rows. For two features and random points the Gram matrix has exactly nonzero eigenvalues.
∎
Cross-check with Bloch vectors (one qubit)
- Step 1:First column of .
- Step 2:and : moves the Bloch vector on the great circle of the -plane.
- Step 3:The Pauli-coordinate formula for one qubit, the addition theorem for the cosine, and the half-angle identity: the same result as the theorem with , . Geometrically, is the angle between the two Bloch vectors.
Worked example: x = (0.3, 1.2), x′ = (1.0, 0.4) with the R_X encoding
- Step 1:Feature-wise differences and their halves (scale ).
- Step 2:The encoded state of as a Kronecker product (qubit is the left factor): , , , .
- Step 3:The same for .
- Step 4:Direct inner product: conjugating the bra turns into , and , so all four terms are positive.
- Step 5:The closed form gives the same overlap without writing any state vector.
- Step 6:Square the overlap. On hardware, inversion-test shots would return about times, with standard deviation .
Result
Circuit · 2 qubits
The product encoding of : on qubit and on qubit . The statevector is the product state of the worked example.
Unitary verified: (max deviation 1.4e-17)
The heatmap shows the Gram matrix of points of the two-circles dataset (features min–max scaled to ) under the product encoding, together with its eigenvalues. Because the kernel depends only on the differences , it is a translation-invariant kernel, a product of one-dimensional cosine kernels; nearby points have entries close to . Switch the encoding to the ZZ feature map below: its entangling phases make the kernel depend on products of features, the block structure changes, and no closed form is available.
Quick check
Two features are encoded with rotations (scale ). What is for and ?
Exponential concentration#
Definition
Exponential concentration of a kernel
Let be a family of quantum kernels on qubits and let be drawn independently from data distributions . The family is exponentially concentrated (towards ) if there is with By Chebyshev's inequality, for every fixed the probability , , is then : almost every pair of inputs has essentially the same kernel value (Thanasilp et al. 2024).
The difference of a uniform angle and any independent angle is uniform
Let be independent with uniform. Then is uniform on and independent of , and for every -periodic integrable ,
Proof (4 steps)
- Step 1:For fixed , is a rotation of the circle : a bijection that maps every interval to an interval (or a union of two intervals) of the same total length.
- Step 2:is uniform and independent of , and preserves length (translation invariance of length on the circle), for every interval .
- Step 3:The conditional law does not depend on , so it is also the unconditional law, and is independent of . Note that need not be uniform.
- Step 4:and differ by a multiple of , which a -periodic function does not see.
∎
Mean and variance of the product-encoding kernel
Let (the or product encoding with ), and let all coordinates of be independent and uniform on . Then In particular the kernel is exponentially concentrated with , and its standard deviation is below .
Proof (7 steps)
- Step 1:is -periodic; apply the lemma.
- Step 2:Half-angle identity; the cosine integrates to zero over a full period.
- Step 3:Square the half-angle form and use once more.
- Step 4:The lemma again; for .
- Step 5:The pairs are independent for different , hence so are functions of them, and the expectation of a product of independent bounded variables is the product of the expectations.
- Step 6:Apply the factorisation to and to , using .
- Step 7:Definition of the variance; the bound gives the concentration rate of the definition.
∎
Tail bounds and the typical kernel value
Under the assumptions of the theorem, for every : and . Moreover almost surely, i.e. a typical off-diagonal entry is , even smaller than the mean .
Proof (6 steps)
- Step 1:Markov's inequality for the nonnegative variable .
- Step 2:Chebyshev's inequality: Markov applied to with .
- Step 3:With features, fewer than one pair in ten thousand has a kernel value above : the Gram matrix is numerically the identity matrix.
- Step 4:The substitution swaps sine and cosine. Adding the two forms and using ; the substitution and the symmetry of about give . Hence .
- Step 5:The lemma, the substitution , and by symmetry about .
- Step 6:is a sum of i.i.d. integrable terms, so the strong law of large numbers applies. The mean is dominated by rare pairs with unusually large values.
∎
The uniform dataset draws points i.i.d. on . With features the off-diagonal entries cluster near (most of them far below it), the heatmap is a bright diagonal on a dark background, and the eigenvalues bunch around (roughly between and for points, against a few large eigenvalues and many zeros for the two-dimensional datasets): the Gram matrix approaches the identity , and does so faster as grows. In the basis-encoding lesson we proved that a kernel with makes kernel ridge regression predict a constant at every unseen input; exponential concentration drives a continuous encoding into the same failure mode. Reduce the number of features to or and the structure returns.
A small bandwidth prevents concentration
Suppose for all and the scale is with . Then for the product encoding for every pair of inputs, independently of .
Proof (4 steps)
- Step 1:for all real .
- Step 2:The assumptions on , and .
- Step 3:Weierstrass product inequality, by induction: whenever and (if the right-hand side is negative and the left-hand side is nonnegative).
- Step 4:Combine the three lines. Choosing the bandwidth keeps every kernel value of order one (Shaydulin and Wild 2022). In the heatmap widget the parameter is the range onto which each feature of the two-dimensional datasets is scaled, which plays exactly this role.
∎
Quick check
Ten features with i.i.d. uniform values on are encoded with rotations, one qubit per feature. What is the expected value of the fidelity kernel for two independent inputs?
Projected quantum kernels#
Definition
Projected quantum kernel
For a quantum feature map on qubits let be the reduced density matrix of qubit (a density matrix, mixed when qubit is entangled with the others). For the projected quantum kernel of Huang et al. (2021) is Instead of comparing the full -dimensional states, it compares their one-qubit marginals and turns the summed distance into a similarity with a Gaussian of rate .
Frobenius distance of qubit states in Bloch coordinates
For one-qubit density matrices and with Bloch vectors , :
Proof (6 steps)
- Step 1:The identity parts cancel.
- Step 2:is Hermitian; expand the square bilinearly and use linearity of the trace.
- Step 3:has trace ; for , is traceless.
- Step 4:Only the diagonal terms survive.
- Step 5:Expand the product; the Pauli matrices are traceless and .
- Step 6:For pure qubit states, ; the Frobenius distance and the one-qubit fidelity kernel carry the same information.
∎
Gaussian kernels on feature vectors are positive definite
For , is a positive-definite kernel on , and for any map the kernel is positive definite on .
Proof (6 steps)
- Step 1:Expand the squared distance and split the exponential.
- Step 2:is the linear kernel with feature ; the product rule of the RKHS lesson (Schur product theorem) applied times; for the constant has feature .
- Step 3:A sum of positive-definite kernels with nonnegative coefficients (sum and scaling rules).
- Step 4:For finitely many points the exponential series converges for every pair, so the quadratic forms converge; a limit of nonnegative numbers is nonnegative. Hence is positive definite.
- Step 5:The rule of the RKHS lesson: absorb into the coefficients .
- Step 6:The Gram matrix of the composed kernel on is the Gram matrix of on the points , which is positive semidefinite (also when some coincide).
∎
The projected quantum kernel is positive definite
For every quantum feature map and every , is a positive-definite kernel with and . With the Bloch vectors of the reduced states, a Schur product of Gaussian kernels on the reduced-state vectors.
Proof (5 steps)
- Step 1:The Bloch lemma applied to the reduced state of each qubit (a valid, possibly mixed, one-qubit density matrix).
- Step 2:The exponential of a sum is the product of the exponentials.
- Step 3:Each factor is a Gaussian kernel with rate composed with the map ; apply the Gaussian lemma.
- Step 4:The Schur product theorem (closure under pointwise products, RKHS lesson), by induction on the number of factors.
- Step 5:The exponent is minus a finite nonnegative number. Equivalently, is one Gaussian kernel of the concatenated vector .
∎
Projected kernel of the R_X product encoding and its scale
- Step 1:The partial trace of a product operator traces each discarded factor; every factor has trace . So depends on only.
- Step 2:from the Bloch cross-check; expand and use the addition theorem.
- Step 3:The Bloch lemma. Compare : a product of factors with mean against the exponential of a sum whose rate is a free parameter.
- Step 4:The uniform-difference lemma for uniform data; is the modified Bessel function of order zero, defined here by this integral.
- Step 5:The exponential series converges uniformly on , so it can be integrated term by term. With , , and only a term with survives the integration: odd powers integrate to , and the -th power to .
- Step 6:Independence across qubits, as in the concentration theorem. The bounds hold termwise, since and the term is .
- Step 7:Raise the bounds to the power . With a rate proportional to the mean kernel value stays of order one for every , instead of decaying like .
- Step 8:Independent terms; and by the lemma. The exponent fluctuates by around , so kernel values differ polynomially, not exponentially, and can be resolved with polynomially many shots.
Result
Why the projection helps, and what it costs. The fidelity kernel compares two vectors in a -dimensional space, and two generic vectors in high dimension are nearly orthogonal; for product encodings this appears as a product of factors with average . The projected kernel only compares one-qubit marginals, aggregates the local distances by a sum, and maps the sum through with a rate that can be matched to . It also changes the measurement budget: is fixed by its Bloch vector , and measuring all qubits in the , and bases gives every at once. Training on points therefore needs circuit settings instead of overlap circuits, and the kernel values are computed classically from the estimated Bloch vectors, each component to precision with shots. Two caveats: for product encodings both kernels are classically computable, and the motivation of Huang et al. is entangling encodings whose reduced states are hard to simulate; and the projected kernel concentrates as well when the reduced states approach the maximally mixed state (), as they do for highly entangling or noisy encodings.
Quick check
What is the squared Frobenius distance between and ?
Estimating a kernel matrix with shots#
Shot cost of one kernel entry
Run the inversion test times and let count the outcomes ; set . Then (a) and ; (b) , so shots give precision with probability at least ; (c) by Hoeffding's inequality suffices; (d) for the SWAP-test estimator , and suffices. In all cases .
Proof (7 steps)
- Step 1:Each shot prepares a fresh state, so the indicators of the outcome are independent Bernoulli variables with success probability (inversion-test derivation).
- Step 2:Linearity of expectation; variances of independent variables add; .
- Step 3:Complete the square: the Bernoulli variance is largest at .
- Step 4:Chebyshev's inequality and the worst-case variance.
- Step 5:Hoeffding's inequality (1963) for the mean of independent variables with values in ; it improves the dependence on the confidence from to .
- Step 6:The SWAP-test outcome is Bernoulli with ; the affine map multiplies the variance by .
- Step 7:Hoeffding with precision on : the SWAP test needs four times as many shots as the inversion test for the same guarantee, in exchange for not needing .
∎
Cost of a whole Gram matrix
For training points with pure encoded states, the Gram matrix requires distinct circuits. With inversion-test shots per entry, all entries are within simultaneously with probability at least , for a total of shots. Predictions on test points need further entries.
Proof (6 steps)
- Step 1:Pure states have purity , and the kernel is symmetric, so only the entries above the diagonal must be estimated.
- Step 2:Number of unordered pairs of distinct indices.
- Step 3:Union bound, with each entry estimated at confidence .
- Step 4:Hoeffding's bound of the previous theorem at confidence , with .
- Step 5:Multiply the number of circuits by the shots per circuit.
- Step 6:A modest dataset already needs hundreds of millions of shots, which at typical rates of a few thousand shots per second is a day of machine time. The test kernel has neither symmetry nor a known diagonal, hence entries.
∎
Concentrated kernels need exponentially many shots
If a kernel entry has size , then (a) a relative precision requires shots; (b) , so for the concentrated product-encoding kernel with a shot budget almost every estimated off-diagonal entry is exactly , the estimated Gram and test matrices are the identity and zero, and the trained model predicts the same constant at every new input.
Proof (6 steps)
- Step 1:Square both sides of the relative-precision requirement and divide by .
- Step 2:Multiply numerator and denominator by : exponentially many shots per entry.
- Step 3:All independent shots must miss the outcome .
- Step 4:Bernoulli's inequality, by induction: .
- Step 5:Average the pointwise inequality over random pairs and use the concentration theorem. For example and shots give a fraction of zero entries.
- Step 6:The basis-encoding lesson: with an identity Gram matrix, kernel ridge regression with bias predicts for every unseen input, independently of the data's structure.
∎
Quick check
How many distinct kernel circuits must be run to estimate the training Gram matrix of data points with pure encoded states?
Quick check
How many inversion-test shots per entry guarantee a standard deviation for every possible kernel value ?
The TypeScript cell below checks the main results with the platform's simulator and QML library: the lab value from the simulated states against the closed form, the positive semidefiniteness of a ZZ-feature-map Gram matrix, the concentration of the product-encoding kernel (Monte Carlo means over random pairs against , with the predicted standard deviation ), and the Frobenius–Bloch identity behind the projected kernel.
import { matrix, mulberry32, reducedStateFromPure, runStatevector } from '@/lib/quantum-simulator';
import { angleEncoding, fidelityKernel, isPositiveSemidefinite, kernelMatrix, zzFeatureMap } from '@/lib/qml';
// (1) One kernel entry: R_X product encoding, x = (0.3, 1.2), x' = (1.0, 0.4).
const rx = angleEncoding(2, { rotation: 'RX' });
const x = [0.3, 1.2];
const xp = [1.0, 0.4];
const closed = Math.cos(0.35) ** 2 * Math.cos(0.4) ** 2;
console.log("K(x, x') simulated = " + fidelityKernel(rx, x, xp).toFixed(12) + ' closed form = ' + closed.toFixed(12));
// (2) A Gram matrix of the entangling ZZ feature map: symmetric, unit diagonal, positive semidefinite.
const rng = mulberry32(39);
const X = Array.from({ length: 10 }, () => [0, 1, 2].map(() => 2 * Math.PI * rng()));
const K = kernelMatrix(zzFeatureMap(3, { reps: 2 }), X);
const trace = K.reduce((s, row, i) => s + row[i], 0);
console.log('ZZ Gram matrix 10 x 10: trace = ' + trace + ', PSD = ' + isPositiveSemidefinite(K));
// (3) Exponential concentration of the product-encoding kernel over i.i.d. uniform pairs.
for (let n = 1; n <= 6; n++) {
const enc = angleEncoding(n, { rotation: 'RX' });
const S = 2000;
let sum = 0;
for (let s = 0; s < S; s++) {
const a = Array.from({ length: n }, () => 2 * Math.PI * rng());
const b = Array.from({ length: n }, () => 2 * Math.PI * rng());
sum += fidelityKernel(enc, a, b);
}
const sd = Math.sqrt((3 / 8) ** n - 4 ** -n);
console.log('n = ' + n + ': mean K = ' + (sum / S).toFixed(4) + ' 2^-n = ' + (2 ** -n).toFixed(4) + ' predicted std = ' + sd.toFixed(4));
}
// (4) Projected kernel: ||rho_j(x) - rho_j(x')||_F^2 = |r - r'|^2 / 2 = 1 - cos(x_j - x'_j) for R_X encodings.
const sx = runStatevector(rx(x));
const sxp = runStatevector(rx(xp));
let exponent = 0;
for (let j = 0; j < 2; j++) {
const diff = matrix.sub(reducedStateFromPure(sx, [j]).toMatrix(), reducedStateFromPure(sxp, [j]).toMatrix());
const d2 = matrix.frobeniusNorm(diff) ** 2;
exponent += d2;
console.log('qubit ' + j + ': squared Frobenius distance = ' + d2.toFixed(12) + ' 1 - cos(dx) = ' + (1 - Math.cos(x[j] - xp[j])).toFixed(12));
}
console.log('projected kernel (gamma = 1) = ' + Math.exp(-exponent).toFixed(6) + ' fidelity kernel = ' + closed.toFixed(6));Expected output
K(x, x') simulated = 0.748604895026 closed form = 0.748604895026 ZZ Gram matrix 10 x 10: trace = 10, PSD = true n = 1: mean K = 0.5058 2^-n = 0.5000 predicted std = 0.3536 n = 2: mean K = 0.2518 2^-n = 0.2500 predicted std = 0.2795 n = 3: mean K = 0.1252 2^-n = 0.1250 predicted std = 0.1926 n = 4: mean K = 0.0595 2^-n = 0.0625 predicted std = 0.1260 n = 5: mean K = 0.0314 2^-n = 0.0313 predicted std = 0.0802 n = 6: mean K = 0.0168 2^-n = 0.0156 predicted std = 0.0504 qubit 0: squared Frobenius distance = 0.235157812716 1 - cos(dx) = 0.235157812716 qubit 1: squared Frobenius distance = 0.303293290653 1 - cos(dx) = 0.303293290653 projected kernel (gamma = 1) = 0.583652 fidelity kernel = 0.748605
The NumPy cell builds the encoded states as explicit Kronecker products, confirms and , evaluates the moments and exactly on the equispaced grid (the rectangle rule on a periodic grid of nodes is exact for trigonometric polynomials of degree below , and has degree ), tabulates the mean, the variance and the relative-precision shot count with , and checks the Bloch identity on a partial trace.
import numpy as np
def rx(t):
c, s = np.cos(t / 2), np.sin(t / 2)
return np.array([[c, -1j * s], [-1j * s, c]])
def phi(x):
psi = np.array([1.0 + 0j])
for xj in x:
psi = np.kron(psi, rx(xj) @ np.array([1.0, 0.0]))
return psi
# (1) One kernel entry three ways: overlap, Tr(rho rho'), product formula.
x, xp = np.array([0.3, 1.2]), np.array([1.0, 0.4])
a, b = phi(x), phi(xp)
rho, sig = np.outer(a, a.conj()), np.outer(b, b.conj())
print(f"|<phi(x)|phi(x')>| = {abs(np.vdot(a, b)):.12f}")
print(f"|<phi(x)|phi(x')>|^2 = {abs(np.vdot(a, b)) ** 2:.12f}")
print(f"Tr(rho(x) rho(x')) = {np.trace(rho @ sig).real:.12f}")
print(f"prod cos^2(dx/2) = {np.prod(np.cos((x - xp) / 2) ** 2):.12f}")
# (2) The Gram matrix is the Gram matrix of the vectors vec(rho_i), hence PSD.
pts = np.stack([np.linspace(0.0, 6.0, 8), np.linspace(2.5, 0.2, 8)], axis=1)
states = [phi(p) for p in pts]
K = np.array([[abs(np.vdot(u, v)) ** 2 for v in states] for u in states])
V = np.stack([np.outer(u, u.conj()).ravel() for u in states], axis=1)
G = V.conj().T @ V
print("K = V^dagger V:", bool(np.allclose(G, K, atol=1e-12)), "| min eigenvalue >= -1e-10:", bool(np.linalg.eigvalsh(K).min() >= -1e-10))
# (3) Moments over a uniform difference (exact on an equispaced grid): E cos^2 = 1/2, E cos^4 = 3/8.
d = 2 * np.pi * np.arange(4096) / 4096
m2, m4 = round(float(np.mean(np.cos(d / 2) ** 2)), 12), round(float(np.mean(np.cos(d / 2) ** 4)), 12)
print(f"E[cos^2] = {m2:.6f}, E[cos^4] = {m4:.6f}")
for n in (1, 2, 4, 8, 16):
mean, var = m2 ** n, m4 ** n - m2 ** (2 * n)
print(f"n = {n:2d}: E[K] = {mean:.3e}, Var[K] = {var:.3e}, shots for 10% relative error ~ {(1 - mean) / (0.01 * mean):.3e}")
# (4) Bloch vectors: ||rho - rho'||_F^2 = |r - r'|^2 / 2 for the reduced state of qubit 0.
paulis = [np.array([[0, 1], [1, 0]]), np.array([[0, -1j], [1j, 0]]), np.array([[1, 0], [0, -1]])]
def bloch(r1):
return np.array([np.trace(r1 @ p).real for p in paulis])
r0 = rho.reshape(2, 2, 2, 2).trace(axis1=1, axis2=3)
s0 = sig.reshape(2, 2, 2, 2).trace(axis1=1, axis2=3)
print(f"||rho_0 - rho_0'||_F^2 = {np.linalg.norm(r0 - s0) ** 2:.12f}, |r - r'|^2 / 2 = {np.sum((bloch(r0) - bloch(s0)) ** 2) / 2:.12f}")Expected output
|<phi(x)|phi(x')>| = 0.865219564634 |<phi(x)|phi(x')>|^2 = 0.748604895026 Tr(rho(x) rho(x')) = 0.748604895026 prod cos^2(dx/2) = 0.748604895026 K = V^dagger V: True | min eigenvalue >= -1e-10: True E[cos^2] = 0.500000, E[cos^4] = 0.375000 n = 1: E[K] = 5.000e-01, Var[K] = 1.250e-01, shots for 10% relative error ~ 1.000e+02 n = 2: E[K] = 2.500e-01, Var[K] = 7.812e-02, shots for 10% relative error ~ 3.000e+02 n = 4: E[K] = 6.250e-02, Var[K] = 1.587e-02, shots for 10% relative error ~ 1.500e+03 n = 8: E[K] = 3.906e-03, Var[K] = 3.758e-04, shots for 10% relative error ~ 2.550e+04 n = 16: E[K] = 1.526e-05, Var[K] = 1.527e-07, shots for 10% relative error ~ 6.554e+06 ||rho_0 - rho_0'||_F^2 = 0.235157812716, |r - r'|^2 / 2 = 0.235157812716
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
- M. Schuld, Supervised quantum machine learning models are kernel methods, arXiv:2101.11020 (2021).arxiv.org
- 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
- S. Thanasilp, S. Wang, M. Cerezo and Z. Holmes, Exponential concentration in quantum kernel methods, Nature Communications 15, 5200 (2024).doi:10.1038/s41467-024-49287-w
- 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
- J. M. Kübler, S. Buchholz and B. Schölkopf, The inductive bias of quantum kernels, Advances in Neural Information Processing Systems 34 (NeurIPS 2021), arXiv:2106.03747.arxiv.org
- W. Hoeffding, Probability inequalities for sums of bounded random variables, Journal of the American Statistical Association 58(301), 13–30 (1963).doi:10.1080/01621459.1963.10500830
Hands-on labs
Evaluate a quantum kernel entry
1 step · auto-gradedOpen labCompute one entry of a quantum kernel matrix by hand: the fidelity kernel of the two-qubit product encoding at and , using the closed form derived in the lesson.