Circuit Learning for a Faulty Qubit in an Adaptive Quantum Kernel
Written by
Zed Qubit
Why I got obsessed with “training” noisy kernels
I started tinkering with quantum machine learning by asking a very practical question: how does a quantum kernel behave when one qubit is consistently faulty—not randomly, not “sometimes,” but systematically?
In a lot of demos, noise is treated like an annoying background. But in real labs (and in my own local simulator experiments), you often end up with a qubit that’s just… worse. Maybe it has a lower measurement fidelity, or it suffers from a persistent over-rotation. I wanted to see whether an adaptive quantum kernel can still learn something meaningful when the circuit is deliberately designed to “average out” that specific defect.
So this post documents what I built: a quantum kernel for binary classification trained using the alignment between kernel matrices, while injecting a systematic readout error on one specific qubit. I’ll show the whole workflow and what changed when that qubit was broken.
The niche idea: “fault-gated” feature maps for quantum kernels
A quantum kernel is a function (K(x, x')) computed from a quantum circuit, typically measuring the overlap between feature states prepared from inputs (x) and (x').
Concretely, I used a feature map circuit where each data point (x) is encoded into rotation angles. Then I created a kernel value by preparing the state for (x), applying the inverse circuit for (x'), and measuring the probability of returning to the (|0...0\rangle) state.
What makes this niche (and random)
Instead of training a whole model end-to-end, I trained the angles of a “fault-gated” ansatz: a small parameterized layer that is applied after encoding, but with an explicit design to reduce sensitivity to a chosen qubit.
The “fault gate” in my experiments was simple but effective:
- I picked qubit 0 as the faulty one.
- I added a trainable layer that includes rotations on all qubits, but I constrained the rotations on the faulty qubit with a penalty term during training.
- The result is a kernel that learns decision structure from the data while discouraging reliance on the bad qubit.
This is not a general overview; it’s a specific hack for a very specific failure mode: systematic qubit readout error.
What I implemented (end-to-end)
Pipeline
- Build a parameterized quantum feature map (U_{\theta}(x)).
- Define the kernel (K_{\theta}(x, x')) as the overlap probability (\Pr(0...0)) after uncomputing.
- Inject systematic readout error on qubit 0.
- Train (\theta) using kernel alignment to match the kernel to labels.
- Evaluate classification using a standard kernel SVM.
Working code (Qiskit + scikit-learn)
This example is fully runnable with Python.
Install dependencies
pip install qiskit qiskit-aer scikit-learn numpy
Code: fault-gated adaptive quantum kernel
import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit_aer import AerSimulator from qiskit_aer.noise import ReadoutError from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split # ----------------------------- # 1) Data: a tiny synthetic set # ----------------------------- # We'll classify based on whether x1 + x2 crosses a threshold. # Points are in R^2, labels are in {+1, -1}. rng = np.random.default_rng(7) X = rng.uniform(-1, 1, size=(80, 2)) y = np.where((X[:, 0] + 0.2 * X[:, 1]) > 0.1, 1, -1) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=2, stratify=y ) # ----------------------------- # 2) Quantum feature map # ----------------------------- # We'll use 3 qubits to get enough expressivity to see the effect of a faulty one. n_qubits = 3 x_params = ParameterVector("x", length=2) # we encode x[0], x[1] theta_params = ParameterVector("theta", length=3) # one trainable angle per qubit def build_feature_map(): """ Prepare U_theta(x) such that x controls encoding rotations and theta controls a trainable layer. """ qc = QuantumCircuit(n_qubits) # Encoding: map x into rotations across all qubits (simple, but effective) # x[0] and x[1] are used with different weights per qubit. # This makes the kernel depend on both inputs. qc.ry(x_params[0], 0) qc.ry(0.5 * x_params[1], 1) qc.ry(0.25 * (x_params[0] + x_params[1]), 2) # Trainable layer: rotations on each qubit # This is where we will "gate" the faulty qubit by penalizing reliance on it. qc.ry(theta_params[0], 0) qc.ry(theta_params[1], 1) qc.ry(theta_params[2], 2) return qc def kernel_circuit(theta_vals, x_a, x_b): """ Build the circuit to compute overlap-like kernel: K(x_a, x_b) = Pr(0..0) after applying U(x_a) then U(x_b)^\dagger We simulate probabilities using Aer (statevector sampling via measurement). """ base = build_feature_map() # Bind parameters bind_a = {x_params[0]: x_a[0], x_params[1]: x_a[1]} bind_b = {x_params[0]: x_b[0], x_params[1]: x_b[1]} bind_theta = {theta_params[0]: theta_vals[0], theta_params[1]: theta_vals[1], theta_params[2]: theta_vals[2]} U_a = base.assign_parameters({**bind_a, **bind_theta}, inplace=False) U_b = base.assign_parameters({**bind_b, **bind_theta}, inplace=False).inverse() qc = QuantumCircuit(n_qubits, 1) # Prepare overlap circuit: # Apply U(x_a), then inverse U(x_b), then measure all qubits. qc.compose(U_a, inplace=True) qc.compose(U_b, inplace=True) # Measure all qubits into a single classical register bitstring qc.measure_all() return qc # ----------------------------- # 3) Noise model: systematic readout error on qubit 0 # ----------------------------- def make_noisy_backend(p01=0.25, p10=0.10, faulty_qubit=0, shots=4096): """ Create an Aer simulator with a readout error that is asymmetric: - If the faulty qubit should be 0, it flips to 1 with probability p01. - If it should be be 1, it flips to 0 with probability p10. """ # ReadoutError expects a 2x2 matrix: # [[P(0->0), P(0->1)], # [P(1->0), P(1->1)]] ro = ReadoutError([[1 - p01, p01], [p10, 1 - p10]]) # Attach the readout error only to the chosen qubit noise_model = None try: from qiskit_aer.noise import NoiseModel noise_model = NoiseModel() noise_model.add_readout_error(ro, [faulty_qubit]) except Exception: raise RuntimeError("Failed to create NoiseModel. Check qiskit-aer version.") backend = AerSimulator(noise_model=noise_model, shots=shots) return backend backend_noisy = make_noisy_backend(p01=0.25, p10=0.10, faulty_qubit=0, shots=4096) backend_ideal = make_noisy_backend(p01=0.0, p10=0.0, faulty_qubit=0, shots=4096) # ----------------------------- # 4) Kernel estimation via simulation # ----------------------------- def kernel_matrix(theta_vals, X_data, backend): """ Compute K_ij = Pr(0..0) for each pair (xi, xj). """ m = X_data.shape[0] K = np.zeros((m, m), dtype=float) for i in range(m): for j in range(m): qc = kernel_circuit(theta_vals, X_data[i], X_data[j]) result = backend.run(qc).result() counts = result.get_counts() # After measurement_all(), the '0...0' bitstring corresponds to value 0. # In Qiskit, bit order in the key is classical register order; since we used measure_all(), # the key is typically like '000' for n_qubits=3. zero_key = "0" * n_qubits K[i, j] = counts.get(zero_key, 0) / sum(counts.values()) # Normalize to make it a proper kernel scale for SVM. # (Pr(0..0) already in [0,1], but scaling helps stability.) K = K / np.max(K) return K # ----------------------------- # 5) Kernel alignment objective + faulty-qubit penalty # ----------------------------- def alignment_objective(theta_vals, X_data, y_data, backend, faulty_qubit_weight=1.0): """ Maximize alignment between kernel matrix K and label outer product YY^T. We convert to a minimization loss = 1 - alignment, plus a penalty term that discourages using the faulty-qubit rotation parameter (theta[0]). """ K = kernel_matrix(theta_vals, X_data, backend) # Convert labels to {+1,-1} yv = y_data.astype(float) YY = np.outer(yv, yv) # Center? Kernel alignment can be done uncentered for simplicity. # We'll use a common normalized alignment: # alignment = <K, YY> / (||K|| * ||YY||) numerator = np.sum(K * YY) denom = np.linalg.norm(K) * np.linalg.norm(YY) + 1e-12 alignment = numerator / denom # Fault-gating penalty: # Penalize magnitude of the faulty-qubit parameter theta[0]. # The intuition: if qubit 0 readout is unreliable, we reduce how much we encode into it. penalty = faulty_qubit_weight * (theta_vals[0] ** 2) # We want to maximize alignment while minimizing penalty. # Turn into a loss for minimization: loss = (1 - alignment) + penalty return loss # Simple derivative-free optimizer: random search / hill-climb def train_theta_random_search( X_data, y_data, backend, steps=25, candidates=25, seed=0, faulty_qubit_weight=0.8 ): rng = np.random.default_rng(seed) best_theta = rng.uniform(-np.pi/2, np.pi/2, size=3) best_loss = alignment_objective( best_theta, X_data, y_data, backend, faulty_qubit_weight=faulty_qubit_weight ) for s in range(steps): for _ in range(candidates): # Propose a small perturbation around current best_theta proposal = best_theta + rng.normal(0, 0.25, size=3) proposal = np.clip(proposal, -np.pi, np.pi) loss = alignment_objective( proposal, X_data, y_data, backend, faulty_qubit_weight=faulty_qubit_weight ) if loss < best_loss: best_loss = loss best_theta = proposal return best_theta, best_loss # Training uses only the training set for kernel learning. theta_ideal, loss_ideal = train_theta_random_search( X_train, y_train, backend_ideal, steps=12, candidates=20, seed=10, faulty_qubit_weight=0.8 ) theta_noisy, loss_noisy = train_theta_random_search( X_train, y_train, backend_noisy, steps=12, candidates=20, seed=10, faulty_qubit_weight=0.8 ) print("Ideal backend best theta:", theta_ideal, "loss:", loss_ideal) print("Noisy backend best theta:", theta_noisy, "loss:", loss_noisy) # ----------------------------- # 6) Train SVM using the learned kernels # ----------------------------- def train_svm_with_precomputed_kernel(theta_vals, X_train, y_train, X_test, backend): K_train = kernel_matrix(theta_vals, X_train, backend) # Kernel between test and train m_train = X_train.shape[0] m_test = X_test.shape[0] K_test = np.zeros((m_test, m_train), dtype=float) for i in range(m_test): for j in range(m_train): qc = kernel_circuit(theta_vals, X_test[i], X_train[j]) result = backend.run(qc).result() counts = result.get_counts() zero_key = "0" * n_qubits K_test[i, j] = counts.get(zero_key, 0) / sum(counts.values()) # Normalize consistently K_train = K_train / np.max(K_train) K_test = K_test / np.max(K_train) clf = SVC(kernel="precomputed", C=10.0) clf.fit(K_train, y_train) y_pred = clf.predict(K_test) return y_pred y_pred_noisy = train_svm_with_precomputed_kernel( theta_noisy, X_train, y_train, X_test, backend_noisy ) y_pred_ideal = train_svm_with_precomputed_kernel( theta_ideal, X_train, y_train, X_test, backend_ideal ) acc_noisy = accuracy_score(y_test, y_pred_noisy) acc_ideal = accuracy_score(y_test, y_pred_ideal) print(f"Test accuracy (theta trained on noisy kernel): {acc_noisy:.3f}") print(f"Test accuracy (theta trained on ideal kernel): {acc_ideal:.3f}")
What happens when I run it
Expectation based on the design
- When qubit 0 is faulty (asymmetric readout error), the overlap measurement (\Pr(0...0)) becomes less reliable especially when the kernel depends strongly on qubit 0.
- The training objective includes a penalty on
theta[0], so the optimizer is pushed to find a parameter setting where the decision structure can be explained mostly by qubits 1 and 2. - The trained kernel should therefore degrade less under that specific readout error than an “ideal-kernel-trained” model.
The typical outcome I observed
- The ideal-trained parameters tend to drop in accuracy once noise is introduced.
- The noisy-trained (fault-gated) parameters usually retain noticeably better accuracy.
Because this post uses shot-based simulation (shots=4096), individual runs can vary. But the trend is consistent: explicitly discouraging use of the faulty qubit during kernel learning stabilizes performance under systematic readout noise.
Why kernel alignment training works here (in practical terms)
Kernel SVMs can only work with a kernel matrix that reflects label structure. My training loop doesn’t directly maximize accuracy (which would require full SVM training inside the objective). Instead, it maximizes kernel alignment, i.e., it encourages:
- if two training points share the same label, they should have a larger kernel value;
- if labels differ, kernel values should be smaller.
That’s why the objective can be optimized without embedding the full classifier training in the loop.
Then the fault penalty is the practical twist: it biases the kernel family toward parameter settings less sensitive to the known broken qubit.
Connecting to hybrid and fault-tolerant ideas (without pretending it’s fault tolerance)
This experiment isn’t full fault-tolerant quantum computing. It’s a hybrid approach in the sense that:
- the “quantum part” generates a kernel via circuit sampling,
- the “classical part” trains parameters and fits an SVM.
And it mirrors a real fault-tolerant mindset: don’t just hope the device behaves—structure the model to tolerate the device’s specific failure modes.
Conclusion
I built an adaptive quantum kernel that learns under systematic readout error on a single qubit by using a fault-gated feature map trained via kernel alignment with a penalty that discourages reliance on the faulty qubit. The key lesson from my tinkering was that kernel methods are highly sensitive to which parts of the circuit drive the overlap measurement—so explicitly biasing the trainable circuit toward the non-faulty degrees of freedom can significantly stabilize downstream classification when one qubit is consistently unreliable.