简介
本实验演示了如何使用标签传播(Label Spreading)算法进行半监督学习。我们将使用手写数字数据集的一个子集,其中只有 40 个样本会被标注。然后,我们将使用标签传播来预测其余 300 个样本。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”(Notebook)标签页,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,可以随时向 Labby 提问。课程结束后请提供反馈,我们会及时为你解决问题。
加载并打乱数据
我们首先加载数字数据集并随机打乱数据。
digits = datasets.load_digits()
rng = np.random.RandomState(2)
indices = np.arange(len(digits.data))
rng.shuffle(indices)
为半监督学习准备数据
我们选择 340 个样本,其中只有 40 个样本与已知标签相关联。我们存储另外 300 个样本的索引,这些样本的标签我们不应该知道。然后我们打乱标签,以便未标记的样本标记为 -1。
X = digits.data[indices[:340]]
y = digits.target[indices[:340]]
n_total_samples = len(y)
n_labeled_points = 40
indices = np.arange(n_total_samples)
unlabeled_set = indices[n_labeled_points:]
y_train = np.copy(y)
y_train[unlabeled_set] = -1
训练标签传播模型
我们使用 gamma=0.25 和 max_iter=20 来训练标签传播(Label Spreading)模型。
lp_model = LabelSpreading(gamma=0.25, max_iter=20)
lp_model.fit(X, y_train)
评估模型性能
我们通过生成分类报告和混淆矩阵来评估模型的性能。
predicted_labels = lp_model.transduction_[unlabeled_set]
true_labels = y[unlabeled_set]
print(
"Label Spreading model: %d labeled & %d unlabeled points (%d total)"
% (n_labeled_points, n_total_samples - n_labeled_points, n_total_samples)
)
print(classification_report(true_labels, predicted_labels))
ConfusionMatrixDisplay.from_predictions(
true_labels, predicted_labels, labels=lp_model.classes_
)
绘制最不确定的预测结果
我们挑选并展示前 10 个最不确定的预测结果。
pred_entropies = stats.distributions.entropy(lp_model.label_distributions_.T)
uncertainty_index = np.argsort(pred_entropies)[-10:]
f = plt.figure(figsize=(7, 5))
for index, image_index in enumerate(uncertainty_index):
image = images[image_index]
sub = f.add_subplot(2, 5, index + 1)
sub.imshow(image, cmap=plt.cm.gray_r)
plt.xticks([])
plt.yticks([])
sub.set_title(
"predict: %i\ntrue: %i" % (lp_model.transduction_[image_index], y[image_index])
)
f.suptitle("Learning with small amount of labeled data")
plt.show()
总结
在本实验中,我们展示了如何使用标签传播(Label Spreading)算法进行半监督学习。我们使用少量带标签的数据训练模型,并使用它来预测其余样本的标签。该模型表现良好,正确预测了大多数样本的标签。