This hands-on quantum machine learning tutorial shows how to build, train, and evaluate a small hybrid quantum-classical model with PennyLane and PyTorch. You will prepare a compact dataset, encode features into qubits, calculate gradients through a parameterized circuit, compare the result with a classical baseline, and use a repeatable checklist when changing datasets, encodings, optimizers, or SDK versions.
Overview
A hybrid model divides the learning task between a classical machine-learning framework and a quantum circuit. PyTorch can manage tensors, loss functions, optimization, and evaluation, while PennyLane can define a differentiable quantum node. The circuit acts as a trainable layer rather than a complete replacement for a classical neural network.
A practical workflow usually follows this sequence:
- Choose a small, well-defined classification problem.
- Scale the input features so that they can be mapped to rotation angles.
- Encode the features into a limited number of qubits.
- Apply trainable gates and measure expectation values.
- Pass the quantum outputs to a classical loss function.
- Train with an optimizer and evaluate on data excluded from training.
- Compare the hybrid model with a classical baseline using the same split and metrics.
The concept map is simple: features → feature map → variational circuit → measured expectations → prediction → loss → gradient update. Keeping these stages separate makes it easier to diagnose whether a problem comes from preprocessing, circuit design, differentiation, or optimization.
This example assumes a simulator and a binary classification task with two input features. It is intentionally small: a compact experiment is easier to reproduce and more useful for testing a new PennyLane and PyTorch setup than an unnecessarily large quantum neural network.
Suggested project structure
qml-hybrid-demo/
├── data.py # load, split, and scale the dataset
├── circuit.py # device, feature map, and variational circuit
├── model.py # PyTorch-compatible model and loss
├── train.py # optimization loop and checkpoints
├── evaluate.py # metrics, confusion matrix, and baseline comparison
├── experiments.csv # settings and results for each run
└── requirements.txt # pinned or documented package versions
For a broader comparison of evaluation discipline, see Quantum Algorithm Benchmarking in Python. The same habit—recording settings, metrics, and results—helps prevent misleading comparisons between quantum and classical models.
Checklist by scenario
Starting a first hybrid model
- Use a dataset small enough to inspect manually and with only a few meaningful features.
- Make the train, validation, and test split before fitting a scaler. Fit preprocessing only on the training data.
- Choose a qubit count that matches the encoded feature count, or document how features are reduced or reused.
- Start with one or two circuit layers. More layers increase the number of parameters and can make training harder to interpret.
- Set a random seed where supported, but still report variability across multiple runs when results matter.
Implementing a PennyLane and PyTorch workflow
The exact device and interface names can change between library releases, so confirm the current PennyLane and PyTorch compatibility guidance before copying an older example. The core pattern is as follows:
import pennylane as qml
import torch
from torch import nn
n_qubits = 2
dev = qml.device('default.qubit', wires=n_qubits)
@qml.qnode(dev, interface='torch', diff_method='backprop')
def circuit(x, weights):
for wire in range(n_qubits):
qml.RY(x[wire], wires=wire)
for layer in weights:
for wire in range(n_qubits):
qml.RY(layer[wire, 0], wires=wire)
qml.RZ(layer[wire, 1], wires=wire)
qml.CNOT(wires=[0, 1])
return [qml.expval(qml.PauliZ(wire)) for wire in range(n_qubits)]
class HybridClassifier(nn.Module):
def __init__(self, layers=2):
super().__init__()
self.weights = nn.Parameter(0.01 * torch.randn(layers, n_qubits, 2))
self.readout = nn.Linear(n_qubits, 1)
def forward(self, x):
quantum_outputs = torch.stack([circuit(row, self.weights) for row in x])
return self.readout(quantum_outputs).squeeze(-1)
This is a teaching pattern, not a drop-in guarantee for every installed version. A QNode may return a list, tuple, or tensor depending on the interface and measurement configuration. Check the returned shape before passing it to the readout layer. For a real project, add a small test that sends one batch through the circuit and verifies the output shape and gradient.
Comparing against a classical baseline
Train a small classical model with the same input features, data split, loss function, and evaluation metrics. A baseline might be a linear classifier or a compact multilayer perceptron. The aim is not to force the hybrid model to win; it is to determine whether the quantum component changes accuracy, parameter count, training behavior, or resource requirements in a useful way.
Planning controlled experiments
| Variable | Values to test | What to record |
|---|---|---|
| Circuit depth | One, two, and three layers | Loss curve, validation score, gradient size, runtime |
| Optimizer | For example, SGD and Adam | Learning rate, convergence speed, final test score |
| Encoding | Angle encoding or a documented alternative | Feature scaling, qubit use, output distribution |
| Training stability | Several seeds or initializations | Mean, spread, failed runs, and stopping point |
What to double-check
Data and labels
Confirm that labels have the shape expected by the loss function. Binary classification commonly uses one logit per example, while a multiclass setup may require one output per class. Check class balance and report more than accuracy when a skewed label distribution is possible.
Feature encoding
Rotation gates consume angles, so raw features may be unsuitable. Scaling is not merely a cosmetic preprocessing step: very large or poorly distributed values can make the circuit difficult to interpret and train. Record the scaling range and ensure the same fitted transformation is applied to validation and test data.
Autodiff and tensor types
Verify that the selected device, differentiation method, interface, and tensor dtype work together. A circuit that runs in a forward pass may still fail during backpropagation. Test a single loss calculation followed by loss.backward() before starting a long training run.
Evaluation and measurement
Simulator results may be exact expectation values, while shot-based execution introduces sampling variation. Do not compare those results without recording the measurement mode and shot count. For shot-based experiments, include uncertainty or repeated runs where appropriate. The guide to Quantum Measurement Results in Python provides a useful framework for documenting this difference.
Reproducibility
Save the dataset version or preparation script, split indices, preprocessing parameters, circuit architecture, optimizer settings, package versions, device configuration, random seeds, and final metrics. If an API changes, these records make it possible to distinguish a code migration issue from a genuine modeling result.
Common mistakes
- Assuming more qubits means a better model. Increase the circuit size only when the additional representation is justified and measurable.
- Skipping the classical baseline. Without a baseline, a hybrid result has no practical reference point.
- Reusing test data during development. Keep the test set untouched until the model and hyperparameters are selected.
- Ignoring output shapes. Mixed lists, tensors, batches, and scalar expectations are a frequent source of silent errors or failed training.
- Reporting one favorable run. Train with more than one initialization when the conclusion depends on a small score difference.
- Confusing simulation with hardware performance. A noiseless simulator does not represent queueing, device noise, finite shots, or hardware-specific compilation.
- Copying an outdated interface example. Read the installed versions’ documentation and run a minimal compatibility test before adapting a tutorial.
When to revisit
Return to this checklist whenever you move from simulation to hardware, change the dataset, add features, alter the encoding, increase circuit depth, or upgrade PennyLane, PyTorch, Python, or a device plugin. Also revisit it before comparing results from separate projects: identical metric names do not guarantee identical splits, preprocessing, shots, or stopping rules.
A practical refresh sequence is:
- Read the current compatibility and autodiff notes for the installed stack.
- Run a smoke test that constructs the device, executes one circuit, computes one loss, and performs one gradient update.
- Re-run the classical baseline and one small hybrid configuration.
- Compare output shapes, training curves, runtime, and evaluation metrics with the previous record.
- Update
experiments.csvwith the new versions and any changed assumptions.
For noisy or hardware-oriented work, pair this workflow with a documented error-mitigation and validation process, such as the practices described in Quantum Error Mitigation in Python. The goal is a defensible experiment, not simply a circuit that executes.
Once the smoke test passes, change one experimental variable at a time. That final habit turns a basic PennyLane and PyTorch example into a reusable quantum machine learning workflow: measurable, comparable, and easier to maintain as the surrounding tools change.