Korean
언어
English
Bengali
French
Hindi
Italian
Japanese
Korean
Malayalam
Russian
Spanish
Tamil
Turkish
Vietnamese
Shortcuts

참고

이 페이지는 docs/tutorials/03_quantum_kernel.ipynb 에서 생성되었다.

양자 커널 기계 학습

일반적으로 기계학습은 데이터에서 패턴을 찾고 학습하는 것이다. 많은 양의 데이터에서 데이터 포인트들은 더 높은 차원의 feature space에서 더 잘 이해되는데, 이는 다음과 같은 커널 함수를 사용함으로써 가능해진다: \(k(\vec{x}_i, \vec{x}_j) = \langle f(\vec{x}_i), f(\vec{x}_j) \rangle\) 에서, \(k\) 는 커널 함수, \(\vec{x}_i, \vec{x}_j\)\(n\) 차원의 입력, \(f\)\(n\) 차원으로부터 \(m\) 차원 공간으로의 맵, 그리고 \(\langle a,b \rangle\) 는 내적을 의미한다. 유한한 데이터를 고려할 때, 커널 함수는 다음과 같은 행렬로서 표현될 수 있다: \(K_{ij} = k(\vec{x}_i,\vec{x}_j)\)

양자 커널 기계학습에서, 양자 feature map \(\phi(\vec{x})\) 은 고전적인 특징 벡터 \(\vec{x}\) 를 양자 힐베르트 공간 \(| \phi(\vec{x})\rangle \langle \phi(\vec{x})|\) 으로 mapping하는데 쓰일 수 있는데, 예를 들면 \(K_{ij} = \left| \langle \phi^\dagger(\vec{x}_j)| \phi(\vec{x}_i) \rangle \right|^{2}\) 와 같다. 더 자세한 사항은 Supervised learning with quantum enhanced feature spaces 을 참조하라.

이 노트북 예제에서는 양자 특성 맵을 사용하여 커널 행렬을 계산하기 위해 qiskit 을 사용하였고, scikit-learn 분류 및 군집화 알고리즘에서 앞서 계산한 커널 행렬을 사용한다.

[1]:
import matplotlib.pyplot as plt
import numpy as np

from sklearn.svm import SVC
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score

from qiskit import BasicAer
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.kernels import FidelityQuantumKernel
from qiskit_machine_learning.datasets import ad_hoc_data

seed = 12345
algorithm_globals.random_seed = seed

분류

이 분류 예제에서는 Supervised learning with quantum enhanced feature spaces 에 설명된 바와 같이 ad hoc dataset 을 다시 사용할 것이고, scikit-learn support vector machine classification(svc) 알고리즘을 사용할 것이다.

[2]:
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
    training_size=20,
    test_size=5,
    n=adhoc_dimension,
    gap=0.3,
    plot_data=False,
    one_hot=False,
    include_sample_total=True,
)

plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
    np.asmatrix(adhoc_total).T,
    interpolation="nearest",
    origin="lower",
    cmap="RdBu",
    extent=[0, 2 * np.pi, 0, 2 * np.pi],
)

plt.scatter(
    train_features[np.where(train_labels[:] == 0), 0],
    train_features[np.where(train_labels[:] == 0), 1],
    marker="s",
    facecolors="w",
    edgecolors="b",
    label="A train",
)
plt.scatter(
    train_features[np.where(train_labels[:] == 1), 0],
    train_features[np.where(train_labels[:] == 1), 1],
    marker="o",
    facecolors="w",
    edgecolors="r",
    label="B train",
)
plt.scatter(
    test_features[np.where(test_labels[:] == 0), 0],
    test_features[np.where(test_labels[:] == 0), 1],
    marker="s",
    facecolors="b",
    edgecolors="w",
    label="A test",
)
plt.scatter(
    test_features[np.where(test_labels[:] == 1), 0],
    test_features[np.where(test_labels[:] == 1), 1],
    marker="o",
    facecolors="r",
    edgecolors="w",
    label="B test",
)

plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for classification")

plt.show()
../_images/tutorials_03_quantum_kernel_3_0.png

With our training and testing datasets ready, we set up the FidelityQuantumKernel class to calculate a kernel matrix using the ZZFeatureMap. We use the reference implementation of the Sampler primitive and the ComputeUncompute fidelity that computes overlaps between states. These are the default values and if you don’t pass a Sampler or Fidelity instance, the same objects will be created automatically for you.

