टिप्पणी
यह पृष्ठ docs/tutorials/03_quantum_kernel.ipynb से उत्पन्न किया गया है।
प्रमात्रा कर्नेल मशीन लर्निंग¶
आम तौर पर मशीन-लर्निंग का कार्य डेटा में पैटर्न खोजने और अध्ययन करना है, कई डेटासेट के लिए कर्नेल फंक्शन के उपयोग के माध्यम से डेटापॉइंट को उच्च आयामी फीचर स्पेस में बेहतर ढंग से समझा जाता है : \(k(\vec{x}_i, \vec{x}_j) = \langle f(\vec{x}_i), f(\vec{x}_j) \rangle\) जहाँ \(k\) कर्नेल फंक्शन है, \(\vec{x}_i, \vec{x}_j\) are \(n\) आयामी इनपुट, \(f\) एक \(n\)-आयाम से \(m\)-आयाम स्थान का मैप है और \(\langle a,b \rangle\) डॉट उत्पाद को दर्शाता है. परिमित डेटा पर विचार करते समय, कर्नेल फ़ंक्शन को मैट्रिक्स के रूप में दर्शाया जा सकता है: \(K_{ij} = k(\vec{x}_i,\vec{x}_j)\).
क्वांटम कर्नेल मशीन लर्निंग में, एक क्वांटम फीचर मैप \(\phi(\vec{x})\) का उपयोग एक शास्त्रीय फीचर \(\vec{x}\) को क्वांटम एक हिल्बर्ट स्थान \(| \phi(\vec{x})\rangle \langle \phi(\vec{x})|\),में मैप करने के लिए उपयोग किया जाता है जिससे हमें \(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, और scikit-learn
support vector machine वर्गीकरण (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()

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
एल्गोरिथम प्रदान करने से पहले प्रशिक्षण और परीक्षण कर्नेल matrices को प्रीकंप्यूट करता है और प्लॉट करता है:
[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}")

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, और scikit-learn` spectral
गुच्छन कलन विधि में वर्णित है।
We will regenerate the dataset with a larger gap between the two classes, and as clustering is an unsupervised machine learning task, we don’t need a test sample.
[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()

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 स्पेक्ट्रल क्लस्टरिंग एल्गोरिथम को प्रदान करने से पहले कर्नेल मैट्रिस को प्रीकंप्यूट और प्लॉट करता है, और सामान्यीकृत पारस्परिक जानकारी का उपयोग करके लेबल को स्कोर करता है, क्योंकि हम एक प्राथमिकता वर्ग लेबल जानते हैं।
[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}")

Clustering score: 0.7287008798015754
scikit-learn
के अन्य एल्गोरिथ्म हैं जो पूर्वगणना कर्नेल मैट्रिक्स का उपयोग कर सकते हैं, यहाँ कुछ हैं:
क्लस्टरिंग ढेर <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html>`__
सहयोग वैक्टर प्रतिगमन <https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html>`__
चोटी प्रतिगमन <https://scikit-learn.org/stable/modules/generated/sklearn.kernel_ridge.KernelRidge.html>`__
प्रमुख घटक विश्लेषण <https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.KernelPCA.html>`__
[10]:
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
Version Information
Qiskit Software | Version |
---|---|
qiskit-terra | 0.22.0 |
qiskit-aer | 0.11.0 |
qiskit-ignis | 0.7.0 |
qiskit | 0.33.0 |
qiskit-machine-learning | 0.5.0 |
System information | |
Python version | 3.7.9 |
Python compiler | MSC v.1916 64 bit (AMD64) |
Python build | default, Aug 31 2020 17:10:11 |
OS | Windows |
CPUs | 4 |
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.