IBM Qiskit量子机器学习速成(四)
2023-12-13 08:45:34
量子核机器学习
一般步骤
量子核机器学习的一般步骤如下
定义量子核
我们使用FidelityQuantumKernel类创建量子核,该类需要传入两个参数:特征映射和忠诚度(fidelity)。如果我们不传入忠诚度,该类会自动创建一个忠诚度。
注意各个类所属的模块!
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit_algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
feature_map = ZZFeatureMap(feature_dimension=dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
利用经典支持向量分类器
量子核在经典支持向量分类器中有两种方式:
- 将核本身作为可调用函数
注意:经典模式下传入的是kernel.evaluate
from sklearn.svm import SVC
svc = SVC(kernel=kernel.evaluate)
svc.fit(train_features, train_labels)
score_callable_function = svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {score_callable_function}")
- 提前计算核矩阵
使用kernel.evaluate函数进行核矩阵的计算
matrix_train = kernel.evaluate(x_vec=train_features)
matrix_test = kernel.evaluate(x_vec=test_features, y_vec=train_features)
利用量子支撑向量分类器
注意:量子模式下传入的是kernel本身
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
使用量子核的谱聚类方法
定义量子核方法同前,此处只需要从sklearn中导入SpectralClustering类。
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
matrix = kernel.evaluate(x_vec=train_features)
spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = spectral.fit_predict(matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
实战演练
导入数据集
我们接下来使用一组来自qiskit_machine_learning.datasets的人造随机数据
from qiskit_machine_learning.datasets import ad_hoc_data
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,
)
其中gap描述了两类不同数据间的距离。官网提供了以下函数来可视化这一组数据
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
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],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
运行以下命令查看数据形状
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
随后,和一般步骤完全相同,先定义量子核。
注意此时还没有导入数据!
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit_algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
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)
接下来我们分别介绍经典支撑向量分类器 和量子支撑向量分类器的用法
经典支撑向量分类器
一方面,我们可以直接传入量子核的取值函数
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
另一方面,我们还可以根据已知数据提前计算核矩阵
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
量子支撑向量分类器
直接传入量子核即可
from qiskit_machine_learning.algorithms import QSVC
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}")
文章来源:https://blog.csdn.net/qq_33943772/article/details/134889849
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!