Skip to main content
KetQat

Appearance

Lesson 81 h 10 min

Quantum machine learning fundamentals

Data encoding, variational classifiers, kernels, and the evidence for and against advantage.

After this lesson you can

  • Compare basis, angle and amplitude encoding by qubit count, circuit cost and classical simulability
  • Show that a product angle encoding yields a classically computable kernel, and derive it
  • Explain variational classifiers as linear models in a quantum feature space
  • Implement a fidelity quantum kernel and kernel ridge classification from scratch, with hyperparameters chosen on training data only
  • Compare a quantum kernel with classical baselines honestly and report what the comparison does and does not show
  • Summarise the evidence for and against quantum advantage in learning, including dequantization and a rigorous but specialised speed-up
  • Derive the exponential concentration of a simple quantum kernel and its consequence for shot counts

Read first: The variational quantum eigensolver, VQE in practice, Classical versus quantum complexity

What this lesson is, and is not

"Quantum machine learning" covers very different proposals: quantum algorithms for linear algebra on classical data, quantum models trained on classical data, and learning from data that is itself quantum. This lesson focuses on the second family in its simplest, most studied form: supervised classification with a quantum feature map, either as a variational classifier or as a quantum kernel. You will implement a quantum kernel from scratch, compare it with classical baselines on the same data split, and learn the results that constrain what such models can offer.

Nothing here runs on hardware; kernels are computed exactly from state vectors, which is the most favourable setting a quantum model can get. Even so, the comparison has to be fair.

Encoding data into states

A quantum model starts with an encoding circuit U(x)U(\mathbf x) that maps a data point x∈Rd\mathbf x \in \R^d to a state ∣ϕ(x)⟩=U(x)∣0⟩\ket{\phi(\mathbf x)} = U(\mathbf x)\ket{0}.

encoding state qubits circuit cost notes
basis ∣x1x2…xd⟩\ket{x_1x_2\dots x_d} for bit strings dd ≤d\le d XX gates only discrete data; one point per basis state
angle ⨂kRY(xk)∣0⟩\bigotimes_k R_Y(x_k)\ket0 dd dd rotations product state; kernel computable classically (below)
amplitude ∑jxj∣j⟩/∥x∥\sum_j x_j\ket j/\norm{\mathbf x} ⌈log⁡2d⌉\lceil\log_2 d\rceil order dd gates in general exponentially compact, but generic preparation is expensive

Amplitude encoding is the source of many exponential-speed-up claims: dd numbers in log⁡2d\log_2 d qubits. The catch is in the last column. Preparing an arbitrary amplitude vector needs order dd gates, which is as much work as reading the data classically, unless one assumes a quantum RAM or special structure. Those assumptions are exactly what dequantization results examine, below.

Angle encoding gives a classical kernel

For angle encoding, each qubit is in cos⁡(xk/2)∣0⟩+sin⁡(xk/2)∣1⟩\cos(x_k/2)\ket0 + \sin(x_k/2)\ket1, so

