Quantum Machine Learning with PennyLane: A Practical Variational Classifier Tutorial
quantum machine learningPennyLanevariational algorithmsclassificationquantum feature maps

Quantum Machine Learning with PennyLane: A Practical Variational Classifier Tutorial

CCoQubit Editorial Team
2026-11-27
8 min read

Build and evaluate a PennyLane variational classifier with data preprocessing, feature maps, batching, baselines, and a reusable experiment checklist.

A small variational classifier is a useful way to learn quantum machine learning with Python because it exposes the full hybrid workflow: prepare data, encode features, execute a circuit, optimize parameters, and compare the result with a classical model. This PennyLane tutorial provides a reusable implementation checklist, a compact example, and an experiment record you can adapt when datasets, devices, or SDK interfaces change.

Overview

A variational quantum classifier (VQC) combines a parameterized quantum circuit with a classical optimizer. The circuit produces a measurement value, the value is compared with a target label, and the optimizer adjusts circuit parameters to reduce the loss. In practice, the workflow is hybrid: Python and classical libraries handle data preparation and optimization, while a PennyLane device evaluates the circuit.

The example below uses a two-feature binary classification problem. Each feature is mapped to a rotation angle, an entangling circuit supplies trainable parameters, and the expectation value of a Pauli-Z measurement becomes the model output. The goal is not to claim a quantum advantage. It is to create a controlled experiment that can be rerun on a simulator, adapted to a different backend, and compared fairly with a classical baseline.

Before starting, install the packages used by your chosen PennyLane version and confirm the device and autodiff interfaces in its documentation. Interfaces can change, so treat the code as a compact reference implementation rather than a promise that every release will use identical defaults.

pip install pennylane scikit-learn

For broader evaluation guidance, see How to Benchmark Quantum Algorithms Fairly. If you want a larger hybrid classifier example, compare this workflow with Quantum Neural Networks in Python.

Checklist by scenario

Scenario 1: Build a reproducible baseline experiment

  1. Define the task. Choose a binary target, identify the input features, and decide which metric matters. Accuracy alone may be insufficient when classes are unbalanced; record precision, recall, F1, or a confusion matrix when they are relevant.
  2. Split before fitting transformations. Create training and test sets first. Fit scaling, feature selection, or dimensionality reduction only on the training data, then apply the learned transformation to the test data.
  3. Match features to wires. A simple angle-encoding example may use one qubit per feature. If the dataset has many columns, reduce the feature count deliberately rather than silently dropping columns.
  4. Fix the experiment conditions. Record the random seed, split method, number of wires, circuit layers, optimizer, learning rate, epochs, batch size, and number of shots or simulator settings.

Scenario 2: Implement a small variational classifier

The following example uses scikit-learn to create a two-dimensional dataset and PennyLane to define the quantum model. It uses a simulator for fast iteration. The exact device name, interface behavior, and differentiability support should be checked against the installed release before moving to another backend.

import pennylane as qml
from pennylane import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score

# Reproducible toy data
X, y = make_moons(n_samples=200, noise=0.15, random_state=7)
y = 2 * y - 1  # labels become -1 and +1

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=7
)

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# Map standardized values into a practical rotation range.
X_train = np.array(np.pi * np.tanh(X_train), requires_grad=False)
X_test = np.array(np.pi * np.tanh(X_test), requires_grad=False)
y_train = np.array(y_train, requires_grad=False)
y_test = np.array(y_test, requires_grad=False)

n_qubits = 2
n_layers = 2
dev = qml.device('default.qubit', wires=n_qubits)

weight_shape = qml.StronglyEntanglingLayers.shape(
    n_layers=n_layers, n_wires=n_qubits
)
rng = np.random.default_rng(7)
weights = 0.01 * rng.standard_normal(weight_shape)
weights = np.array(weights, requires_grad=True)

@qml.qnode(dev)
def circuit(features, weights):
    qml.AngleEmbedding(features, wires=range(n_qubits), rotation='Y')
    qml.StronglyEntanglingLayers(weights, wires=range(n_qubits))
    return qml.expval(qml.PauliZ(0))

def predict(weights, X):
    return np.stack([circuit(x, weights) for x in X])

def loss(weights, X, y):
    scores = predict(weights, X)
    return np.mean((scores - y) ** 2)

opt = qml.AdamOptimizer(stepsize=0.05)
batch_size = 16
n_epochs = 30

for epoch in range(n_epochs):
    order = rng.permutation(len(X_train))
    X_epoch = X_train[order]
    y_epoch = y_train[order]

    for start in range(0, len(X_epoch), batch_size):
        stop = start + batch_size
        X_batch = X_epoch[start:stop]
        y_batch = y_epoch[start:stop]
        weights, current_loss = opt.step_and_cost(
            lambda w: loss(w, X_batch, y_batch), weights
        )

    if (epoch + 1) % 5 == 0:
        print(f'Epoch {epoch + 1}: loss={loss(weights, X_train, y_train):.4f}')

