This quantum machine learning tutorial walks through a small, controlled experiment: prepare a two-class dataset, encode features in a variational quantum circuit, train a hybrid classifier, and compare it with a classical baseline. The goal is not to claim quantum advantage, but to give you a reusable workflow for testing a quantum classifier honestly as libraries, backends, datasets, and hardware change.
Overview
A variational quantum classifier combines a parameterized quantum circuit with a classical optimizer. The circuit receives encoded data, applies trainable gates, and returns an expectation value that can be converted into a class prediction. A classical training loop then updates the circuit parameters to reduce a loss function.
This approach is useful for learning the mechanics of hybrid quantum machine learning because it exposes each stage: preprocessing, feature encoding, circuit design, measurement, optimization, and evaluation. It is also deliberately constrained. Small datasets and shallow circuits make experiments easier to inspect, although they do not establish that a quantum model is better than a conventional machine-learning model.
The example below uses a binary, two-feature dataset generated with scikit-learn and a PennyLane-style interface. Exact device names, autodiff behavior, and optimizer support can vary by installed release and execution backend. Treat the code as a compact starting point, then check the documentation for your chosen version before moving to cloud hardware.
Before beginning, confirm that you have Python, NumPy, scikit-learn, and PennyLane installed in an isolated environment. If you are new to circuits, first review a basic quantum circuit tutorial and the trade-offs discussed in this guide to quantum simulators.
Checklist by scenario
Scenario 1: Build a reproducible simulator experiment
- Fix the data split. Use a seed, hold out a test set, and fit preprocessing steps on the training data only.
- Constrain the features. Begin with two numerical features so each feature can be mapped directly to one qubit. Standardize or rescale values before angle encoding.
- Choose a small circuit. Start with one or two variational layers. Record the number of qubits, layers, trainable parameters, and two-qubit gates.
- Define a measurable output. Measure an expectation value such as the Pauli-Z observable on one wire. Map values below a chosen threshold to one class and values above it to the other.
- Record the baseline. Train a simple classical model with the same training and test split. A logistic regression model is a reasonable first comparison.
import numpy as np
import pennylane as qml
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X, y = make_moons(n_samples=160, noise=0.12, random_state=7)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=7
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
baseline = LogisticRegression(random_state=7)
baseline.fit(X_train, y_train)
print("Classical accuracy:", accuracy_score(y_test, baseline.predict(X_test)))
n_qubits = 2
n_layers = 2
dev = qml.device("default.qubit", wires=n_qubits, shots=None)
@qml.qnode(dev)
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 predict_one(x, weights):
return circuit(x, weights)
def loss(weights, X_batch, y_batch):
targets = 2 * y_batch - 1
predictions = qml.math.stack([predict_one(x, weights) for x in X_batch])
return qml.math.mean((predictions - targets) ** 2)
shape = qml.StronglyEntanglingLayers.shape(n_layers=n_layers, n_wires=n_qubits)
rng = np.random.default_rng(7)
weights = 0.01 * rng.standard_normal(shape)
opt = qml.GradientDescentOptimizer(stepsize=0.2)
for step in range(60):
weights, current_loss = opt.step_and_cost(
lambda w: loss(w, X_train, y_train), weights
)
quantum_scores = np.array([predict_one(x, weights) for x in X_test])
quantum_pred = (quantum_scores < 0).astype(int)
print("Quantum-model accuracy:", accuracy_score(y_test, quantum_pred))The sign convention in the final line depends on how labels and the measured observable are associated. If predictions are systematically reversed, inspect the training targets and switch the threshold mapping rather than changing the test labels. For a more realistic training loop, use mini-batches, track training and validation loss, and repeat the experiment with several seeds.
Scenario 2: Compare a simulator with finite shots
Run the same trained circuit with an explicit shot count after validating it with exact or high-shot simulation. Finite shots estimate expectation values from samples, so the output can become noisier and optimization can become less stable. Keep the circuit, split, seed, and evaluation metric fixed while changing only the execution setting.
Scenario 3: Prepare for cloud hardware
Do not send the first untested circuit directly to hardware. Check qubit connectivity, supported gates, measurement requirements, queue or execution constraints, and whether the selected framework can differentiate through that backend. Start with inference or a very short optimization run, then compare results against a noisy simulator when available.
What to double-check
- Preprocessing: Was the scaler fitted only on training data? Are all features within the circuit’s useful angle range?
- Labels: Does the loss use the same label convention as the prediction rule?
- Capacity: Is the circuit deep enough to represent the task, but shallow enough to execute and diagnose?
- Optimization: Are learning rate, initialization, steps, batch size, and stopping criteria recorded?
- Evaluation: Are accuracy, confusion matrix, and class balance reported? A single split can be unstable on a small dataset.
- Resources: Record runtime, shots, qubit count, circuit depth, two-qubit gates, and whether results came from an ideal, noisy, or physical device.
Use a results table instead of a broad claim about quantum advantage:
| Model or backend | Test accuracy | Circuit depth | Runtime | Shots |
|---|---|---|---|---|
| Classical baseline | Record value | Not applicable | Record value | Not applicable |
| Ideal simulator | Record value | Record value | Record value | Analytic or record value |
| Finite-shot simulator | Record value | Record value | Record value | Record value |
| Cloud or hardware backend | Record value | Record value | Record value | Record value |
A useful comparison controls variables. If the quantum model uses two features but the classical model uses ten, the results are not directly comparable. Likewise, a faster simulator run does not demonstrate a faster production workflow if compilation, queue time, sampling, and repeated optimization are excluded.
Common mistakes
Calling a toy result quantum advantage. A tiny dataset and an ideal simulator are appropriate for education, not for proving practical superiority. Compare against strong, appropriately sized classical baselines.
Optimizing on the test set. Use training data for parameter updates and reserve the test set for final evaluation. If you tune hyperparameters repeatedly, add a validation split or cross-validation strategy.
Making the circuit unnecessarily deep. More layers increase parameters and execution cost. Add capacity only when a documented experiment shows that the simpler circuit is insufficient.
Ignoring randomness. Initialization, data splitting, optimizer behavior, and finite shots can all affect results. Repeat runs and report the spread, not only the most favorable score.
Assuming every backend supports the same workflow. Autodiff, gradients, custom observables, batching, and noise models differ across simulators and hardware integrations. Validate a minimal circuit first. For broader context, compare SDK responsibilities in Qiskit, Cirq, and PennyLane.
When to revisit
Revisit this experiment before a new project cycle, whenever the quantum SDK or autodiff backend changes, and before reporting results outside your development team. Re-run the environment setup, confirm device and gradient behavior, and compare the updated quantum model with the same classical baseline.
Also revisit the workflow when you change the dataset, feature count, encoding method, circuit depth, shot count, or execution backend. A new dataset may require different scaling and a new baseline; a hardware run may require shallower connectivity-aware circuits; and a framework update may change which parameters can be differentiated.
Your practical next step is to place the code in a version-controlled project with a requirements file, fixed seeds, a configuration record, and a results table. Add one controlled change at a time: first repeat the simulator run, then add finite shots, then test a noisy or cloud backend. This checklist makes the quantum classifier tutorial reusable without turning a small demonstration into an unsupported claim about real-world quantum advantage.