This practical quantum machine learning tutorial shows how classical data preparation, a parameterised quantum circuit, an optimiser, and a classical baseline fit into one repeatable hybrid quantum-classical workflow. Use it as a starting checklist for simulator experiments, then adapt the same structure to a cloud backend or hardware run.
Overview
Hybrid quantum-classical computing does not mean replacing an entire machine-learning system with a quantum computer. In most useful prototypes, classical code manages the dataset, feature scaling, batching, optimisation, metrics, and application logic. A quantum circuit evaluates a parameterised function inside that larger loop. The classical optimiser then updates the circuit parameters according to the measured result.
A small binary classification experiment is a useful first example. The classical side loads and cleans the data, reduces each record to a number of features that the circuit can encode, and separates training from testing data. The quantum side prepares a circuit, applies data-encoding operations, adds trainable rotations, measures an expectation value, and returns a prediction. The optimiser repeatedly calls that circuit until the chosen loss stops improving or a defined budget is reached.
This division of responsibilities is important. A circuit that produces an interesting output is not automatically a useful machine-learning model. You need a reference implementation, fixed evaluation rules, recorded random seeds, and a clear account of execution cost. A simulator can validate the workflow and expose software errors, but it does not demonstrate an advantage over a classical method.
Reference architecture
Dataset
|\n |-- classical cleaning, scaling, feature selection
v
Encoded features ---> parameterised quantum circuit ---> measurements
|
v
loss <--- predictions <--- post-processing
|
v
classical optimiser updates circuit parameters
|
+------ repeat for the next training step
The example below is deliberately framework-neutral. PennyLane is a natural fit when automatic differentiation and hybrid models are central, while Qiskit and Cirq can also support parameterised circuits through their own primitives, simulators, and optimisation integrations. Before copying an installation command or function name, check the current documentation for the framework and backend version you intend to use. A useful comparison of design differences is available in the Qiskit, Cirq, and PennyLane SDK comparison and migration checklist.
Checklist by scenario
Scenario 1: Build and validate locally
- Define the task. Choose a small, measurable problem such as binary classification. Write down the input columns, target definition, metric, and what counts as a successful experiment before selecting a circuit.
- Prepare the data classically. Handle missing values, encode labels, scale features, and split the data without allowing test records to influence training decisions. Limit the feature count to match the circuit design rather than compressing data without explanation.
- Choose a simulator deliberately. A state-vector simulator is convenient for small noiseless experiments. A shot-based or noise-aware simulator is more representative of measurement sampling and hardware imperfections. Record the simulator type, precision settings, shot count, and software versions.
- Construct the circuit. Start with a simple feature map and a shallow trainable layer. Use one qubit per encoded feature only when that mapping is justified; otherwise document the compression or feature-map choice. Test that the circuit accepts the expected parameter shape.
- Check a single forward pass. Run one sample before starting optimisation. Confirm that the output is finite, has the expected range, and changes when either the input features or trainable parameters change.
Scenario 2: Run a training loop
A reusable loop should keep the model, loss, optimiser, and logging separate. The following pseudocode uses a PennyLane-like interface without depending on a particular release:
prepare X_train, y_train, X_test, y_test
scale X using training data only
initialise circuit_parameters with a recorded seed
for step in range(max_steps):
predictions = quantum_model(X_train, circuit_parameters)
loss = classification_loss(predictions, y_train)
gradients = differentiate(loss, circuit_parameters)
circuit_parameters = optimiser_update(circuit_parameters, gradients)
log step, loss, gradient_norm, circuit_parameters
if stopping_rule_is_met:
break
train_metrics = evaluate(quantum_model, X_train, y_train)
test_metrics = evaluate(quantum_model, X_test, y_test)
compare_with_classical_baseline(test_metrics)
Use mini-batches only if the framework and experiment justify them. For a small tutorial dataset, full-batch training is easier to inspect. For every run, save the initial parameters, final parameters, preprocessing configuration, circuit structure, optimiser settings, number of shots, and stopping condition.
Scenario 3: Add a classical baseline
Choose a baseline that is appropriate to the task and straightforward to reproduce, such as logistic regression or a small conventional neural network. Give it the same train/test split and preprocessing boundary. Compare more than accuracy where relevant: include loss, precision, recall, calibration, runtime, memory, and the number of circuit evaluations. A quantum model that matches a baseline but requires substantially more execution may still be useful as a learning exercise, but it should not be presented as an improvement.
Scenario 4: Move towards hardware or a cloud backend
- Estimate qubit count, circuit depth, measurement count, and expected runtime before submitting jobs. The quantum resource estimation guide provides a structured way to record these assumptions.
- Transpile or compile the circuit for the selected target and inspect how much depth and gate count change.
- Run a small smoke test before a full training schedule. Verify authentication, queue or runtime limits, supported observables, shot behaviour, and returned result formats.
- Keep simulator and hardware results in separate experiment records. Do not silently substitute one for the other.
- Repeat the baseline comparison with the same evaluation protocol. Hardware noise can alter both predictions and optimiser behaviour.
What to double-check
Data and objective
Confirm that the label convention is consistent throughout training and evaluation. Check that scaling is fitted only on training data and that categorical variables are not being interpreted as continuous values without a reason. Decide whether the circuit output is a probability, an expectation value, or a score that requires a separate threshold. Store that decision in the experiment configuration.
Gradients and optimisation
Parameterised circuits can be sensitive to initialisation, depth, learning rate, and gradient estimation method. If the loss does not move, test a single gradient numerically or with a small finite-difference check. If the loss is unstable, reduce the learning rate, simplify the circuit, or inspect the scale of the encoded features. Record failed runs rather than reporting only the best result.
Shots, noise, and reproducibility
Noiseless analytic expectations and finite-shot measurements answer different questions. Increasing shots may reduce sampling variability but also increases execution work. When noise is enabled, record the noise model and its parameters; when using hardware, record the backend identifier and relevant compilation settings. A seed may control some random operations but not every source of variation, particularly in managed services.
For circuit depth, gate-count, and execution-cost checks, use the workflow in this practical circuit optimisation guide. If hardware is involved, pair it with a repeatable backend test rather than relying on a single run.
Framework and connector boundaries
Quantum SDKs change their module layouts, primitive interfaces, device names, and optimiser integrations over time. Pin working versions in a project environment, capture the lockfile, and keep a short compatibility note near the code. Treat pseudocode as a design template, not a promise that an exact API will remain unchanged. For platform selection, consult a current quantum cloud platform decision guide and verify supported simulators, hardware targets, quotas, and runtime limits directly before deployment.
Common mistakes
- Starting with an oversized dataset or circuit. Begin with a small slice that lets you inspect every tensor, circuit output, and loss value.
- Optimising against the test set. Use validation data or cross-validation for design decisions, then evaluate the test set once the workflow is fixed.
- Comparing unlike baselines. Keep the data split, preprocessing, metric, and stopping budget aligned across models.
- Assuming more layers mean a better model. Extra depth can increase compilation work, measurement noise, and optimisation difficulty. Add capacity only when an experiment supports it.
- Ignoring measurement variance. Repeat shot-based runs or report uncertainty where it affects the conclusion.
- Hiding preprocessing inside the model. Separate classical transformations from the circuit so that leakage, cost, and reproducibility can be audited.
- Reporting only a successful run. Keep a run log containing errors, timeouts, non-convergent cases, and resource use.
Error mitigation may be worth testing for noisy experiments, but it should be treated as another measured component of the workflow rather than a guaranteed correction. See the practical error-mitigation guide for techniques and evaluation questions.
When to revisit
Revisit this workflow before each seasonal planning or research cycle, and whenever a framework, provider connector, simulator, compiler, or backend changes. A formal review every six months is a sensible minimum for a team that maintains reusable quantum experiments. Review sooner when a dependency introduces a breaking change, an execution target changes, or a new dataset alters the feature-encoding assumptions.
Use this final checklist before acting:
- Can another developer reproduce the preprocessing, circuit, optimiser, and baseline from the repository?
- Are framework versions, backend settings, seeds, shots, and resource limits recorded?
- Has the circuit passed a local forward-pass and gradient smoke test?
- Have simulator, noisy-simulator, and hardware results been labelled separately?
- Does the experiment report a classical baseline and the cost of obtaining the quantum result?
- Have current package APIs, connector requirements, supported devices, and runtime limits been checked?
- Does the result justify the next experiment, or is a simpler classical method the better engineering choice?
Once those checks pass, substitute a new dataset or backend one variable at a time. That makes the workflow reusable: changes in data, circuit design, or execution target can be diagnosed without losing the evidence from the previous experiment.