CustomVQA¶
- class CustomVQA(qscript, *, param_shape=None, data_param_indices=None, feature_batch=None, arg_shapes=None, data_arg=None, labels=None, loss_fn='squared_error', loss_reduction='mean', max_iterations=10, **kwargs)[source]¶
Bases:
DataBindingMixin,VariationalQuantumAlgorithmCustom variational algorithm for a parameterized circuit.
Wraps a PennyLane
QuantumScript, a PennyLaneQNode, or a QiskitQuantumCircuitand optimizes its trainable parameters to minimize a single expectation-value measurement. AQNodeis converted to aQuantumScriptupfront, with its required (no-default) arguments taken as the trainable parameters. Qiskit measurements on selected qubits convert to a sum-of-Z observable on those wires. QiskitParameterExpressionobjects (e.g.2 * theta) are preserved natively through the Qiskit DAG.Optionally accepts a classical
feature_batchplusdata_param_indices(indices into the circuit’s parameter ordering) to train in QNN style: the selected parameters are bound from each row of the batch viaDataBindingStage, per-sample expectation values are aggregated byloss_reduction, and only the remaining parameters are exposed to the optimizer.- Variables:
qscript – The input
QuantumScriptorQuantumCircuit.param_shape – Shape of a single parameter set.
n_qubits (
int) – Number of qubits in the circuit.n_layers (
int) – Layer count (fixed to 1 for this wrapper).cost_hamiltonian – Observable being minimized, as a Qiskit
SparsePauliOp.loss_constant (
float) – Constant term extracted from the observable.measured_wires (
tuple[int,...]) – For Qiskit input, the qubit indices targeted bymeasureinstructions.feature_batch (
numpy.ndarrayorNone) – Classical feature batch when data binding is active; otherwiseNone.labels (
numpy.ndarrayorNone) – Supervised targets of shape(n_samples,)when training a supervised loss; otherwiseNone.loss_reduction – User-facing aggregation across samples when data binding is active; ignored otherwise.
optimizer – Classical optimizer for parameter updates.
max_iterations (
int) – Maximum number of optimization iterations.current_iteration (
int) – Current optimization iteration.
Initialize a CustomVQA instance.
- Parameters:
qscript (
QuantumScript|QNode|QuantumCircuit) – A parameterizedQuantumScriptorQNodewith a single expectation-value measurement, or a QiskitQuantumCircuitwith computational-basis measurements (mapped to a sum-of-Z observable on the measured wires).QNodeinputs are converted toQuantumScriptupfront; the storedqscriptattribute then holds the convertedQuantumScript, not the originalQNode. AQNodeargument with a Python default is treated as a fixed constant (not trained), matching PennyLane’s trainability semantics. Structural values (qubit/layer counts used only for control flow, never as gate angles) are neither data nor weights: close over them in the enclosing scope or give them a default — a no-default structural argument is symbolized like a weight and then breaks (e.g.range(<symbol>)). The QNode is traced one sample at a time, so index by the structural size (range(n_qubits)), not the batch dimension (len(inputs[0])).param_shape (
tuple[int,...] |int|None) – Shape of a single parameter set. If None, uses a flat shape inferred from trainable parameters. Must beNonewhendata_param_indicesis set — the optimizer view is automatically flat over the remaining weight parameters.data_param_indices (
Sequence[int] |None) – Integer indices (into the circuit’s flat parameter ordering) marking which parameters are bound fromfeature_batchrather than optimized. For Qiskit input, indices referencelist(qc.parameters); for PennyLane input, indices reference the trainable-parameter ordering used to synthesize the internal parameter vector. Mutually required withfeature_batch.feature_batch (
TypeAliasType|None) – Classical feature batch of shape(n_samples, len(data_param_indices)). Mutually required withdata_param_indices(ordata_arg).arg_shapes (
Mapping[str,tuple[int,...]] |None) – For multi-argument or structured-shape QNode inputs (e.g.circuit(inputs, weights)withStronglyEntanglingLayers), maps each array argument’s name to its shape so the QNode can be traced symbolically. Thedata_arg’s shape is filled in automatically fromfeature_batch. Only valid for QNode inputs.data_arg (
str|None) – Name of the QNode argument fed fromfeature_batch(the data axis), as an alternative todata_param_indicesfor multi-argument QNodes. The remaining arguments’ parameters are the trainable weights. Requiresfeature_batchand a QNode input; mutually exclusive withdata_param_indices.labels (
TypeAliasType|None) – Optional supervised targets of shape(n_samples,), aligned withfeature_batch’s rows. When given (data binding must be active), each sample’s prediction (the observable’s expectation value) is compared to its label vialoss_fnbeforeloss_reductionaggregates — turning the unsupervised objective into a supervised training loss.None(default) keeps the unsupervised behavior.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 (expectation values when unsupervised, or per-sample losses whenlabelsis set) into the scalar loss the optimizer sees."mean"(default),"sum", or a callable(n_samples,) -> float. Ignored whendata_param_indicesis unset.max_iterations (
int) – Maximum number of optimization iterations.**kwargs – Additional keyword arguments passed to the parent class, including backend and optimizer.
- Raises:
TypeError – If
qscriptis not a supported type.ValueError – If the input has an invalid measurement, no trainable parameters, or inconsistent data-binding args.
Attributes Summary
Number of trainable parameters per ansatz layer.
Shape of a single parameter set.
Attributes Documentation
- n_params_per_layer¶
- param_shape¶
Shape of a single parameter set.