Code exampleIntermediateQuantum machine learning

A Tiny Variational Classifier in PennyLane

A two-qubit variational classifier in PennyLane: angle embedding plus StronglyEntanglingLayers, trained by gradient descent for 15 steps on four points.

In PennyLane a circuit is defined as a Python function decorated with @qml.qnode(dev), returning an expectation value. AngleEmbedding encodes the features as $R_Y$ angles, and StronglyEntanglingLayers are general rotation layers with entanglement. PennyLane computes derivatives automatically (on a simulator with reverse-mode differentiation or with parameter shift).

The loss is the mean squared error between $\langle Z_0\rangle$ and the $\pm1$ labels. The data are four clearly separated points, and the example only demonstrates how training works; it does not evaluate the model.

Requirements: pip install pennylane. The code runs on your machine or in Colab, not inside WordPress.

Code

PennyLane
import pennylane as qml
from pennylane import numpy as np

dev = qml.device("default.qubit", wires=2)


@qml.qnode(dev)
def circuit(weights, x):
    qml.AngleEmbedding(x, wires=[0, 1], rotation="Y")
    qml.StronglyEntanglingLayers(weights, wires=[0, 1])
    return qml.expval(qml.PauliZ(0))


X = np.array([[0.1, 0.2], [0.3, 0.1], [2.8, 2.9], [3.0, 2.7]], requires_grad=False)
y = np.array([1, 1, -1, -1], requires_grad=False)


def cost(weights):
    preds = [circuit(weights, x) for x in X]
    return sum((p - t) ** 2 for p, t in zip(preds, y)) / len(y)


np.random.seed(0)
shape = qml.StronglyEntanglingLayers.shape(n_layers=1, n_wires=2)
weights = np.random.uniform(0, np.pi, size=shape, requires_grad=True)
opt = qml.GradientDescentOptimizer(stepsize=0.3)
for step in range(15):
    weights, c = opt.step_and_cost(cost, weights)
    if step % 5 == 0:
        print(f"step {step:2d}  cost {c:.4f}")
print("final cost:", round(float(cost(weights)), 4))
print("signs:", [int(np.sign(circuit(weights, x))) for x in X], "targets:", [int(t) for t in y])

Line-by-line code explanation

LineExplanation
1-2Import PennyLane and its differentiable version of numpy.
4A two-qubit simulation device.
7-8Define the quantum node.
9Encode the two features with RY rotations.
10Trainable rotation and entanglement layers.
11The output: ⟨Z⟩ on qubit 0.
14Four training points (not differentiable).
15The ±1 labels.
18-20The loss function: mean squared error.
23Fix the numpy seed.
24The shape of the weight array for one layer and two qubits.
25Random trainable initial weights.
26Gradient descent optimiser with step 0.3.
27-2815 training steps returning the weights and the loss.
29-30Print the loss every 5 steps.
31The final loss.
32Compare the sign of the output with the labels.

Expected output (from an actual run)

step  0  cost 0.6163
step  5  cost 0.0237
step 10  cost 0.0098
final cost: 0.0063
signs: [1, 1, -1, -1] targets: [1, 1, -1, -1]

The seed np.random.seed(0) makes the initial weights and the results reproducible.

Try it yourself

Related topics

References

  1. Xanadu (2025). PennyLane Documentation. PennyLane docs.pennylane.ai
  2. Xanadu (2025). Variational classifier. PennyLane Demos pennylane.ai
  3. Maria Schuld; Alex Bocharov; Krysta M. Svore; Nathan Wiebe (2020). Circuit-centric quantum classifiers. Phys. Rev. A 101:032308 doi:10.1103/PhysRevA.101.032308
  4. Ville Bergholm et al. (2018). PennyLane: Automatic differentiation of hybrid quantum-classical computations. arXiv:1811.04968 doi:10.48550/arXiv.1811.04968