Hands-on lab · 2 steps
Quantum-kernel SVM on two moons
Build the complete quantum-kernel classifier of the lesson in Python. First implement the fidelity kernel of the two-qubit ZZ feature map with one repetition by simulating its circuit with NumPy; the grader compares your matrices with the platform's statevector engine and checks symmetry and positive semidefiniteness. Then train scikit-learn's SVC(kernel="precomputed", C=1.0) on the training Gram matrix of the two-moons data scaled to and predict the held-out points; the grader computes the test accuracy from your predictions and requires at least (the reference pipeline reaches ).
Step 1: The ZZ feature-map kernel
Write the Python function zz_kernel``(X1, X2) that returns the NumPy array
for the two-qubit ZZ feature map with one repetition,
where the rightmost gate acts first, is the phase gate on qubit and has control and target :
Qubit is the most significant bit of the basis index , so a gate on qubit is np.kron(U, I2) and a gate on qubit is np.kron(I2, V). Use NumPy only (import numpy as np).
Visible test two-by-two: and . Since , ; the reference matrix is
compared entrywise with absolute tolerance .
Hidden tests (the arguments reach your browser, the expected values do not): three pairs of point sets in of sizes , and , each compared with the engine's kernel at tolerance .
Structural tests symmetric-6 and psd-6: for six points , the matrix must satisfy and have smallest eigenvalue at least . Both hold automatically for a correct fidelity kernel; the lesson proves it.
The platform's engine builds the same map with instead of ; the states differ by the global phase and the kernels are identical, so either gate gives full marks.
Step 2: Train and evaluate the quantum-kernel SVM
Write train_and_predict``(X_train, y_train, X_test) that trains a soft-margin support vector machine on the precomputed ZZ kernel and returns the predicted labels of the test points as a NumPy array (or list) of values:
-
zz_kernel(X_train, X_train), the Gram matrix ; -
zz_kernel(X_test, X_train), the matrix whose row holds for all training points; - fit
SVC(kernel="precomputed", C=1.0)fromsklearn.svmon and returnpredicton .
The classifier is with , where scikit-learn internally maps the labels to , solves the dual problem for and fixes from the Karush–Kuhn–Tucker conditions.
Each step runs its own source, so define zz_kernel again in this step (copy your passing function from step 1); the starter shows both signatures.
Data (passed as arguments): the two-moons sample make_moons(n_samples=100, noise=0.1, random_state=0) of scikit-learn, each feature min–max scaled over all rows to ; rows – are X_train, y_train, rows – are X_test.
Hidden test moons: the grader compares your predictions with the true test labels, which never leave the server, and requires a test accuracy of at least , i.e. at least of correct. The reference pipeline reaches .