Quantum Neural Networks in Python: Build, Train, and Evaluate a Hybrid Classifier
quantum machine learningquantum neural networksQNNPythonclassificationPennyLanehybrid quantum computing

Quantum Neural Networks in Python: Build, Train, and Evaluate a Hybrid Classifier

CCoQubit Editorial Team
2026-11-19
7 min read

Build a reproducible Python QNN classifier, compare it with a classical baseline, and estimate training cost under finite-shot execution.

This quantum neural network tutorial shows how to build a small hybrid classifier in Python, train it with a classical optimizer, compare it with a classical baseline, and estimate the practical cost of changing circuit depth, shots, and backend. The workflow is designed for repeatable experiments rather than claims of automatic quantum advantage.

Overview

A quantum neural network (QNN) is usually a parameterized quantum circuit embedded in a larger classical machine-learning workflow. Classical code prepares features, supplies trainable parameters, evaluates a loss, and updates the parameters. The circuit encodes data and returns expectation values, probabilities, or other measurement results that become model outputs.

For a practical first experiment, use a small binary classification dataset with two or four numerical features. Standardize the features, reserve separate training and validation sets, and keep the circuit shallow enough to run repeatedly. A variational classifier can then be evaluated against a classical model such as logistic regression. The comparison matters: accuracy alone cannot show whether a quantum model is useful if the classical baseline is simpler, faster, or more stable.

The core experiment has six stages:

  1. Choose and clean a binary dataset.
  2. Scale features to a range that suits the encoding circuit.
  3. Design a data-encoding layer and a trainable ansatz.
  4. Initialize parameters and optimize a clearly defined loss.
  5. Evaluate on held-out data using both ideal and finite-shot settings.
  6. Record accuracy, loss, runtime, circuit depth, qubit count, and shot count.

PennyLane is a convenient choice for this style of hybrid quantum machine learning because the circuit can be exposed as a differentiable Python function. Qiskit and other quantum SDKs can implement the same workflow, but their neural-network wrappers, primitive interfaces, gradient options, and optimizer APIs may change between releases. Pin the versions used in an experiment and check the installed documentation before adapting code.

How to estimate

Estimate a QNN experiment in two parts: predictive performance and execution cost. Treat both as outputs of the experiment, not assumptions made in advance.

1. Estimate the training workload

A simple workload estimate is:

training evaluations ≈ epochs × batches × forward-and-gradient evaluations

The exact number of circuit executions depends on the differentiation method. Analytic differentiation, parameter-shift calculations, backpropagation through a simulator, and finite differences can require different numbers of evaluations. Instead of relying on a theoretical count alone, time one training step and multiply it by the planned number of steps.

For a shot-based run, a rough execution estimate is:

shot workload ≈ circuit evaluations × shots per evaluation

This is useful when comparing a noiseless simulator with a finite-shot simulator or hardware backend. It does not predict queue delay or provider billing, which depend on the selected platform and its current terms. For a cost estimate, record the provider, backend, job count, circuit count, shot count, and the pricing rules applicable at the time of execution.

2. Estimate model capacity

Record the number of qubits, trainable parameters, layers, and post-measurement classical parameters. Increasing layers may give the optimizer more flexibility, but it also increases circuit depth and can make training less stable. A small ansatz with a reproducible seed is generally a better diagnostic starting point than a large circuit chosen for appearance.

3. Estimate success with repeated splits

Do not treat one train-validation split as a reliable estimate of generalization. Begin with a fixed split for debugging, then repeat the experiment with several seeds or cross-validation when the workflow is stable. Report the mean and spread of the chosen metric, along with the number of runs. If the dataset is imbalanced, include balanced accuracy, precision, recall, F1 score, or an appropriate threshold-independent metric rather than accuracy alone.

Inputs and assumptions

The following assumptions make a QNN classifier easier to reproduce:

  • Features: Use numeric inputs and document missing-value handling, feature order, and scaling. Angle encoding often benefits from mapping standardized values into a bounded interval, but the interval should match the gates used by the circuit.
  • Labels: Encode a binary target consistently, such as 0 and 1. Define how an expectation value becomes a class prediction, for example by using a threshold.
  • Data split: Keep validation data out of parameter fitting. Fit preprocessing transforms on the training partition only.
  • Initialization: Use a recorded random seed and small parameter values unless the chosen ansatz requires another initialization strategy.
  • Optimizer: Start with a conservative learning rate and a modest iteration budget. Compare optimizers only after the data pipeline and objective have been tested.
  • Execution mode: Separate ideal, finite-shot, and noisy-backend results. They answer different questions and should not be placed in one undifferentiated benchmark.

