← Quantum Store · Guides · Lessons · Glossary · Packages · About · Türkçe

Quantum machine learning and hardware course · Lesson 1 / 5 · 10 min

Loading data into qubits: basis, angle and amplitude encoding

The first step of quantum machine learning is to turn classical data into a quantum state. Try the three basic encoding methods with Qiskit and learn the price of each.

Basis encoding

The simplest method is to write a number in binary and put each bit into a qubit: for 5 = 101, X is applied to q0 and q2. n qubits hold a number between 0 and 2ⁿ − 1. It is easy but uses many qubits per data point and makes no use of superposition.

Angle encoding

In angle encoding each number becomes the rotation angle of a qubit: for a value x, ry(x) is applied and the probability of the qubit giving 1 is sin²(x/2). A data point with n features needs n qubits. The circuit is very short, which is why it is the most widely used method on today’s devices.

import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector

features = [0.0, np.pi / 2, np.pi]          # three features, three qubits
qc = QuantumCircuit(3)
for i, x in enumerate(features):
    qc.ry(x, i)
sv = Statevector(qc)
print([round(float(sv.probabilities([i])[1]), 3) for i in range(3)])   # [0.0, 0.5, 1.0]

Amplitude encoding

In amplitude encoding 2ⁿ numbers become the amplitudes of n qubits: four numbers fit into two qubits and a million numbers into only 20. The vector is first scaled to have length 1. This exponential compression looks very attractive, but its price is high: preparing a general vector can need an exponential number of gates, and measurement does not give all the amplitudes back.

This “data loading bottleneck” explains why many algorithms that promise a quantum advantage on large data struggle in practice.

import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector

v = np.array([3, 4, 0, 0]) / 5              # 4 numbers with length 1
amp = QuantumCircuit(2)
amp.prepare_state(v, [0, 1])
print(Statevector(amp).probabilities(decimals=2))   # [0.36 0.64 0.   0.  ]: 0.36 for 00, 0.64 for 01

Try it yourself

This circuit is basis encoding: the X on q0 loads 001, the number 1. Add an X on q2 too: the result is 101, the number 5. With three qubits you can load any number from 0 to 7.

Open the circuit in your browser

The circuit playground is in Turkish. Button guide: “1000 kez ölç” = measure 1000 times, “Durum vektörünü göster” = show the state vector, “Bu devrenin Qiskit kodu” = this circuit’s Qiskit code, “Geri al” = undo, “Temizle” = clear. Click a gate in the circuit to remove it.

Key points

Test yourself

With amplitude encoding, how many qubits are needed for about a million (2²⁰) numbers?

Show the answer

20. n qubits have 2ⁿ amplitudes; 2²⁰ ≈ a million numbers fit into 20 qubits.

The variational classifier: training a circuit like a neural network →

Share: X · LinkedIn