Quantum Machine Learning with PennyLane: A Practical Hybrid Model Tutorial
quantum machine learningPennyLanePythonhybrid computingvariational circuitsquantum tutorials

Quantum Machine Learning with PennyLane: A Practical Hybrid Model Tutorial

QQubeTech Labs
2026-11-16
8 min read

Build a reproducible PennyLane hybrid classifier in Python with encoding, training, batching, evaluation, baselines, and troubleshooting.

This practical PennyLane tutorial shows how to build and train a small hybrid quantum-classical machine-learning model in Python. You will prepare a compact dataset, encode features into qubits, define a parameterized quantum circuit, optimize its parameters with a classical optimizer, evaluate a held-out test set, and compare the result with a classical baseline. The example is deliberately small so that you can reproduce it on a local simulator before adapting it to another device.

Overview

A hybrid model divides the work between a classical program and a quantum circuit. Python loads and transforms the data, selects batches, calculates the loss, and updates trainable parameters. The quantum component evaluates a parameterized circuit, often called a variational circuit or quantum neural network, and returns expectation values or sampled outcomes.

The goal of this workflow is not to assume that a quantum model will outperform a classical model. A useful experiment must establish a baseline, keep the dataset manageable, and make the circuit and evaluation procedure easy to inspect. For an introduction to backend trade-offs, see Quantum Simulator vs Real Hardware.

Our example uses a binary classification task with two numerical features. That choice keeps the circuit understandable: one feature can control a rotation on each qubit, while a second feature can influence a trainable or data-dependent rotation. In a real project, the encoding method should match the data shape and the available circuit budget. Basis, angle, and amplitude encoding have different preparation costs and constraints; compare them in Quantum Data Encoding Methods.

Project layout

qml-demo/
  train.py
  requirements.txt
  README.md
  results/

Keep the first experiment in one script or notebook. Once the circuit, data pipeline, and evaluation are stable, separate them into modules. A typical dependency file might include PennyLane, NumPy, and scikit-learn, but install versions that are mutually compatible in your environment rather than copying an unverified version pin.

How to compare options

Before choosing a device or circuit design, compare the options against the question your experiment needs to answer.

  • Simulator or hardware: A local simulator is appropriate for debugging shapes, gradients, and training logic. Hardware can introduce sampling noise, device-specific constraints, queueing, and additional execution considerations. Move to hardware only after the simulator experiment is deterministic enough to diagnose. See Quantum Workloads in CI/CD for a test-first workflow.
  • Analytic or finite-shot execution: Analytic expectation values are convenient for early development. Finite shots more closely represent measurement-based execution but can make the loss noisier. The choice affects both training behavior and evaluation.
  • Autodiff interface: PennyLane can connect a QNode to a supported automatic-differentiation workflow. The interface must match the device and operation settings you use. Confirm compatibility in the installed documentation when changing versions.
  • Encoding: Angle encoding is a clear starting point for a few normalized features. More compressed encodings may require additional state preparation and can make debugging harder.
  • Classical baseline: A quantum model is difficult to interpret without a conventional comparator using the same train and test split. A small logistic regression or multilayer perceptron is enough for an initial benchmark.

A practical comparison records the dataset split, feature scaling, number of qubits, circuit depth, shots, optimizer, learning rate, number of steps, random seed, and device name. This turns a notebook result into an experiment that another developer can reproduce.

Feature-by-feature breakdown

1. Prepare a small reproducible dataset

Choose data with a low feature count and a clear binary target. Synthetic points are useful when learning the workflow because they avoid download failures and licensing questions. The following example creates two clusters, scales the features into a rotation-friendly range, and uses a fixed seed.

import pennylane as qml
from pennylane import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(7)
class_zero = rng.normal(loc=(-0.8, -0.6), scale=0.35, size=(40, 2))
class_one = rng.normal(loc=(0.8, 0.6), scale=0.35, size=(40, 2))
X = np.vstack([class_zero, class_one])
y = np.concatenate([np.zeros(40), np.ones(40)])

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=11, stratify=y
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
X_train = np.asarray(X_train, requires_grad=False)
X_test = np.asarray(X_test, requires_grad=False)
y_train = np.asarray(y_train, requires_grad=False)
y_test = np.asarray(y_test, requires_grad=False)

Scaling is important because rotation angles have a finite, interpretable range. Standardization alone does not guarantee an ideal encoding, so inspect the transformed values and choose a mapping deliberately. For example, you can multiply each feature by a modest factor before applying rotations.

2. Define the quantum circuit

Use two wires for the two features. The circuit first applies data-dependent rotations, then repeats a trainable layer containing single-qubit rotations and entangling gates. The output is the expectation value of a Pauli-Z measurement on the first wire.

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

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

def variational_layer(weights):
    for wire in range(n_qubits):
        qml.Rot(*weights[wire], wires=wire)
    qml.CNOT(wires=[0, 1])

@qml.qnode(dev, interface='autograd')
def circuit(x, weights):
    feature_map(x)
    for layer in weights:
        variational_layer(layer)
    return qml.expval(qml.PauliZ(0))

