This PennyLane quantum machine learning tutorial shows how to connect a variational quantum circuit to a classical Python workflow. You will build a small hybrid classifier, prepare data, encode features into qubits, optimize circuit parameters, compare the result with a classical baseline, and use a repeatable checklist before moving from a simulator to real hardware.
Overview
A hybrid quantum-classical workflow divides the job between two types of computation. Classical Python code prepares the dataset, manages batches, calculates loss values, and updates trainable parameters. A quantum circuit acts as a parameterized model: it encodes an input example, applies trainable gates, and returns an expectation value or measurement result that can be interpreted as a prediction.
In PennyLane, the connection between these parts is a differentiable quantum node, commonly called a QNode. A QNode combines a quantum device with a Python function that describes the circuit. PennyLane can expose the circuit as a callable model and integrate it with supported machine-learning interfaces. Exact interface details can change between releases, so pin the package versions used for an experiment and consult the matching documentation when adapting this example.
For a first experiment, use a small binary dataset with two or a few numerical features. Keeping the feature count low makes the circuit easier to inspect and reduces the number of design decisions. The goal is not to prove quantum advantage. It is to establish a controlled experiment that you can rerun, measure, and extend.
Before coding, decide what success means. A useful first target is a fair comparison with a classical model using the same train-test split, preprocessing, metric, and data budget. A quantum model that trains successfully but performs no better than a simple baseline is still a useful engineering result: it identifies where further circuit or data experimentation is needed.
Checklist by scenario
Scenario 1: Prepare a reproducible notebook
- Create an isolated Python environment for the experiment.
- Record the Python version, PennyLane version, machine-learning interface, and simulator device name.
- Set random seeds where the data splitter, parameter initializer, or baseline model supports them.
- Keep a short experiment configuration containing the dataset, feature count, circuit depth, optimizer, learning rate, number of steps, and shot setting.
- Start with a simulator and exact or high-shot measurements while validating the model logic.
A minimal installation might begin with pip install pennylane scikit-learn matplotlib, but the appropriate command depends on the environment and the interfaces you choose. Treat the installation command as part of the notebook documentation rather than assuming it will remain unchanged across releases.
Scenario 2: Prepare and encode the data
Split the data before fitting any scaler. Fit preprocessing only on the training set, then apply the learned transformation to validation and test data. This prevents information from the test set leaking into training.
Quantum gates accept bounded angles or amplitudes, so the numerical range matters. Standardization can be useful for classical models, while min-max scaling or an explicit angle mapping may be more convenient for rotation-based encoding. Document the mapping. For example, if a feature is mapped to a rotation angle, state the source range and target range so that another reader can reproduce it.
Feature encoding choices have different qubit and circuit implications. Angle encoding is often a straightforward starting point because each feature can control a rotation, but it may require more qubits as the feature count grows. Review the trade-offs in this comparison of quantum data encoding methods in Python before selecting a representation.
Scenario 3: Build the variational classifier
The circuit normally has three layers: feature encoding, trainable operations, and measurement. A simple two-feature sketch can look like this:
import pennylane as qml
from pennylane import numpy as np
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit(x, weights):
qml.AngleEmbedding(x, wires=[0, 1], rotation="Y")
for layer in range(weights.shape[0]):
qml.RY(weights[layer, 0], wires=0)
qml.RY(weights[layer, 1], wires=1)
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(0))
This circuit returns a value in the expectation-value range. Convert that output into a class prediction with a threshold, or pass it through a suitable classical transformation when defining the loss. The weight shape must match the circuit design. If you add layers or gates, update initialization and validation checks together.
Scenario 4: Train and evaluate the model
Use a loss function that matches the output interpretation. For a small binary experiment, mean squared error on labels represented as negative and positive values can make the circuit output easy to inspect. Binary cross-entropy may be appropriate when the model produces probabilities, but do not treat an expectation value as a probability without defining the conversion.
During training, log the loss on the training set and a separate validation set. After optimization, evaluate the untouched test set once or according to a clearly documented evaluation plan. Report more than accuracy when the classes are imbalanced; include a confusion matrix or class-level precision and recall where relevant.
Always train a classical reference model. Logistic regression is a useful simple baseline for a small numerical dataset, while a more expressive model can show whether the quantum circuit is competing with a stronger decision boundary. Keep preprocessing and splits identical. A comparison is meaningful only when the experimental conditions are aligned.
Scenario 5: Move from simulator experiments to hardware
Do not use real hardware to debug basic data-shape or optimization errors. First confirm that the circuit runs, gradients behave as expected, labels are aligned, and the baseline comparison is complete. Then introduce finite shots in simulation to estimate sampling effects. Only after that should you consider submitting a small workload to a QPU or a managed quantum cloud backend.
Hardware execution adds operational variables such as queue time, device availability, supported operations, connectivity, compilation, and measurement noise. The backend-selection checklist in this guide to simulator, CPU, GPU, and QPU options can help separate model questions from infrastructure questions.
What to double-check
- Shapes: Confirm that the number of encoded features matches the wires or encoding strategy, and that the trainable weight tensor matches the circuit loop.
- Labels: Verify label values, class ordering, prediction thresholds, and the direction of the loss. A sign mismatch can make a functioning circuit appear ineffective.
- Gradients: Check that the selected differentiation method supports the device, gates, measurements, and shot configuration you are using.
- Scaling: Record whether scaling occurs before encoding and whether the same fitted transformation is applied to every split.
- Capacity: Increase circuit depth cautiously. More layers can increase optimization difficulty and runtime rather than automatically improving generalization.
- Noise and shots: Distinguish an exact simulator result from a finite-shot result. Repeat finite-shot evaluations when you need to understand measurement variability.
- Evaluation: Compare against a classical baseline and retain the split, seed, preprocessing, and metric definitions in the experiment record.
For portability, avoid hiding the whole workflow inside provider-specific code. Keep data preparation, model definition, training, and backend configuration separate. This makes it easier to compare PennyLane with another framework or connect the circuit to a different execution service. The quantum circuit portability guide provides a useful design perspective for that separation.
Common mistakes
Using an oversized dataset too early. Large datasets make it harder to identify whether a problem comes from preprocessing, batching, circuit execution, or optimization. Begin with a small, documented subset and expand only after the complete loop works.
Calling a circuit “quantum machine learning” without a baseline. A variational circuit is an interesting model, but its value is difficult to interpret without a comparable classical method. Baselines are part of the experiment, not an optional final step.
Changing several variables at once. If you change the encoding, optimizer, circuit depth, dataset split, and shot count together, you cannot explain an improvement or regression. Change one controlled factor at a time.
Assuming simulator performance predicts hardware performance. Simulators are excellent for debugging and controlled experiments, but hardware introduces sampling and device-specific effects. Treat the transition as a new evaluation stage.
Ignoring package compatibility. PennyLane APIs, plugins, interface integrations, and device capabilities can evolve. Pin versions, save the environment definition, and test the notebook from a clean environment before sharing it.
When to revisit
Revisit this tutorial before a new experiment cycle, after changing the PennyLane or Python environment, or when moving from a simulator to a cloud or QPU backend. Recheck the device interface, differentiation support, measurement behavior, and any integration code rather than assuming a previously working notebook will run unchanged.
Use this practical refresh checklist:
- Recreate the environment from the recorded dependency versions.
- Run a tiny smoke test that prepares one input, executes one circuit, and checks the output shape and numeric range.
- Rerun the classical baseline before comparing new quantum results.
- Repeat the same seed and configuration, then make one documented change.
- Record simulator type, shot setting, backend, circuit depth, training steps, metric, and test result.
- Update the notebook notes when an API, device capability, or preprocessing assumption changes.
The reusable pattern is simple: prepare data without leakage, encode it explicitly, keep the variational circuit small, optimize with observable diagnostics, compare fairly with a classical model, and treat each backend as a separate experimental condition. That discipline makes a PennyLane tutorial useful beyond one notebook and gives you a reliable foundation for larger hybrid quantum-classical workflows.