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, VariationalQuantumAlgorithm

Quantum Neural Network trained on a classical feature batch.

Composes a FeatureMap (data-binding layer) with an Ansatz (trainable layer) into a single parameterized circuit. At each optimization step, the framework evaluates the cost observable on the composed circuit once per sample in feature_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 in dry_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.ndarray or None) – Shape (n_samples,) supervised targets when training a supervised loss; None for 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 to DataBindingStage.

  • 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 from feature_batch at 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), where n_data_params equals feature_map.n_params(n_qubits).

  • observable (SparsePauliOp | None) – Cost observable as a SparsePauliOp. Must act on n_qubits qubits. Defaults to the all-qubit parity operator Z 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 with feature_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 via loss_fn, and those per-sample losses are aggregated by loss_reduction. When None (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 when labels is 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 when labels is set) into the scalar the optimizer sees. "mean" (default), "sum", or a callable np.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_map or ansatz are not the expected base types, or if observable is not a SparsePauliOp.

  • ValueError – On shape mismatches, non-positive layer counts, or degenerate Hamiltonians.

Attributes Summary

n_params_per_layer

Trainable parameters per ansatz layer (data params are excluded).

Attributes Documentation

n_params_per_layer

Trainable parameters per ansatz layer (data params are excluded).