QuantumCore

Lesson 42 · 120 min · advanced

End-to-End Quantum-Kernel SVM

Loading progress…

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 Ktrain∈Rm×mK_{\text{train}}\in\mathbb R^{m\times m} and prediction only through the test block Ktest∈Rm′×mK_{\text{test}}\in\mathbb R^{m'\times m}, and fixes the bias from the Karush–Kuhn–Tucker conditions. It proves that the two-qubit ZZ feature map prepares 12∑qeiθq(x)∣q⟩\tfrac12\sum_qe^{i\theta_q(x)}\lvert q\rangle, that its CNOT–phase–CNOT gadget is a Z⊗ZZ\otimes Z rotation up to a global phase, and that building it with RZR_Z instead of phase gates multiplies every state by e−i(x0+x1+φ01)e^{-i(x_0+x_1+\varphi_{01})} 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 0.93330.9333, two repetitions drop to 0.76670.7667, and the classical cos⁡2\cos^2 angle kernel reaches 1.01.0.

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 KtrainK_{\text{train}} and KtestK_{\text{test}}, derive the soft-margin dual with a precomputed kernel, and compute the bias bb and the decision function f(x)=∑iαiyiK(xi,x)+bf(x)=\sum_i\alpha_iy_iK(x_i,x)+b from the KKT conditions.

  • Write the gate-level circuit of the two-qubit ZZ feature map, prove that CNOT01 (I⊗P(λ)) CNOT01=eiλ/2e−iλZ⊗Z/2\mathrm{CNOT}_{01}\,(I\otimes P(\lambda))\,\mathrm{CNOT}_{01}=e^{i\lambda/2}e^{-i\lambda Z\otimes Z/2}, and derive the closed form of the feature state and its kernel.

  • Prove that the RZR_Z and phase-gate versions of the ZZ map differ only by the global phase e−i(x0+x1+φ01)e^{-i(x_0+x_1+\varphi_{01})} and therefore define the same kernel.

  • Explain min–max scaling to [0,π][0,\pi] and prove that for angle encodings the scale factor ss plays the role of an inverse bandwidth: ∏jcos⁡2sΔj2≤e−s2∥Δ∥2/4\prod_j\cos^2\frac{s\Delta_j}2\le e^{-s^2\lVert\Delta\rVert^2/4} 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 Vmax⁡(Λ,0)V⊤V\max(\Lambda,0)V^\top 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
max⁡0≤αi≤C, ∑iαiyi=0 ∑iαi−12∑i,jαiαjyiyj(Ktrain)ij,f(xt∗)=∑iαiyi(Ktest)ti+b\max_{0\le\alpha_i\le C,\ \sum_i\alpha_iy_i=0}\ \sum_i\alpha_i-\tfrac12\sum_{i,j}\alpha_i\alpha_jy_iy_j(K_{\text{train}})_{ij},\qquad f(x^\ast_t)=\sum_i\alpha_iy_i(K_{\text{test}})_{ti}+b
identity · ZZ gadget
CNOT01 (I⊗P(λ)) CNOT01=diag(1,eiλ,eiλ,1)=eiλ/2 e−iλ2Z⊗Z\mathrm{CNOT}_{01}\,\big(I\otimes P(\lambda)\big)\,\mathrm{CNOT}_{01}=\mathrm{diag}(1,e^{i\lambda},e^{i\lambda},1)=e^{i\lambda/2}\,e^{-i\frac\lambda2Z\otimes Z}
formula · Two-qubit ZZ feature state
∣ϕ(x)⟩=12(∣00⟩+ei(2x1+2φ01)∣01⟩+ei(2x0+2φ01)∣10⟩+ei(2x0+2x1)∣11⟩),φ01=(π−x0)(π−x1)\lvert\phi(x)\rangle=\tfrac12\big(\lvert00\rangle+e^{i(2x_1+2\varphi_{01})}\lvert01\rangle+e^{i(2x_0+2\varphi_{01})}\lvert10\rangle+e^{i(2x_0+2x_1)}\lvert11\rangle\big),\quad\varphi_{01}=(\pi-x_0)(\pi-x_1)
theorem · R_Z and phase-gate ZZ maps give the same kernel
∣ϕRZ(x)⟩=e−i(x0+x1+φ01)∣ϕ(x)⟩ ⇒ KRZ(x,x′)=K(x,x′)\lvert\phi_{R_Z}(x)\rangle=e^{-i(x_0+x_1+\varphi_{01})}\lvert\phi(x)\rangle\ \Rightarrow\ K_{R_Z}(x,x')=K(x,x')
theorem · Scale is bandwidth for angle encodings
∏jcos⁡2sΔj2≤exp⁡(−s24∥Δ∥2)(s∣Δj∣≤π),=1−s24∥Δ∥2+O(s4∥Δ∥4)\prod_j\cos^2\frac{s\Delta_j}{2}\le\exp\Big(-\frac{s^2}{4}\lVert\Delta\rVert^2\Big)\quad(s\lvert\Delta_j\rvert\le\pi),\qquad=1-\frac{s^2}4\lVert\Delta\rVert^2+O(s^4\lVert\Delta\rVert^4)
theorem · Eigenvalue clipping is the nearest PSD matrix
min⁡B⪰0∥K^−B∥F=∥K^−Vmax⁡(Λ,0)V⊤∥F=(∑λi<0λi2)1/2\min_{B\succeq0}\lVert\hat K-B\rVert_F=\lVert\hat K-V\max(\Lambda,0)V^\top\rVert_F=\Big(\sum_{\lambda_i<0}\lambda_i^2\Big)^{1/2}

The quantum-kernel SVM pipeline#

The lessons of this module built every component of a quantum kernel method separately: the fidelity kernel K(x,x′)=∣⟨ϕ(x)∣ϕ(x′)⟩∣2K(x,x')=\lvert\langle\phi(x)\vert\phi(x')\rangle\rvert^2 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 [0,π][0,\pi]. (2) Encode: choose a feature map x↦∣ϕ(x)⟩=U(x)∣0n⟩x\mapsto\lvert\phi(x)\rangle=U(x)\lvert0^n\rangle, here the two-qubit ZZ map. (3) Estimate the training block KtrainK_{\text{train}} with m(m−1)/2m(m-1)/2 kernel circuits. (4) Train a soft-margin SVM classically on KtrainK_{\text{train}}. (5) Estimate the test block KtestK_{\text{test}} with m′mm'm 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, m=70m=70 and m′=30m'=30, the two blocks need 2415+2100=45152415+2100=4515 distinct circuits.

Definition

Training and test kernel blocks

Let (x1,y1),…,(xm,ym)(x_1,y_1),\dots,(x_m,y_m) be the training data with labels yi∈{−1,+1}y_i\in\{-1,+1\} and x1∗,…,xm′∗x^\ast_1,\dots,x^\ast_{m'} the test inputs. For a kernel KK, the training block and the test block are Ktrain∈Rm×m,(Ktrain)ij=K(xi,xj);Ktest∈Rm′×m,(Ktest)ti=K(xt∗,xi).K_{\text{train}}\in\mathbb R^{m\times m},\quad(K_{\text{train}})_{ij}=K(x_i,x_j);\qquad K_{\text{test}}\in\mathbb R^{m'\times m},\quad(K_{\text{test}})_{ti}=K(x^\ast_t,x_i). Row tt of KtestK_{\text{test}} compares test point tt with every training point, in the order of the training set. For a fidelity kernel, KtrainK_{\text{train}} is symmetric with unit diagonal and KtestK_{\text{test}} has no structure beyond 0≤(Ktest)ti≤10\le(K_{\text{test}})_{ti}\le1.

Theorem

The soft-margin SVM needs only the kernel blocks

Let φ:X→F\varphi:\mathcal X\to\mathcal F be a feature map into a real inner-product space with ⟨φ(x),φ(x′)⟩=K(x,x′)\langle\varphi(x),\varphi(x')\rangle=K(x,x'), and let C>0C>0. The soft-margin primal problem min⁡w,b,ξ 12∥w∥2+C∑i=1mξis.t.yi(⟨w,φ(xi)⟩+b)≥1−ξi,  ξi≥0\min_{w,b,\xi}\ \tfrac12\lVert w\rVert^2+C\sum_{i=1}^m\xi_i\quad\text{s.t.}\quad y_i\big(\langle w,\varphi(x_i)\rangle+b\big)\ge1-\xi_i,\ \ \xi_i\ge0 has the dual max⁡α∈Rm ∑iαi−12∑i,jαiαjyiyj(Ktrain)ijs.t.0≤αi≤C,  ∑iαiyi=0,\max_{\alpha\in\mathbb R^m}\ \sum_{i}\alpha_i-\frac12\sum_{i,j}\alpha_i\alpha_jy_iy_j(K_{\text{train}})_{ij}\quad\text{s.t.}\quad0\le\alpha_i\le C,\ \ \sum_i\alpha_iy_i=0, with zero duality gap; an optimal ww is w=∑iαiyiφ(xi)w=\sum_i\alpha_iy_i\varphi(x_i) and the decision function is f(x)=∑iαiyiK(xi,x)+bf(x)=\sum_i\alpha_iy_iK(x_i,x)+b, so f(xt∗)=∑i(Ktest)ti αiyi+bf(x^\ast_t)=\sum_i(K_{\text{test}})_{ti}\,\alpha_iy_i+b. For a fidelity kernel one may take F\mathcal F = the Hermitian matrices with the Hilbert–Schmidt inner product and φ(x)=ρ(x)\varphi(x)=\rho(x); then ww is a Hermitian observable OO and f(x)=Tr(Oρ(x))+bf(x)=\mathrm{Tr}\big(O\rho(x)\big)+b.

Proof (8 steps)
  1. Step 1:
    L(w,b,ξ,α,μ)=12∥w∥2+C∑iξi−∑iαi[yi(⟨w,φ(xi)⟩+b)−1+ξi]−∑iμiξi,α,μ≥0L(w,b,\xi,\alpha,\mu)=\tfrac12\lVert w\rVert^2+C\sum_i\xi_i-\sum_i\alpha_i\big[y_i(\langle w,\varphi(x_i)\rangle+b)-1+\xi_i\big]-\sum_i\mu_i\xi_i,\qquad\alpha,\mu\ge0
    Lagrangian with one multiplier αi≥0\alpha_i\ge0 for each margin constraint and one μi≥0\mu_i\ge0 for each ξi≥0\xi_i\ge0.
  2. Step 2:
    ∇wL=w−∑iαiyiφ(xi)=0 ⇒ w=∑iαiyiφ(xi)\nabla_wL=w-\sum_i\alpha_iy_i\varphi(x_i)=0\ \Rightarrow\ w=\sum_i\alpha_iy_i\varphi(x_i)
    LL is a convex quadratic in ww; its gradient vanishes at the minimiser. The normal vector is a combination of training features, as the representer theorem predicts.
  3. Step 3:
    ∂L∂b=−∑iαiyi=0,∂L∂ξi=C−αi−μi=0 ⇒ 0≤αi=C−μi≤C\frac{\partial L}{\partial b}=-\sum_i\alpha_iy_i=0,\qquad\frac{\partial L}{\partial\xi_i}=C-\alpha_i-\mu_i=0\ \Rightarrow\ 0\le\alpha_i=C-\mu_i\le C
    LL is linear in bb and ξi\xi_i, so the infimum is −∞-\infty unless these coefficients vanish; μi≥0\mu_i\ge0 turns the second equation into the box constraint.
  4. Step 4:
    ∥∑iαiyiφ(xi)∥2=∑i,jαiαjyiyj⟨φ(xi),φ(xj)⟩=∑i,jαiαjyiyj(Ktrain)ij\Big\lVert\sum_i\alpha_iy_i\varphi(x_i)\Big\rVert^2=\sum_{i,j}\alpha_i\alpha_jy_iy_j\langle\varphi(x_i),\varphi(x_j)\rangle=\sum_{i,j}\alpha_i\alpha_jy_iy_j(K_{\text{train}})_{ij}
    Bilinearity of the inner product and the kernel property ⟨φ(xi),φ(xj)⟩=K(xi,xj)\langle\varphi(x_i),\varphi(x_j)\rangle=K(x_i,x_j): the feature vectors never appear on their own, only through kernel values.
  5. Step 5:
    L=12∥w∥2−∥w∥2−b∑iαiyi+∑iαi+∑iξi(C−αi−μi)=∑iαi−12∑i,jαiαjyiyj(Ktrain)ijL=\tfrac12\lVert w\rVert^2-\lVert w\rVert^2-b\sum_i\alpha_iy_i+\sum_i\alpha_i+\sum_i\xi_i(C-\alpha_i-\mu_i)=\sum_i\alpha_i-\tfrac12\sum_{i,j}\alpha_i\alpha_jy_iy_j(K_{\text{train}})_{ij}
    Insert the three stationarity conditions: ∑iαiyi⟨w,φ(xi)⟩=∥w∥2\sum_i\alpha_iy_i\langle w,\varphi(x_i)\rangle=\lVert w\rVert^2, the bb term and the ξ\xi terms vanish. This is the dual objective.
  6. Step 6:
    w=0, b=0, ξi=1 is feasible ⇒ primal optimum=dual optimumw=0,\ b=0,\ \xi_i=1\ \text{is feasible}\ \Rightarrow\ \text{primal optimum}=\text{dual optimum}
    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).
  7. Step 7:
    f(x)=⟨w,φ(x)⟩+b=∑iαiyi⟨φ(xi),φ(x)⟩+b=∑iαiyiK(xi,x)+bf(x)=\langle w,\varphi(x)\rangle+b=\sum_i\alpha_iy_i\langle\varphi(x_i),\varphi(x)\rangle+b=\sum_i\alpha_iy_iK(x_i,x)+b
    Insert ww; at a test point xt∗x^\ast_t the kernel values are the entries of row tt of KtestK_{\text{test}}, so f=Ktest(α∘y)+b1f=K_{\text{test}}(\alpha\circ y)+b\mathbf 1 for all test points at once.
  8. Step 8:
    ⟨ρ(x),ρ(x′)⟩HS=Tr(ρ(x)ρ(x′))=K(x,x′),w=∑iαiyiρ(xi)=:O=O†\langle\rho(x),\rho(x')\rangle_{HS}=\mathrm{Tr}\big(\rho(x)\rho(x')\big)=K(x,x'),\qquad w=\sum_i\alpha_iy_i\rho(x_i)=:O=O^\dagger
    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.

∎

Proposition

The bias from the KKT conditions

At an optimum, complementary slackness gives αi[yif(xi)−1+ξi]=0\alpha_i\big[y_if(x_i)-1+\xi_i\big]=0 and (C−αi)ξi=0(C-\alpha_i)\xi_i=0. Consequently: αi=0⇒yif(xi)≥1\alpha_i=0\Rightarrow y_if(x_i)\ge1; αi=C⇒yif(xi)≤1\alpha_i=C\Rightarrow y_if(x_i)\le1; and for every free support vector ss (0<αs<C0<\alpha_s<C), ysf(xs)=1y_sf(x_s)=1 and b=ys−∑iαiyi(Ktrain)is.b=y_s-\sum_{i}\alpha_iy_i(K_{\text{train}})_{is}. If the set SS of free support vectors is non-empty, all of them give the same bb, and solvers report the average b=1∣S∣∑s∈S(ys−∑iαiyi(Ktrain)is)b=\frac1{\lvert S\rvert}\sum_{s\in S}\big(y_s-\sum_i\alpha_iy_i(K_{\text{train}})_{is}\big).

Proof (6 steps)
  1. Step 1:
    αi[yi(⟨w,φ(xi)⟩+b)−1+ξi]=0,μiξi=(C−αi)ξi=0\alpha_i\big[y_i(\langle w,\varphi(x_i)\rangle+b)-1+\xi_i\big]=0,\qquad\mu_i\xi_i=(C-\alpha_i)\xi_i=0
    KKT complementary slackness: a multiplier can be positive only when its constraint is active. The second form uses μi=C−αi\mu_i=C-\alpha_i from the previous theorem.
  2. Step 2:
    0<αs<C ⇒ C−αs>0 ⇒ ξs=00<\alpha_s<C\ \Rightarrow\ C-\alpha_s>0\ \Rightarrow\ \xi_s=0
    A free support vector has μs>0\mu_s>0, so its slack vanishes: it lies exactly on the margin.
  3. Step 3:
    αs>0 ⇒ ysf(xs)−1+ξs=0 ⇒ ysf(xs)=1\alpha_s>0\ \Rightarrow\ y_sf(x_s)-1+\xi_s=0\ \Rightarrow\ y_sf(x_s)=1
    The margin constraint of ss is active and ξs=0\xi_s=0.
  4. Step 4:
    ys2=1 ⇒ f(xs)=ys ⇒ ∑iαiyi(Ktrain)is+b=ys ⇒ b=ys−∑iαiyi(Ktrain)isy_s^2=1\ \Rightarrow\ f(x_s)=y_s\ \Rightarrow\ \sum_i\alpha_iy_i(K_{\text{train}})_{is}+b=y_s\ \Rightarrow\ b=y_s-\sum_i\alpha_iy_i(K_{\text{train}})_{is}
    Multiply ysf(xs)=1y_sf(x_s)=1 by ysy_s and insert the decision function of the previous theorem at the training point xsx_s.
  5. Step 5:
    αi=0 ⇒ ξi=0 ⇒ yif(xi)≥1;αi=C ⇒ yif(xi)=1−ξi≤1\alpha_i=0\ \Rightarrow\ \xi_i=0\ \Rightarrow\ y_if(x_i)\ge1;\qquad\alpha_i=C\ \Rightarrow\ y_if(x_i)=1-\xi_i\le1
    For αi=0\alpha_i=0, μi=C>0\mu_i=C>0 forces ξi=0\xi_i=0 and primal feasibility gives yif(xi)≥1y_if(x_i)\ge1; for αi=C\alpha_i=C the margin constraint is active with ξi≥0\xi_i\ge0.
  6. Step 6:
    bs=bs′  ∀s,s′∈S ⇒ 1∣S∣∑s∈Sbs=bb_s=b_{s'}\ \ \forall s,s'\in S\ \Rightarrow\ \frac1{\lvert S\rvert}\sum_{s\in S}b_s=b
    In exact arithmetic every free support vector yields the same value; an iterative solver stops at a tolerance, and averaging the bsb_s 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 bb when SS is empty).

∎

Quick check

A precomputed-kernel SVM was trained on m=70m=70 points. Which matrix must be passed to predict to classify m′=30m'=30 new points?

Select one answer

The two-qubit ZZ feature map#

Definition

Two-qubit ZZ feature map (one repetition)

For x=(x0,x1)∈R2x=(x_0,x_1)\in\mathbb R^2 let φ01(x)=(π−x0)(π−x1)\varphi_{01}(x)=(\pi-x_0)(\pi-x_1). The ZZ feature map of Havlíček et al. (2019) with one repetition prepares ∣ϕ(x)⟩=CNOT01 P1(2φ01(x)) CNOT01 P0(2x0) P1(2x1) (H⊗H)∣00⟩,\lvert\phi(x)\rangle=\mathrm{CNOT}_{01}\,P_1\big(2\varphi_{01}(x)\big)\,\mathrm{CNOT}_{01}\,P_0(2x_0)\,P_1(2x_1)\,(H\otimes H)\lvert00\rangle, where the rightmost operator acts first, Pq(λ)P_q(\lambda) is the phase gate P(λ)=diag(1,eiλ)P(\lambda)=\mathrm{diag}(1,e^{i\lambda}) on qubit qq, and CNOT01\mathrm{CNOT}_{01} has control 00 and target 11. With qubit 00 as the most significant bit, P0(λ)=P(λ)⊗IP_0(\lambda)=P(\lambda)\otimes I, P1(λ)=I⊗P(λ)P_1(\lambda)=I\otimes P(\lambda) and CNOT01=(1000010000010010),H⊗H=12(11111−11−111−1−11−1−11).\mathrm{CNOT}_{01}=\begin{pmatrix}1&0&0&0\\0&1&0&0\\0&0&0&1\\0&0&1&0\end{pmatrix},\qquad H\otimes H=\frac12\begin{pmatrix}1&1&1&1\\1&-1&1&-1\\1&1&-1&-1\\1&-1&-1&1\end{pmatrix}. With rr repetitions the block CNOT01P1(2φ01)CNOT01P0(2x0)P1(2x1)(H⊗H)\mathrm{CNOT}_{01}P_1(2\varphi_{01})\mathrm{CNOT}_{01}P_0(2x_0)P_1(2x_1)(H\otimes H) is applied rr times. The single-qubit phases encode the features, the CNOT–phase–CNOT gadget encodes their product, and the kernel is K(x,x′)=∣⟨ϕ(x)∣ϕ(x′)⟩∣2K(x,x')=\lvert\langle\phi(x)\vert\phi(x')\rangle\rvert^2.

Circuit · 2 qubits

Quantum circuit on 2 qubitsH on q0; H on q1; P(0.60) on q0; P(2.40) on q1; X on q1 controlled by q0; P(11.03) on q1; X on q1 controlled by q0q0q1HHP(0.60)P(2.40)P(11.03)

The ZZ feature map at x=(0.3,1.2)x=(0.3,1.2): HH on both qubits, P0(0.6)P_0(0.6), P1(2.4)P_1(2.4), then CNOT01 P1(2(π−0.3)(π−1.2)) CNOT01\mathrm{CNOT}_{01}\,P_1\big(2(\pi-0.3)(\pi-1.2)\big)\,\mathrm{CNOT}_{01}. All four amplitudes of the output have modulus 12\tfrac12; only their phases carry the data.

∣ψ⟩=12∣00⟩+(0.3232+0.3815i)∣01⟩+(0.2981−0.4014i)∣10⟩+(−0.495+0.0706i)∣11⟩\lvert\psi\rangle = \tfrac{1}{2}\lvert 00\rangle + \left(0.3232 + 0.3815i\right)\lvert 01\rangle + \left(0.2981 - 0.4014i\right)\lvert 10\rangle + \left(-0.495 + 0.0706i\right)\lvert 11\rangle
Lemma

The CNOT–phase–CNOT gadget is a ZZ rotation

For every λ∈R\lambda\in\mathbb R, CNOT01 (I⊗P(λ)) CNOT01=diag(1,eiλ,eiλ,1)=eiλ/2exp⁡(−iλ2 Z⊗Z).\mathrm{CNOT}_{01}\,\big(I\otimes P(\lambda)\big)\,\mathrm{CNOT}_{01}=\mathrm{diag}\big(1,e^{i\lambda},e^{i\lambda},1\big)=e^{i\lambda/2}\exp\Big(-i\frac\lambda2\,Z\otimes Z\Big). On basis states it multiplies ∣q0q1⟩\lvert q_0q_1\rangle by eiλ(q0⊕q1)e^{i\lambda(q_0\oplus q_1)}, a phase that depends only on the parity of the two bits.

Proof (6 steps)
  1. Step 1:
    CNOT01∣q0q1⟩=∣q0, q0⊕q1⟩,CNOT012=I\mathrm{CNOT}_{01}\lvert q_0q_1\rangle=\lvert q_0,\,q_0\oplus q_1\rangle,\qquad\mathrm{CNOT}_{01}^2=I
    The CNOT flips the target exactly when the control is 11; applying it twice adds q0q_0 twice modulo 22, which is the identity.
  2. Step 2:
    (I⊗P(λ))∣q0, q0⊕q1⟩=eiλ(q0⊕q1)∣q0, q0⊕q1⟩\big(I\otimes P(\lambda)\big)\lvert q_0,\,q_0\oplus q_1\rangle=e^{i\lambda(q_0\oplus q_1)}\lvert q_0,\,q_0\oplus q_1\rangle
    P(λ)∣b⟩=eiλb∣b⟩P(\lambda)\lvert b\rangle=e^{i\lambda b}\lvert b\rangle for b∈{0,1}b\in\{0,1\}, here applied to the target bit b=q0⊕q1b=q_0\oplus q_1.
  3. Step 3:
    CNOT01(I⊗P(λ))CNOT01∣q0q1⟩=eiλ(q0⊕q1) CNOT01∣q0, q0⊕q1⟩=eiλ(q0⊕q1)∣q0q1⟩\mathrm{CNOT}_{01}\big(I\otimes P(\lambda)\big)\mathrm{CNOT}_{01}\lvert q_0q_1\rangle=e^{i\lambda(q_0\oplus q_1)}\,\mathrm{CNOT}_{01}\lvert q_0,\,q_0\oplus q_1\rangle=e^{i\lambda(q_0\oplus q_1)}\lvert q_0q_1\rangle
    Linearity pulls the scalar out; the second CNOT undoes the first because q0⊕(q0⊕q1)=q1q_0\oplus(q_0\oplus q_1)=q_1.
  4. Step 4:
    (q0⊕q1)q=00,01,10,11=(0,1,1,0) ⇒ diag(1,eiλ,eiλ,1)(q_0\oplus q_1)_{q=00,01,10,11}=(0,1,1,0)\ \Rightarrow\ \mathrm{diag}(1,e^{i\lambda},e^{i\lambda},1)
    The operator is diagonal in the computational basis, ordered ∣00⟩,∣01⟩,∣10⟩,∣11⟩\lvert00\rangle,\lvert01\rangle,\lvert10\rangle,\lvert11\rangle.
  5. Step 5:
    (Z⊗Z)∣q0q1⟩=(−1)q0(−1)q1∣q0q1⟩=(−1)q0⊕q1∣q0q1⟩,q0⊕q1=1−(−1)q0⊕q12(Z\otimes Z)\lvert q_0q_1\rangle=(-1)^{q_0}(-1)^{q_1}\lvert q_0q_1\rangle=(-1)^{q_0\oplus q_1}\lvert q_0q_1\rangle,\qquad q_0\oplus q_1=\frac{1-(-1)^{q_0\oplus q_1}}2
    Z∣b⟩=(−1)b∣b⟩Z\lvert b\rangle=(-1)^b\lvert b\rangle, and (−1)q0+q1=(−1)q0⊕q1(-1)^{q_0+q_1}=(-1)^{q_0\oplus q_1} since only the parity of the exponent matters; the second identity checks on the two parities 00 and 11.
  6. Step 6:
    eiλ(q0⊕q1)=eiλ/2 e−iλ2(−1)q0⊕q1 ⇒ diag(1,eiλ,eiλ,1)=eiλ/2exp⁡(−iλ2Z⊗Z)e^{i\lambda(q_0\oplus q_1)}=e^{i\lambda/2}\,e^{-i\frac\lambda2(-1)^{q_0\oplus q_1}}\ \Rightarrow\ \mathrm{diag}(1,e^{i\lambda},e^{i\lambda},1)=e^{i\lambda/2}\exp\Big(-i\frac\lambda2Z\otimes Z\Big)
    Insert the parity identity. A function of a diagonal matrix acts entrywise on its eigenvalues, so exp⁡(−iλ2Z⊗Z)\exp(-i\frac\lambda2Z\otimes Z) has the eigenvalue e−iλ2(−1)q0⊕q1e^{-i\frac\lambda2(-1)^{q_0\oplus q_1}} on ∣q0q1⟩\lvert q_0q_1\rangle.

∎

CNOT01(I⊗P(π2))CNOT01=(10000i0000i00001)=eiπ/4exp⁡(−iπ4Z⊗Z)\mathrm{CNOT}_{01}\big(I\otimes P(\tfrac\pi2)\big)\mathrm{CNOT}_{01}=\begin{pmatrix}1&0&0&0\\0&i&0&0\\0&0&i&0\\0&0&0&1\end{pmatrix}=e^{i\pi/4}\exp\Big(-i\frac\pi4Z\otimes Z\Big)
CNOT_01 (I ⊗ P(π/2)) CNOT_014×4

Unitary verified: U†U=IU^\dagger U = I (max deviation 0.0e+0)

Proposition

Closed form of the ZZ feature state and its kernel

With φ01=(π−x0)(π−x1)\varphi_{01}=(\pi-x_0)(\pi-x_1), ∣ϕ(x)⟩=12∑q∈{0,1}2eiθq(x)∣q⟩,θ00=0,  θ01=2x1+2φ01,  θ10=2x0+2φ01,  θ11=2x0+2x1,\lvert\phi(x)\rangle=\frac12\sum_{q\in\{0,1\}^2}e^{i\theta_q(x)}\lvert q\rangle,\qquad\theta_{00}=0,\ \ \theta_{01}=2x_1+2\varphi_{01},\ \ \theta_{10}=2x_0+2\varphi_{01},\ \ \theta_{11}=2x_0+2x_1, equivalently ∣ϕ(x)⟩=ei(x0+x1+φ01)exp⁡(−i(x0Z0+x1Z1+φ01Z0Z1))∣++⟩\lvert\phi(x)\rangle=e^{i(x_0+x_1+\varphi_{01})}\exp\big(-i(x_0Z_0+x_1Z_1+\varphi_{01}Z_0Z_1)\big)\lvert{+}{+}\rangle, and K(x,x′)=116∣∑q∈{0,1}2ei(θq(x′)−θq(x))∣2.K(x,x')=\frac1{16}\Big\lvert\sum_{q\in\{0,1\}^2}e^{i(\theta_q(x')-\theta_q(x))}\Big\rvert^2 .

