QNN¶
- class QNN(n_qubits, feature_map, ansatz, feature_batch, *, observable=None, n_layers=1, labels=None, loss_fn='squared_error', loss_reduction='mean', max_iterations=10, **kwargs)[source]¶
Bases:
DataBindingMixin,VariationalQuantumAlgorithmQuantum Neural Network trained on a classical feature batch.
Composes a
FeatureMap(data-binding layer) with anAnsatz(trainable layer) into a single parameterized circuit. At each optimization step, the framework evaluates the cost observable on the composed circuit once per sample infeature_batch, reduces the per-sample expectation values along the sample axis (mean by default), and reports one scalar loss per weight candidate to the optimizer. The optimizer never sees the data axis.The data fan-out and reduction live in
DataBindingStage, so the per-sample axis shows up cleanly indry_run()alongside the param-set axis — no custom evaluator on the QNN class itself.- Variables:
n_qubits (
int) – Number of qubits in the circuit.feature_map – Classical → quantum encoder (
FeatureMap).ansatz – Trainable variational layer (
Ansatz).n_layers (
int) – Number of ansatz layers.feature_batch (
numpy.ndarray) – Shape(n_samples, n_data_params)classical feature batch fed into the feature map every step.labels (
numpy.ndarrayorNone) – Shape(n_samples,)supervised targets when training a supervised loss;Nonefor the unsupervised objective.cost_hamiltonian – The observable being minimized (
SparsePauliOp).loss_constant (
float) – Constant term extracted from the observable.loss_reduction – User-facing aggregation across samples —
"mean","sum", or a callable(n_samples,) → float. The resolved callable is stored privately and forwarded toDataBindingStage.optimizer – Classical optimizer for weight updates.
max_iterations (
int) – Maximum number of optimization iterations.current_iteration (
int) – Current optimization iteration.
Initialize a QNN.
- Parameters:
n_qubits (
int) – Number of qubits in the circuit.feature_map (
FeatureMap) – Encoder applied first; its parameters are bound fromfeature_batchat execution time.ansatz (
Ansatz) – Trainable variational block applied after the feature map.feature_batch (
TypeAliasType) – Classical feature batch of shape(n_samples, n_data_params), wheren_data_paramsequalsfeature_map.n_params(n_qubits).observable (
SparsePauliOp|None) – Cost observable as aSparsePauliOp. Must act onn_qubitsqubits. Defaults to the all-qubit parity operatorZ ⊗ Z ⊗ … ⊗ Z, which gives a single readout in[-1, 1]and uses information from every qubit.n_layers (
int) – Number of ansatz layers. Defaults to 1.labels (
TypeAliasType|None) – Optional supervised targets of shape(n_samples,), aligned withfeature_batch’s rows. When given, the QNN trains a supervised loss: each sample’s prediction (the cost observable’s expectation value, in[-1, 1]for the default parity observable) is compared to its label vialoss_fn, and those per-sample losses are aggregated byloss_reduction. WhenNone(default) the QNN minimizes the bare expectation value (unsupervised).loss_fn (
Literal['squared_error'] |Callable[[float,float],float]) – Per-sample supervised loss(prediction, label) -> float, used only whenlabelsis given."squared_error"(default) with the default"mean"reduction yields mean-squared error; pass a callable for a custom loss. A custom callable must return a finite value — a NaN/Inf loss propagates to the optimizer with no diagnostic.loss_reduction (
Literal['mean','sum'] |Callable[[ndarray[tuple[Any,...],dtype[double]]],float]) – How to aggregate the per-sample values (predictions when unsupervised, or per-sample losses whenlabelsis set) into the scalar the optimizer sees."mean"(default),"sum", or a callablenp.ndarray (n_samples,) -> float.max_iterations (
int) – Maximum number of optimization iterations.**kwargs – Forwarded to
VariationalQuantumAlgorithm(e.g.backend,optimizer,seed).
- Raises:
TypeError – If
feature_maporansatzare not the expected base types, or ifobservableis not aSparsePauliOp.ValueError – On shape mismatches, non-positive layer counts, or degenerate Hamiltonians.
Attributes Summary
Trainable parameters per ansatz layer (data params are excluded).
Attributes Documentation
- n_params_per_layer¶
Trainable parameters per ansatz layer (data params are excluded).