Quantum Machine Learning with PennyLane: A Practical Hybrid Model Tutorial
quantum machine learningPennyLanePythonhybrid computingquantum AIvariational quantum circuit

Quantum Machine Learning with PennyLane: A Practical Hybrid Model Tutorial

SSmart Qubit Labs Editorial Team
2026-11-04
7 min read

Build and evaluate a PennyLane hybrid quantum-classical model with practical guidance on encoding, training, baselines, resources and cost estimates.

This practical PennyLane tutorial shows how to build, train and evaluate a hybrid quantum-classical machine-learning model, then compare it with a classical baseline and estimate the resources required before moving beyond simulation.

Overview

Quantum machine learning combines a conventional machine-learning workflow with a parameterised quantum circuit. The classical part prepares data, updates model parameters and evaluates performance; the quantum part produces measurements that become features, predictions or loss values. PennyLane is designed for this style of hybrid quantum-classical computing because it connects quantum circuits with automatic differentiation and familiar Python machine-learning tools.

The goal of a small experiment should not be to assume that a quantum model will outperform a well-tuned classical model. A better goal is to create a repeatable comparison. You should be able to answer five questions:

  • Can the circuit represent a useful decision boundary for the chosen data?
  • Can the model train reliably with the available simulator or device?
  • How does it perform against a simple classical baseline?
  • What are the circuit depth, qubit count, shot count and training cost?
  • Would changing the device, dataset or framework version alter the conclusion?

This approach is useful for developers exploring a quantum computing developer roadmap, researchers testing variational quantum circuits and teams assessing whether a quantum proof of concept deserves further investment. It is also a useful complement to a broader quantum benchmarking workflow.

How to estimate

Estimate the experiment in three layers: predictive outcome, computational resources and operational cost. Keeping these layers separate prevents an impressive accuracy result from hiding an impractical workflow.

1. Estimate predictive outcome

Choose a small, clearly defined task first. Binary classification is often easier to inspect than a large multi-class problem. Split the data into training, validation and test sets before fitting the model. Record at least accuracy and a loss value, but do not rely on one metric if the classes are unbalanced. A confusion matrix or class-specific scores may reveal that a model is simply favouring the majority class.

Run the quantum model with several random initialisations. For each run, record the final validation score, test score, number of optimisation steps and whether training converged. A useful summary is the median result and the spread between runs, rather than the best result alone.

2. Estimate quantum resources

For each training step, record:

  • Qubits: the number required to encode the input and hold trainable circuit states.
  • Layers: the number of repeated rotation and entangling blocks.
  • Gate count and depth: useful indicators of circuit complexity after compilation.
  • Shots: the number of measurements used to estimate an expectation value when sampling is enabled.
  • Evaluations: the number of circuit executions required by the optimiser and gradient method.

A simple planning estimate is:

Total circuit evaluations ≈ training steps × parameter or gradient evaluations × shots.

The exact count depends on the differentiation method, optimiser and device. Treat the formula as a planning tool, not a universal billing formula. If a circuit has 4 qubits, 3 trainable layers, 100 optimisation steps and 500 shots, you can use those values to create an initial resource budget, then verify the actual execution count from logs.

3. Estimate financial and operational cost

Do not hard-code a cloud price into the experiment. Provider pricing, free allocations, simulator settings and hardware access conditions can change. Instead, calculate:

Estimated cost = simulator or device execution units × current provider rate + storage, orchestration and development overheads.

Keep the execution count, rate and currency as separate inputs in a spreadsheet or configuration file. This makes the estimate easy to update when pricing changes. For platform choices, see the comparison of IBM Quantum, Azure Quantum and Amazon Braket, then confirm current terms in the provider documentation before making a purchasing decision.

Inputs and assumptions

A useful PennyLane experiment starts with explicit assumptions. The following example uses a small two-feature binary classification problem. The numbers are illustrative and should be replaced with your own dataset and measurements.

  • Data encoding: two scaled features are mapped to rotation angles on two qubits.
  • Ansatz: each layer applies trainable single-qubit rotations followed by an entangling operation.
  • Output: the expectation value of a Pauli-Z measurement on one qubit.
  • Prediction: the expectation value is converted into a binary class using a threshold.
  • Training: a classical optimiser updates the circuit parameters using automatic differentiation.
  • Evaluation: the same held-out test set is used for both the quantum model and the classical baseline.