Proof (7 steps)
  1. Step 1:
    (H⊗H)∣00⟩=∣+⟩⊗∣+⟩=12(∣00⟩+∣01⟩+∣10⟩+∣11⟩)(H\otimes H)\lvert00\rangle=\lvert{+}\rangle\otimes\lvert{+}\rangle=\frac12\big(\lvert00\rangle+\lvert01\rangle+\lvert10\rangle+\lvert11\rangle\big)
    H∣0⟩=12(∣0⟩+∣1⟩)H\lvert0\rangle=\frac1{\sqrt2}(\lvert0\rangle+\lvert1\rangle) on each qubit; expand the tensor product.
  2. Step 2:
    P0(2x0)P1(2x1)∣q0q1⟩=e2i(x0q0+x1q1)∣q0q1⟩P_0(2x_0)P_1(2x_1)\lvert q_0q_1\rangle=e^{2i(x_0q_0+x_1q_1)}\lvert q_0q_1\rangle
    Each phase gate multiplies by eiλbe^{i\lambda b} where bb is the bit of its own qubit.
  3. Step 3:
    CNOT01P1(2φ01)CNOT01∣q0q1⟩=e2iφ01(q0⊕q1)∣q0q1⟩\mathrm{CNOT}_{01}P_1(2\varphi_{01})\mathrm{CNOT}_{01}\lvert q_0q_1\rangle=e^{2i\varphi_{01}(q_0\oplus q_1)}\lvert q_0q_1\rangle
    The lemma with λ=2φ01\lambda=2\varphi_{01}.
  4. Step 4:
    θq=2x0q0+2x1q1+2φ01(q0⊕q1):θ00=0, θ01=2x1+2φ01, θ10=2x0+2φ01, θ11=2x0+2x1\theta_q=2x_0q_0+2x_1q_1+2\varphi_{01}(q_0\oplus q_1):\quad\theta_{00}=0,\ \theta_{01}=2x_1+2\varphi_{01},\ \theta_{10}=2x_0+2\varphi_{01},\ \theta_{11}=2x_0+2x_1
    All gates after the Hadamards are diagonal, so their phases add on each basis state of the uniform superposition; 1⊕1=01\oplus1=0 removes the product phase from ∣11⟩\lvert11\rangle.
  5. Step 5:
    qj=1−zj2,  q0⊕q1=1−z0z12 ⇒ θq=(x0+x1+φ01)−(x0z0+x1z1+φ01z0z1)q_j=\frac{1-z_j}2,\ \ q_0\oplus q_1=\frac{1-z_0z_1}2\ \Rightarrow\ \theta_q=(x_0+x_1+\varphi_{01})-(x_0z_0+x_1z_1+\varphi_{01}z_0z_1)
    zj=(−1)qjz_j=(-1)^{q_j} is the eigenvalue of ZjZ_j on ∣q⟩\lvert q\rangle. Hence the diagonal phase operator equals ei(x0+x1+φ01)exp⁡(−i(x0Z0+x1Z1+φ01Z0Z1))e^{i(x_0+x_1+\varphi_{01})}\exp\big(-i(x_0Z_0+x_1Z_1+\varphi_{01}Z_0Z_1)\big), which acting on ∣++⟩\lvert{+}{+}\rangle gives the exponential form.
  6. Step 6:
    ⟨ϕ(x)∣ϕ(x′)⟩=14∑qeiθq(x)‾ eiθq(x′)=14∑qei(θq(x′)−θq(x))\langle\phi(x)\vert\phi(x')\rangle=\frac14\sum_q\overline{e^{i\theta_q(x)}}\,e^{i\theta_q(x')}=\frac14\sum_qe^{i(\theta_q(x')-\theta_q(x))}
    Inner product antilinear in the first argument, computed in the orthonormal computational basis.
  7. Step 7:
    K(x,x′)=116∣∑qei(θq(x′)−θq(x))∣2,K(x,x)=∣4∣216=1K(x,x')=\frac1{16}\Big\lvert\sum_qe^{i(\theta_q(x')-\theta_q(x))}\Big\rvert^2,\qquad K(x,x)=\frac{\lvert4\rvert^2}{16}=1
    Square the modulus. The diagonal check confirms normalisation; four phases can cancel completely, so KK ranges over all of [0,1][0,1].

∎

Theorem

The R_Z version of the map differs by a global phase only

Let ∣ϕRZ(x)⟩\lvert\phi_{R_Z}(x)\rangle be the circuit of the definition with every phase gate P(λ)P(\lambda) replaced by RZ(λ)=e−iλZ/2R_Z(\lambda)=e^{-i\lambda Z/2} (this is how the platform's zzFeatureMap builds it). Then, for rr repetitions, ∣ϕRZ(x)⟩=e−ir(x0+x1+φ01)∣ϕ(x)⟩,\lvert\phi_{R_Z}(x)\rangle=e^{-ir(x_0+x_1+\varphi_{01})}\lvert\phi(x)\rangle, for r=1r=1 in particular ∣ϕRZ(x)⟩=exp⁡(−i(x0Z0+x1Z1+φ01Z0Z1))∣++⟩\lvert\phi_{R_Z}(x)\rangle=\exp\big(-i(x_0Z_0+x_1Z_1+\varphi_{01}Z_0Z_1)\big)\lvert{+}{+}\rangle, and the two kernels are identical: KRZ(x,x′)=K(x,x′)K_{R_Z}(x,x')=K(x,x') for all x,x′x,x'.

Proof (6 steps)
  1. Step 1:
    RZ(λ)=(e−iλ/200eiλ/2)=e−iλ/2(100eiλ)=e−iλ/2P(λ)R_Z(\lambda)=\begin{pmatrix}e^{-i\lambda/2}&0\\0&e^{i\lambda/2}\end{pmatrix}=e^{-i\lambda/2}\begin{pmatrix}1&0\\0&e^{i\lambda}\end{pmatrix}=e^{-i\lambda/2}P(\lambda)
    Factor e−iλ/2e^{-i\lambda/2} out of both diagonal entries.
  2. Step 2:
    RZ(2x0)⊗RZ(2x1)=e−ix0e−ix1 P(2x0)⊗P(2x1)R_Z(2x_0)\otimes R_Z(2x_1)=e^{-ix_0}e^{-ix_1}\,P(2x_0)\otimes P(2x_1)
    The Kronecker product is bilinear, so scalar factors of the two operands multiply.
  3. Step 3:
    CNOT01(I⊗RZ(2φ01))CNOT01=e−iφ01 CNOT01(I⊗P(2φ01))CNOT01\mathrm{CNOT}_{01}\big(I\otimes R_Z(2\varphi_{01})\big)\mathrm{CNOT}_{01}=e^{-i\varphi_{01}}\,\mathrm{CNOT}_{01}\big(I\otimes P(2\varphi_{01})\big)\mathrm{CNOT}_{01}
    Same factorisation with λ=2φ01\lambda=2\varphi_{01}, pulled out of the matrix product by linearity.
  4. Step 4:
    URZ(x)=e−i(x0+x1+φ01) UP(x),(e−iαUP)r=e−irαUPrU_{R_Z}(x)=e^{-i(x_0+x_1+\varphi_{01})}\,U_P(x),\qquad\big(e^{-i\alpha}U_P\big)^r=e^{-ir\alpha}U_P^r
    A scalar multiple of the identity commutes with every matrix, so all phases collect in front of one repetition UP(x)U_P(x) of the phase-gate circuit, and rr repetitions collect rr copies.
  5. Step 5:
    r=1: ∣ϕRZ(x)⟩=e−i(x0+x1+φ01)ei(x0+x1+φ01)exp⁡(−i(x0Z0+x1Z1+φ01Z0Z1))∣++⟩r=1:\ \lvert\phi_{R_Z}(x)\rangle=e^{-i(x_0+x_1+\varphi_{01})}e^{i(x_0+x_1+\varphi_{01})}\exp\big(-i(x_0Z_0+x_1Z_1+\varphi_{01}Z_0Z_1)\big)\lvert{+}{+}\rangle
    Insert the exponential form of the closed-form proposition; the two phases cancel, leaving the Havlíček form UΦ(x)H⊗2∣00⟩U_\Phi(x)H^{\otimes2}\lvert00\rangle with UΦ(x)=exp⁡(−i∑SϕS(x)∏j∈SZj)U_\Phi(x)=\exp\big(-i\sum_S\phi_S(x)\prod_{j\in S}Z_j\big).
  6. Step 6:
    KRZ(x,x′)=∣⟨e−iβ(x)ϕ(x)∣e−iβ(x′)ϕ(x′)⟩∣2=∣ei(β(x)−β(x′))∣2 ∣⟨ϕ(x)∣ϕ(x′)⟩∣2=K(x,x′)K_{R_Z}(x,x')=\big\lvert\langle e^{-i\beta(x)}\phi(x)\vert e^{-i\beta(x')}\phi(x')\rangle\big\rvert^2=\big\lvert e^{i(\beta(x)-\beta(x'))}\big\rvert^2\,\lvert\langle\phi(x)\vert\phi(x')\rangle\rvert^2=K(x,x')
    With β=r(x0+x1+φ01)\beta=r(x_0+x_1+\varphi_{01}): 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 x=(0,0)x=(0,0) and x′=(π,π)x'=(\pi,\pi) of the data square. Give the value to three decimals.

