If a learning model uses a quantum circuit instead of a neural network, does it learn better? The honest answer today is: it has not been shown. What exists are two precise ideas, quantum kernels and parametrised circuits trained like networks, and an equally precise problem, the difficulty of training large circuits. This article simulates them in numpy and scikit-learn on a test dataset, to get a feel for what works and where it breaks, and to know which questions to ask when faced with a headline like "quantum machine learning beats classical".
No experiment here runs on quantum hardware: they are exact simulations on two, and up to ten, qubits, and they count as a laboratory, not as proof of advantage. You need the circuit and the ansatz from article 07, and the idea of parametrised layers from QAOA in article 08; the representation of data as a state is the one from the qubit in article 01.
From data to a state: encoding as a feature map
A quantum circuit works on states, not on numbers: to use it on data you must first encode them, that is prepare a state |φ(x)⟩ that depends on the point x. Schuld and Killoran read this operation as a nonlinear feature map into Hilbert space, and derive from it the link with kernel methods: if the device estimates the inner product between two encoded states, that value can feed a classical classifier such as a support vector machine (SVM). The kernel is k(x, y) = |⟨φ(x)|φ(y)⟩|²: a number between 0 and 1 that says how similar two points are for the model.
The listing defines two encodings on two qubits. Encoding A prepares RY(x_i)|0⟩ on each qubit: each feature occupies one qubit and there is no entanglement. Encoding B, in the style of the map proposed by Havlíček and collaborators but defined here by the formulas in the code, applies Hadamards, a phase exp(i(x₀Z₀ + x₁Z₁ + (π-x₀)(π-x₁)Z₀Z₁)) and repeats the pair twice; the term with Z₀Z₁ mixes the two features. The function kernel computes the matrix of squared moduli of the inner products, and __main__ does two things: it checks the matrix and trains an SVM on the "two moons" dataset (make_moons, 200 points, noise 0.2, scaled to [0, π]).
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import SVC
H1 = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
H2 = np.kron(H1, H1)
Z0, Z1 = np.array([1, 1, -1, -1]), np.array([1, -1, 1, -1]) # eigenvalues of Z on qubit 0 and on qubit 1
def stato_prodotto(X):
"""Encoding A: RY(x_i)|0> on each qubit: amplitudes (cos x/2, sin x/2)."""
q = [np.stack([np.cos(X[:, i] / 2), np.sin(X[:, i] / 2)], axis=1) for i in range(2)]
return np.einsum("na,nb->nab", q[0], q[1]).reshape(len(X), 4).astype(complex)
def stato_entangling(X, repetitions=2):
"""Encoding B: Hadamard + phases exp(i(x0 Z0 + x1 Z1 + (pi-x0)(pi-x1) Z0 Z1)), repeated."""
fase = X[:, [0]] * Z0 + X[:, [1]] * Z1 + (np.pi - X[:, [0]]) * (np.pi - X[:, [1]]) * Z0 * Z1
psi = np.tile(np.array([1, 0, 0, 0], dtype=complex), (len(X), 1))
for _ in range(repetitions):
psi = (psi @ H2.T) * np.exp(1j * fase)
return psi
def kernel(stato, A, B):
return np.abs(stato(A) @ stato(B).conj().T) ** 2 # |<phi(a)|phi(b)>|^2
if __name__ == "__main__":
rng = np.random.default_rng(0)
P, Q = rng.uniform(0, np.pi, (50, 2)), rng.uniform(0, np.pi, (40, 2))
chiuso = np.prod(np.cos((P[:, None, :] - Q[None, :, :]) / 2) ** 2, axis=2)
print("encoding A = product of cosines (closed formula, deviation < 1e-12):",
bool(np.abs(kernel(stato_prodotto, P, Q) - chiuso).max() < 1e-12))
for nome, f in (("A", stato_prodotto), ("B", stato_entangling)):
K = kernel(f, P, P)
print(f"encoding {nome}: diagonal=1: {np.allclose(np.diag(K), 1)}, minimum eigenvalue >= -1e-12: "
f"{np.linalg.eigvalsh(K).min() >= -1e-12}")
risultati = {"classical RBF": [], "quantum A": [], "quantum B": [],
"untuned RBF": [], "untuned quantum B": []}
for seme in range(5):
X, y = make_moons(200, noise=0.2, random_state=seme)
X = MinMaxScaler((0, np.pi)).fit_transform(X)
Xa, Xt, ya, yt = train_test_split(X, y, test_size=0.5, random_state=seme, stratify=y)
# bandwidth chosen by cross-validation on the training set only, for all three
gamma = max([0.1, 0.3, 1, 3, 10], key=lambda g: cross_val_score(SVC(gamma=g), Xa, ya, cv=5).mean())
risultati["classical RBF"].append(SVC(gamma=gamma).fit(Xa, ya).score(Xt, yt))
risultati["untuned RBF"].append(SVC().fit(Xa, ya).score(Xt, yt)) # gamma="scale"
risultati["untuned quantum B"].append(
SVC(kernel="precomputed").fit(kernel(stato_entangling, Xa, Xa), ya).score(kernel(stato_entangling, Xt, Xa), yt))
for nome, f in (("quantum A", stato_prodotto), ("quantum B", stato_entangling)):
s = max([0.25, 0.5, 1, 2, 4], key=lambda c: cross_val_score(
SVC(kernel="precomputed"), kernel(f, c * Xa, c * Xa), ya, cv=5).mean())
svm = SVC(kernel="precomputed").fit(kernel(f, s * Xa, s * Xa), ya)
risultati[nome].append(svm.score(kernel(f, s * Xt, s * Xa), yt))
for nome, v in risultati.items():
print(f"{nome:>20}: test accuracy, mean over 5 seeds = {np.mean(v):.3f} (min {min(v):.2f}, max {max(v):.2f})")
# Output:
# encoding A = product of cosines (closed formula, deviation < 1e-12): True
# encoding A: diagonal=1: True, minimum eigenvalue >= -1e-12: True
# encoding B: diagonal=1: True, minimum eigenvalue >= -1e-12: True
# classical RBF: test accuracy, mean over 5 seeds = 0.966 (min 0.94, max 0.99)
# quantum A: test accuracy, mean over 5 seeds = 0.850 (min 0.82, max 0.87)
# quantum B: test accuracy, mean over 5 seeds = 0.930 (min 0.89, max 0.95)
# untuned RBF: test accuracy, mean over 5 seeds = 0.948 (min 0.94, max 0.96)
# untuned quantum B: test accuracy, mean over 5 seeds = 0.762 (min 0.74, max 0.80)
The first three lines are checks. For encoding A the kernel coincides with a closed formula, the product of the cos²((x_i - y_i)/2), to within 10-12: no quantum computer is needed to compute it, because an encoding without entanglement gives product states and the inner product factorises. A legitimate kernel matrix has diagonal 1 and non-negative eigenvalues, and both encodings satisfy this. Then the results, over five different splits of the dataset: the SVM with a classical RBF kernel reaches 0.966 test accuracy, quantum kernel B 0.930, kernel A 0.850. Kernel A is a product of two terms, one per feature, as the closed formula says: it cannot represent interactions between the two features, whereas B has the Z₀Z₁ term. This is a plausible explanation of the gap, not verified with a control experiment.
One detail is worth more than the comparison: the bandwidth. The factor c that multiplies the data before encoding (chosen by cross-validation on the training set only, like gamma for the RBF) changes the result radically. The last two lines of the output show the same five splits without tuning (c = 1 for the quantum kernel and the default gamma for the RBF): kernel B drops to 0.762 instead of 0.930, the RBF to 0.948 instead of 0.966. A comparison between quantum and classical kernels that does not optimise the two sides in the same way measures the tuning more than the kernel. It is also worth noting what the simulator does not say: each element of the matrix, on a device, is a probability estimated with a finite number of shots, and for 100 training points the distinct pairs are 100·99/2 = 4,950.
Parametrised circuits and barren plateaus
The second idea is to train the circuit directly: an ansatz with parameters, a cost function measured on the output and a classical optimiser, as in VQE. Here the problem is trainability. McClean and collaborators showed that, for a broad class of circuits inspired by random circuits, the probability that a gradient is non-zero at a fixed precision is exponentially small in the number of qubits: this is the phenomenon of barren plateaus. Cerezo and collaborators then proved, for an alternating layered ansatz made of blocks that are local 2-designs (an assumption the circuit in the listing does not necessarily satisfy), that it also depends on the cost function: with global observables the gradients vanish exponentially even at small depth, with local observables at worst polynomially if the depth grows as the logarithm of the number of qubits.
The listing measures the phenomenon instead of citing it. The ansatz alternates RY rotations on every qubit and a chain of CZ gates between adjacent qubits, with uniform random angles. costo computes the mean value of a product of Z on the chosen qubits; varianza_gradiente estimates the derivative with respect to the first angle with the π/2 shift rule (valid for RY rotations) over 200 random initialisations and returns its variance. The __main__ block first checks the rule against a finite difference, then compares three configurations as the qubits go from 2 to 10.
import numpy as np
def ry(psi, q, theta, n):
t = psi.reshape([2] * n)
c, s = np.cos(theta / 2), np.sin(theta / 2)
a, b = np.take(t, 0, axis=q), np.take(t, 1, axis=q)
return np.stack([c * a - s * b, s * a + c * b], axis=q).reshape(-1)
def cz_catena(n):
"""Phase -1 when two adjacent qubits are both 1, for all pairs (q, q+1)."""
bit = (np.arange(2**n)[:, None] >> np.arange(n)[None, :][:, ::-1]) & 1 # bit[z, q]
return np.prod([1 - 2 * (bit[:, q] & bit[:, q + 1]) for q in range(n - 1)], axis=0), bit
def costo(theta, n, strati, qubit_osservati):
fase, bit = cz_catena(n)
psi = np.zeros(2**n)
psi[0] = 1
k = 0
for _ in range(strati):
for q in range(n):
psi = ry(psi, q, theta[k], n)
k += 1
psi = psi * fase
segno = np.prod([1 - 2 * bit[:, q] for q in qubit_osservati], axis=0) # eigenvalues of Z on the chosen qubits
return float((psi**2) @ segno)
def varianza_gradiente(n, strati, qubit_osservati, campioni=200, seme=3):
rng = np.random.default_rng(seme)
g = []
for _ in range(campioni):
th = rng.uniform(0, 2 * np.pi, n * strati)
piu, meno = th.copy(), th.copy()
piu[0] += np.pi / 2
meno[0] -= np.pi / 2
g.append((costo(piu, n, strati, qubit_osservati) - costo(meno, n, strati, qubit_osservati)) / 2)
return np.var(g)
if __name__ == "__main__":
# check of the pi/2 shift rule against the finite difference
n, L = 4, 3
th = np.random.default_rng(1).uniform(0, 2 * np.pi, n * L)
e = 1e-6
p, m = th.copy(), th.copy()
p[2] += e
m[2] -= e
fd = (costo(p, n, L, range(n)) - costo(m, n, L, range(n))) / (2 * e)
ps = (costo(th + np.eye(n * L)[2] * np.pi / 2, n, L, range(n)) - costo(th - np.eye(n * L)[2] * np.pi / 2, n, L, range(n))) / 2
print(f"derivative: pi/2 shift = {ps:+.6f}, finite difference = {fd:+.6f}, equal within 1e-6: {abs(ps - fd) < 1e-6}")
print(f"{'n':>3} {'global cost (Z on all), n layers':>38} {'local cost (Z0 Z1), n layers':>32} {'local cost, 2 layers':>24}")
righe = []
for n in (2, 4, 6, 8, 10):
righe.append((varianza_gradiente(n, n, range(n)), varianza_gradiente(n, n, [0, 1]), varianza_gradiente(n, 2, [0, 1])))
a, b, c = righe[-1]
print(f"{n:>3} {a:>38.2e} {b:>32.2e} {c:>24.2e}")
for j, nome in enumerate(("global", "local, n layers", "local, 2 layers")):
pendenza = np.polyfit([2, 4, 6, 8, 10], np.log2([r[j] for r in righe]), 1)[0]
print(f"cost ({nome}): the variance is multiplied by {2 ** pendenza:.2f} for each added qubit")
# Output:
# derivative: pi/2 shift = +0.148559, finite difference = +0.148559, equal within 1e-6: True
# n global cost (Z on all), n layers local cost (Z0 Z1), n layers local cost, 2 layers
# 2 1.72e-01 1.72e-01 1.72e-01
# 4 6.22e-02 1.53e-01 2.12e-01
# 6 1.55e-02 1.33e-01 1.77e-01
# 8 5.82e-03 1.12e-01 1.68e-01
# 10 1.59e-03 8.53e-02 1.85e-01
# cost (global): the variance is multiplied by 0.56 for each added qubit
# cost (local, n layers): the variance is multiplied by 0.92 for each added qubit
# cost (local, 2 layers): the variance is multiplied by 1.00 for each added qubit
The shift rule coincides with the finite difference (0.148559 in both cases). With the global cost, that is the product of Z on all the qubits, the gradient variance falls from 0.172 to 0.0016 between 2 and 10 qubits, and is multiplied by about 0.56 for each added qubit. To estimate the gradient at the same relative precision you then need about 1.8 times more shots for each additional qubit (1 divided by 0.56). With the local cost (Z₀Z₁) and n layers the variance is multiplied by 0.92, much more slowly, and with only 2 layers it stays practically constant. These are three measurements on one ansatz and two costs, with 200 samples per point: they confirm the trend described in the literature, they do not prove it in general, and the comparison holds only for this circuit, with uniform angles.
Two practical rules follow, of which the code verifies only the first. First: define the cost with local observables, if the problem allows it, and keep the circuit shallow. Second: do not start from a random circuit, a choice that the abstract of McClean and collaborators judges unsuitable beyond a few qubits (the listing does not compare different initialisations: this rule comes from the source, not from the measurement). The experiments do not cover remedies such as structured initialisations or problem-specific ansätze, which the literature proposes but which are not measured here.
The comparison with the classical: where the promises deflated
The two previous ideas are heuristics, with no guarantee of advantage. The most instructive case comes from an algorithm for recommendation systems that was considered among the strongest candidates for a provable exponential advantage in quantum machine learning. Tang gave a classical analogue, which with a data structure that allows sampling with probability proportional to the squared moduli produces a sample from a rank-k approximation of the matrix in time O(poly(k) log(mn)), only polynomially slower. The consequence stated in the abstract is that the quantum algorithm does not give an exponential advantage. The lesson is not that quantum machine learning is useless; it is that an advantage depends on the assumptions about the input, and has to be compared with the best classical method that exploits the same assumptions.
Havlíček and collaborators proposed and implemented on a superconducting processor a variational classifier and a kernel estimator. Of the two methods, only the kernel estimator was simulated here, in exact and small form; the variational classifier was not. Before reporting a QML result as an advantage it is worth asking four questions:
- how the data enter the circuit, and how much it costs to prepare them compared with the computation that follows;
- whether the model is compared with the best classical model with the same care in tuning;
- whether the circuit can be trained at the stated scale, or whether the cost function is subject to plateaus;
- whether the result is on hardware with noise and finite shots, or on an exact simulator.
The questions are not a list of quibbles: each corresponds to a point where, in this article, the comparison changed. The first is the reason why the low-dimensional data above prove nothing; the second moved kernel B from 0.76 to 0.93; the third is the result of the plateau listing; the fourth is the declared limit of every simulation reported here.
What you can do now
You can encode classical data in a state, compute a quantum kernel and use it in an SVM, and you can check it with a closed formula when the encoding allows it. You can measure the gradient variance of a parametrised circuit as a function of the qubits and recognise the difference between global and local cost. You can also pose the four questions that separate a laboratory result from a proof of advantage. What remains is to see on which machines the algorithms of this series could run: the last article compares the technologies of quantum hardware. The complete sequence is on the series page.
Frequently asked questions
What is a quantum kernel?
It is the similarity between two points computed as the squared modulus of the inner product between the quantum states that encode them. The value can be estimated on a device and used in a classical support vector machine.
What is a barren plateau?
A region in which the gradients of the cost function of a parametrised circuit are exponentially small in the number of qubits, and training has no direction. In the simulations of the article, with a global cost the gradient variance is multiplied by about 0.56 for each added qubit.
Does quantum machine learning beat classical machine learning?
It has not been shown. On the article's test dataset the classical RBF kernel obtains 0.966 accuracy against 0.930 for the best simulated quantum kernel, and a known case of expected exponential advantage was scaled down by a classical algorithm.
Sources
- Schuld, Killoran, Quantum machine learning in feature Hilbert spaces - encoding as a feature map and the link with kernel methods (abstract), consulted on 2026-11-13
- Havlíček et al., Supervised learning with quantum enhanced feature spaces - variational classifier and kernel estimator on a superconducting processor (abstract), consulted on 2026-11-13
- McClean et al., Barren plateaus in quantum neural network training landscapes - exponentially small gradients for circuits inspired by random ones (abstract), consulted on 2026-11-13
- Cerezo et al., Cost Function Dependent Barren Plateaus in Shallow Parametrized Quantum Circuits - global cost versus local cost (abstract), consulted on 2026-11-13
- Tang, A quantum-inspired classical algorithm for recommendation systems - the classical analogue of the quantum recommendation algorithm and the consequence for exponential advantage (abstract), consulted on 2026-11-13
The two listings were run twice with Python 3.14, numpy 2.5.4, scipy 1.18.1 and scikit-learn 1.9.1, with identical outputs (fixed seeds). The outputs reported are the real ones. They are exact simulations, with no noise and no finite shots.
Commenti
Caricamento commenti...
Sign in to comment