iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐱

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:

  1. Implement Qiskit's ZZFeatureMap in Blueqat.
  2. 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 P gate and R_z gate are the same gate except for the difference in global phase, I used the R_z gate here. Note that since Blueqat does not have a method like .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 \mathcal{U}_{\Phi}(\xi), where \xi represents the data from the dataset. In the n-qubit case,

\begin{align*} k(\xi_j, \xi_i) = \left| \braket{0^n | \mathcal{U}_{\Phi}^\dagger(\xi_j) \mathcal{U}_{\Phi}(\xi_i) |0^n} \right|^2 \tag{1} \end{align*}

The matrix with these elements as (i,j)-components becomes the custom kernel (k(\xi_i, \xi_j))_{1 \leq i,j \leq N}. In this case, n=2.

This can also be implemented straightforwardly, similar to what was done with Qiskit. Ideally, the state vector resulting from \mathcal{U}_{\Phi}(\xi_i) \ket{0^n} should be determined by measurement to find the probability amplitudes, but for simplicity, we use a statevector simulator here as well. To do this, we can use Blueqat's 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

GitHubで編集を提案

Discussion