[3]:
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)

The scikit-learn SVC algorithm allows us to define a custom kernel in two ways: by providing the kernel as a callable function or by precomputing the kernel matrix. We can do either of these using the FidelityQuantumKernel class in qiskit.

다음 코드는 커널을 호출 가능한 함수로 제공한다.

[4]:
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score = adhoc_svc.score(test_features, test_labels)

print(f"Callable kernel classification test score: {adhoc_score}")
Callable kernel classification test score: 1.0

다음 코드는 훈련 및 테스트 커널 행렬을 사전 계산하고 플로팅하여 scikit-learn svc 알고리즘에 제공한다.

[5]:
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)

fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
    np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()

adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score = adhoc_svc.score(adhoc_matrix_test, test_labels)

print(f"Precomputed kernel classification test score: {adhoc_score}")
../_images/tutorials_03_quantum_kernel_9_0.png
Precomputed kernel classification test score: 1.0

Qiskit Machine Learning also contains the QSVC class that extends the SVC class from scikit-learn, that can be used as follows:

[6]:
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)

print(f"QSVC classification test score: {qsvc_score}")
QSVC classification test score: 1.0

군집화

우리의 군집화 예제에서는 Supervised learning with quantum enhanced feature spaces 에 설명된 바와 같이 ad hoc dataset 를 다시 사용할 것이고, scikit-learn spectral 군집화 알고리즘을 사용할 것이다.

두 클래스 간에 큰 간격을 두고 데이터셋을 다시 생성하고, 군집화는 비지도학습 머신러닝 태스크이기 때문에 테스트 샘플은 준비하지 않는다.

[7]:
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
    training_size=25,
    test_size=0,
    n=adhoc_dimension,
    gap=0.6,
    plot_data=False,
    one_hot=False,
    include_sample_total=True,
)

plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
    np.asmatrix(adhoc_total).T,
    interpolation="nearest",
    origin="lower",
    cmap="RdBu",
    extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
plt.scatter(
    train_features[np.where(train_labels[:] == 0), 0],
    train_features[np.where(train_labels[:] == 0), 1],
    marker="s",
    facecolors="w",
    edgecolors="b",
    label="A",
)
plt.scatter(
    train_features[np.where(train_labels[:] == 1), 0],
    train_features[np.where(train_labels[:] == 1), 1],
    marker="o",
    facecolors="w",
    edgecolors="r",
    label="B",
)

plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")

plt.show()
../_images/tutorials_03_quantum_kernel_13_0.png

We again set up the FidelityQuantumKernel class to calculate a kernel matrix using the ZZFeatureMap, and the default values this time.

[8]:
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")

adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)

The scikit-learn spectral clustering algorithm allows us to define a custom kernel in two ways: by providing the kernel as a callable function or by precomputing the kernel matrix. Using the FidelityQuantumKernel class in Qiskit Machine Learning, we can only use the latter.

아래의 코드는 커널 행렬을 scikit-learn 스펙트럼 군집 알고리즘 적용전에 커널 행렬을 미리 계산하고 플롯팅한다. 우리는 클래스의 정답 라벨을 알고 있기 때문에 정규화된 상호정보(mutual information)를 사용하여 예측된 라벨을 채점한다.

[9]:
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)

plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()

adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)

print(f"Clustering score: {cluster_score}")
../_images/tutorials_03_quantum_kernel_17_0.png
Clustering score: 0.7287008798015754

scikit-learn 은 미리 계산된 커널 행렬을 사용할 수 있는 다른 알고리즘을 가지고 있는데, 이것들이 그 중 일부이다.

[10]:
import qiskit.tools.jupyter

%qiskit_version_table
%qiskit_copyright

Version Information

Qiskit SoftwareVersion
qiskit-terra0.22.0
qiskit-aer0.11.0
qiskit-ignis0.7.0
qiskit0.33.0
qiskit-machine-learning0.5.0
System information
Python version3.7.9
Python compilerMSC v.1916 64 bit (AMD64)
Python builddefault, Aug 31 2020 17:10:11
OSWindows
CPUs4
Memory (Gb)31.837730407714844
Mon Oct 10 12:01:53 2022 GMT Daylight Time

This code is a part of Qiskit

© Copyright IBM 2017, 2022.

This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.

Any modifications or derivative works of this code must retain this
copyright notice, and modified files need to carry a notice indicating
that they have been altered from the originals.