iTranslated by AI
Experimenting with Quantum Kernel SVM — Blueqat
Purpose
This article aims to implement the content of Playing with Quantum Kernel SVM — Qiskit using Blueqat as well.
Dataset
It is the same every time, but I want to use the following dataset as I did previously.

As before, assume that the training set (train_data, train_labels) and the test set (test_data, test_labels) are prepared as follows.
from sklearn.datasets import make_circles
X, Y = make_circles(n_samples=200, noise=0.05, factor=0.4)
A = X[np.where(Y==0)]
B = X[np.where(Y==1)]
A_label = np.zeros(A.shape[0], dtype=int)
B_label = np.ones(B.shape[0], dtype=int)
def make_train_test_sets(test_ratio=.3):
def split(arr, test_ratio):
sep = int(arr.shape[0]*(1-test_ratio))
return arr[:sep], arr[sep:]
A_label = np.zeros(A.shape[0], dtype=int)
B_label = np.ones(B.shape[0], dtype=int)
A_train, A_test = split(A, test_ratio)
B_train, B_test = split(B, test_ratio)
A_train_label, A_test_label = split(A_label, test_ratio)
B_train_label, B_test_label = split(B_label, test_ratio)
X_train = np.concatenate([A_train, B_train])
y_train = np.concatenate([A_train_label, B_train_label])
X_test = np.concatenate([A_test, B_test])
y_test = np.concatenate([A_test_label, B_test_label])
return X_train, y_train, X_test, y_test
train_data, train_labels, test_data, test_labels = make_train_test_sets()
What I want to do this time
I need to independently implement the parts that were previously handled by Qiskit. Specifically, this involves the following two points:
- Implement Qiskit's ZZFeatureMap in Blueqat.
- Implement
calculate_kernel, which computes a custom kernel, in Blueqat.
Implementing ZZFeatureMap in Blueqat
In short, we just need to implement the following circuit:

It can be implemented straightforwardly, but for comparison, I will keep the interface close to the Qiskit version. Since the .bind_parameters() found in Qiskit, I decided to receive the data as a list via the argument x and immediately embed it into the circuit using phase encoding.
from blueqat import Circuit
def zz_feature_map(x, reps):
def sub_circuit(x):
n_qubit = len(x)
c = Circuit().h[:]
for i in range(n_qubit):
c.rz(2*x[i])[i]
for i in range(n_qubit - 1):
for j in range(i+1, n_qubit):
c.cx[i, j].rz(2*(np.pi-x[i])*(np.pi-x[j]))[j].cx[i, j]
return c
c = Circuit()
for _ in range(reps):
c += sub_circuit(x)
return c
This time, I want to handle it with reps=2 as I did in the Qiskit version, so I'll use partial application to bind the parameter in advance:
from functools import partial
feature_map = partial(zz_feature_map, reps=2)
Implementing calculate_kernel for Custom Kernels in Blueqat
Let's review. We will denote the quantum circuit part using zz_feature_map as
The matrix with these elements as
This can also be implemented straightforwardly, similar to what was done with Qiskit. Ideally, the state vector resulting from numpy backend.
def calculate_kernel(feature_map, x_data, y_data=None):
if y_data is None:
y_data = x_data
x_matrix, y_matrix = [], []
for x0, x1 in x_data:
c = feature_map([x0, x1])
sv = c.run(backend='numpy')
x_matrix.append(sv)
for y0, y1 in y_data:
c = feature_map([y0, y1])
sv = c.run(backend='numpy')
y_matrix.append(sv)
x_matrix, y_matrix = np.array(x_matrix), np.array(y_matrix)
kernel = np.abs(
y_matrix.conjugate() @ x_matrix.transpose()
)**2
return kernel
Computing the Kernel and Training
Using the train_data from the beginning, we compute the custom kernel with calculate_kernel and train the model.
from sklearn.svm import SVC
train_kernel = calculate_kernel(feature_map, train_data)
model = SVC(kernel='precomputed')
model.fit(train_kernel, train_labels)
Verification
We will also compute the test kernel and visualize the label estimation results.
import matplotlib
test_kernel = calculate_kernel(feature_map, train_data, test_data)
pred = model.predict(test_kernel)
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111)
ax.set_aspect('equal')
ax.set_title("Predicted data classification")
ax.set_ylim(-2, 2)
ax.set_xlim(-2, 2)
for (x, y), pred_label in zip(test_data, pred):
c = 'C0' if pred_label == 0 else 'C3'
ax.add_patch(matplotlib.patches.Circle((x, y), radius=.01,
fill=True, linestyle='solid', linewidth=4.0,
color=c))
plt.grid()
plt.show()

The results look generally good this time as well. Let's check the score just in case.
model.score(test_kernel, test_labels)
1.0
Summary
I tried performing Quantum Kernel SVM using Blueqat as well. Since I used the library-implemented ZZFeatureMap in Qiskit, I had a feeling that "maybe something incredible is happening inside...". However, implementing the circuit manually exactly as described in the paper and getting the same results makes me think, "Oh, that's it." While the term "Quantum Kernel SVM" sounds impressive, I understood that it's simply a matter of using the quantum circuits that predecessors have identified as good feature maps to execute a custom kernel version of the kernel SVM.
Other conclusions are the same as Playing with Quantum Kernel SVM — Qiskit#Summary, so I will omit them. It's always good to implement and verify things yourself until you're satisfied.
References
- [QSVM] Quantum feature maps and kernels, Qiskit Textbook
- [H-C-T-H-K-C-G] Vojtech Havlicek, Antonio D. Córcoles, Kristan Temme, Aram W. Harrow, Abhinav Kandala, Jerry M. Chow, Jay M. Gambetta, Supervised learning with quantum enhanced feature spaces, arXiv, 2018
- [QGSS2021] Kristan Temme, Quantum Feature Spaces and Kernels, Qiskit Global Summer School 2021
- [S-P] Maria Schuld, Francesco Petruccione, Machine Learning with Quantum Computers, Kyoritsu Shuppan, 2020
- [S-K] Maria Schuld, Nathan Killoran, Quantum machine learning in feature Hilbert spaces, arXiv, 2018
- [S-B-S-W] Maria Schuld, Alex Bocharov, Krysta Svore, Nathan Wiebe, Circuit-centric quantum classifiers, arXiv, 2018
- [T-C-C-G] Francesco Tacchino, Alessandro Chiesa, Stefano Carretta, Dario Gerace Quantum computers as universal quantum simulators: state-of-art and perspectives, arXiv, 2019
- [PRML] C. M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006
- [PML] S. Raschka, Python Machine Learning, Impress, 2020
- [Kernel Methods] Kenji Fukumizu, Introduction to Kernel Methods, Asakura Shoten, 2010
- [sklearn.svm.SVC] sklearn.svm.SVC
Discussion