A differentiable variational circuit in PennyLane
Optimising the parameters of a quantum circuit by gradient.
Goal: Training a small quantum-classical classifier on synthetic data.
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library import real_amplitudes, zz_feature_map
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
from qiskit_machine_learning.neural_networks import EstimatorQNN
from qiskit_machine_learning.optimizers import COBYLA
from qiskit_machine_learning.utils import algorithm_globals
algorithm_globals.random_seed = 0
rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, (40, 2)); y = np.where(X.sum(1) > 0, 1, -1)
fm, ansatz = zz_feature_map(2, reps=1), real_amplitudes(2, reps=2)
qc = QuantumCircuit(2); qc.compose(fm, inplace=True); qc.compose(ansatz, inplace=True)
qnn = EstimatorQNN(circuit=qc, input_params=fm.parameters, weight_params=ansatz.parameters)
clf = NeuralNetworkClassifier(qnn, optimizer=COBYLA(maxiter=120))
clf.fit(X[:30], y[:30])
print("Number of trainable parameters:", qnn.num_weights)
print(f"Training accuracy: {clf.score(X[:30], y[:30]):.2f} | test: {clf.score(X[30:], y[30:]):.2f}")
We use ZZFeatureMap to encode features into the quantum state and RealAmplitudes as a trainable circuit, combine them into an EstimatorQNN, then into a NeuralNetworkClassifier with the COBYLA optimizer. The computation runs on a local simulator; results on such small data illustrate the API and do not demonstrate a quantum advantage.
Number of trainable parameters: 6 Training accuracy: 0.77 | test: 0.70
This example was actually run and tested on 21 November 2026 on a CPU — qiskit-machine-learning 0.9.1, qiskit 2.6.2, python 3.13.18
Optimising the parameters of a quantum circuit by gradient.
Sections
No section has this name. Press “Search” to search all site content.
Favourites
My results & certificates
My academy progressMy quiz resultsKids’ progressAcademy certificatesQuiz certificatesStart any lesson or quiz and it will show up here so you can get back to it quickly.
Settings
I am the AI Frameworks & Libraries Assistant. Describe your project or ask me about a library, a comparison or a code example, and I will answer from the encyclopedia's database with links and sources.
Answers from the encyclopedia's database only, without a language model and without sending your question to any third party.
The assistant can make mistakes, so check the attached sources.