This is a compact variational quantum classifier rather than a complete production model. The returned expectation value is in a bounded range. Convert it to a class prediction by applying a threshold, such as zero, and map the result to the two labels.

3. Add a loss, batching, and optimization

Mean squared error is simple for a first experiment if labels are represented as -1 and 1. Binary cross-entropy or another objective can also be appropriate, but its output range and numerical safeguards must match the model output.

y_train_signed = 2 * y_train - 1
weights = 0.01 * np.random.default_rng(3).normal(
    size=(n_layers, n_qubits, 3), requires_grad=True
)
optimizer = qml.AdamOptimizer(stepsize=0.08)

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

def loss(weights, X_batch, y_batch):
    values = predictions(X_batch, weights)
    return np.mean((values - y_batch) ** 2)

batch_size = 12
steps = 60
for step in range(steps):
    start = (step * batch_size) % len(X_train)
    indices = np.arange(start, min(start + batch_size, len(X_train)))
    if len(indices) == 0:
        continue
    X_batch = X_train[indices]
    y_batch = y_train_signed[indices]
    weights, current_loss = optimizer.step_and_cost(
        lambda w: loss(w, X_batch, y_batch), weights
    )
    if step % 10 == 0:
        print(step, float(current_loss))

The exact optimizer syntax can vary with PennyLane and interface versions, so treat this as a structural template and verify it against the documentation installed in your environment. Batching reduces the amount of data processed in each update, but it also makes the loss curve less smooth. For a small dataset, compare mini-batch training with full-batch training before drawing conclusions.

4. Evaluate the model and establish a baseline

def classify(values):
    return (np.asarray(values) >= 0).astype(int)

train_values = predictions(X_train, weights)
test_values = predictions(X_test, weights)
train_accuracy = np.mean(classify(train_values) == y_train)
test_accuracy = np.mean(classify(test_values) == y_test)
print('train accuracy:', float(train_accuracy))
print('test accuracy:', float(test_accuracy))

Use the test set once for final evaluation, not as a tuning loop. Add a classical baseline with the same split and preprocessing. If the baseline performs well while the quantum model does not, investigate circuit depth, encoding, optimization, and data size before increasing complexity.

Workflow diagram

raw features
     |
scaling and split
     |
angle encoding --> parameterized circuit --> expectation value
     |                                      |
classical loss <----- prediction <---------+
     |
optimizer updates circuit parameters

Troubleshooting table

SymptomLikely causePractical check
Parameters do not changeWeights are not marked trainable or the interface is mismatched.Inspect the parameter type, QNode interface, and gradient result.
Gradient is unavailableThe selected device, operation, or differentiation method is incompatible.Test one circuit evaluation and one gradient on the smallest circuit.
Loss becomes NaNInputs, labels, or a custom loss contain invalid values.Print ranges before the circuit and reduce the learning rate.
Training is extremely slowFinite shots, a large batch, or repeated Python-level circuit calls add overhead.Use a smaller dataset and analytic simulation while debugging.
Hardware submission failsThe circuit uses unsupported operations, wire counts, or measurement forms.Compile or transform the circuit for the target backend before submitting.

Best fit by scenario

Learning quantum machine learning: Use a local simulator, two to four qubits, a synthetic dataset, and analytic expectations. Focus on understanding data flow and gradients.

Comparing encodings: Keep the dataset, split, optimizer, and evaluation fixed. Change only the feature map, then record circuit depth and training behavior. This makes the comparison more informative than changing several components at once.

Testing hardware feasibility: First estimate qubits, gates, depth, shots, and runtime using the guidance in Quantum Circuit Resource Estimation. Then check whether the target backend supports the circuit and measurement pattern.

Building a team workflow: Store the dataset seed, environment details, circuit definition, and evaluation output with each run. If a cloud backend is involved, review region and security requirements using the quantum cloud data residency checklist. A broader SDK and backend decision can follow the migration checklist in How to Choose a Quantum SDK and Cloud Platform.

When to revisit

Revisit this tutorial when your PennyLane release, autodiff interface, device plugin, or target backend changes. APIs and supported device capabilities can evolve, so rerun the smallest circuit before investing in a longer training job. Also update the example when you change from an analytic simulator to finite-shot execution or real hardware, because measurement noise and backend constraints can alter the experiment.

For a practical maintenance routine, review the following every six months and after a major dependency release:

  1. Create a clean environment and install the current project dependencies.
  2. Run one circuit evaluation, one gradient calculation, and one short training loop.
  3. Confirm that the device, interface, measurement, and optimizer APIs still behave as expected.
  4. Record any changes in convergence, runtime, circuit transforms, or backend support.
  5. Rerun the classical baseline whenever the preprocessing or dataset changes.

Once the local experiment is stable, move one variable at a time: a different encoding, a new optimizer, a finite-shot simulator, or a hardware device. That disciplined progression is more useful than simply adding qubits. It gives you a clear answer to the central question: whether a hybrid quantum-classical model is appropriate for the data, constraints, and evidence your application requires.

Related Topics

#quantum machine learning#PennyLane#Python#hybrid computing#variational circuits#quantum tutorials
Q

QubeTech Labs

Quantum Computing and AI 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.