This beginner-friendly quantum machine learning tutorial walks through a small hybrid classifier in PennyLane: prepare a dataset, scale and encode features, train a variational quantum circuit with a classical optimizer, evaluate it against a conventional baseline, and decide whether the quantum component adds useful value.
Overview
A hybrid quantum-classical model divides the work between ordinary machine-learning code and a parameterized quantum circuit. The classical part prepares data, manages parameters, computes a loss, and updates the model. The quantum part transforms encoded features and returns measurements that become model outputs.
That division is important for setting expectations. A small simulator experiment is primarily a learning project and a reproducible benchmark. It is not evidence that a quantum model is automatically better than a classical model. The correct comparison is a conventional baseline trained on the same split, using a comparable amount of tuning effort.
In this project, the input has two numeric features and two classes. Each feature is scaled and supplied as a rotation angle. A two-qubit variational circuit applies those rotations, adds trainable gates, and measures the Pauli-Z expectation value of one wire. A classical optimizer adjusts the circuit parameters to reduce a classification loss.
Concept-to-code glossary
- Feature scaling: Transforming input columns into a controlled numeric range so rotations do not receive poorly conditioned values.
- Angle encoding: Representing a feature as the angle of a quantum rotation gate. With two features, a two-wire circuit is a natural starting point.
- Variational circuit: A circuit containing trainable parameters, often called weights, that are optimized from measurement results.
- QNode: PennyLane's connection between a quantum function and a selected device. It makes the circuit callable from ordinary Python code.
- Expectation value: A statistical measurement, such as the average Pauli-Z result, used here as a continuous model output.
- Hybrid model: A model whose training loop is classical but includes one or more quantum-circuit evaluations.
If rotation gates or measurement notation are unfamiliar, use the Quantum Gates Reference for Programmers before changing the circuit. For a broader learning path, the quantum computing roadmap for software engineers places this project in context.
Environment setup checklist
- Create a fresh virtual environment for the experiment.
- Install PennyLane, scikit-learn, and a numerical Python dependency supported by the PennyLane release you choose.
- Record the Python and package versions after the first successful run.
- Begin with a simulator rather than a remote quantum device.
- Save the random seed, train-test split, circuit depth, optimizer, and number of training steps.
python -m venv .venv
# Activate .venv using the command for your operating system
python -m pip install pennylane scikit-learn
Package interfaces and differentiation behavior can change. Treat this installation command as a starting point, then pin the versions that pass your own test run. Recheck the current PennyLane documentation before moving from a simulator to hardware.
Checklist by scenario
Scenario 1: Build the smallest working classifier
Use a compact, easy-to-inspect dataset first. The following example selects two classes and two features from scikit-learn's iris dataset. The labels are converted to -1 and 1 because a signed prediction works conveniently with a hinge-style loss.
import pennylane as qml
from pennylane import numpy as np
from sklearn.datasets import load_iris
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, confusion_matrix
iris = load_iris()
mask = iris.target < 2
X = iris.data[mask, :2]
y = np.where(iris.target[mask] == 0, -1.0, 1.0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=7, stratify=y
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Map standardized values into a rotation-friendly range.
angle_scale = np.pi / 2
X_train = np.asarray(X_train * angle_scale, requires_grad=False)
X_test = np.asarray(X_test * angle_scale, requires_grad=False)
Fit the scaler only on the training data. Applying a test-set transformation before fitting the scaler would leak information into training and make the evaluation less trustworthy. The angle scale is a design choice, not a universal rule; compare it with alternatives in a later experiment.
Scenario 2: Add a variational quantum circuit
Start with one circuit layer. More layers introduce more parameters and can make debugging, optimization, and hardware execution harder.
n_qubits = 2
n_layers = 1
dev = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(dev)
def circuit(features, weights):
qml.AngleEmbedding(features, wires=range(n_qubits), rotation="Y")
qml.BasicEntanglerLayers(weights, wires=range(n_qubits))
return qml.expval(qml.PauliZ(0))
rng = np.random.default_rng(7)
weights = 0.05 * rng.standard_normal((n_layers, n_qubits))
weights = np.asarray(weights, requires_grad=True)
def predict_one(features, weights):
return circuit(features, weights)
def loss(weights, X_batch, y_batch):
predictions = np.stack([predict_one(x, weights) for x in X_batch])
margins = y_batch * predictions
return np.mean(np.maximum(0.0, 1.0 - margins))
The circuit output lies in a measurement-dependent range, while the labels are signed. The loss does not require a probability interpretation. If you want probabilities, add a clearly defined classical mapping and evaluate that mapping consistently; do not call raw expectation values probabilities without justification.
Scenario 3: Train and evaluate
opt = qml.AdamOptimizer(stepsize=0.05)
steps = 40
for step in range(steps):
weights, current_loss = opt.step_and_cost(
lambda w: loss(w, X_train, y_train), weights
)
if step == 0 or (step + 1) % 10 == 0:
print(f"step={step + 1}, loss={current_loss:.4f}")
def predict_dataset(X_data, weights):
raw = np.array([predict_one(x, weights) for x in X_data])
return np.where(raw >= 0, 1.0, -1.0)
quantum_predictions = predict_dataset(X_test, weights)
quantum_accuracy = accuracy_score(y_test, quantum_predictions)
print("quantum accuracy:", quantum_accuracy)
print(confusion_matrix(y_test, quantum_predictions))
For a fair classical comparison, train logistic regression on the same scaled training features and evaluate it on the same test features:
baseline = LogisticRegression(random_state=7)
baseline.fit(X_train, y_train)
classical_predictions = baseline.predict(X_test)
classical_accuracy = accuracy_score(y_test, classical_predictions)
print("classical accuracy:", classical_accuracy)
Scenario 4: Compare models instead of declaring a winner
| Check | Quantum model | Classical baseline |
|---|---|---|
| Input split | Same training and test rows | Same training and test rows |
| Preprocessing | Training-fitted scaler | Training-fitted scaler |
| Primary metric | Accuracy plus confusion matrix | Accuracy plus confusion matrix |
| Stability | Repeat with several seeds | Repeat with several seeds |
| Operational cost | Include circuit evaluations and runtime | Include training and prediction runtime |
A quantum model adds value only if it meets a defined requirement: for example, comparable quality under a constraint, a useful representation for a later task, or a research question that justifies the added complexity. A single favorable accuracy result on a small dataset is not enough.
What to double-check
- Shapes: The feature vector must have the same length as the number of embedded wires. The weight array must match the template's expected layer and wire dimensions.
- Labels: Confirm whether your loss expects -1 and 1, 0 and 1, or one-hot vectors. Convert labels once and document the convention.
- Gradients: Make sure trainable weights use the numerical type and interface expected by your installed PennyLane version. If gradients are absent, inspect the QNode interface, parameter construction, and optimizer input.
- Preprocessing: Fit scalers and feature-selection steps on training data only.
- Reproducibility: Record seeds, data selection, split strategy, optimizer settings, circuit depth, and device name.
- Evaluation: Use more than one metric when classes or errors have different importance. Accuracy alone can hide a weak class-specific result.
- Backend assumptions: A noiseless simulator does not represent all the effects of hardware execution. Review the quantum hardware access guide before interpreting device results.
For encoding experiments, compare angle encoding with another method while holding the data split and evaluation protocol constant. The guide to quantum data encoding methods can help structure that comparison.
Common mistakes
Using too many qubits too soon
Adding wires does not automatically add useful information. Begin with one feature per wire, then test whether extra features improve a held-out result enough to justify a larger circuit.
Comparing against an unprepared baseline
A weak or untuned classical model makes the quantum comparison misleading. Use a simple baseline first, then give both approaches a reasonable, documented tuning budget.
Treating simulator output as hardware evidence
Simulation is valuable for verifying logic and learning the workflow. Hardware introduces execution constraints and noise that should be measured separately, with the backend and sampling configuration recorded.
Ignoring variance
Small datasets and random initialization can produce unstable results. Repeat the complete experiment with multiple seeds and report the range or distribution, not just the best run.
Changing several variables at once
If you change the encoding, optimizer, circuit depth, and dataset simultaneously, you cannot tell which change mattered. Use a small experiment matrix and alter one major factor at a time.
When to revisit
Revisit this project before using it as a template for new work and whenever the underlying tools change. In particular, rerun the setup and smoke test after a PennyLane release, a Python upgrade, a device-name change, or a change in differentiation behavior. Confirm that the QNode executes, gradients are nonzero when expected, and the baseline still produces results.
Return to the experiment during a new project cycle when you have a different dataset, feature count, encoding, or hardware target. Use this action checklist:
- Freeze the environment and save the previous configuration.
- Run the original two-feature example as a regression test.
- Replace only one component, such as the dataset or encoding.
- Rebuild the classical baseline under the same split and preprocessing rules.
- Repeat across seeds and record quality, runtime, circuit depth, and failures.
- Move to a sampled or hardware-backed device only after the simulator version is understood.
- Decide explicitly whether the quantum circuit improved the defined objective or merely increased complexity.
For a next project, compare this classifier workflow with a parameterized optimization example such as QAOA, or use the quantum developer starter kit to organize experiments. The durable lesson is not that every dataset needs a quantum model; it is that a sound hybrid quantum-classical experiment makes its assumptions, baseline, measurements, and update conditions visible.