Feature scaling matters because rotation gates receive angles, not arbitrary raw business values. Standardise or otherwise bound features before encoding them, and save the preprocessing step so that new data is transformed identically. Also define a fixed random seed where the framework and device support reproducible execution. Hardware noise, shot sampling and parallel execution can still introduce variation.

The following compact model illustrates the workflow. It is deliberately small enough to inspect and extend:

import pennylane as qml
from pennylane import numpy as np

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

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

def prediction(x, weights):
    return circuit(x, weights)

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

shape = qml.StronglyEntanglingLayers.shape(n_layers, n_qubits)
weights = np.array(0.01 * np.random.randn(*shape), requires_grad=True)
opt = qml.GradientDescentOptimizer(stepsize=0.1)

for step in range(100):
    weights, current_loss = opt.step_and_cost(lambda w: loss(w, X_train, y_train), weights)

predictions = np.array([prediction(x, weights) for x in X_test])

In a production experiment, add input validation, a proper train-validation-test split, a baseline model, multiple seeds and logging. The exact APIs and supported interfaces can change, so check the PennyLane documentation for the version used by your environment. The same principle applies if you later port the circuit to another framework or cloud backend; consult the relevant Qiskit workflow or platform guide rather than assuming identical behaviour.

Worked examples

Example A: simulator-first feasibility test

Suppose a team has 200 labelled examples with two features. It begins with a two-qubit circuit and two trainable layers on a local simulator. The baseline is logistic regression using the same scaled features and the same data split.

The first estimate might use 100 optimisation steps and a small number of random seeds. At this stage, the main outcome is not a commercial forecast; it is a feasibility record containing:

  • test performance for both models;
  • training time on the development machine;
  • number of circuit evaluations;
  • parameter count and circuit depth;
  • variation across initialisations.

If the quantum model is unstable or no better than the baseline, increase complexity only for a specific reason. Try a different encoding, optimiser or circuit depth as controlled experiments. Do not change the dataset split and model design at the same time, because you will not know which change affected the result.

Example B: estimating a device run

Next, the team repeats the best simulator configuration with finite shots. If the circuit is evaluated 1,000 times and each evaluation uses 500 shots, the planning volume is approximately 500,000 individual measurement shots. The provider may expose pricing and execution in a different unit, so this figure should be translated using the current service documentation.

The team should also compare noiseless and finite-shot results. A lower score on the device does not automatically identify the cause: sampling noise, hardware noise, compilation changes, connectivity constraints and calibration conditions may all matter. Record the transpiled or compiled circuit, measurement settings, device identifier and run date so that the test can be repeated meaningfully.

Example C: deciding whether to continue

A sensible continuation decision uses a threshold agreed before the experiment. For example, continue only if the quantum model matches or exceeds the baseline on held-out data, remains stable across seeds and fits within a defined resource budget. If it fails one condition, document the failure and identify the next test. This creates an evidence trail instead of turning a proof of concept into an open-ended search.

When to recalculate

Recalculate the estimate whenever an input that affects outcome, execution or cost changes. In practice, revisit it in these situations:

  • Pricing changes: update provider rates, minimum charges, credits, storage costs and execution-unit definitions.
  • Framework changes: check whether PennyLane, its plugins or automatic-differentiation interfaces alter supported devices, gradient methods or defaults.
  • Hardware changes: repeat resource estimates after changing qubit topology, compiler settings, shot count or device.
  • Dataset changes: recalculate when the number of samples, feature range, class balance or preprocessing pipeline changes.
  • Model changes: update estimates after adding layers, qubits, measurements, parameters or training epochs.
  • Benchmark changes: rerun the classical baseline whenever the split, feature engineering or evaluation metric changes.

Keep a small experiment ledger with the code revision, environment, dataset version, device, circuit specification, shots, seeds, measured results and cost assumptions. That record makes an old result useful rather than obsolete. For teams moving from experimentation to wider quantum adoption, this disciplined approach fits alongside a broader post-quantum readiness process and general technology review.

To get started, reproduce the two-qubit simulator example, add a classical baseline, run several seeds and record the resource inputs before changing the circuit. Only then move to finite-shot simulation or a cloud device. The most valuable result may be a clear decision not to proceed yet—but it should be based on measurements that can be checked when prices, software and hardware change.

Related Topics

#quantum machine learning#PennyLane#Python#hybrid computing#quantum AI#variational quantum circuit
S

Smart Qubit Labs Editorial Team

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