This practical hybrid quantum machine learning tutorial shows how to build, test, and evaluate a small quantum-classical model in Python. You will create a reproducible workflow for scaling data, selecting features, adding a variational circuit, training with a classical optimizer, and comparing the result with a conventional baseline.
Overview
A hybrid quantum machine learning model divides the work between a classical computer and a quantum circuit. The classical side prepares data, updates trainable parameters, calculates metrics, and usually controls the training loop. The quantum side evaluates a parameterized circuit and returns measurements that become features, predictions, or part of a loss function.
For a first project, use a small binary classification dataset with two to four numerical features. Limiting the feature count is not a claim that quantum models require tiny datasets in every setting; it keeps the experiment understandable and avoids treating circuit width as a substitute for good feature engineering. A useful starting question is not whether a quantum model sounds promising, but whether it produces a measurable improvement over a clearly defined classical baseline under the same data split and evaluation rules.
The workflow below uses PennyLane-style concepts: a device, a quantum node, a feature map, a variational circuit, and a differentiable training loop. Framework APIs and supported machine-learning backends can change, so check the installed version's documentation before adapting code for production. The design principles remain useful when implementing the same experiment with other quantum software development kits.
How to compare options
Compare the complete pipeline, not only the quantum circuit. A model with an elegant ansatz can still be a poor experiment if preprocessing leaks test information, the baseline is weak, or the quantum backend makes training impractically slow.
- Define the task. Choose a supervised objective such as binary classification, specify the target metric, and decide what counts as a useful improvement.
- Fix the data protocol. Create training, validation, and test splits before fitting scalers or selecting features. Fit preprocessing only on the training portion.
- Match features to qubits. Select a compact feature set or use a documented dimensionality-reduction step. Do not silently discard features simply to make a circuit fit.
- Compare against a baseline. A logistic regression model, small multilayer perceptron, or another appropriate classical model provides a reference for accuracy, calibration, training time, and complexity.
- Track resources. Record qubit count, circuit depth, number of trainable parameters, shots, forward evaluations, wall-clock time, and whether the result came from an ideal simulator, noisy simulator, or QPU.
- Repeat the experiment. Quantum measurements and parameter initialization can introduce variability. Use fixed seeds where supported, repeat with several seeds, and report the spread rather than one favorable run.
This comparison method also helps when choosing between a statevector simulator, a shot-based simulator, and hardware. An ideal simulator is useful for checking circuit logic and learning behavior. A shot-based or noisy environment is more representative of sampling and noise effects. Hardware adds queueing, calibration, connectivity, and execution constraints. Treat these as different experimental conditions, not interchangeable backends.
Feature-by-feature breakdown
1. Data preparation and feature selection
Scale numerical inputs to a range that suits the encoding method. For angle encoding, a bounded interval such as a range around zero is usually easier to reason about than raw values with widely different magnitudes. Fit the scaler on training data only, then apply it unchanged to validation and test data.
Begin with features that have a defensible relationship to the task. If the original dataset has many columns, compare a compact selected subset with a classical model trained on the same subset. This prevents a quantum model from receiving a more convenient input representation than its baseline.
2. Circuit architecture
A small circuit commonly contains three parts: data encoding, trainable single-qubit rotations, and entangling gates. One layer may be enough for a first test. Increasing depth adds parameters and circuit operations, but it can also make optimization harder and increase sensitivity to noise.
Conceptually, a quantum node can be written as:
def circuit(x, weights):
encode_features(x)
for layer in weights:
apply_trainable_rotations(layer)
apply_entanglers()
return measure_observable()
In a PennyLane implementation, the measurement might be an expectation value, a probability vector, or samples. Choose one output shape and keep the classical prediction layer explicit. For binary classification, a measured value can be mapped to a probability, but the mapping and loss must be consistent with the labels.
3. Classical optimizer and batching
Use a classical optimizer to update circuit parameters. Gradient-based optimizers are convenient when the selected device and interface support automatic differentiation. Other optimizers can be useful when gradients are unavailable or noisy, but they may require more circuit evaluations.
Start with full-batch updates for a small dataset because they simplify debugging. Move to mini-batches when the dataset or circuit evaluation cost makes full-batch training inconvenient. Keep the batch construction deterministic during debugging, and record the batch size along with the learning rate, number of epochs, initialization method, and stopping rule.
4. Validation and baseline evaluation
Use the validation set to select settings such as circuit depth, learning rate, feature subset, and number of training steps. Reserve the test set for the final comparison. Report more than accuracy when the classes are imbalanced; include metrics such as balanced accuracy, precision, recall, or area under the relevant curve as appropriate.
A compact pseudocode training loop looks like this:
for epoch in range(epochs):
for X_batch, y_batch in batches(X_train, y_train):
predictions = model(X_batch, weights)
loss = loss_function(predictions, y_batch)
weights = optimizer_step(weights, loss)
validation_score = evaluate(model, X_valid, y_valid)
test_score = evaluate(model, X_test, y_test)
The exact function names differ across PennyLane, Qiskit-based workflows, Cirq integrations, and classical machine-learning libraries. Preserve the separation between training, validation, and final testing even when the framework changes.
5. Resource and reproducibility checks
Save the environment details, dataset version or acquisition method, preprocessing parameters, circuit definition, backend name, shots, seeds, optimizer settings, and per-epoch metrics. These details make it possible to determine whether a result came from a better model or simply a different execution condition.
Add basic tests before training: verify the circuit accepts the expected feature shape, confirm that the output has the expected dimensions, check that parameters change after an optimizer step, and test that labels are encoded consistently. For additional guidance, see quantum software testing and CI workflows and the reproducible quantum experiments template.
Best fit by scenario
Learning quantum programming: Use a two-feature dataset, one or two circuit layers, and an ideal simulator. Focus on understanding encoding, measurement, gradients, and the training loop. The guide to quantum feature maps and variational circuits provides useful background.
Testing a modeling idea: Keep the data split and classical baseline fixed while comparing feature maps, ansatz layouts, and measurement choices. Change one major factor at a time so the results remain interpretable.
Studying realistic execution: Move from an ideal simulator to shot-based and noisy conditions, then record how metrics and resource use change. Do not describe a simulator result as hardware evidence. Review the quantum backend selection guide before selecting an execution target.
Building a larger hybrid AI workflow: Consider the quantum circuit as one component inside a classical pipeline. A classical encoder, dimensionality-reduction stage, or post-processing layer may be appropriate, but each added component should be included in the baseline comparison and documented.
Exploring optimization or chemistry: The same variational pattern appears in other workloads, although the objective, observables, and evaluation criteria differ. A variational quantum eigensolver workflow can help illustrate how expectation values and classical optimization fit together.
When to revisit
Revisit this workflow whenever a framework changes its autodiff interfaces, device plugins, optimizer APIs, measurement behavior, or supported execution backends. Also update the experiment when you change the dataset, feature count, circuit ansatz, shot count, noise model, or hardware target. These changes can alter both runtime and model quality.
Before each rerun, use this checklist:
- Confirm that the installed framework and device plugin support the chosen differentiation method.
- Recheck tensor shapes, measurement outputs, and label encoding with a small test batch.
- Run the classical baseline and quantum model on identical splits and preprocessing.
- Record circuit width, depth, trainable parameter count, shots, execution time, and seeds.
- Repeat promising results across multiple seeds or executions before drawing a conclusion.
- Separate simulator, noisy-simulator, and hardware results in both code and reporting.
If the quantum model does not beat the baseline, that is still a useful result. Inspect data quality, feature encoding, optimization stability, measurement variance, and resource cost before increasing circuit depth. A disciplined negative result is more valuable than a favorable result that cannot be reproduced. For related debugging practices, see how to debug quantum circuits and the guide to practical quantum error mitigation.
The durable lesson is to evaluate hybrid quantum machine learning as an end-to-end engineering experiment. Start with a modest, testable circuit; compare it with a fair classical alternative; measure its resource requirements; and preserve enough metadata to repeat the work when tools, datasets, or backends change.