def labels_from_scores(scores):
    return np.where(scores >= 0.0, 1, -1)

train_pred = labels_from_scores(predict(weights, X_train))
test_pred = labels_from_scores(predict(weights, X_test))
print('Train accuracy:', accuracy_score(y_train, train_pred))
print('Test accuracy:', accuracy_score(y_test, test_pred))

The loss uses a regression-style squared error because the circuit returns a continuous expectation value between approximately -1 and +1. The sign of that value supplies the binary prediction. Other choices are possible, including a probability-based output and a cross-entropy objective, but the output convention and loss must agree.

Scenario 3: Add a classical comparison

Train a simple classical model on the same training split, with the same preprocessing and evaluation set. Logistic regression is a reasonable first comparison because it is easy to inspect. A small multilayer perceptron can be added later if the task requires a nonlinear classical baseline. Keep model selection separate from the final test evaluation.

Compare more than the final accuracy. Record training time, inference time, parameter count, circuit depth, two-qubit gate count, simulator or hardware conditions, and variability across seeds. A quantum model that appears better under one split may not remain better under repeated splits. The purpose of the baseline is to establish whether the added circuit complexity is justified for this dataset.

Scenario 4: Move from a simulator to another backend

Change one variable at a time. First confirm that the circuit produces the same type and shape of output on the new device. Then test a few fixed inputs before retraining. If the backend uses finite shots, expectation values become estimates and training can become noisier. Record the shot count, compilation or transpilation settings, queue or execution behavior relevant to the experiment, and any error-mitigation procedure.

For backend selection and simulator-versus-hardware trade-offs, use this quantum cloud backend selection matrix. Circuit depth and two-qubit operations also deserve attention; the transpilation optimization guide provides a practical review checklist.

What to double-check

  • Data leakage: confirm that the test set never influences scaling, feature selection, hyperparameter selection, or early stopping.
  • Encoding range: inspect the transformed feature values. Very large or poorly scaled angles can make training difficult, while aggressive compression can discard useful information.
  • Output semantics: document whether the model returns an expectation value, probability, counts, or another quantity. Do not compare these outputs as if they were interchangeable.
  • Gradient support: verify that the selected device, interface, measurement, and shot configuration support the differentiation method used by the optimizer.
  • Parameter initialization: repeat training with several seeds. A single favorable run is weak evidence for a variational model.
  • Capacity and depth: increase layers only when there is a measured reason. More parameters can raise execution cost and make optimization less stable.
  • Evaluation protocol: preserve a final test set or use nested validation when tuning many settings. Report the protocol alongside the score.

Use an experiment record such as this for every run:

Dataset and version:
Target definition:
Train/test split and seed:
Preprocessing fitted on:
Feature encoding:
Qubits and circuit layers:
Ansatz and measurement:
Device and interface:
Shots:
Optimizer, learning rate, epochs, batch size:
Training seeds:
Quantum metrics:
Classical baseline and metrics:
Circuit depth and two-qubit gates:
Runtime:
Notes and software versions:

Common mistakes

Calling a toy demonstration a production classifier. A small simulator experiment teaches the workflow; it does not establish practical value for a business dataset.

Changing preprocessing between models. Different transformations make the comparison difficult to interpret. Use a shared data protocol unless preprocessing itself is the subject of the experiment.

Using the test set repeatedly. Inspecting test accuracy after every change effectively turns the test set into a training signal. Keep a validation split or cross-validation process for iteration.

Ignoring batching. Evaluating every sample independently can make training unnecessarily slow. Start with small batches and measure whether batching improves throughput without changing the intended objective.

Adding layers before diagnosing the problem. Low accuracy may result from poor encoding, labels, scaling, initialization, or an unsuitable baseline—not simply from an undersized ansatz.

Reporting only the best seed. Include the number of runs and summarize variation. This is especially important when finite shots, noisy devices, or nonconvex optimization are involved.

When to revisit

Revisit this tutorial before a new experiment cycle, when the dataset or label definition changes, and whenever you switch PennyLane versions, autodiff frameworks, devices, shot settings, or execution APIs. Recheck imports, device names, gradient behavior, measurement return formats, and the shape expected by initialization utilities. A code example that ran on a simulator may need changes before it runs on a hardware-backed or shot-based device.

Also revisit the evaluation checklist when a result looks unusually strong. Re-run the classical baseline, repeat the quantum model across seeds, inspect the train-test protocol, and verify that circuit depth and execution conditions were recorded. If the objective is optimization rather than classification, apply the same discipline to a related variational workflow such as VQE or QAOA for Max-Cut.

Action plan: first run the simulator example unchanged; then replace the toy data with a small, documented dataset; next train a classical baseline under the same split; finally test one backend change while preserving the experiment record. This sequence keeps the quantum machine learning tutorial useful as a working benchmark rather than a one-time code sample.

Related Topics

#quantum machine learning#PennyLane#variational algorithms#classification#quantum feature maps
C

CoQubit Editorial Team

Quantum Software Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.