A compact PennyLane-style implementation can look like this. Names and interfaces may differ across releases, so verify the installed SDK documentation before running it:

import pennylane as qml
from pennylane import numpy as np

n_qubits = 2
n_layers = 2

dev = qml.device("default.qubit", wires=n_qubits, shots=None)

def encode(x):
    for wire in range(n_qubits):
        qml.RY(x[wire], wires=wire)

def ansatz(weights):
    for layer in range(n_layers):
        for wire in range(n_qubits):
            qml.Rot(*weights[layer, wire], wires=wire)
        for wire in range(n_qubits - 1):
            qml.CNOT(wires=[wire, wire + 1])

@qml.qnode(dev, interface="autograd")
def circuit(x, weights):
    encode(x)
    ansatz(weights)
    return qml.expval(qml.PauliZ(0))

def predict(x, weights):
    return (circuit(x, weights) + 1) / 2

def loss(weights, X, y):
    predictions = np.stack([predict(x, weights) for x in X])
    return np.mean((predictions - y) ** 2)

# Initialize weights, choose an optimizer, and update weights in a loop.
# Record the loss after every epoch and evaluate validation data separately.

This example uses two features and two qubits for clarity. With more features, reduce dimensionality, group features across repeated circuit evaluations, or design a wider encoding scheme. Each choice changes the model and should be recorded rather than hidden in preprocessing code.

Worked examples

Example A: ideal-simulator baseline

Start with a noiseless simulator and a small binary dataset. Use a fixed train-validation split, two qubits, two variational layers, a fixed seed, and a limited epoch budget. Train the QNN and a logistic-regression baseline on exactly the same transformed features. Record:

  • training and validation metrics;
  • wall-clock training time;
  • number of epochs and circuit evaluations;
  • qubit count, ansatz layers, and approximate transpiled depth if relevant;
  • SDK, Python, simulator, and dependency versions.

The purpose of this run is to verify that gradients move the loss in the intended direction and that the QNN can be reproduced. It is not a hardware performance claim.

Example B: finite-shot comparison

Repeat the same experiment with a fixed shot budget, such as a value selected for your available simulator or backend. Keep the circuit, data split, initialization, and optimizer unchanged. Compare ideal and finite-shot results using the same final threshold and validation set.

If the finite-shot model is less stable, test one variable at a time: increase shots, reduce the learning rate, average gradients over more samples, or simplify the ansatz. A useful estimate is the additional shot workload required to reach a stable validation metric. Record that workload beside accuracy; a small accuracy change may not justify a large increase in execution.

Results template

RunBackendAccuracyValidation metricTimeQubitsDepthShots
Ideal baselineSimulator—————Analytic or configured value
Finite-shotSimulator or hardware——————

For related variational workflows, compare your measurement and resource accounting with the approaches described in quantum circuit resource estimation and quantum measurement results. If the circuit will run on hardware, review transpilation and depth optimization before interpreting results.

Troubleshooting unstable training and overfitting

  • Loss does not change: verify that parameters are connected to the circuit, labels have the expected shape, and the chosen interface supports the selected differentiation method.
  • Gradients are noisy: test the circuit on an ideal simulator, reduce depth, lower the learning rate, or increase shots. Check whether the measurement output is saturated near its minimum or maximum.
  • Training accuracy is high but validation accuracy is low: reduce layers or parameters, add regularization in the classical part, use a smaller epoch budget, and inspect the split for leakage.
  • Results change substantially between seeds: run several seeds, report the spread, and examine initialization, dataset size, and shot noise before selecting the best run.
  • Hardware results degrade: compare gate counts and depth after transpilation, test a noise model when possible, and distinguish readout effects from optimization failure.

When to recalculate

Recalculate the experiment whenever an input that affects performance or execution changes. That includes the dataset, preprocessing, train-validation split, feature count, encoding, ansatz, optimizer, learning rate, epoch budget, shot count, simulator, hardware backend, transpilation settings, or SDK version.

Update the cost and workload estimate when a platform changes its pricing inputs or execution model. Do not copy an old runtime or price into a new report without checking the current provider information. Likewise, refresh benchmark results at least when the experiment is moved to a materially different backend or when major SDK and autodifferentiation changes alter the implementation.

A practical rerun sequence is: first execute a tiny smoke test, then reproduce the ideal baseline, then repeat the finite-shot run, and finally run the full seed or cross-validation set. Store code, environment details, seeds, circuit configuration, metrics, and raw results together. This turns a QNN classifier from a one-off demonstration into a comparison that can be revisited when the underlying inputs change.

Related Topics

#quantum machine learning#quantum neural networks#QNN#Python#classification#PennyLane#hybrid quantum computing
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.