tolerance ±0.001

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 [−1.10, 2.06]×[−0.64, 1.12][-1.10,\,2.06]\times[-0.64,\,1.12]; the lab maps them to [0,π]2[0,\pi]^2.

Definition

Min–max scaling to [0, s]

Given data x(1),…,x(N)∈Rdx^{(1)},\dots,x^{(N)}\in\mathbb R^d with per-feature minimum ℓj=min⁡kxj(k)\ell_j=\min_kx^{(k)}_j and maximum hj=max⁡kxj(k)h_j=\max_kx^{(k)}_j, the min–max scaled features are x~j=s xj−ℓjhj−ℓj=s uj,uj∈[0,1],\tilde x_j=s\,\frac{x_j-\ell_j}{h_j-\ell_j}=s\,u_j,\qquad u_j\in[0,1], (and x~j=0\tilde x_j=0 for a constant feature). The lab uses s=πs=\pi and computes ℓj,hj\ell_j,h_j over all 100100 rows.

Theorem

For angle encodings the scale is the bandwidth

Encode u∈[0,1]du\in[0,1]^d by the RXR_X product encoding of susu, s>0s>0, and let Δ=u−u′\Delta=u-u'. The kernel is Ks(u,u′)=∏j=1dcos⁡2sΔj2K_s(u,u')=\prod_{j=1}^d\cos^2\frac{s\Delta_j}2, and: (a) if s∣Δj∣≤πs\lvert\Delta_j\rvert\le\pi for all jj (always true for s≤πs\le\pi), then Ks(u,u′)≤exp⁡(−s24∥Δ∥2)K_s(u,u')\le\exp\big(-\frac{s^2}4\lVert\Delta\rVert^2\big); (b) Ks(u,u′)=1−s24∥Δ∥2+O(s4∥Δ∥4)K_s(u,u')=1-\frac{s^2}4\lVert\Delta\rVert^2+O\big(s^4\lVert\Delta\rVert^4\big), the same second-order behaviour as the Gaussian kernel e−γ∥Δ∥2e^{-\gamma\lVert\Delta\rVert^2} with γ=s2/4\gamma=s^2/4, i.e. a length scale proportional to 1/s1/s; (c) for s≤πs\le\pi each factor is strictly decreasing in ∣Δj∣∈[0,1]\lvert\Delta_j\rvert\in[0,1], whereas for s=2πs=2\pi the points uj=0u_j=0 and uj′=1u'_j=1 have identical encodings; (d) as s→0s\to0, Ks→1K_s\to1 uniformly and the Gram matrix tends to the rank-one matrix 11⊤\mathbf 1\mathbf 1^\top.

