Encoding¶
Getting classical data into a circuit, and the scaling decisions that come first.
qmlkit.encoding.angle¶
angle ¶
Angle and basis encoding — getting classical numbers into a circuit.
angle_encode ¶
angle_encode(
x: Sequence[float],
rotation: str = "ry",
trainable: bool = False,
) -> CircuitSpec
One feature per qubit, written into a rotation angle.
trainable=False bakes the values in as literals. trainable=True makes
them circuit parameters instead — which is what lets the same shift rule
deliver df/dx, the gradient a classical pre-net needs in a hybrid stack.
Source code in src/qmlkit/encoding/angle.py
basis_encode ¶
basis_encode(bits: Sequence[int]) -> CircuitSpec
Computational-basis encoding: flip a qubit wherever the bit is 1.
Source code in src/qmlkit/encoding/angle.py
basis_index ¶
n_qubits_for ¶
Qubits needed to hold n_values amplitudes: ceil(log2 N).
qmlkit.encoding.amplitude¶
amplitude ¶
Amplitude encoding — :math:n qubits hold :math:2^n numbers.
Built from uniformly-controlled rotations, not from a backend state-preparation primitive. That matters: the resulting circuit is made of ordinary registered gates, so it runs identically on every backend, can be drawn and transpiled, and its resource cost is visible rather than hidden inside an SDK call.
The construction is the standard one. Magnitudes come from a binary tree of partial
norms, each level applying a uniformly-controlled Ry; phases, when the data is
complex, come from a second cascade of uniformly-controlled Rz.
A uniformly-controlled rotation decomposes recursively:
.. code-block:: text
UCR(theta, [c0, ...], t) = UCR(alpha, [...], t) . CX(c0, t) . UCR(beta, [...], t) . CX(c0, t)
alpha_j = (theta_j + theta_{j + h}) / 2 beta_j = (theta_j - theta_{j + h}) / 2
which costs 2**m rotations and 2**(m+1) - 2 CX gates for m controls — the
exponential price of loading exponentially many numbers. Ordering the branches by
Gray code instead would bring the CX count down to 2**m, since each step would
then differ in one control bit and cancel its neighbour; that optimisation is not
done here, and the counts :meth:~qmlkit.core.ir.CircuitSpec.resources reports are
the ones actually emitted.
That recursion is a layout plus a linear map, and the two are separable. Where
the gates go depends only on the control count; what the rotations are is
:func:ucr_emitted_angles applied to the desired angles. :func:ucr_layout and
:func:ucr_emitted_angles are the two halves, and splitting them is what makes
:class:AmplitudeFeatureMap possible — one circuit whose free parameters are filled
in per data point, rather than a fresh circuit per point. A kernel needs exactly that
to evaluate a Gram matrix in one batch.
Global phase. The phase cascade reproduces every relative phase exactly and
drops one overall factor, which is unobservable. If you embed an amplitude-encoded
block inside a larger controlled circuit, that factor stops being global; use
check=True to assert the prepared state matches your target up to phase.
AmplitudeFeatureMap ¶
Bases: FeatureMap
Amplitude encoding with its angles left free — the form a kernel can batch.
:func:amplitude_encode builds a circuit per vector, which is all a one-shot
load needs and exactly wrong for a Gram matrix: nothing can be reused across rows,
so m points cost m circuit constructions and the batched evaluation paths
do not apply. The cascade's structure does not actually depend on the data,
though — only its rotation angles do — so the whole thing fits the
:class:~qmlkit.encoding.feature_maps.FeatureMap contract, and a Gram matrix
becomes one batched call.
QuantumKernel(amplitude_encode) works too, through
:class:~qmlkit.encoding.feature_maps.CallableFeatureMap, and costs the same
number of circuits — the row-state shortcut needs a state, not a parametric
circuit. What this buys is the batch underneath it. Measured on a Gram matrix
over 300 rows, one circuit per row against one batched evaluation:
| features | qubits | per row | batched | |
|---|---|---|---|---|
| 4 | 2 | 87.7 ms | 31.8 ms | 2.8x |
| 16 | 4 | 467.9 ms | 86.0 ms | 5.4x |
| 64 | 6 | 2374.4 ms | 333.4 ms | 7.1x |
The kernel this induces has a closed form, and it is a classical one. The
encoded state is :math:x/\lVert x\rVert, so
:math:k(x, x') = |\langle x, x'\rangle|^2 / (\lVert x\rVert^2 \lVert x'\rVert^2)
— the squared cosine similarity. That is a linear kernel on normalised data,
computable in microseconds without a circuit. Amplitude encoding earns its place
as a data-loading step underneath something that does more, not as a feature map
you would choose for its expressivity. Knowing which side of that line you are on
is the difference between a benchmark and a demonstration.
Two consequences worth naming, because neither raises:
- Bandwidth does nothing. Rescaling every feature before encoding leaves the
direction unchanged, so the usual first fix for a concentrated kernel is inert
here. :attr:
scale_invariantsays so, andQuantumKernelwarns. - The magnitude is gone. Two points on the same ray through the origin encode to the same state and have kernel exactly 1. If the norm of a sample carries information, amplitude encoding discards it.
A feature vector is real here, because a feature vector is real everywhere in this
library. :func:amplitude_encode takes complex amplitudes and this does not.
Arguments
n_features
Length of the input vectors. Zero-padded up to 2**ceil(log2 n_features).
normalize
False refuses a vector that is not already a unit vector rather than
rescaling it.
phases
Whether to emit the Rz cascade that carries the amplitudes' signs. Keep it
on for any data that can be negative — standardised features usually can, and
dropping the sign silently is a wrong answer, not a slower one. False
halves the parametric circuit and raises on a negative entry rather than
encoding |x|.
Source code in src/qmlkit/encoding/amplitude.py
angles ¶
Every emitted rotation angle, magnitudes first and then phases.
Already transformed by :func:ucr_emitted_angles, so :meth:_emit only has to
place them — which is what keeps it usable with ParamRef slots that cannot
be added or halved.
Source code in src/qmlkit/encoding/amplitude.py
statevector ¶
The state this map prepares, without building or simulating anything.
Amplitude encoding is the one map whose output state is known in closed form: it is the normalised, padded input. Handy for checking the circuit against what it is supposed to produce — which is how this construction is tested.
Source code in src/qmlkit/encoding/amplitude.py
pad_to_power_of_two ¶
Zero-pad a vector up to the next power of two.
Source code in src/qmlkit/encoding/amplitude.py
ucr_layout ¶
Where a uniformly-controlled rotation puts its gates, whatever the angles are.
One entry per gate, in circuit order: None for a rotation on target, which
consumes the next emitted angle, or (control, target) for a CX. 2**m
rotations and 2**(m+1) - 2 CX gates for m controls.
This carries no angle values at all, which is the point — the same layout serves a concrete circuit and a parametric one.
Source code in src/qmlkit/encoding/amplitude.py
ucr_emitted_angles ¶
The angles a uniformly-controlled rotation actually emits, in circuit order.
The recursion turns the 2**m desired angles — one per control basis state —
into 2**m emitted ones by repeated sum-and-difference halving. That is the
only arithmetic in the construction, and it is linear, so it can be done up front
on the data and never again: :func:ucr_layout then places the results without
looking at them.
Source code in src/qmlkit/encoding/amplitude.py
uniformly_controlled_rotation ¶
uniformly_controlled_rotation(
qc: QCircuit,
rotation: str,
angles: NDArray[Any],
controls: Sequence[int],
target: int,
) -> None
Apply R(angles[k]) to target for each control basis state k.
controls[0] is the most significant bit of k. Emits only Ry/Rz
and CX, so it works on any backend.
Source code in src/qmlkit/encoding/amplitude.py
state_preparation_angles ¶
state_preparation_angles(
amplitudes: NDArray[Any],
) -> tuple[list[NDArray[Any]], list[NDArray[Any]]]
Ry angles per level (magnitudes) and Rz angles per level (phases).
Source code in src/qmlkit/encoding/amplitude.py
amplitude_encode ¶
amplitude_encode(
vec: Sequence[float] | NDArray[Any],
normalize: bool = True,
pad: bool = True,
check: bool = False,
) -> CircuitSpec
Encode a vector into the amplitudes of ceil(log2 len(vec)) qubits.
Only the direction of the vector survives — amplitudes must be normalised, so
the magnitude is lost. normalize=False refuses a vector that is not already
a unit vector rather than silently rescaling it.
check=True re-simulates the circuit and asserts it prepares the intended
state (up to global phase). Cheap insurance while you are getting a pipeline
working; leave it off in a training loop.
This is the one-shot form: a circuit per vector. For a kernel or a Gram matrix,
:class:AmplitudeFeatureMap is the same construction with the angles left free,
which is what lets a whole dataset go through one batched evaluation.
Source code in src/qmlkit/encoding/amplitude.py
qmlkit.encoding.loading¶
What getting the data in costs, and the QRAM the exponential-speedup claims assume.
loading ¶
What it costs to get the data in — and where the exponential speedup went.
Amplitude encoding puts N numbers into log2(N) qubits, and that compression is
real: 1024 features in 10 qubits. It is also the most quoted and least examined number
in quantum machine learning, because the qubits are not what you pay in.
Measured, in this library: preparing a 1024-amplitude state costs 4,052 CNOTs and
a depth of 6,027 — 3.96 two-qubit gates per feature, converging on 4N as N
grows. Loading the data is linear in the data. An algorithm that then runs in
O(polylog N) has not beaten a classical one that reads the same vector: it has
moved the linear cost from the algorithm into the state preparation and stopped
counting it.
QRAM, and what it would have to be
The device that would fix this is QRAM: bucket-brigade memory that returns
sum_i psi_i |i>|x_i> in O(log N) depth (Giovannetti, Lloyd and Maccone 2008).
Every exponential-speedup claim built on amplitude-encoded classical data — HHL,
qPCA, quantum recommendation — assumes one.
No such device exists beyond toy demonstrations, and the accounting is worse than "not yet built":
- It is
O(log N)in depth, never in total resources. HoldingNvalues needsΘ(N)memory cells andΘ(N)routing components, all coherent at once. There is no regime in whichNnumbers live in fewer thanNplaces. - The depth advantage assumes every one of those
Θ(N)components acts in parallel and none of them decoheres. - Under error correction the per-cell overhead multiplies that
Θ(N). - And where the access model was the whole source of the advantage, the advantage was not quantum: given the classical analogue of QRAM access — length-squared sampling — classical algorithms match the quantum ones to polynomial factors for recommendation systems, PCA and low-rank linear systems (Tang 2019, and the dequantisation results that followed).
So this module ships a cost model rather than a QRAM. :func:loading_cost prices the
encoders qmlkit actually has, from their measured gate counts; :func:qram_cost prices
the device you would need instead, so the comparison is in front of you rather than
in a footnote. Neither is discouraging by itself — amplitude encoding is the right
choice for a state you compute rather than load, and for that case the Θ(N)
never appears.
What to use instead, when the data is classical
Angle encoding costs one rotation per feature and no two-qubit gates at all, at one
qubit per feature. That is the trade: amplitude encoding is exponential in space and
linear in time, angle encoding is linear in space and constant in depth. For the
feature counts a simulator can reach, and for every NISQ device, the second is usually
the honest choice — which is why :func:~qmlkit.encoding.angle.angle_encode and
:class:~qmlkit.encoding.feature_maps.AngleFeatureMap are the library's defaults and
amplitude encoding is not.
LoadingCost
dataclass
¶
LoadingCost(
method: str,
n_features: int,
n_qubits: int,
two_qubit_gates: int,
depth: int,
exact: bool,
)
Qubits, gates and depth to get one sample into a circuit.
exact distinguishes a counted circuit from a fitted estimate: below a few
hundred features :func:loading_cost builds the circuit and counts it, and above
that it extrapolates from the measured constants rather than allocating a
2^n-amplitude statevector to find out.
two_qubit_gates is structural — every generic vector of the same length gives
the same count. depth moves by a percent or two with the particular angles
(measured: 1,458 to 1,484 over six random 256-vectors), so read it as a scale
rather than a guarantee.
QramCost
dataclass
¶
QramCost(
n_addresses: int,
address_qubits: int,
memory_qubits: int,
routing_qubits: int,
ideal_depth: int,
encoding: LoadingCost,
)
What a bucket-brigade QRAM would need, against what encoding needs instead.
loading_cost ¶
loading_cost(
n_features: int, method: str = "amplitude"
) -> LoadingCost
Price one sample's encoding, by counting the circuit or extrapolating from it.
The three methods trade the same budget in different directions:
=========== ================= =================== =========================
Method Qubits Two-qubit gates Depth
=========== ================= =================== =========================
angle n 0 1
basis n 0 1
amplitude ceil(log2 n) ~4n ~6n
=========== ================= =================== =========================
Amplitude encoding is the only one that compresses, and the only one whose cost
grows with the data. That is not an implementation detail to be optimised away:
Θ(n) two-qubit gates is a lower bound for preparing an arbitrary state
(Plesch and Brukner 2011), so no better circuit exists to find.
The amplitude figure is for a generic vector. A real, non-negative one — which many feature vectors are — needs no phase preparation and costs exactly half: measured, 2,026 CNOTs against 4,052 at 1024 features. This reports the generic number, so treat it as an upper bound and halve it if your data has no signs.
Examples:
>>> import qmlkit as qk
>>> qk.loading_cost(1024, "amplitude").n_qubits
10
>>> qk.loading_cost(1024, "angle").two_qubit_gates
0
Source code in src/qmlkit/encoding/loading.py
qram_cost ¶
qram_cost(n_addresses: int) -> QramCost
Resources a bucket-brigade QRAM would need, beside what encoding needs instead.
The point of the comparison is the qubit count. O(log N) is a claim about
depth, and it holds only on hardware holding Θ(N) coherent memory cells and
Θ(N) routing components — so the exponential saving never existed in total
resources, only in how many of them run at once.
This prices the architecture. It does not build one, and qmlkit has no QRAM
backend: a simulated QRAM is a Θ(N)-qubit circuit whose only honest use is to
demonstrate that cost.
Examples:
>>> import qmlkit as qk
>>> cost = qk.qram_cost(1024)
>>> cost.address_qubits
10
>>> cost.memory_qubits
1024
Source code in src/qmlkit/encoding/loading.py
qmlkit.encoding.feature_maps¶
feature_maps ¶
Pauli feature maps.
Each term :math:S of a feature map contributes
.. math:: \exp!\left(-i\,\phi_S(x) \prod_{j \in S} P_j\right)
realised as W . (CX ladder, Rz(2 phi), CX ladder) . W^dagger, where W is the
basis change that sends each Pauli to Z. The default data map is the standard
one: :math:\phi_{\{i\}}(x) = x_i for singletons and
:math:\phi_S(x) = \prod_{j \in S}(\pi - x_j) for higher-order terms.
A Pauli feature map needs two pieces that are usually left implicit: the basis
change that diagonalises each Pauli string, and the data map that turns features into
angles. Both are public here — :func:basis_change and :func:default_data_map — so
either can be replaced without rewriting the map, and the map is tested against the
analytic kernel it is supposed to induce rather than against itself.
:class:FeatureMap itself is the wider extension point. Anything that turns one
feature vector into one circuit is an encoding, and :func:as_feature_map adapts a
bare x -> CircuitSpec function into one — which is what lets
:class:~qmlkit.kernels.matrix.QuantumKernel take amplitude_encode, a hand-rolled
loader, or a closure over your own state-preparation routine, and not only the Pauli
family below.
FeatureMap ¶
Turns a feature vector into a circuit.
Subclasses implement three methods, and :meth:build is not one of them --
it is concrete, and composes the other three:
- :meth:
angles— the feature vector to its rotation angles. - :meth:
n_angles— how many slots those angles occupy. - :meth:
_emit— the angles to a circuit. It receives either floats or :class:~qmlkit.core.ir.ParamRefslots, so it must not assume arithmetic.
Optionally also :meth:angle_jacobian, d(angle)/d(feature), which is what
lets a gradient reach back through the encoding to a classical pre-net.
Overriding :meth:build instead leaves :meth:build_parametric calling the base
:meth:_emit, which raises -- so the torch layer breaks and nothing else does.
adjoint comes free from the IR, which is what the fidelity kernel's
compute-uncompute test needs.
A map that genuinely cannot be written that way -- amplitude encoding as a raw
function, or any loader you already have -- overrides :meth:build and sets
:attr:supports_parametric to False. That is a contract, not a label:
callers read it to decide whether one circuit can stand in for the whole
dataset, and a map that lies about it fails inside a batched evaluation rather
than at the point of the mistake.
build ¶
build(x: ArrayLike) -> CircuitSpec
angles ¶
build_parametric ¶
build_parametric(offset: int = 0) -> CircuitSpec
The circuit with each encoding angle as a free parameter.
This is what lets a gradient flow back to the data: the circuit is
differentiated with respect to its angles, and the chain rule to x is
finished classically by :meth:angle_jacobian.
Source code in src/qmlkit/encoding/feature_maps.py
angle_jacobian ¶
d(angle) / d(feature), shape (n_angles, n_features).
The default differences the classical data map — no circuits involved, so it costs nothing quantum. Override it when a closed form is available.
Source code in src/qmlkit/encoding/feature_maps.py
adjoint ¶
adjoint(x: Sequence[float]) -> CircuitSpec
bind_width ¶
Tell a map that does not know its own input width. A no-op for one that does.
A :class:FeatureMap declares n_features up front, but a bare
x -> CircuitSpec function does not — and an estimator can need the register
width before it encodes anything, since the Hadamard test sizes its ancilla
first. Whoever is holding the data answers in advance.
Source code in src/qmlkit/encoding/feature_maps.py
resources ¶
CallableFeatureMap ¶
CallableFeatureMap(
encode: Callable[[Any], CircuitSpec],
n_features: int | None = None,
n_qubits: int | None = None,
name: str | None = None,
)
Bases: FeatureMap
Any x -> CircuitSpec function, as a feature map.
amplitude_encode is a function, not a :class:FeatureMap, so
QuantumKernel(qk.amplitude_encode) failed on 'function' object has no
attribute 'build' — an error about the adapter that was missing rather than
about anything the caller had done. This is that adapter, and
:func:as_feature_map applies it, so a kernel, a QSVC or a projected kernel takes
a plain encoder and a Pauli map on the same footing.
The wrapper stays honest about what a bare function gives up. There are no angles
to vary independently of the circuit, so :attr:supports_parametric is False,
:meth:build_parametric, :meth:angles and :meth:n_angles raise with the
reason, and callers that would have batched fall back to encoding one row at a
time. It also checks what comes back: a non-circuit, a circuit with unbound
parameters, or a register width that moves between inputs are each a mistake that
would otherwise surface much later as a wrong number.
Arguments
encode
The function. It is handed one 1-D float array and must return a fully-bound
:class:~qmlkit.core.ir.CircuitSpec.
n_features, n_qubits
Optional. Both are learnt from the first vector encoded, so a kernel takes
amplitude_encode with no further ceremony. Pass them when something needs
a width before any data has arrived.
name
What errors call it. Defaults to the function's own __name__.
Source code in src/qmlkit/encoding/feature_maps.py
bind_width ¶
Adopt an input width learnt from the data, unless one is already fixed.
PauliFeatureMap ¶
PauliFeatureMap(
n_features: int,
paulis: Sequence[str] = ("Z", "ZZ"),
reps: int = 2,
entanglement: str = "linear",
data_map: DataMap | None = None,
)
Bases: FeatureMap
The general Pauli feature map, for any set of Pauli strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_features
|
int
|
One qubit per feature. |
required |
paulis
|
Sequence[str]
|
Pauli strings to include, e.g. |
('Z', 'ZZ')
|
reps
|
int
|
How many times to repeat the whole block. More reps means higher reachable frequencies, at proportional depth. |
2
|
entanglement
|
str
|
Pattern for two-body terms: |
'linear'
|
data_map
|
DataMap | None
|
Override the default :func: |
None
|
Source code in src/qmlkit/encoding/feature_maps.py
n_angles
property
¶
One angle per term. Reps reuse the same angles, so they add depth only.
angle_jacobian ¶
Closed form for the standard data map; falls back to differencing otherwise.
Source code in src/qmlkit/encoding/feature_maps.py
ZFeatureMap ¶
Bases: PauliFeatureMap
First-order, no entanglement — so its kernel factorises over features.
Source code in src/qmlkit/encoding/feature_maps.py
ZZFeatureMap ¶
Bases: PauliFeatureMap
First order plus entangling ZZ couplings — the kernel stops factorising.
Source code in src/qmlkit/encoding/feature_maps.py
AngleFeatureMap ¶
AngleFeatureMap(
n_features: int,
rotation: str = "ry",
entangle: bool = True,
entanglement: str = "chain",
reps: int = 1,
)
Bases: FeatureMap
One rotation per feature, optionally followed by an entangling layer.
The plainest map there is, and the one whose kernel has a closed form:
cos^2((x - x')/2) per feature when entangle=False.
Source code in src/qmlkit/encoding/feature_maps.py
angle_jacobian ¶
default_data_map ¶
The standard data map: x_i for one index, prod(pi - x_j) for more.
The product form is what makes higher-order terms nonlinear in the features — a linear map there would leave the kernel factorisable and the entanglers pointless.
Source code in src/qmlkit/encoding/feature_maps.py
basis_change ¶
Gates that rotate pauli into the Z basis, and the gates that undo it.
Returns (forward, inverse) as gate-name tuples applied in circuit order.
X = H Z H so W = H; Y = (SH) Z (SH)^dagger so W = H S^dagger,
which in circuit order is sdg then h.
Source code in src/qmlkit/encoding/feature_maps.py
pauli_terms ¶
pauli_terms(
paulis: Sequence[str],
n_features: int,
entanglement: str = "linear",
) -> list[tuple[tuple[int, ...], str]]
Expand Pauli strings into concrete (qubit indices, pauli string) terms.
A one-character string like "Z" becomes one term per qubit. A two-character
string like "ZZ" follows the entanglement pattern. Longer strings enumerate
combinations of that size.
Source code in src/qmlkit/encoding/feature_maps.py
as_feature_map ¶
as_feature_map(
encoding: EncodingLike,
n_features: int | None = None,
n_qubits: int | None = None,
) -> FeatureMap
Whatever the caller passed as an encoding, as a :class:FeatureMap.
A :class:FeatureMap comes back unchanged — the same object, not a copy, so a
kernel and the map it was handed stay identical. Anything else callable is wrapped
in :class:CallableFeatureMap. Anything else at all raises here, rather than
several frames deeper on a missing build.
qk.QuantumKernel(qk.amplitude_encode) # a function
qk.QuantumKernel(qk.ZZFeatureMap(4)) # a feature map
qk.QuantumKernel(lambda x: my_loader(x)) # anything you like
Source code in src/qmlkit/encoding/feature_maps.py
qmlkit.encoding.hamiltonian¶
hamiltonian ¶
Hamiltonian (IQP-style) encoding and data re-uploading.
Hamiltonian encoding evolves the register under a data-dependent Hamiltonian
:math:H(x) = \sum_i x_i Z_i + \sum_{(i,j)} x_i x_j Z_i Z_j for a time t,
Trotterised into steps slices. Because every term commutes here, the Trotter
split is exact at any number of steps — steps changes the circuit depth and
nothing else. That is worth knowing before anyone tunes it hoping for accuracy.
Data re-uploading interleaves the encoding with trainable blocks. Each repeat
widens the reachable Fourier spectrum: L uploads reach frequencies 0..L,
which is the knob that decides which functions the model can represent at all,
separately from the ansatz that picks the coefficients.
DataReuploadEncoder ¶
DataReuploadEncoder(
n_features: int,
n_uploads: int = 3,
rotations: Sequence[str] = ("rz", "ry", "rz"),
encoding_rotation: str = "ry",
entanglement: str | None = "chain",
trainable_input: bool = False,
)
One convenient re-uploading shape: angle encoding, rotations, entangler.
.. note::
Re-uploading is a pattern, not a structure — any feature map, any
trainable block, any interleaving. This class fixes one convenient choice.
For anything else use :func:qmlkit.reupload, or compose
:class:~qmlkit.ansatz.blocks.EncodingLayer directly with the block
vocabulary. This remains for the plain angle-encoding case.
The circuit alternates S(x) — an angle encoding — with W(theta), a
trainable rotation block, n_uploads times. Data enters as literals by
default; pass trainable_input=True to make the features circuit parameters
too, which is what yields df/dx for a classical pre-net.
The parameter vector is laid out as (n_uploads, n_qubits, len(rotations)),
flattened, with the input parameters (if trainable) appended after it.
Source code in src/qmlkit/encoding/hamiltonian.py
n_params
property
¶
Total circuit parameters — weights, plus inputs when they are trainable.
build ¶
build(x: Sequence[float] | None = None) -> CircuitSpec
Build the circuit.
With trainable_input=False (default) x is required and baked in.
With trainable_input=True x is ignored: the features become
parameters, supplied later alongside the weights.
Source code in src/qmlkit/encoding/hamiltonian.py
trotter_rz_angle ¶
Single-qubit Rz angle per Trotter step: 2 * x_i * t / steps.
Source code in src/qmlkit/encoding/hamiltonian.py
trotter_zz_angle ¶
Two-qubit coupling angle per Trotter step: 2 * x_i * x_j * t / steps.
Source code in src/qmlkit/encoding/hamiltonian.py
hamiltonian_encode ¶
hamiltonian_encode(
x: Sequence[float],
t: float = 1.0,
steps: int = 3,
entanglement: str = "chain",
initial_hadamard: bool = True,
) -> CircuitSpec
Evolve under a data-dependent Ising Hamiltonian.
initial_hadamard=True starts in the uniform superposition, which is what
makes the Z-diagonal evolution do anything observable — without it the register
stays in a computational basis state and only picks up a global phase.
Source code in src/qmlkit/encoding/hamiltonian.py
n_reachable_frequencies ¶
L uploads reach frequencies 0..L -- so L + 1 of them.
This holds only when the trainable block does not commute with the encoding
rotation. If it does, the uploads merge into one rotation and the model reaches
a single frequency instead. :class:DataReuploadEncoder warns when you build
such a pairing.
Source code in src/qmlkit/encoding/hamiltonian.py
qmlkit.encoding.pipeline¶
Standardise, reduce to n_qubits columns, scale into rotation angles — one
scikit-learn-clonable object, used in every case study.
pipeline ¶
Getting a real dataset onto a small number of qubits, once and reproducibly.
Almost every quantum model starts the same way: standardise the features, reduce them to as many columns as you have qubits, and scale those into rotation angles. Done by hand that is three objects to keep in sync and one easy mistake — fitting the reducer on the test set — so it is one object here.
pipeline = FeaturePipeline(n_qubits=4).fit(X_train)
Z_train, Z_test = pipeline.transform(X_train), pipeline.transform(X_test)
fit sees only the training data, and transform reuses exactly what it learned.
:attr:FeaturePipeline.explained_variance_ reports what the reduction cost, because a
model that never saw 20% of the variance is not underperforming — it was never shown
the data.
Everything here is duck-typed to scikit-learn's estimator protocol (get_params /
set_params / fit / transform), so it drops into Pipeline and
GridSearchCV without qmlkit depending on scikit-learn.
SklearnCompatible ¶
get_params / set_params, read off the constructor signature.
scikit-learn duck-types: clone, Pipeline and GridSearchCV need these
two methods, not a base class. Implementing them directly is what lets a qmlkit
estimator sit in a scikit-learn workflow while scikit-learn stays an optional
dependency — which matters, because the NumPy backend is meant to work alone.
The one rule this imposes: an __init__ parameter must be stored on an
attribute of the same name, unchanged.
FeaturePipeline ¶
FeaturePipeline(
n_qubits: int,
method: str = "pca",
standardize: bool = True,
angle_range: tuple[float, float] = (0.0, 2 * pi),
)
Bases: SklearnCompatible
Standardise, reduce to n_qubits columns, and scale into rotation angles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_qubits
|
int
|
How many columns to come out with — one rotation angle per qubit. |
required |
method
|
str
|
|
'pca'
|
standardize
|
bool
|
Centre and scale to unit variance first. PCA without this is dominated by whichever feature happens to be measured in the largest units. |
True
|
angle_range
|
tuple[float, float]
|
Where the output lands. The default |
(0.0, 2 * pi)
|
Source code in src/qmlkit/encoding/pipeline.py
fit ¶
fit(X: NDArray[Any], y: Any = None) -> FeaturePipeline
Learn every step from the training data alone.
Source code in src/qmlkit/encoding/pipeline.py
transform ¶
Apply the fitted steps. Never re-fits — that is the whole point.
Source code in src/qmlkit/encoding/pipeline.py
qmlkit.encoding.scaling¶
scaling ¶
Getting real data into the range and width an encoding needs.
Two problems every quantum model hits before any quantum step happens: features arrive on arbitrary scales when rotations want radians, and there are usually more features than qubits.
These are preprocessing, not classical baselines — no model is fitted here, and there is no sklearn dependency. The PCA reduction is a plain SVD.
AngleScaler
dataclass
¶
AngleScaler(
lo: float = 0.0,
hi: float = 2 * pi,
data_min: NDArray[Any] | None = None,
data_max: NDArray[Any] | None = None,
)
Fit-then-transform angle scaling, so train and test share one range.
PCAReducer
dataclass
¶
PCAReducer(
n_components: int,
mean_: NDArray[Any] | None = None,
components_: NDArray[Any] | None = None,
explained_variance_ratio_: NDArray[Any] | None = None,
)
Project features onto their leading principal components, via SVD.
Angle encoding needs one qubit per feature, so a 64-feature dataset needs 64
qubits — usually out of reach. Reducing first is the ordinary way through, and
explained_variance_ratio_ says how much you gave up doing it.
to_angle_range ¶
to_angle_range(
x: NDArray[Any],
lo: float = 0.0,
hi: float = 2 * pi,
data_min: NDArray[Any] | None = None,
data_max: NDArray[Any] | None = None,
) -> NDArray[Any]
Rescale features into an angle window, per column.
Fit the range on training data and reuse it on test data by passing
data_min/data_max explicitly — otherwise each call rescales to its own
extremes, which silently makes train and test incomparable. A constant column
maps to the middle of the window rather than dividing by zero.
Source code in src/qmlkit/encoding/scaling.py
reduce_to_qubits ¶
reduce_to_qubits(
x: NDArray[Any],
n_qubits: int,
method: str = "pca",
to_angles: bool = True,
lo: float = 0.0,
hi: float = 2 * pi,
) -> NDArray[Any]
Reduce a feature matrix to n_qubits columns, ready for angle encoding.
method="pca" keeps the leading principal components; method="truncate"
keeps the first n_qubits columns unchanged, which is only sensible when the
features are already ordered by importance.