Quantum data encoding determines how classical values become qubit states, gates, and measurable outcomes. This guide compares basis, amplitude, angle, and related encodings in Python, then gives a practical checklist for choosing an approach based on dataset shape, preprocessing effort, circuit resources, and hardware constraints.
Overview
A quantum circuit cannot consume a spreadsheet column or a NumPy array directly. Before a model or algorithm can use classical data, the values must be mapped to a quantum state. That mapping is called quantum data encoding, or state preparation when the focus is specifically on creating the required state.
The right method depends on what the data represents and what the circuit needs to preserve. A binary identifier may fit naturally into basis encoding. A small vector of continuous features may be convenient to map to rotation angles. A normalized vector can use amplitude encoding, although preparing and reading that state may be more demanding. For many quantum machine learning experiments, a feature map combines angle rotations with entangling gates rather than using a single textbook encoding in isolation.
There is no universally best encoding. The important questions are:
- How many features and samples must be represented?
- Are the values binary, categorical, bounded continuous numbers, or arbitrary real values?
- Can the data be normalized without removing information that matters?
- How many qubits, state-preparation gates, and circuit repetitions can the experiment afford?
- Will the circuit run on a simulator, or must it tolerate the noise and connectivity of real hardware?
Comparison at a glance
| Method | Typical qubit requirement | Preprocessing | Main trade-off | Useful starting point |
|---|---|---|---|---|
| Basis encoding | Often one qubit per binary feature or bit | Convert values to bits, categories, or binary representations | Simple and interpretable, but qubit use can grow with representation length | Binary data, discrete states, small categorical problems |
| Amplitude encoding | n qubits represent up to 2n amplitudes | Flatten, pad, and normalize the vector | Compact qubit count, but state preparation and measurement can be costly | Small vectors where the full amplitude structure matters |
| Angle encoding | Commonly one qubit per feature per layer | Scale values to a suitable rotation range | Accessible circuits, but repeated or periodic angles can blur distinctions | Small-to-medium continuous feature sets and variational models |
| Qubit or one-hot encoding | One qubit per category in a direct one-hot design, or a logarithmic number for a binary index | Choose a categorical representation | Direct one-hot states are clear but may use many qubits | Categories, labels, and discrete search spaces |
Checklist by scenario
Choose basis encoding for explicit binary structure
Basis encoding represents a classical bit string as a computational-basis state. For example, the bit string 101 maps to a three-qubit basis state, subject to the bit-order convention used by the SDK. It is a good fit when the binary structure itself is meaningful and you want the encoded state to be easy to inspect.
First convert every input into a fixed-length bit string. Check the ordering convention before interpreting measurements, because frameworks may display or index qubits differently. Basis encoding does not automatically compress a large integer or a high-cardinality category; the chosen representation determines the number of qubits.
import pennylane as qml
bits = [1, 0, 1]
dev = qml.device('default.qubit', wires=len(bits), shots=None)
@qml.qnode(dev)
def basis_state():
qml.BasisState(bits, wires=range(len(bits)))
return qml.state()
state = basis_state()
print(state)
Use this approach when the circuit operates on discrete configurations, but consider angle or amplitude encoding if the original data is primarily continuous.
Choose amplitude encoding when vector structure matters more than simple preparation
Amplitude encoding places the entries of a vector into the amplitudes of a quantum state. A vector of length d requires a state dimension large enough to hold it, so the number of qubits is typically the smallest n for which 2**n is at least d. If the length is not a power of two, pad the vector consistently and document the padding.
The vector must be normalized so that the sum of squared magnitudes equals one. Normalization is not a cosmetic step: it changes the numerical scale and can affect downstream interpretation. Preserve the original norm separately if that scale carries business or scientific meaning.
import numpy as np
import pennylane as qml
features = np.array([0.2, 0.4, 0.8, 0.1], dtype=float)
features = features / np.linalg.norm(features)
dev = qml.device('default.qubit', wires=2, shots=None)
@qml.qnode(dev)
def amplitude_state():
qml.AmplitudeEmbedding(features, wires=[0, 1], normalize=False)
return qml.state()
print(amplitude_state())
Amplitude encoding can be attractive for compact simulations of small vectors. It is less attractive when the main bottleneck is preparing the state, repeatedly loading many training examples, or extracting enough information through measurements.
Choose angle encoding for scaled continuous features
Angle encoding maps each feature to a gate rotation. A simple version uses one qubit per feature and applies a rotation such as RY. The feature values must be scaled to the range and convention expected by the circuit. Min-max scaling, standardization followed by a bounded transform, or domain-specific scaling may be appropriate; the choice should be made using the training data and applied unchanged to validation and test data.
import numpy as np
import pennylane as qml
raw = np.array([12.0, 80.0, 0.35])
low = np.array([0.0, 0.0, 0.0])
high = np.array([20.0, 100.0, 1.0])
angles = np.pi * (raw - low) / (high - low)
dev = qml.device('default.qubit', wires=3, shots=None)
@qml.qnode(dev)
def angle_state():
for wire, angle in enumerate(angles):
qml.RY(angle, wires=wire)
return qml.probs(wires=range(3))
print(angle_state())
Angle encoding is often the most practical first experiment for continuous tabular data. However, a rotation is periodic, and different preprocessing choices can produce similar states. Test whether the encoding preserves the distinctions your classifier or optimizer needs.
Use one-hot or discrete qubit encoding for categories deliberately
For a category such as a color, product class, or finite action set, decide whether the category has an ordinal relationship. If it does not, assigning arbitrary integers and treating them as angles can introduce a false order. One-hot encoding preserves category identity directly but can require one qubit per category. Binary indexing uses fewer qubits but makes the representation more compact and less directly interpretable.
What to double-check
- Dimension and padding: Confirm that the feature vector length matches the number of wires or the state dimension expected by the embedding utility. For amplitude encoding, record which entries were padding rather than real features.
- Normalization: Verify amplitude normalization numerically. Do not silently normalize values when their absolute scale is part of the problem definition.
- Scaling leakage: Fit classical scalers only on training data. Reuse those parameters for other splits and for production inference.
- Qubit ordering: Write a small basis-state test and inspect the measured bit strings. This catches endianness mistakes before they reach a larger experiment.
- Resource estimates: Count qubits, embedding gates, entangling layers, circuit repetitions, and the number of data reuploads. A compact qubit count does not necessarily mean a shallow or inexpensive circuit.
- Backend behavior: Test first on a simulator, then assess whether the target hardware supports the required gates, connectivity, shot budget, and circuit depth. The simulator-versus-hardware decision should be part of experiment design, not an afterthought.
- Information access: Ask how the model will use the encoded information. A state may contain many amplitudes, but a measurement returns limited classical information per circuit execution.
For a maintainable project, keep preprocessing code separate from circuit construction. Store the feature order, scaling parameters, padding rule, encoding name, and SDK version with each experiment. That makes it easier to compare results when moving between frameworks; a related portability checklist is available in Quantum Circuit Portability: Translating Workloads Between Qiskit, Cirq, and PennyLane.
Common mistakes
- Choosing by qubit count alone: Amplitude encoding may use fewer qubits than a feature-by-feature approach, but state preparation and repeated loading can dominate the workflow.
- Skipping a classical baseline: Compare the quantum model with a simple classical model using the same train-test split. This separates encoding problems from model problems.
- Using arbitrary category numbers: Integer labels can imply an order that does not exist. Select a categorical encoding intentionally.
- Ignoring periodicity: Angle values separated by a full rotation can produce the same rotation. Keep the scaling range controlled and inspect the resulting states or observables.
- Changing feature order: Reordering columns between preprocessing and inference changes the meaning of every wire. Define the order once and validate it.
- Assuming simulator results transfer directly: Noise, connectivity, compilation, and finite shots can change the useful depth and accuracy of a circuit.
- Comparing encodings with different preprocessing budgets: Report scaling, dimensionality reduction, feature selection, padding, and data reuploading so the comparison is fair.
For hybrid quantum-classical models, encoding is only one part of the pipeline. The optimizer, measurement strategy, trainable circuit, and classical preprocessing should be evaluated together. See the PennyLane hybrid model tutorial for a broader workflow.
When to revisit
Revisit the encoding before changing datasets, adding features, moving from simulation to hardware, or replacing the SDK. Also review it when training becomes unstable, circuit depth grows, measurements become expensive, or a model appears insensitive to important features.
At each review, run this short checklist:
- Describe the data type and its true dimensionality.
- Compare at least one simple encoding with the proposed encoding.
- Validate scaling, normalization, padding, and qubit order with unit tests.
- Estimate circuit depth and execution cost on the intended backend.
- Measure predictive performance against a classical baseline.
- Record SDK syntax, embedding utilities, backend assumptions, and preprocessing metadata.
As a practical default, start with angle encoding for a small continuous dataset, basis or discrete encoding for clearly binary inputs, and amplitude encoding only when its compact state representation justifies the added preparation and measurement considerations. Then test the choice rather than treating the rule as universal. Encoding decisions should be refreshed when the data, circuit, hardware target, or software tooling changes.