Proof (8 steps)
  1. Step 1:
    Ks(u,u′)=∏jcos⁡2suj−suj′2=∏jcos⁡2sΔj2K_s(u,u')=\prod_{j}\cos^2\frac{su_j-su'_j}{2}=\prod_j\cos^2\frac{s\Delta_j}2
    Product-encoding kernel of the lesson Quantum Kernels & Fidelity Kernels, evaluated at the scaled features susu and su′su'.
  2. Step 2:
    g(t)=ln⁡cos⁡t+t22,g(0)=0,g′(t)=−tan⁡t+t≤0(0≤t<π2)g(t)=\ln\cos t+\frac{t^2}2,\quad g(0)=0,\quad g'(t)=-\tan t+t\le0\quad(0\le t<\tfrac\pi2)
    tan⁡t≥t\tan t\ge t on [0,π2)[0,\frac\pi2) because tan⁡t−t\tan t-t vanishes at 00 and has derivative tan⁡2t≥0\tan^2t\ge0. Hence gg is non-increasing and ln⁡cos⁡t≤−t22\ln\cos t\le-\frac{t^2}2.
  3. Step 3:
    t=s∣Δj∣2<π2:cos⁡2sΔj2=e2ln⁡cos⁡t≤e−t2=e−s2Δj2/4t=\frac{s\lvert\Delta_j\rvert}2<\frac\pi2:\quad\cos^2\frac{s\Delta_j}2=e^{2\ln\cos t}\le e^{-t^2}=e^{-s^2\Delta_j^2/4}
    cos⁡\cos is even, so ∣Δj∣\lvert\Delta_j\rvert may replace Δj\Delta_j. At t=π2t=\frac\pi2 the left side is 00 and the inequality holds trivially.
  4. Step 4:
    Ks(u,u′)≤∏je−s2Δj2/4=exp⁡(−s24∑jΔj2)=exp⁡(−s24∥Δ∥2)K_s(u,u')\le\prod_je^{-s^2\Delta_j^2/4}=\exp\Big(-\frac{s^2}4\sum_j\Delta_j^2\Big)=\exp\Big(-\frac{s^2}4\lVert\Delta\rVert^2\Big)
    Multiply the dd non-negative inequalities; this is (a).
  5. Step 5:
    cos⁡2t2=1+cos⁡t2=1−t24+t448−⋯ ⇒ ∏j(1−s2Δj24+O(s4Δj4))=1−s24∥Δ∥2+O(s4∥Δ∥4)\cos^2\frac{t}2=\frac{1+\cos t}2=1-\frac{t^2}4+\frac{t^4}{48}-\cdots\ \Rightarrow\ \prod_j\Big(1-\frac{s^2\Delta_j^2}4+O(s^4\Delta_j^4)\Big)=1-\frac{s^2}4\lVert\Delta\rVert^2+O(s^4\lVert\Delta\rVert^4)
    Half-angle identity and the cosine series; products of two second-order terms are O(s4Δi2Δj2)⊆O(s4∥Δ∥4)O(s^4\Delta_i^2\Delta_j^2)\subseteq O(s^4\lVert\Delta\rVert^4). The Gaussian e−γ∥Δ∥2=1−γ∥Δ∥2+O(∥Δ∥4)e^{-\gamma\lVert\Delta\rVert^2}=1-\gamma\lVert\Delta\rVert^2+O(\lVert\Delta\rVert^4) matches for γ=s2/4\gamma=s^2/4: this is (b).
  6. Step 6:
    ddδcos⁡2sδ2=−s2sin⁡(sδ)<0(0<sδ<π)\frac{\mathrm d}{\mathrm d\delta}\cos^2\frac{s\delta}2=-\frac s2\sin(s\delta)<0\quad(0<s\delta<\pi)
    For s≤πs\le\pi and δ=∣Δj∣∈(0,1]\delta=\lvert\Delta_j\rvert\in(0,1] we have 0<sδ≤π0<s\delta\le\pi, so similarity decreases strictly with distance in each feature: the first part of (c).
  7. Step 7:
    s=2π, Δj=1:cos⁡2π=1,RX(2π)∣0⟩=−∣0⟩=−RX(0)∣0⟩s=2\pi,\ \Delta_j=1:\quad\cos^2\pi=1,\qquad R_X(2\pi)\lvert0\rangle=-\lvert0\rangle=-R_X(0)\lvert0\rangle
    The rotation by 2π2\pi returns every state up to the global phase −1-1: the two ends of the feature range are identified (aliasing), the second part of (c).
  8. Step 8:
    ∣1−Ks(u,u′)∣≤s24∥Δ∥2≤s2d4 → 0(s→0)\lvert1-K_s(u,u')\rvert\le\frac{s^2}4\lVert\Delta\rVert^2\le\frac{s^2d}4\ \to\ 0\quad(s\to0)
    From 1−cos⁡2t2=sin⁡2t2≤t241-\cos^2\frac t2=\sin^2\frac t2\le\frac{t^2}4 and 1−∏jaj≤∑j(1−aj)1-\prod_ja_j\le\sum_j(1-a_j) for aj∈[0,1]a_j\in[0,1] (induction on dd). With every entry near 11 the Gram matrix approaches 11⊤\mathbf 1\mathbf 1^\top, the decision function ∑iαiyiK(xi,x)+b\sum_i\alpha_iy_iK(x_i,x)+b tends to a constant, and the classifier cannot separate anything: (d).

∎

The heatmap starts with the angle encoding of 2424 two-circles points scaled to [0,0.5][0,0.5]: every entry is close to 11, 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 π\pi and the block structure of the two circles appears, because the effective length scale ∝1/s\propto1/s shrinks below the distance between the classes. Push it towards 2π2\pi 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 e2ixje^{2ix_j} have period π\pi in xjx_j, so [0,π][0,\pi] is exactly one period: a smaller range uses only part of the circle, a larger one wraps around it. The product phase 2φ01=2(π−x0)(π−x1)2\varphi_{01}=2(\pi-x_0)(\pi-x_1) ranges over [0,2π2]≈[0,19.7][0,2\pi^2]\approx[0,19.7] on [0,π]2[0,\pi]^2, more than three full turns, and it is not a function of x−x′x-x'. This is why the opposite corners (0,0)(0,0) and (π,π)(\pi,\pi) have kernel cos⁡2π2≈0.815\cos^2\pi^2\approx0.815 (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 [0,s][0,s] with s=π/2s=\pi/2 and encoded by RXR_X. What is the kernel between the two extreme points u=0u=0 and u′=1u'=1?

tolerance ±0.000001

Finite shots, lost positivity and eigenvalue clipping#

On hardware, every kernel entry is a relative frequency. With NN inversion-test shots per entry, K^ij=N0/N=Kij+εij\hat K_{ij}=N_0/N=K_{ij}+\varepsilon_{ij} with E[εij]=0\mathbb E[\varepsilon_{ij}]=0 and Var[εij]=Kij(1−Kij)/N\mathrm{Var}[\varepsilon_{ij}]=K_{ij}(1-K_{ij})/N, and entries estimated by different circuits have independent errors (lesson Quantum Kernels & Fidelity Kernels). The diagonal of KtrainK_{\text{train}} is known to be 11 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.

Proposition

Rank of a quantum Gram matrix

For nn-qubit pure feature states, rank Ktrain≤dim⁡Rspan{ρ(x1),…,ρ(xm)}≤4n\mathrm{rank}\,K_{\text{train}}\le\dim_{\mathbb R}\mathrm{span}\{\rho(x_1),\dots,\rho(x_m)\}\le4^n. For the two-qubit ZZ map with one repetition the bound improves to 1313, and for the RXR_X product encoding of nn features to 3n3^n. Hence for m>13m>13 points the ZZ Gram matrix has at least m−13m-13 zero eigenvalues.

Proof (7 steps)
  1. Step 1:
    Kij=Tr(ρiρj)=⟨ρi,ρj⟩HS=vi⊤vj ⇒ Ktrain=V⊤VK_{ij}=\mathrm{Tr}(\rho_i\rho_j)=\langle\rho_i,\rho_j\rangle_{HS}=v_i^\top v_j\ \Rightarrow\ K_{\text{train}}=V^\top V
    The Hermitian 2n×2n2^n\times2^n matrices form a real inner-product space of dimension 4n4^n; viv_i is the coordinate vector of ρ(xi)\rho(x_i) in an orthonormal basis (for instance the normalised Pauli strings), and VV has the columns viv_i.
  2. Step 2:
    rank(V⊤V)=rank(V)=dim⁡span{v1,…,vm}≤4n\mathrm{rank}(V^\top V)=\mathrm{rank}(V)=\dim\mathrm{span}\{v_1,\dots,v_m\}\le4^n
    V⊤Vc=0⇒∥Vc∥2=c⊤V⊤Vc=0⇒Vc=0V^\top Vc=0\Rightarrow\lVert Vc\rVert^2=c^\top V^\top Vc=0\Rightarrow Vc=0, so both matrices have the same kernel and hence the same rank.
  3. Step 3:
    ρ(x)qq′=14ei(θq(x)−θq′(x)) ⇒ ρ(x)qq=14 for every x\rho(x)_{qq'}=\tfrac14e^{i(\theta_q(x)-\theta_{q'}(x))}\ \Rightarrow\ \rho(x)_{qq}=\tfrac14\ \text{for every }x
    Outer product of the closed form 12∑qeiθq∣q⟩\frac12\sum_qe^{i\theta_q}\lvert q\rangle with itself: every diagonal entry has modulus squared 14\frac14, independent of the data.
  4. Step 4:
    ρ(x)∈14I+W,W=spanR{Eqq′+Eq′q, i(Eqq′−Eq′q):q<q′},dim⁡W=2(42)=12\rho(x)\in\tfrac14I+W,\qquad W=\mathrm{span}_{\mathbb R}\big\{E_{qq'}+E_{q'q},\ i(E_{qq'}-E_{q'q}):q<q'\big\},\quad\dim W=2\binom42=12
    A Hermitian matrix with a fixed diagonal is determined by the real and imaginary parts of its 66 entries above the diagonal; Eqq′E_{qq'} are the matrix units.
  5. Step 5:
    span{ρ(xi)}⊆span{I}⊕W ⇒ rank Ktrain≤1+12=13\mathrm{span}\{\rho(x_i)\}\subseteq\mathrm{span}\{I\}\oplus W\ \Rightarrow\ \mathrm{rank}\,K_{\text{train}}\le1+12=13
    Every ρ(xi)\rho(x_i) lies in the 1313-dimensional space spanned by II and WW.
  6. Step 6:
    RX(x)∣0⟩⟨0∣RX(x)†=12(I−sin⁡x Y+cos⁡x Z) ⇒ ρ(x)∈span{⨂jPj:Pj∈{I,Y,Z}},  dim⁡=3nR_X(x)\lvert0\rangle\langle0\rvert R_X(x)^\dagger=\tfrac12\big(I-\sin x\,Y+\cos x\,Z\big)\ \Rightarrow\ \rho(x)\in\mathrm{span}\Big\{\textstyle\bigotimes_jP_j:P_j\in\{I,Y,Z\}\Big\},\ \ \dim=3^n
    RX(x)∣0⟩=cos⁡x2∣0⟩−isin⁡x2∣1⟩R_X(x)\lvert0\rangle=\cos\frac x2\lvert0\rangle-i\sin\frac x2\lvert1\rangle has Bloch vector (0,−sin⁡x,cos⁡x)(0,-\sin x,\cos x); a product state is the tensor product of its one-qubit density matrices.
  7. Step 7:
    m=70:#{λ=0}≥70−13=57m=70:\quad\#\{\lambda=0\}\ge70-13=57
    Rank–nullity for the symmetric 70×7070\times70 matrix. The engine finds rank exactly 1313 for the reps-1 ZZ map, 16=4216=4^2 for two repetitions and 9=329=3^2 for the angle encoding (TypeScript cell of the results section).

∎

Proposition

Shot noise makes a singular Gram matrix indefinite with positive probability

Let K⪰0K\succeq0 have a unit null vector vv (Kv=0Kv=0) with vivj≠0v_iv_j\ne0 for some pair with 0<Kij<10<K_{ij}<1. Let K^=K+E\hat K=K+E where EE is symmetric with zero diagonal and independent entries εij\varepsilon_{ij} (i<ji<j) of mean 00 and variance σij2=Kij(1−Kij)/N\sigma_{ij}^2=K_{ij}(1-K_{ij})/N. Then λmin⁡(K^)≤v⊤Ev\lambda_{\min}(\hat K)\le v^\top Ev, where E[v⊤Ev]=0\mathbb E[v^\top Ev]=0 and Var[v⊤Ev]=4∑i<jvi2vj2σij2>0\mathrm{Var}[v^\top Ev]=4\sum_{i<j}v_i^2v_j^2\sigma_{ij}^2>0; consequently P(λmin⁡(K^)<0)>0P\big(\lambda_{\min}(\hat K)<0\big)>0.

Proof (7 steps)
  1. Step 1:
    λmin⁡(A)=min⁡∥u∥=1u⊤Au\lambda_{\min}(A)=\min_{\lVert u\rVert=1}u^\top Au
    Spectral theorem: with A=∑kλkekek⊤A=\sum_k\lambda_ke_ke_k^\top and u=∑kckeku=\sum_kc_ke_k, u⊤Au=∑kλkck2≥λmin⁡∑kck2=λmin⁡u^\top Au=\sum_k\lambda_kc_k^2\ge\lambda_{\min}\sum_kc_k^2=\lambda_{\min}, with equality at the eigenvector of λmin⁡\lambda_{\min}.
  2. Step 2:
    λmin⁡(K^)≤v⊤K^v=v⊤Kv+v⊤Ev=v⊤Ev\lambda_{\min}(\hat K)\le v^\top\hat Kv=v^\top Kv+v^\top Ev=v^\top Ev
    Use the unit vector vv in the variational formula and Kv=0Kv=0.
  3. Step 3:
    v⊤Ev=∑i≠jvivjεij=2∑i<jvivjεijv^\top Ev=\sum_{i\ne j}v_iv_j\varepsilon_{ij}=2\sum_{i<j}v_iv_j\varepsilon_{ij}
    The diagonal of EE vanishes and εji=εij\varepsilon_{ji}=\varepsilon_{ij}.
  4. Step 4:
    E[v⊤Ev]=2∑i<jvivj E[εij]=0,Var[v⊤Ev]=4∑i<jvi2vj2σij2\mathbb E[v^\top Ev]=2\sum_{i<j}v_iv_j\,\mathbb E[\varepsilon_{ij}]=0,\qquad\mathrm{Var}[v^\top Ev]=4\sum_{i<j}v_i^2v_j^2\sigma_{ij}^2
    Linearity of expectation, and additivity of variances for independent summands.
  5. Step 5:
    Var[v⊤Ev]≥4vi2vj2Kij(1−Kij)N>0\mathrm{Var}[v^\top Ev]\ge4v_i^2v_j^2\frac{K_{ij}(1-K_{ij})}N>0
    All terms are non-negative and the assumed pair contributes a positive one.
  6. Step 6:
    Z:=v⊤Ev,  E[Z]=0,  Var[Z]>0 ⇒ P(Z<0)>0Z:=v^\top Ev,\ \ \mathbb E[Z]=0,\ \ \mathrm{Var}[Z]>0\ \Rightarrow\ P(Z<0)>0
    Otherwise Z≥0Z\ge0 almost surely, and a non-negative variable with mean 00 vanishes almost surely, contradicting Var[Z]>0\mathrm{Var}[Z]>0.
  7. Step 7:
    P(λmin⁡(K^)<0)≥P(v⊤Ev<0)>0P\big(\lambda_{\min}(\hat K)<0\big)\ge P(v^\top Ev<0)>0
    By the second step, v⊤Ev<0v^\top Ev<0 implies λmin⁡(K^)<0\lambda_{\min}(\hat K)<0. With 5757 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 N=100N=100 Bernoulli shots with success probability KijK_{ij} (the inversion-test outcome 0000), 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.

TypeScriptrunnable
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 5757 exact zero eigenvalues, 2929 have become negative, the smallest at −0.5710-0.5710, so the estimate is far from being a valid Gram matrix. After clipping, the distance from the estimate to the repaired matrix equals (∑λi<0λi2)1/2=1.573392\big(\sum_{\lambda_i<0}\lambda_i^2\big)^{1/2}=1.573392 to all printed digits, and the repaired matrix is closer to the exact Gram matrix than the raw estimate (2.07642.0764 against 2.62392.6239). The next two results prove that both observations hold in general.

Theorem

Eigenvalue clipping is the Frobenius-nearest positive semidefinite matrix

Let K^∈Rm×m\hat K\in\mathbb R^{m\times m} be symmetric with eigendecomposition K^=VΛV⊤\hat K=V\Lambda V^\top, VV orthogonal, Λ=diag(λ1,…,λm)\Lambda=\mathrm{diag}(\lambda_1,\dots,\lambda_m), and set K^+=Vmax⁡(Λ,0)V⊤\hat K_+=V\max(\Lambda,0)V^\top (entrywise maximum on the diagonal). Then K^+⪰0\hat K_+\succeq0 and for every symmetric positive semidefinite BB ∥K^−B∥F ≥ ∥K^−K^+∥F=(∑λi<0λi2)1/2,\lVert\hat K-B\rVert_F\ \ge\ \lVert\hat K-\hat K_+\rVert_F=\Big(\sum_{\lambda_i<0}\lambda_i^2\Big)^{1/2}, with equality if and only if B=K^+B=\hat K_+.

Proof (8 steps)
  1. Step 1:
    u⊤K^+u=(V⊤u)⊤max⁡(Λ,0)(V⊤u)=∑imax⁡(λi,0) (V⊤u)i2≥0u^\top\hat K_+u=(V^\top u)^\top\max(\Lambda,0)(V^\top u)=\sum_i\max(\lambda_i,0)\,(V^\top u)_i^2\ge0
    K^+\hat K_+ is positive semidefinite: a diagonal matrix with non-negative entries, conjugated by an orthogonal matrix.
  2. Step 2:
    ∥VAV⊤∥F2=Tr(VA⊤V⊤VAV⊤)=Tr(A⊤AV⊤V)=∥A∥F2\lVert VAV^\top\rVert_F^2=\mathrm{Tr}\big(VA^\top V^\top VAV^\top\big)=\mathrm{Tr}\big(A^\top AV^\top V\big)=\lVert A\rVert_F^2
    ∥A∥F2=Tr(A⊤A)\lVert A\rVert_F^2=\mathrm{Tr}(A^\top A), V⊤V=IV^\top V=I and the cyclicity of the trace: the Frobenius norm is invariant under orthogonal conjugation.
  3. Step 3:
    C:=V⊤BV:∥K^−B∥F=∥V(Λ−C)V⊤∥F=∥Λ−C∥F,u⊤Cu=(Vu)⊤B(Vu)≥0C:=V^\top BV:\qquad\lVert\hat K-B\rVert_F=\lVert V(\Lambda-C)V^\top\rVert_F=\lVert\Lambda-C\rVert_F,\qquad u^\top Cu=(Vu)^\top B(Vu)\ge0
    Write B=VCV⊤B=VCV^\top and apply the invariance; CC is symmetric and positive semidefinite because BB is.
  4. Step 4:
    cii=ei⊤Cei≥0(i=1,…,m)c_{ii}=e_i^\top Ce_i\ge0\qquad(i=1,\dots,m)
    The diagonal entries of a positive semidefinite matrix are values of its quadratic form at the unit vectors.
  5. Step 5:
    ∥Λ−C∥F2=∑i(λi−cii)2+∑i≠jcij2 ≥ ∑i(λi−cii)2 ≥ ∑λi<0(λi−cii)2\lVert\Lambda-C\rVert_F^2=\sum_i(\lambda_i-c_{ii})^2+\sum_{i\ne j}c_{ij}^2\ \ge\ \sum_i(\lambda_i-c_{ii})^2\ \ge\ \sum_{\lambda_i<0}(\lambda_i-c_{ii})^2
    Λ\Lambda is diagonal, so the off-diagonal part of Λ−C\Lambda-C is that of CC; then drop the non-negative off-diagonal terms and the diagonal terms with λi≥0\lambda_i\ge0.
  6. Step 6:
    λi<0≤cii ⇒ cii−λi≥−λi=∣λi∣>0 ⇒ (λi−cii)2≥λi2\lambda_i<0\le c_{ii}\ \Rightarrow\ c_{ii}-\lambda_i\ge-\lambda_i=\lvert\lambda_i\rvert>0\ \Rightarrow\ (\lambda_i-c_{ii})^2\ge\lambda_i^2
    Squaring preserves the order of non-negative numbers. Summing, ∥K^−B∥F2≥∑λi<0λi2\lVert\hat K-B\rVert_F^2\ge\sum_{\lambda_i<0}\lambda_i^2 for every admissible BB.
  7. Step 7:
    C=max⁡(Λ,0):Λ−C=min⁡(Λ,0),∥Λ−C∥F2=∑λi<0λi2,B=VCV⊤=K^+C=\max(\Lambda,0):\quad\Lambda-C=\min(\Lambda,0),\quad\lVert\Lambda-C\rVert_F^2=\sum_{\lambda_i<0}\lambda_i^2,\quad B=VCV^\top=\hat K_+
    The bound is attained by the clipped matrix, so it is the minimum and ∥K^−K^+∥F=(∑λi<0λi2)1/2\lVert\hat K-\hat K_+\rVert_F=\big(\sum_{\lambda_i<0}\lambda_i^2\big)^{1/2}.
  8. Step 8:
    equality ⇒ cij=0 (i≠j),cii=λi (λi≥0),cii=0 (λi<0) ⇒ C=max⁡(Λ,0)\text{equality}\ \Rightarrow\ c_{ij}=0\ (i\ne j),\quad c_{ii}=\lambda_i\ (\lambda_i\ge0),\quad c_{ii}=0\ (\lambda_i<0)\ \Rightarrow\ C=\max(\Lambda,0)
    Equality in the three inequalities forces each dropped term to vanish and (λi−cii)2=λi2(\lambda_i-c_{ii})^2=\lambda_i^2 with cii≥0>λic_{ii}\ge0>\lambda_i, i.e. cii=0c_{ii}=0. Hence the minimiser is unique (Higham 1988).

∎

Corollary

Clipping never moves the estimate away from the true Gram matrix

For every symmetric positive semidefinite KK, in particular the exact Gram matrix, ∥K^+−K∥F2+∥K^−K^+∥F2≤∥K^−K∥F2\lVert\hat K_+-K\rVert_F^2+\lVert\hat K-\hat K_+\rVert_F^2\le\lVert\hat K-K\rVert_F^2; hence ∥K^+−K∥F≤∥K^−K∥F\lVert\hat K_+-K\rVert_F\le\lVert\hat K-K\rVert_F.

Proof (6 steps)
  1. Step 1:
    K^=K^+−N,N:=Vmax⁡(−Λ,0)V⊤⪰0\hat K=\hat K_+-N,\qquad N:=V\max(-\Lambda,0)V^\top\succeq0
    Split every eigenvalue as λ=max⁡(λ,0)−max⁡(−λ,0)\lambda=\max(\lambda,0)-\max(-\lambda,0); NN collects the negative parts with a plus sign.
  2. Step 2:
    ⟨N,K^+⟩F=Tr(Vmax⁡(−Λ,0)max⁡(Λ,0)V⊤)=0\langle N,\hat K_+\rangle_F=\mathrm{Tr}\big(V\max(-\Lambda,0)\max(\Lambda,0)V^\top\big)=0
    V⊤V=IV^\top V=I, cyclicity of the trace, and max⁡(−λ,0)max⁡(λ,0)=0\max(-\lambda,0)\max(\lambda,0)=0 for every real λ\lambda.
  3. Step 3:
    A,B⪰0 ⇒ Tr(AB)=Tr(A1/2BA1/2)≥0 ⇒ ⟨N,K⟩F≥0A,B\succeq0\ \Rightarrow\ \mathrm{Tr}(AB)=\mathrm{Tr}\big(A^{1/2}BA^{1/2}\big)\ge0\ \Rightarrow\ \langle N,K\rangle_F\ge0
    A1/2BA1/2A^{1/2}BA^{1/2} is positive semidefinite, so its trace, the sum of its eigenvalues, is non-negative.
  4. Step 4:
    ∥K^−K∥F2=∥(K^+−K)−N∥F2=∥K^+−K∥F2−2⟨K^+−K,N⟩F+∥N∥F2\lVert\hat K-K\rVert_F^2=\lVert(\hat K_+-K)-N\rVert_F^2=\lVert\hat K_+-K\rVert_F^2-2\langle\hat K_+-K,N\rangle_F+\lVert N\rVert_F^2
    Expand the squared norm with the Frobenius inner product.
  5. Step 5:
    −2⟨K^+−K,N⟩F=−2⋅0+2⟨K,N⟩F≥0-2\langle\hat K_+-K,N\rangle_F=-2\cdot0+2\langle K,N\rangle_F\ge0
    The previous two steps.
  6. Step 6:
    ∥K^−K∥F2≥∥K^+−K∥F2+∥N∥F2,∥N∥F=∥K^−K^+∥F\lVert\hat K-K\rVert_F^2\ge\lVert\hat K_+-K\rVert_F^2+\lVert N\rVert_F^2,\qquad\lVert N\rVert_F=\lVert\hat K-\hat K_+\rVert_F
    Drop the non-negative cross term. In the experiment: 2.62392=6.885≥2.07642+1.57342=6.7872.6239^2=6.885\ge2.0764^2+1.5734^2=6.787.

∎

Quick check

A noisy estimate of a three-point Gram matrix is K^=(10.900.910.900.91)\hat K=\begin{pmatrix}1&0.9&0\\0.9&1&0.9\\0&0.9&1\end{pmatrix}. What is its smallest eigenvalue? (Four decimals.)

tolerance ±0.001

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 5050 points each, scaled to [0,π]2[0,\pi]^2, with rows 00–6969 for training and rows 7070–9999 (1414 of class 00, 1616 of class 11) for testing. Every classifier is a soft-margin SVM with C=1C=1 on a precomputed, exactly simulated kernel. Three kernels are compared: the ZZ map with one repetition, the ZZ map with two repetitions, and the RXR_X angle encoding, whose kernel ∏jcos⁡2xj−xj′2\prod_j\cos^2\frac{x_j-x'_j}2 is a classical function of two cosines.

kernelrank of KtrainK_{\text{train}}alignment A(Ktrain,y)A(K_{\text{train}},y)train accuracytest accuracy
ZZ, one repetition13130.19870.19870.87140.87140.93330.9333 (28/3028/30)
ZZ, two repetitions16160.10920.10920.81430.81430.76670.7667 (23/3023/30)
angle cos⁡2\cos^2 (classical)990.21560.21560.85710.85711.00001.0000 (30/3030/30)

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 C=1000C=1000. It also confirms the closed form of the feature state and the RZR_Z global phase on the first training point.

Pythonrunnable
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.1987

The 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 0.50.5) or far apart (distance above 22).

TypeScriptrunnable
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 K≠0K\ne0 and labels y∈{−1,+1}my\in\{-1,+1\}^m, the kernel–target alignment (Cristianini et al. 2002) is the cosine of the angle between KK and the ideal kernel yy⊤yy^\top in the Frobenius inner product, A(K,y)=⟨K,yy⊤⟩F∥K∥F ∥yy⊤∥F=y⊤Kym ∥K∥F.A(K,y)=\frac{\langle K,yy^\top\rangle_F}{\lVert K\rVert_F\,\lVert yy^\top\rVert_F}=\frac{y^\top Ky}{m\,\lVert K\rVert_F}. 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.

Proposition

Range of the alignment

−1≤A(K,y)≤1-1\le A(K,y)\le1, with A(K,y)=1A(K,y)=1 if and only if K=c yy⊤K=c\,yy^\top for some c>0c>0. If K⪰0K\succeq0, then A(K,y)≥0A(K,y)\ge0.

Proof (5 steps)
  1. Step 1:
    ⟨K,yy⊤⟩F=Tr(K⊤yy⊤)=∑i,jKijyiyj=y⊤Ky\langle K,yy^\top\rangle_F=\mathrm{Tr}(K^\top yy^\top)=\sum_{i,j}K_{ij}y_iy_j=y^\top Ky
    Definition of the Frobenius inner product ⟨A,B⟩F=Tr(A⊤B)=∑ijAijBij\langle A,B\rangle_F=\mathrm{Tr}(A^\top B)=\sum_{ij}A_{ij}B_{ij}.
  2. Step 2:
    ∥yy⊤∥F2=∑i,jyi2yj2=m2 ⇒ ∥yy⊤∥F=m\lVert yy^\top\rVert_F^2=\sum_{i,j}y_i^2y_j^2=m^2\ \Rightarrow\ \lVert yy^\top\rVert_F=m
    Every yi2=1y_i^2=1.
  3. Step 3:
    ∣⟨K,yy⊤⟩F∣≤∥K∥F∥yy⊤∥F ⇒ ∣A(K,y)∣≤1\lvert\langle K,yy^\top\rangle_F\rvert\le\lVert K\rVert_F\lVert yy^\top\rVert_F\ \Rightarrow\ \lvert A(K,y)\rvert\le1
    Cauchy–Schwarz inequality in the inner-product space of real m×mm\times m matrices.
  4. Step 4:
    A(K,y)=1  ⟺  K=c yy⊤, c>0A(K,y)=1\iff K=c\,yy^\top,\ c>0
    Equality in Cauchy–Schwarz holds exactly for parallel vectors, and the sign of the inner product must be positive.
  5. Step 5:
    K⪰0 ⇒ y⊤Ky≥0 ⇒ A(K,y)≥0K\succeq0\ \Rightarrow\ y^\top Ky\ge0\ \Rightarrow\ A(K,y)\ge0
    The numerator is a value of the quadratic form of KK.

∎

What the numbers say. One repetition of the ZZ map yields a good classifier, 2828 of 3030 test points. A second repetition lowers the test accuracy to 23/3023/30. 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 2−n2^{-n}, 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: A=0.1092A=0.1092 instead of 0.19870.1987. 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 0.50.5 have mean kernel 0.7000.700 under one repetition but only 0.5840.584 under two, while pairs farther apart than 22 stay at 0.2750.275 in both cases, close to the value 2−2=142^{-2}=\frac14 that unrelated two-qubit states have on average. Neighbours look less alike, and distant points look as alike as before.
  • At C=1C=1 the reps-2 model does not memorise: its training accuracy, 0.81430.8143, is lower than that of the reps-1 model, 0.87140.8714. 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 C=1000C=1000 classifies every training point correctly and drops to 27/3027/30 on the test set.
  • The classical angle kernel is the best of the three, 30/3030/30, with the largest alignment (0.21560.2156), the smallest rank (99) and the strongest locality (near pairs 0.9740.974, far pairs 0.1450.145). By the bandwidth theorem it behaves like a Gaussian kernel with γ=14\gamma=\frac14 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 KtrainK_{\text{train}} and KtestK_{\text{test}}, trains the SVM and draws the decision function ff 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 RYR_Y rotations, which give the same cos⁡2\cos^2 kernel as RXR_X) to see the classical baseline, and vary CC and the feature scale to connect the picture with the bandwidth theorem.

Quick check

At C=1C=1, the ZZ kernel with two repetitions has training accuracy 0.81430.8143 and test accuracy 0.76670.7667; with one repetition, 0.87140.8714 and 0.93330.9333. Which conclusion do these numbers support?

Select one answer

References

  1. 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
  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
  3. C. Cortes and V. Vapnik, Support-vector networks, Machine Learning 20, 273–297 (1995).doi:10.1007/BF00994018
  4. 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
  5. F. Pedregosa et al., Scikit-learn: Machine learning in Python, Journal of Machine Learning Research 12, 2825–2830 (2011).jmlr.org
  6. 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
  7. 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
  8. 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
  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
  10. 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-graded

    Build the complete quantum-kernel classifier of the lesson in Python. First implement the fidelity kernel K(x,x′)=∣⟨ϕ(x)∣ϕ(x′)⟩∣2K(x,x')=\lvert\langle\phi(x)\vert\phi(x')\rangle\rvert^2 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 70×7070\times70 training Gram matrix of the two-moons data scaled to [0,π][0,\pi] and predict the 3030 held-out points; the grader computes the test accuracy from your predictions and requires at least 0.900.90 (the reference pipeline reaches 28/3028/30).

    Open lab