Lesson 43 · 100 min · advanced
Variational Quantum Circuits: Architecture
A variational quantum circuit (VQC) is a supervised model built from three parts: a feature map that writes the input into a quantum state, a parameterised ansatz , and an observable whose expectation value is the model output . This lesson proves by the cyclicity of the trace that is a linear function of the encoded density operator, i.e. a linear model in the Hilbert–Schmidt feature space of the previous module; proves that the output lies in ; derives the decision rule, the MSE and hinge losses and their gradients; works out the one-qubit classifier exactly, together with the variant ; computes the shot noise and a Hoeffding shot count; writes the hybrid quantum–classical training loop with its cost per epoch; and derives the exact interval of weights that classifies the lab data correctly.
Prerequisites: Angle & Phase Encoding, Postulate 3: Projective Measurement & the Born Rule
Objectives and key results
Decompose a variational quantum circuit into a feature map , an ansatz and an observable , and write its output as .
Prove and explain why a VQC is a linear model in the Hilbert–Schmidt feature space whose functions lie in the RKHS of the fidelity kernel.
Prove that , define the classifier , and differentiate the MSE and hinge losses with respect to and to .
Derive for , , by matrix algebra, locate its decision boundary, and show that the encoding gives instead.
Compute the variance of the -shot estimator of a Pauli expectation value and the Hoeffding shot count .
Write the hybrid quantum–classical training loop, count its circuit evaluations per epoch, , and distinguish gradient-based, stochastic-approximation and gradient-free loops.
Derive the exact set of weights that classifies the lab data correctly.
- definition · Variational quantum model
- identity · A VQC is linear in the encoded density operator
- theorem · Output range
- formula · One-qubit threshold model
- formula · Shot noise of a Pauli expectation value
- algorithm · Cost of one training epoch
Feature map, ansatz and observable#
Stage 3 used quantum computers in one specific way: a feature map produced states whose overlaps formed a kernel matrix, and all learning happened classically in the dual coefficients of a support vector machine. Stage 4 changes the division of labour. The circuit itself now carries trainable parameters , the quantum computer evaluates the model output for every input, and a classical optimiser adjusts in a loop. Such models are called variational quantum circuits (VQC) or parameterised quantum circuits (PQC), and on noisy intermediate-scale (NISQ) hardware they are the most widely studied form of quantum machine learning. This lesson fixes the architecture once and for all, proves the structural facts that every later lesson relies on (linearity in the encoded state, the output range, the shot noise, the cost of training), and works through a one-qubit classifier that can be solved with pencil and paper and is trained in the lab.
Definition
Feature map, ansatz and observable
Fix qubits and the register state . A variational quantum circuit consists of three components. (i) A feature map (data encoding) from the input domain to unitary matrices, realised by a circuit whose gate angles are functions of ; for example the angle encoding of the lesson Angle & Phase Encoding. (ii) An ansatz from a parameter space to unitaries, realised by a fixed circuit structure whose rotation angles are the trainable weights . (iii) An observable on , given as a real combination of Pauli strings . The data symbols of are set by the input and never trained; the weights of are never set by the input.
Definition
Variational quantum model and classifier
The model output of a VQC is the expectation value of in the state : For binary labels the classifier predicts , where an output of exactly is counted as a wrong prediction (a point on the decision boundary is not classified). The decision boundary is the zero set . On hardware is not available exactly; it is estimated from repetitions (shots) of the circuit followed by a measurement of .
A variational model is linear in the encoded density operator
Let be the encoded density operator and . Then The operator is Hermitian, has the same eigenvalues as and the same Hilbert–Schmidt norm . Consequently, for every fixed the map is a linear functional on the real space of the lesson Quantum Kernels & Fidelity Kernels, and belongs to the RKHS of the fidelity kernel with .
Proof (7 steps)
- Step 1:A matrix equals its trace. Abbreviate and .
- Step 2:Cyclicity of the trace for the row and the matrix-times-column .
- Step 3:Cyclicity once more, moving the leftmost factor to the right end; then the definitions of and , and cyclicity for the last equality.
- Step 4:and . Inserting the spectral decomposition of shows that has the eigenvalues with the orthonormal eigenvectors ( is unitary).
- Step 5:and cyclicity: the Hilbert–Schmidt norm is invariant under unitary conjugation.
- Step 6:For Hermitian matrices . Linearity of the trace makes a real-linear functional on : the model is a linear model whose feature vector is and whose weight vector is .
- Step 7:The RKHS proposition of the kernel lesson: with , and the component of an observable orthogonal to does not change any expectation value . The orthogonal projection does not increase the norm.
∎
The theorem separates the roles of the three components precisely. The feature map alone determines the feature vectors and therefore the kernel and the space of functions any model on this encoding can represent. The ansatz and the observable together choose one weight vector inside the set , a subset of the unitary orbit of , which consists of Hermitian matrices of fixed spectrum and fixed norm . A kernel method searches all of (with a norm penalty) by convex optimisation; a variational circuit searches a curved, norm-bounded subset of it by nonconvex optimisation over . The dependence on is linear in but generally nonlinear in , and the dependence on is nonlinear as well: linearity holds only in the encoded state.
Heisenberg picture for one qubit: the model as a dot product of Bloch vectors
- Step 1:Any one-qubit density matrix has a Bloch vector . is Hermitian and traceless with eigenvalues (the spectrum of ), so it is with a unit vector .
- Step 2:The Pauli matrices are traceless and : the one-qubit model is the Euclidean dot product of the Bloch vector of the encoded state with a measurement direction.
- Step 3:With , , is real, so , and . Double-angle formulas: , . Hence .
- Step 4:Bloch vector of a state with real amplitudes: the encoding moves on the great circle of the -plane at polar angle .
- Step 5:Addition theorem of the cosine. The model of this lesson's worked example is obtained in the Heisenberg picture, where the ansatz acts on the observable instead of on the state; the Schrödinger-picture derivation follows in the section on the one-qubit classifier.
- Step 6:; the values give and , which span . Here , so the trained models form a circle of radius in the three-dimensional RKHS spanned by the functions : the variational family is a one-parameter curve inside the linear model space.
Result
Quick check
For a fixed weight vector , in which of the following quantities is the model output always linear?
Output range, decision rule and losses#
The model output lies between the extreme eigenvalues of the observable
Let have the spectral decomposition with and . Then for every input and every weight vector and the upper (lower) bound is attained exactly when lies in the eigenspace of (). In particular for every Pauli string , and for .
Proof (6 steps)
- Step 1:Spectral theorem for Hermitian matrices: real eigenvalues and an orthonormal eigenbasis.
- Step 2:Abbreviate and insert the decomposition; .
- Step 3:Completeness of the orthonormal basis and normalisation of ( and are unitary). By the Born rule is the probability of measuring the eigenvalue .
- Step 4:is a convex combination of the eigenvalues; replace every by the smallest or the largest one, using and .
- Step 5:A sum of nonnegative terms vanishes only if every term vanishes: equality holds exactly when has no component outside the top eigenspace (and likewise for ).
- Step 6:A Pauli string is Hermitian and squares to the identity, so its eigenvalues satisfy ; it has both eigenvalues because for . For a sum, the triangle inequality and the Pauli bound give the stated interval (a bound, not always attained).
∎
MSE and hinge losses and their gradients
- Step 1:Empirical risk on the training set with a per-sample loss ; the chain rule separates a classical factor from a quantum factor , which the circuit must supply.
- Step 2:The squared error treats the labels as regression targets. Because for a Pauli observable, the targets lie at the end points of the attainable range.
- Step 3:Insert the derivative into the chain rule: each sample needs its output (for the residual) and its gradient .
- Step 4:The hinge loss of the support vector machine. At the kink it is not differentiable; every number between and is a subgradient, and the platform uses .
- Step 5:For a Pauli observable the output never exceeds in modulus, so the margin never exceeds and the hinge is always on its linear branch: the hinge loss becomes minus the average signed output, a linear function of the outputs.
- Step 6:The chain rule with the hinge derivative; for a Pauli observable the sum runs over all samples except those with exactly.
- Step 7:The accuracy of the classifier is piecewise constant in , with zero gradient almost everywhere; it is used to evaluate a model, while the differentiable losses above are used to train it.
Result
Quick check
A two-qubit VQC measures . What is the largest output value any choice of feature map, ansatz, input and weights can produce?
A one-qubit classifier worked out exactly#
The smallest VQC has one qubit, one feature and one weight: feature map , ansatz , observable . It is the model of the lab and of the function singleQubitThresholdModel in the platform's QML library. The Heisenberg-picture derivation above already gave ; here the same result is derived directly from the state, by the matrix algebra one would use for any circuit, and then the encoding is changed from to to see how strongly the feature map constrains what the ansatz can do.
Rotations about the same axis add their angles
For all real and , In particular : the weight of the worked model acts as a shift of the input.
Proof (5 steps)
- Step 1:For commuting matrices the binomial theorem holds, by induction on : commutativity is exactly what is needed to collect the terms .
- Step 2:Both exponential series converge absolutely, so their Cauchy product may be regrouped by total degree , using .
- Step 3:Two multiples of the same matrix commute, so the exponents add.
- Step 4:An independent check by matrix multiplication, with , and the same for ; the matrix form of is with .
- Step 5:Addition theorems of cosine and sine at the half angles. The product is again a rotation about , by the summed angle.
∎
State and output of U(x) = R_Y(x), W(θ) = R_Y(θ), H = Z
- Step 1:The circuit applies first and second; the lemma combines them.
- Step 2:Matrix times the first basis vector is the first column.
- Step 3:A real state at polar angle on the -great circle of the Bloch sphere.
- Step 4:The amplitudes are real, so the bra is the transposed column; flips the sign of the second component.
- Step 5:Double-angle formula with . The value lies in , as the output-range theorem requires.
- Step 6:and . Then , so , the label of in the lab. The circuit below shows this state.
Result
Circuit · 1 qubit
The model circuit then with the data symbol bound to and the weight to . The statevector is , and .
Unitary verified: (max deviation 0.0e+0)
Decision boundary and decision regions
- Step 1:The zeros of the cosine are the odd multiples of ; modulo these are and .
- Step 2:The cosine is positive on and negative on , each modulo .
- Step 3:On the input axis the classifier has a rising boundary , where the prediction changes from to as increases, and a falling boundary , where it changes back.
- Step 4:The weight translates both boundaries rigidly; the two regions always have length . Shifting by exchanges the regions, since : every prediction is negated.
Result
The Bloch sphere shows the encoded state of the data point : polar angle , azimuth , Bloch vector . It lies slightly below the equator, so without an ansatz () the model would output and predict , the wrong label. The ansatz rotates this point by about the -axis (equivalently, it rotates the measurement direction by ), and the lab asks for the rotation that lifts the two points of class above the equator while pushing the two points of class below it.
The pipeline above shows the three stages, feature map, ansatz and measurement, for the four lab points at . The output is , which is positive for and negative for : exactly the opposite of the labels, so the accuracy is and the MSE is . Drag and watch the decision regions translate along the data strip.
Changing the encoding: U(x) = R_X(x) gives f = cos x cos θ
- Step 1:; its first column is the encoded state.
- Step 2:Matrix–vector product with the real matrix . The two rotations are about different axes, so the lemma does not apply and the angles do not add.
- Step 3:for real ; the cross terms cancel because one part is real and the other imaginary.
- Step 4:; factor and use the double-angle formula twice.
- Step 5:The model is not : the term is missing, and the two models differ by up to (the platform's simulator confirms the maximum difference on a grid). They agree only where .
- Step 6:The Heisenberg picture explains why: places the data on the -great circle, the ansatz only tilts the measurement direction within the -plane, and the -component of the encoded Bloch vector, which would carry , is identically .
- Step 7:The weight only rescales the output by and possibly flips its sign; the decision boundary is fixed at for every (for the model is identically ).
Result
With the encoding the model family is , a single function scaled by a factor in . For the lab data this family happens to suffice: the fixed boundary lies between and , and every weight with , e.g. as in the pipeline above, classifies all four points correctly. For data whose classes change at any other place, no weight works. The encoding produces the family of all translated cosines, whose boundary can be placed anywhere. The same ansatz and observable give a strictly richer model on one encoding than on the other, which illustrates the first lesson of the trace form: the feature map fixes the space of features, and the ansatz can only choose a direction inside it.
Quick check
For the worked model , , , compute the output at and (four decimals).
Quick check
With the encoding , ansatz and , what does changing the weight do to the classifier?
Estimating the output with finitely many shots#
Shot noise of a Pauli expectation value
Let be a Pauli string and let the circuit be run times, each run ending in a projective measurement of with outcome . Then (a) with ; (b) the estimator is unbiased with (c) by Hoeffding's inequality , so shots give precision with probability at least ; (d) if , the estimated label differs from with probability at most .
Proof (7 steps)
- Step 1:The eigenprojectors of an operator with eigenvalues : , and they sum to the identity.
- Step 2:Born rule for projective measurements with , and .
- Step 3:The outcome is , so its square is always .
- Step 4:Each shot re-prepares the state, so the outcomes are independent and identically distributed: linearity of expectation, and variances of independent variables add.
- Step 5:Hoeffding's inequality for the mean of independent variables with values in : the exponent is .
- Step 6:Solve for by taking logarithms. The number of shots grows like and only logarithmically in the confidence.
- Step 7:The one-sided Hoeffding bound with ; the case is symmetric. A point far from the decision boundary (large ) is classified correctly with few shots; a point near it needs about shots.
∎
Shot budget for the lab point x = 1.8 at θ = −2.9
- Step 1:Exact output of the worked model and the Born probability of the outcome .
- Step 2:With shots the estimate scatters by about around . The exact binomial computation in the NumPy cell reproduces .
- Step 3:Part (d) of the theorem. The exact binomial probability is : Hoeffding's bound is valid but loose.
- Step 4:Estimating the output itself to two decimals with confidence costs tens of thousands of shots, far more than deciding its sign.
Result
Quick check
How many shots does the Hoeffding bound require to estimate a Pauli expectation value to precision with probability at least ?
The hybrid quantum–classical training loop#
Training a VQC alternates between two machines. The quantum processor evaluates circuits at fixed parameter values and returns estimated expectation values; it cannot store or update . The classical computer holds , assembles the loss and its gradient from the returned numbers, and applies an optimisation step. The loss gradient factorises into a classical part and a quantum part . Backpropagation through the circuit is unavailable because intermediate quantum states cannot be read out without destroying them (the topic of the next module), so the quantum part is obtained from additional circuit evaluations. For gates of the form with a Pauli generator the parameter-shift rule gives it exactly from two evaluations at shifted angles, the rule is stated here and derived in the lesson on the parameter-shift rule.
The parameter-shift rule on the worked model
- Step 1:The exact derivative of the closed-form output.
- Step 2:. The two shifted circuits reproduce the derivative exactly, not approximately: there is no step size and no truncation error, unlike a finite difference.
- Step 3:Insert into the MSE gradient of the previous section; at on the lab data this is , so gradient descent decreases , towards the feasible interval.
Result
Cost of one epoch of gradient-based training
Consider full-batch training on samples of a VQC with weights, each appearing in exactly one Pauli-rotation gate, with the loss gradient computed by the parameter-shift rule and every expectation value estimated with shots. One epoch (one gradient step) requires distinct circuit evaluations and shots. A gradient-free or stochastic-approximation step (SPSA) instead uses circuit evaluations, independently of .
Proof (5 steps)
- Step 1:The chain-rule form of the loss gradient: each sample contributes separately.
- Step 2:The classical factor needs the unshifted output (for the hinge loss it needs the sign of , which also requires ).
- Step 3:Parameter-shift rule with the shift applied only to weight ( is the -th unit vector); for weights circuits.
- Step 4:Sum over the samples and multiply by the shots per circuit. For the lab model (, ) this is circuits per epoch.
- Step 5:Simultaneous-perturbation stochastic approximation perturbs all weights at once along a random sign vector, so a step costs two loss evaluations, i.e. circuits, at the price of a noisy, only asymptotically unbiased gradient estimate.
∎
Varieties of hybrid loops. (a) Gradient-based with exact shifts: the loop of the proposition, used with gradient descent or Adam; its gradients are unbiased under shot noise, and it is the loop of the code cell below. (b) Finite differences: also costs circuits per sample but is biased by , and shot noise is amplified by , so small is unusable on hardware. (c) Stochastic approximation (SPSA): two evaluations per step whatever is, attractive for many weights. (d) Gradient-free direct search (Nelder–Mead, COBYLA): uses only loss values and scales poorly with . (e) Mini-batch versions of any of these replace the samples by a random batch per step and trade gradient noise for cost. All of them share the same structure: the quantum processor is a function evaluator inside a classical optimisation loop.
The TypeScript cell runs the hybrid loop on the worked model with the platform's QML library: it checks the model output and its parameter-shift derivative against and , writes out the training loop explicitly (one output evaluation and one two-circuit shift gradient per sample, then a classical step with ), and confirms that the library routine trainVQC produces the same trajectory. Starting at the all-wrong , the accuracy rises from through and to , and converges to the MSE minimiser , inside the feasible interval derived in the next section.
import { singleQubitThresholdModel, trainVQC, vqcAccuracy, vqcGradient, vqcPredict } from '@/lib/qml';
// The model of this lesson: U(x) = RY(x), W(theta) = RY(theta), H = Z, so f(x) = cos(x + theta).
const model = singleQubitThresholdModel();
const X = [[0.3], [0.9], [1.8], [2.2]];
const y = [-1, -1, 1, 1];
const M = X.length;
// (1) Quantum evaluation: f and its parameter-shift derivative equal cos(x + theta) and -sin(x + theta).
for (const theta of [0, -2.9, Math.PI]) {
const f = X.map((x) => vqcPredict(model, x, { theta }));
const df = X.map((x) => vqcGradient(model, x, { theta }).theta);
const exact = X.every((x, m) => Math.abs(f[m] - Math.cos(x[0] + theta)) < 1e-12 && Math.abs(df[m] + Math.sin(x[0] + theta)) < 1e-12);
console.log('theta = ' + theta.toFixed(4) + ' f = [' + f.map((v) => v.toFixed(4)).join(', ') + '] accuracy = ' + vqcAccuracy(model, X, y, { theta }) + ' closed form: ' + exact);
}
// (2) The hybrid loop written out: circuit evaluations inside, a classical gradient step outside.
const lr = 0.3;
let theta = 0;
for (let epoch = 0; epoch < 30; epoch++) {
let loss = 0;
let grad = 0;
for (let m = 0; m < M; m++) {
const f = vqcPredict(model, X[m], { theta }); // 1 circuit (N_shots shots on hardware)
const df = vqcGradient(model, X[m], { theta }).theta; // 2P = 2 shifted circuits
loss += (f - y[m]) ** 2 / M;
grad += (2 / M) * (f - y[m]) * df; // dL/df times df/dtheta
}
if (epoch % 5 === 0) console.log('epoch ' + epoch + ': theta = ' + theta.toFixed(4) + ' MSE = ' + loss.toFixed(4) + ' accuracy = ' + vqcAccuracy(model, X, y, { theta }));
theta -= lr * grad; // classical optimiser step
}
// (3) The library routine trainVQC runs the same loop.
const run = trainVQC(model, X, y, { init: { theta: 0 }, epochs: 30, optimizer: 'gd', lr, loss: 'mse' });
console.log('hand-written loop: theta = ' + theta.toFixed(6) + ', trainVQC: theta = ' + run.weights.theta.toFixed(6) + ', final accuracy = ' + run.history[30].accuracy);
console.log('circuit evaluations per epoch: M (2P + 1) = ' + M * (2 * model.weightParams.length + 1));Expected output
theta = 0.0000 f = [0.9553, 0.6216, -0.2272, -0.5885] accuracy = 0 closed form: true theta = -2.9000 f = [-0.8569, -0.4161, 0.4536, 0.7648] accuracy = 1 closed form: true theta = 3.1416 f = [-0.9553, -0.6216, 0.2272, 0.5885] accuracy = 1 closed form: true epoch 0: theta = 0.0000 MSE = 2.6206 accuracy = 0 epoch 5: theta = -0.7866 MSE = 2.1141 accuracy = 0.5 epoch 10: theta = -2.4224 MSE = 0.3403 accuracy = 0.75 epoch 15: theta = -2.8662 MSE = 0.1791 accuracy = 1 epoch 20: theta = -2.8881 MSE = 0.1787 accuracy = 1 epoch 25: theta = -2.8890 MSE = 0.1787 accuracy = 1 hand-written loop: theta = -2.889079, trainVQC: theta = -2.889079, final accuracy = 1 circuit evaluations per epoch: M (2P + 1) = 12
Quick check
A VQC with single-occurrence Pauli-rotation weights is trained full-batch on samples with parameter-shift gradients and the MSE loss. How many distinct circuit evaluations does one epoch need?
The lab data set: the exact feasible interval#
The lab trains the worked model on four labelled points: with label and with label . Because the model is the explicit function , the set of weights that classify all points correctly can be computed exactly, and so can the set where every prediction is wrong.
Feasible weights for the lab data
For and the data : an interval of length . Represented in it is , and in it is the union . Moreover exactly on the interval shifted by , , which contains the initial weight .
Proof (7 steps)
- Step 1:Every prediction must equal its label, and an output counts as wrong, so the inequalities are strict.
- Step 2:and must lie in a window ; both lie in the same window, because they are only apart and two consecutive positive windows are separated by a gap of length . So and .
- Step 3:The same argument with the negative windows for the two points apart.
- Step 4:Among the translates of the second interval only meets the first one, for : the translate starts at , and ends at .
- Step 5:The larger lower end point is (since ) and the smaller upper end point is (since ). Length . Equivalently, the rising boundary must lie in the gap between the classes.
- Step 6:Adding gives the representative in . It contains , so in the set splits into and .
- Step 7:negates every output, so a correct prediction becomes wrong and vice versa (no output is unless one already was). The all-wrong set is therefore the feasible set shifted by .
∎
Checking particular weights
- Step 1:Every sign is opposite to the label : the initial circuit of the lab misclassifies all points, which triggers the lab's diagnostic.
- Step 2:The lab's reference solution; the smallest margin is .
- Step 3:The flipped initial model: shifting by negates every output.
- Step 4:The rising boundary lies to the right of both positive points, so both are predicted ; note how close is to .
- Step 5:Now : the boundary separates the two positive points, and only is misclassified.
- Step 6:The midpoint of the interval puts the boundary at , halfway between and , which maximises the smallest margin: the two nearest points have .
Result
Closed-form minimiser of the hinge loss
- Step 1:The hinge loss is linear in the outputs for a Pauli observable (loss section), and .
- Step 2:Sum of the four unit phasors weighted by the labels.
- Step 3:Polar form; lies in the second quadrant.
- Step 4:is maximal at . The hinge minimiser lies inside the feasible interval , so minimising the hinge loss solves the lab.
- Step 5:The MSE loss contains the extra -dependent term and has no equally simple closed form; its minimiser, found numerically and by the training loop of the code cell, is also feasible. The three natural choices (hinge, MSE, maximal margin) differ but all classify the data correctly.
Result
At the pipeline classifies all four points correctly: is negative at and and positive at and , and the MSE drops to . Move through the interval and observe that the accuracy stays while the boundary moves between and ; outside it, at least one point changes sides. The NumPy cell below checks the matrix identities of this lesson, scans the accuracy on a grid of weights, compares the grid with the exact end points, and computes the shot statistics of the previous section from exact binomial sums.
import numpy as np
from math import comb, ceil, exp, log
def ry(t):
c, s = np.cos(t / 2), np.sin(t / 2)
return np.array([[c, -s], [s, c]], dtype=complex)
def rx(t):
c, s = np.cos(t / 2), np.sin(t / 2)
return np.array([[c, -1j * s], [-1j * s, c]])
Z = np.diag([1.0, -1.0]).astype(complex)
Xp = np.array([[0, 1], [1, 0]], dtype=complex)
ket0 = np.array([1, 0], dtype=complex)
def f(theta, x, enc=ry):
psi = ry(theta) @ enc(x) @ ket0
return float(np.vdot(psi, Z @ psi).real)
# (1) R_Y(t)R_Y(u) = R_Y(t + u), f = cos(x + theta) for R_Y encoding, f = cos(x)cos(theta) for R_X encoding.
grid = np.linspace(-np.pi, np.pi, 41)
add_ok = all(np.allclose(ry(t) @ ry(u), ry(t + u), atol=1e-12) for t in grid for u in grid)
ry_ok = all(abs(f(t, u) - np.cos(u + t)) < 1e-12 for t in grid for u in grid)
rx_ok = all(abs(f(t, u, rx) - np.cos(u) * np.cos(t)) < 1e-12 for t in grid for u in grid)
rx_gap = max(abs(f(t, u, rx) - np.cos(u + t)) for t in grid for u in grid)
print("RY(t) RY(u) = RY(t+u):", add_ok, "| RY encoding f = cos(x+theta):", ry_ok, "| RX encoding f = cos(x)cos(theta):", rx_ok)
print(f"RX encoding: max |f - cos(x+theta)| on the grid = {rx_gap:.6f}")
# (2) Heisenberg picture: W^dagger Z W = cos(theta) Z - sin(theta) X, so f = r(x) . n(theta).
heis_ok = all(np.allclose(ry(t).conj().T @ Z @ ry(t), np.cos(t) * Z - np.sin(t) * Xp, atol=1e-12) for t in grid)
print("W^dagger Z W = cos(theta) Z - sin(theta) X:", heis_ok)
# (3) The lab data: accuracy over a fine theta grid and the exact feasible interval.
xs = np.array([0.3, 0.9, 1.8, 2.2])
ys = np.array([-1, -1, 1, 1])
thetas = np.round(np.arange(-3.5, -2.0, 1e-4), 4)
acc = np.array([np.mean(np.cos(xs + t) * ys > 0) for t in thetas])
ok = thetas[acc == 1.0]
print(f"grid points with accuracy 1: from {ok.min():.4f} to {ok.max():.4f}")
print(f"exact interval: (-pi/2 - 1.8, -pi/2 - 0.9) = ({-np.pi / 2 - 1.8:.6f}, {-np.pi / 2 - 0.9:.6f})")
print(f"plus 2 pi: (3 pi/2 - 1.8, 3 pi/2 - 0.9) = ({1.5 * np.pi - 1.8:.6f}, {1.5 * np.pi - 0.9:.6f})")
for t in (0.0, 2.5, 2.8, -2.9, np.pi):
print(f"theta = {t:7.4f}: f = {np.array2string(np.cos(xs + t), precision=4, floatmode='fixed')}, accuracy = {np.mean(np.cos(xs + t) * ys > 0):.2f}")
# (4) Shot noise of f_hat = (N_plus - N_minus)/N at x = 1.8, theta = -2.9 with N = 100 shots (exact binomial sums).
N, fx = 100, float(np.cos(1.8 - 2.9))
p = (1 + fx) / 2
pmf = [comb(N, k) * p ** k * (1 - p) ** (N - k) for k in range(N + 1)]
vals = [2 * k / N - 1 for k in range(N + 1)]
mean = sum(w * v for w, v in zip(pmf, vals))
var = sum(w * (v - mean) ** 2 for w, v in zip(pmf, vals))
p_wrong = sum(w for w, v in zip(pmf, vals) if v <= 0)
print(f"f = {fx:.6f}: E[f_hat] = {mean:.6f}, N Var[f_hat] = {N * var:.6f}, 1 - f^2 = {1 - fx ** 2:.6f}")
print(f"P(sign error) = {p_wrong:.3e} <= Hoeffding bound exp(-N f^2 / 2) = {exp(-N * fx ** 2 / 2):.3e}")
print(f"Hoeffding shots for eps = 0.01, delta = 0.05: N = ceil(2 ln(2/delta) / eps^2) = {ceil(2 * log(2 / 0.05) / 0.01 ** 2)}")Expected output
RY(t) RY(u) = RY(t+u): True | RY encoding f = cos(x+theta): True | RX encoding f = cos(x)cos(theta): True RX encoding: max |f - cos(x+theta)| on the grid = 1.000000 W^dagger Z W = cos(theta) Z - sin(theta) X: True grid points with accuracy 1: from -3.3707 to -2.4708 exact interval: (-pi/2 - 1.8, -pi/2 - 0.9) = (-3.370796, -2.470796) plus 2 pi: (3 pi/2 - 1.8, 3 pi/2 - 0.9) = (2.912389, 3.812389) theta = 0.0000: f = [ 0.9553 0.6216 -0.2272 -0.5885], accuracy = 0.00 theta = 2.5000: f = [-0.9422 -0.9668 -0.4008 -0.0124], accuracy = 0.50 theta = 2.8000: f = [-0.9991 -0.8481 -0.1122 0.2837], accuracy = 0.75 theta = -2.9000: f = [-0.8569 -0.4161 0.4536 0.7648], accuracy = 1.00 theta = 3.1416: f = [-0.9553 -0.6216 0.2272 0.5885], accuracy = 1.00 f = 0.453596: E[f_hat] = 0.453596, N Var[f_hat] = 0.794251, 1 - f^2 = 0.794251 P(sign error) = 1.239e-06 <= Hoeffding bound exp(-N f^2 / 2) = 3.406e-05 Hoeffding shots for eps = 0.01, delta = 0.05: N = ceil(2 ln(2/delta) / eps^2) = 73778
Quick check
What is the length of the interval of weights (within one period) for which the worked model classifies all four lab points correctly?
References
- K. Mitarai, M. Negoro, M. Kitagawa and K. Fujii, Quantum circuit learning, Physical Review A 98, 032309 (2018).doi:10.1103/PhysRevA.98.032309
- E. Farhi and H. Neven, Classification with quantum neural networks on near term processors, arXiv:1802.06002 (2018).arxiv.org
- M. Schuld, A. Bocharov, K. M. Svore and N. Wiebe, Circuit-centric quantum classifiers, Physical Review A 101, 032308 (2020).doi:10.1103/PhysRevA.101.032308
- V. Havlíček, A. D. Córcoles, K. Temme, A. W. Harrow, A. Kandala, J. M. Chow and J. M. Gambetta, Supervised learning with quantum-enhanced feature spaces, Nature 567, 209–212 (2019).doi:10.1038/s41586-019-0980-2
- M. Benedetti, E. Lloyd, S. Sack and M. Fiorentini, Parameterized quantum circuits as machine learning models, Quantum Science and Technology 4, 043001 (2019).doi:10.1088/2058-9565/ab4eb5
- M. Cerezo, A. Arrasmith, R. Babbush, S. C. Benjamin, S. Endo, K. Fujii, J. R. McClean, K. Mitarai, X. Yuan, L. Cincio and P. J. Coles, Variational quantum algorithms, Nature Reviews Physics 3, 625–644 (2021).doi:10.1038/s42254-021-00348-9
- M. Schuld, Supervised quantum machine learning models are kernel methods, arXiv:2101.11020 (2021).arxiv.org
- 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
- J. C. Spall, Multivariate stochastic approximation using a simultaneous perturbation gradient approximation, IEEE Transactions on Automatic Control 37(3), 332–341 (1992).doi:10.1109/9.119632
- W. Hoeffding, Probability inequalities for sums of bounded random variables, Journal of the American Statistical Association 58(301), 13–30 (1963).doi:10.1080/01621459.1963.10500830
Hands-on labs
Train a one-qubit variational classifier
1 step · auto-gradedOpen labThe circuit with observable is the smallest variational quantum classifier: feature map , ansatz , model output and prediction . Choose the single weight so that all four training points are classified correctly.