⟨ϕ(x)∣ϕ(x′)⟩=∏k=1d(cos⁡xk2cos⁡xk′2+sin⁡xk2sin⁡xk′2)=∏k=1dcos⁡xk−xk′2.\braket{\phi(\mathbf x)}{\phi(\mathbf x')} = \prod_{k=1}^d\Big(\cos\tfrac{x_k}{2}\cos\tfrac{x'_k}{2} + \sin\tfrac{x_k}{2}\sin\tfrac{x'_k}{2}\Big) = \prod_{k=1}^d \cos\frac{x_k - x'_k}{2}.

The overlap of two product states is a product of dd numbers that a laptop computes in O(d)O(d) time. Any model built only on this encoding is therefore classically simulable, whatever the number of qubits. To have any chance of being hard to simulate, an encoding must entangle. Havlíček and coauthors proposed entangling feature maps built from products of ZZ rotations interleaved with Hadamards, and ran small instances on superconducting hardware (Havlíček et al. 2019). The exercise uses a two-qubit map in that spirit: twice, apply H⊗HH\otimes H and then the diagonal phase exp⁡(i[x0Z0+x1Z1+(π−x0)(π−x1)Z0Z1])\exp\big(i[x_0Z_0 + x_1Z_1 + (\pi - x_0)(\pi - x_1)Z_0Z_1]\big). We call it the "zz" map; it is modelled on, not identical to, the published construction. Since RZ(θ)=e−iθZ/2R_Z(\theta) = e^{-i\theta Z/2} and CX (I⊗RZ(θ)) CX=e−iθZ0Z1/2\mathrm{CX}\,(I\otimes R_Z(\theta))\,\mathrm{CX} = e^{-i\theta Z_0Z_1/2}, one repetition compiles as follows.

Quantum circuit on 2 wires (a, b). step 1: H on a; H on b. step 2: RZ(-2x0) on a; RZ(-2x1) on b. step 3: CNOT, control a, target b. step 4: RZ(-2φ01) on b. step 5: CNOT, control a, target b.abHHRZ(-2x0)RZ(-2x1)RZ(-2φ01)
One repetition of the two-qubit zz feature map for a data point (x0, x1): Hadamards, single-qubit Z rotations by the features, and a ZZ rotation by φ01 = (π − x0)(π − x1) built from two CNOTs. The exercise applies it twice.

Two ways to build a classifier

Variational classifiers. Apply a trainable circuit W(θ)W(\boldsymbol\theta) after the encoding and measure an observable OO; the model is fθ(x)=⟨ϕ(x)∣W†OW∣ϕ(x)⟩f_{\boldsymbol\theta}(\mathbf x) = \bra{\phi(\mathbf x)}W^\dagger OW\ket{\phi(\mathbf x)}, and its sign is the predicted label. Train θ\boldsymbol\theta with the parameter-shift rule from the VQE in practice lesson. Writing ρ(x)=∣ϕ(x)⟩⟨ϕ(x)∣\rho(\mathbf x) = \ketbra{\phi(\mathbf x)}{\phi(\mathbf x)} and M=W†OWM = W^\dagger OW gives f(x)=Tr⁡(Mρ(x))f(\mathbf x) = \tr(M\rho(\mathbf x)): a linear function of the feature "vector" ρ(x)\rho(\mathbf x). Schuld and Killoran made this view explicit: the encoding is a feature map into a Hilbert space, and quantum classifiers are linear models in that space (Schuld and Killoran 2019). Training such circuits inherits the optimisation problems of the previous lessons, barren plateaus included (McClean et al. 2018).

Quantum kernels. Instead of training a circuit, use the inner product of feature vectors,

K(x,x′)=Tr⁡(ρ(x)ρ(x′))=∣⟨ϕ(x)∣ϕ(x′)⟩∣2,K(\mathbf x, \mathbf x') = \tr\big(\rho(\mathbf x)\rho(\mathbf x')\big) = \abs{\braket{\phi(\mathbf x)}{\phi(\mathbf x')}}^2,

the fidelity kernel, and hand the Gram matrix to a classical kernel method. Because it is an inner product of feature vectors, KK is symmetric and positive semidefinite, with K(x,x)=1K(\mathbf x,\mathbf x) = 1. On hardware, one entry is estimated by running U(x′)†U(x)U(\mathbf x')^\dagger U(\mathbf x) on ∣0⟩\ket0 and counting how often the all-zero outcome appears: with SS shots the estimate is binomial with variance K(1−K)/SK(1-K)/S.

Kernel ridge classification

Fit f(x)=∑iαiK(x,xi)f(\mathbf x) = \sum_i \alpha_i K(\mathbf x, \mathbf x_i) to labels yi∈{−1,+1}y_i \in \{-1, +1\} by minimising squared error plus a ridge penalty λ\lambda. Setting the gradient to zero gives the linear system

(K+λI) α=y,(K + \lambda I)\,\boldsymbol\alpha = \mathbf y ,

and the predicted label of a new point is sign⁡∑iαiK(x,xi)\operatorname{sign}\sum_i\alpha_iK(\mathbf x, \mathbf x_i). The classical baseline uses the same machinery with the radial basis function kernel KRBF(x,x′)=e−γ∥x−x′∥2K_{\text{RBF}}(\mathbf x, \mathbf x') = e^{-\gamma\norm{\mathbf x - \mathbf x'}^2}, so that the only difference between the models is the kernel. A second, deliberately weak baseline, nearest centroid, assigns a point to the class whose mean is closer.

Worked example. For x=(0.5,1.0)\mathbf x = (0.5, 1.0) and x′=(1.0,0.2)\mathbf x' = (1.0, 0.2), the angle-encoding kernel is cos⁡2(0.25)cos⁡2(0.4)=0.93879×0.84835=0.79643\cos^2(0.25)\cos^2(0.4) = 0.93879 \times 0.84835 = 0.79643, which the exercise's statevector overlap reproduces. The zz kernel of the same pair is 0.443280.44328, and the RBF kernel with γ=1\gamma = 1 is e−0.89=0.41066e^{-0.89} = 0.41066.

An honest comparison

The dataset: points uniform in [0,π]2[0, \pi]^2, labelled +1+1 when (x0−π/2)(x1−π/2)>0(x_0 - \pi/2)(x_1 - \pi/2) > 0, an XOR pattern that no linear classifier on the raw features can learn. Forty training points, 200 test points, one seeded split per seed. For each kernel, λ∈{10−3,10−2,10−1,1}\lambda \in \{10^{-3}, 10^{-2}, 10^{-1}, 1\} is chosen by five-fold cross-validation on the training set only; the RBF width is fixed at γ=1\gamma = 1 and not tuned. Test accuracies from the exercise's reference solution:

seed quantum zz kernel quantum angle kernel classical RBF kernel nearest centroid
0 0.765 0.885 0.955 0.495
1 0.710 0.860 0.870 0.535
2 0.670 0.915 0.895 0.515
3 0.665 0.855 0.870 0.510
4 0.725 0.955 0.965 0.495
5 0.660 0.810 0.875 0.490
mean 0.699 0.880 0.905 0.507

What this shows, for this dataset and protocol: the classical RBF kernel is best on five of six splits; the angle-encoding kernel, which is a classical kernel in disguise, is close behind; the entangling zz map is clearly worse, because its feature geometry does not match the structure of the labels. Nearest centroid is at chance, because the two XOR classes have almost the same mean.

What it does not show: anything about larger problems, about hardware with shot noise, or about datasets with structure that suits a particular quantum feature map. It also illustrates a trap: had the comparison used only nearest centroid as the baseline, every quantum kernel would have "won", by 15 to 46 percentage points depending on the split. A claim of advantage needs the strongest reasonable classical baseline, the same data split, and hyperparameters chosen without looking at the test set.

The evidence on advantage

Dequantization. Many early QML speed-ups assumed that the quantum algorithm could sample from its input data efficiently. Tang showed that a classical algorithm with comparable sampling access solves the recommendation problem with only polynomial overhead (Tang 2019), and Chia and coauthors extended the approach to a framework covering many low-rank linear-algebra tasks (Chia et al. 2020). For these problems the exponential separation disappears once the classical algorithm gets the same input model.

A rigorous speed-up. Liu, Arunachalam and Temme constructed a classification problem, built from the discrete logarithm, that a quantum kernel method learns efficiently, while no efficient classical learner exists unless the discrete logarithm is classically easy (Liu, Arunachalam and Temme 2021). This is a proof that quantum learning advantages can exist, under a standard cryptographic assumption, for data with a specific hidden structure. It is not evidence about typical real-world datasets.

The power of data. Huang and coauthors showed that classical models that are given training data can, in many cases, predict as well as quantum models, even when the quantum model is hard to simulate, and they proposed a test that compares the geometry of a quantum kernel with classical ones before any advantage is claimed (Huang et al. 2021).

Taken together: an advantage for learning from classical data has been proven for a contrived problem, has not been demonstrated for a practical one, and several earlier claims were removed by better classical algorithms. This is an open research area, not a settled negative.

Exponential concentration

There is also a statistical obstacle. Thanasilp, Wang, Cerezo and Holmes proved that, under conditions including highly expressive encodings, entanglement, global measurements and noise, quantum kernel values concentrate exponentially in the number of qubits around a fixed value, so that exponentially many shots are needed to tell kernel entries apart, and a model trained on estimated kernels becomes insensitive to its input (Thanasilp et al. 2024).

Even the humble angle encoding shows the effect, and here it can be derived exactly. Draw x,x′\mathbf x, \mathbf x' independently and uniformly from [0,2π)n[0, 2\pi)^n. Then K=∏kcos⁡2(Δk/2)K = \prod_k\cos^2(\Delta_k/2) with Δk=xk−xk′\Delta_k = x_k - x'_k, and the factors are independent. Since cos⁡2(Δ/2)=(1+cos⁡Δ)/2\cos^2(\Delta/2) = (1 + \cos\Delta)/2, E[cos⁡Δ]=0\mathbb E[\cos\Delta] = 0 and E[cos⁡2Δ]=1/2\mathbb E[\cos^2\Delta] = 1/2:

E[K]=(12)n,E[K2]=(E(1+cos⁡Δ)24)n=(38)n,Var⁡[K]=(38)n−(14)n.\mathbb E[K] = \Big(\tfrac12\Big)^n, \qquad \mathbb E[K^2] = \Big(\mathbb E\tfrac{(1+\cos\Delta)^2}{4}\Big)^n = \Big(\tfrac38\Big)^n, \qquad \operatorname{Var}[K] = \Big(\tfrac38\Big)^n - \Big(\tfrac14\Big)^n .

Typical off-diagonal entries are of size 2−n2^{-n}, and estimating one to relative precision needs of order 2n2^n shots. A seeded check with 20,000 random pairs:

import numpy as np

rng = np.random.default_rng(0)
for n in (1, 2, 4, 8, 16):
    a, b = rng.uniform(0, 2 * np.pi, size=(2, 20000, n))
    k = np.prod(np.cos((a - b) / 2) ** 2, axis=1)
    print(n, f"{k.mean():.2e} vs {0.5**n:.2e}", f"{k.var():.2e} vs {(3/8)**n - 0.25**n:.2e}")

The empirical moments match the formulas up to n=8n = 8. At n=16n = 16 the exact mean is 1.5×10−51.5\times10^{-5}, and even 20,000 samples estimate it poorly (the snippet prints 1.16×10−51.16\times10^{-5} for the mean and half the exact variance), because the average is dominated by rare pairs that happen to be close: concentration makes even the statistics of the kernel expensive to resolve. Rescaling the inputs to a narrower range (a bandwidth parameter) is one mitigation; it also makes the model more classical-like, which is part of the point Huang and coauthors make.

Exercise: a quantum kernel against classical baselines

In quantum-kernel-baseline you implement both encodings, the fidelity kernel from state vectors, the classical closed form, the RBF kernel, kernel ridge regression, cross-validated choice of λ\lambda, nearest centroid, the full comparison, and the concentration statistics. The checks test the zz state against an independent construction with scipy.linalg.expm, the angle kernel against the closed form, positive semidefiniteness and unit diagonal of every Gram matrix, interpolation at tiny λ\lambda, nearest centroid on separable and XOR data, and the empirical concentration moments against the exact ones.

Common mistakes

  • A weak baseline. Nearest centroid, a linear model on XOR data, or an untuned classical kernel makes any model look good.
  • Tuning on the test set, or tuning only the quantum model.
  • Calling a product-state encoding "quantum". Its kernel is a product of cosines.
  • Ignoring encoding cost. Amplitude encoding of arbitrary data costs as much as reading it.
  • Ignoring shot noise. Exact kernels are a best case; concentrated kernels need exponentially many shots.
  • Reading a rigorous but contrived advantage as a general one, or reading dequantization as a proof that quantum learning is useless.

Summary

Encodings trade qubits for circuit cost, and product encodings are classically simulable: the angle-encoding kernel is ∏kcos⁡2((xk−xk′)/2)\prod_k\cos^2((x_k - x'_k)/2). Variational classifiers and fidelity kernels are linear models in the space of encoded states, and kernel ridge regression solves (K+λI)α=y(K + \lambda I)\boldsymbol\alpha = \mathbf y. On a small XOR task with hyperparameters chosen on training data, a classical RBF kernel matched or beat both quantum kernels, while a weak baseline would have suggested the opposite. The literature contains a proven learning advantage for a cryptographically structured problem, dequantization of several earlier claims, and theorems showing that expressive kernels concentrate exponentially. Claims of advantage therefore need strong baselines, fair protocols and explicit assumptions. The final lesson asks what it would cost to run the algorithms of this course on fault-tolerant hardware.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

A quantum kernel against honest classical baselines

advanced · about 1 h 30 min · needs numpy, scipy, pytest

Implement two quantum feature maps and their fidelity kernels from state vectors, train kernel ridge classifiers with hyperparameters chosen on the training set only, compare them with classical baselines on the same split, and measure how a quantum kernel concentrates as qubits are added.

Conventions: qubit 0 is the most significant bit of the basis index; labels are ±1\pm1. All kernels are exact (no shot noise): this is the most favourable setting for the quantum models.

Functions to implement in starter.py

Function Contract
make_dataset(n_samples, seed) x\mathbf x uniform in [0,π]2[0,\pi]^2; label +1+1 iff (x0−π/2)(x1−π/2)>0(x_0 - \pi/2)(x_1 - \pi/2) > 0
angle_encoding_state(x) ⨂kRY(xk)∣0⟩\bigotimes_k R_Y(x_k)\ket0
zz_feature_state(x, reps=2) reps times: H⊗HH\otimes H, then diag ei(x0Z0+x1Z1+(π−x0)(π−x1)Z0Z1)\mathrm{diag}\,e^{i(x_0Z_0 + x_1Z_1 + (\pi-x_0)(\pi-x_1)Z_0Z_1)}, on ∣00⟩\ket{00}
fidelity_kernel(XA, XB, feature_state) Kij=∣⟨ϕ(ai)∣ϕ(bj)⟩∣2K_{ij} = \abs{\braket{\phi(a_i)}{\phi(b_j)}}^2
product_kernel_closed_form(XA, XB) ∏kcos⁡2((ak−bk)/2)\prod_k\cos^2((a_k - b_k)/2)
rbf_kernel(XA, XB, gamma) e−γ∥a−b∥2e^{-\gamma\norm{a-b}^2}
kernel_ridge_fit(K, y, lam) / kernel_ridge_predict(K_test_train, alpha) α=(K+λI)−1y\boldsymbol\alpha = (K + \lambda I)^{-1}\mathbf y; labels sign⁡(Kα)\operatorname{sign}(K\boldsymbol\alpha) with 0 → +1
nearest_centroid_predict(X_train, y_train, X_test) label of the closer class mean
accuracy(y_true, y_pred) fraction correct
select_lambda(K, y, lambdas, folds=5) best k-fold CV accuracy on the training kernel (contiguous folds; ties to the larger λ\lambda)
compare_models(seed, n_train=40, n_test=200, ...) test accuracy of zz kernel, angle kernel and RBF kernel ridge (λ\lambda by select_lambda, RBF γ=1\gamma = 1), and nearest centroid, on one split
concentration_stats(n_qubits, n_pairs, seed) empirical mean and variance of the angle kernel for uniform random pairs in [0,2π)n[0,2\pi)^n, plus the exact 2−n2^{-n} and (3/8)n−4−n(3/8)^n - 4^{-n}

What the checks verify

  • The dataset is reproducible and in range; feature states are normalised.
  • The zz state agrees (up to a global phase) with an independent construction via scipy.linalg.expm.
  • Both Gram matrices are symmetric, positive semidefinite, with unit diagonal and entries in [0,1][0,1].
  • The angle kernel equals the classical closed form (it is classically computable).
  • Ridge with tiny λ\lambda interpolates the training labels.
  • Nearest centroid separates two blobs perfectly but stays near chance on the XOR data.
  • The comparison returns all four models, each kernel model beating chance.
  • The empirical concentration moments match the exact ones (5 standard errors for the mean, 12% for the variance) for n=1,2,4,8n = 1, 2, 4, 8.

Run the checks

python -m pytest test_exercise.py

Going further

Tune the RBF width γ\gamma by cross-validation as well, and add a bandwidth cc to the quantum maps (x→c x\mathbf x \to c\,\mathbf x). Does either quantum kernel now beat the tuned classical one on any seed? Write down your protocol before you look at test accuracies.

Terminal
python -m pip install numpy scipy pytest

starter.py

Python
"""Starter: a fidelity quantum kernel against classical baselines, all in NumPy.

Conventions: qubit 0 is the most significant bit of the basis index. Labels are +1/-1.
Everything is simulated exactly from state vectors; nothing here runs on hardware.
"""

import math

import numpy as np


def make_dataset(n_samples, seed):
    """Points x uniform in [0, pi]^2, label +1 if (x0 - pi/2)(x1 - pi/2) > 0 else -1 (an XOR pattern)."""
    raise NotImplementedError


def angle_encoding_state(x):
    """Product state RY(x_0)|0> (x) RY(x_1)|0> (x) ... (one qubit per feature)."""
    raise NotImplementedError


def zz_feature_state(x, reps=2):
    """Two-qubit entangling feature map: reps x [H on both qubits, then the diagonal phase
    exp(i (x0 Z0 + x1 Z1 + (pi - x0)(pi - x1) Z0 Z1))], applied to |00>."""
    raise NotImplementedError


def fidelity_kernel(XA, XB, feature_state):
    """K[i, j] = |<phi(a_i)|phi(b_j)>|^2 for the given feature-state function."""
    raise NotImplementedError


def product_kernel_closed_form(XA, XB):
    """The angle-encoding fidelity kernel computed classically: prod_k cos^2((a_k - b_k) / 2)."""
    raise NotImplementedError


def rbf_kernel(XA, XB, gamma):
    """exp(-gamma |a - b|^2)."""
    raise NotImplementedError


def kernel_ridge_fit(K, y, lam):
    """Dual coefficients alpha = (K + lam I)^{-1} y."""
    raise NotImplementedError


def kernel_ridge_predict(K_test_train, alpha):
    """Labels sign(K alpha), with 0 mapped to +1."""
    raise NotImplementedError


def nearest_centroid_predict(X_train, y_train, X_test):
    """Assign each test point the label of the closer class mean (Euclidean)."""
    raise NotImplementedError


def accuracy(y_true, y_pred):
    raise NotImplementedError


def select_lambda(K, y, lambdas, folds=5):
    """Ridge parameter with the best k-fold cross-validated accuracy on the TRAINING kernel only.

    Folds are contiguous index blocks; ties go to the larger lambda (more regularisation).
    """
    raise NotImplementedError


def compare_models(seed, n_train=40, n_test=200, lambdas=(1e-3, 1e-2, 1e-1, 1.0), rbf_gamma=1.0):
    """Train every model on the same split and return {model name: test accuracy}.

    Models: kernel ridge with the zz quantum kernel, the angle-encoding quantum kernel and the
    RBF kernel (lambda chosen by select_lambda on the training set), and nearest centroid.
    """
    raise NotImplementedError


def concentration_stats(n_qubits, n_pairs, seed):
    """Mean and variance of the angle-encoding kernel for random x, x' uniform in [0, 2 pi)^n.

    Returns (empirical mean, empirical variance, exact mean 2^-n, exact variance (3/8)^n - 4^-n).
    """
    raise NotImplementedError

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import math

import numpy as np
import pytest
from scipy.linalg import expm

Z = np.diag([1.0, -1.0])
I2 = np.eye(2)
H = np.array([[1, 1], [1, -1]]) / math.sqrt(2)


def zz_by_matrix_exponential(x, reps=2):
    """Independent construction of the zz feature state with scipy's expm."""
    G = x[0] * np.kron(Z, I2) + x[1] * np.kron(I2, Z) + (math.pi - x[0]) * (math.pi - x[1]) * np.kron(Z, Z)
    U = expm(1j * G) @ np.kron(H, H)
    state = np.array([1, 0, 0, 0], dtype=complex)
    for _ in range(reps):
        state = U @ state
    return state


def test_dataset_is_reproducible_and_balanced_enough():
    X1, y1 = target.make_dataset(50, 3)
    X2, y2 = target.make_dataset(50, 3)
    assert np.array_equal(X1, X2) and np.array_equal(y1, y2)
    assert set(np.unique(y1)) == {-1, 1}
    assert np.all((X1 >= 0) & (X1 <= math.pi))


def test_feature_states_are_normalised():
    rng = np.random.default_rng(0)
    for x in rng.uniform(0, math.pi, size=(5, 2)):
        assert np.isclose(np.linalg.norm(target.angle_encoding_state(x)), 1)
        assert np.isclose(np.linalg.norm(target.zz_feature_state(x)), 1)


def test_zz_state_matches_a_matrix_exponential_construction():
    rng = np.random.default_rng(1)
    for x in rng.uniform(0, math.pi, size=(5, 2)):
        a = target.zz_feature_state(x)
        b = zz_by_matrix_exponential(x)
        assert np.isclose(abs(np.vdot(a, b)), 1, atol=1e-10)


@pytest.mark.parametrize("which", ["angle", "zz"])
def test_kernels_are_valid_gram_matrices(which):
    fs = target.angle_encoding_state if which == "angle" else target.zz_feature_state
    X, _ = target.make_dataset(25, 0)
    K = target.fidelity_kernel(X, X, fs)
    assert np.allclose(np.diag(K), 1)
    assert np.allclose(K, K.T)
    assert np.linalg.eigvalsh(K).min() > -1e-10
    assert np.all((K >= -1e-12) & (K <= 1 + 1e-12))


def test_angle_encoding_kernel_is_classically_computable():
    rng = np.random.default_rng(2)
    A = rng.uniform(0, 2 * math.pi, size=(6, 3))
    B = rng.uniform(0, 2 * math.pi, size=(4, 3))
    K = target.fidelity_kernel(A, B, target.angle_encoding_state)
    # Independent value: prod cos^2(delta/2), written out here.
    expected = np.array([[np.prod(np.cos((a - b) / 2) ** 2) for b in B] for a in A])
    assert np.allclose(K, expected)
    assert np.allclose(target.product_kernel_closed_form(A, B), expected)


def test_ridge_interpolates_the_training_labels_when_lambda_is_tiny():
    X, y = target.make_dataset(20, 4)
    K = target.rbf_kernel(X, X, 2.0)
    alpha = target.kernel_ridge_fit(K, y, 1e-8)
    assert np.array_equal(target.kernel_ridge_predict(K, alpha), y)


def test_rbf_kernel_values():
    a = np.array([[0.0, 0.0]])
    b = np.array([[1.0, 1.0]])
    assert target.rbf_kernel(a, b, 0.5)[0, 0] == pytest.approx(math.exp(-1.0))


def test_nearest_centroid_separates_two_blobs_but_not_xor():
    rng = np.random.default_rng(5)
    Xa = rng.normal([0, 0], 0.2, size=(30, 2))
    Xb = rng.normal([2, 2], 0.2, size=(30, 2))
    X = np.vstack([Xa, Xb])
    y = np.array([1] * 30 + [-1] * 30)
    assert target.accuracy(y, target.nearest_centroid_predict(X, y, X)) == 1.0
    # On the XOR pattern the two class means nearly coincide: close to chance.
    res = target.compare_models(seed=0)
    assert res["nearest_centroid"] < 0.65


def test_comparison_runs_on_one_split():
    res = target.compare_models(seed=0)
    assert set(res) == {"quantum_zz", "quantum_angle", "classical_rbf", "nearest_centroid"}
    assert all(0.0 <= v <= 1.0 for v in res.values())
    # Every kernel model learns the XOR pattern better than chance on this split.
    assert min(res["quantum_zz"], res["quantum_angle"], res["classical_rbf"]) > 0.6


@pytest.mark.parametrize("n", [1, 2, 4, 8])
def test_concentration_matches_the_exact_moments(n):
    pairs = 20000
    mean, var, exact_mean, exact_var = target.concentration_stats(n, pairs, seed=n)
    assert exact_mean == pytest.approx(2.0**-n)
    assert exact_var == pytest.approx((3 / 8) ** n - 4.0**-n)
    assert abs(mean - exact_mean) < 5 * math.sqrt(exact_var / pairs)
    assert var == pytest.approx(exact_var, rel=0.12)

Check your understanding

7 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. Compute the angle-encoding fidelity kernel K(x,x′)K(\mathbf x, \mathbf x') for x=(0.4,2.0)\mathbf x = (0.4, 2.0) and x′=(1.2,1.0)\mathbf x' = (1.2, 1.0).

    1 pt
  2. Run compare_models(seed=0) from your quantum-kernel-baseline solution. What is the test accuracy of the classical RBF kernel ridge model? (Deterministic for the seed.)

    2 pts

    Computed by running exercise “quantum-kernel-baseline” on your computer.

  3. Same run, compare_models(seed=0): what is the test accuracy of the zz quantum kernel model?

    1 pt

    Computed by running exercise “quantum-kernel-baseline” on your computer.

  4. Why can a model whose only quantum ingredient is the angle encoding ⨂kRY(xk)∣0⟩\bigotimes_k R_Y(x_k)\ket0 never offer a computational advantage, however many qubits it uses?

    1 pt
  5. Which practices are required for an honest quantum-versus-classical kernel comparison? Select all that apply.

    1 pt

    Select all that apply.

  6. For the angle-encoding kernel with x,x′\mathbf x, \mathbf x' uniform in [0,2π)n[0,2\pi)^n, what is the exact variance of KK for n=8n = 8? Enter it in units of 10−410^{-4}.

    1 pt
  7. Which statement best summarises the evidence on quantum advantage for learning from classical data, as presented in the lesson?

    1 pt

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Maria Schuld, Nathan Killoran (2019). Quantum machine learning in feature Hilbert spaces. Physical Review Letters 122, 040504. doi:10.1103/PhysRevLett.122.040504
  2. Vojtěch Havlíček et al. (2019). Supervised learning with quantum-enhanced feature spaces. Nature 567, 209-212. doi:10.1038/s41586-019-0980-2
  3. Ewin Tang (2019). A quantum-inspired classical algorithm for recommendation systems. Proceedings of the 51st Annual ACM SIGACT Symposium on Theory of Computing (STOC 2019). doi:10.1145/3313276.3316310
  4. Nai-Hui Chia et al. (2020). Sampling-based sublinear low-rank matrix arithmetic framework for dequantizing quantum machine learning. Proceedings of the 52nd Annual ACM SIGACT Symposium on Theory of Computing (STOC 2020). doi:10.1145/3357713.3384314
  5. Yunchao Liu, Srinivasan Arunachalam, Kristan Temme (2021). A rigorous and robust quantum speed-up in supervised machine learning. Nature Physics 17, 1013-1017. doi:10.1038/s41567-021-01287-z
  6. Hsin-Yuan Huang et al. (2021). Power of data in quantum machine learning. Nature Communications 12, 2631. doi:10.1038/s41467-021-22539-9
  7. Supanut Thanasilp et al. (2024). Exponential concentration in quantum kernel methods. Nature Communications 15, 5200. doi:10.1038/s41467-024-49287-w
  8. Jarrod R. McClean et al. (2018). Barren plateaus in quantum neural network training landscapes. Nature Communications 9, 4812. doi:10.1038/s41467-018-07090-4