ラベル拡散による半教師あり学習

Machine LearningMachine LearningBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、ラベル拡散アルゴリズム(Label Spreading algorithm)を使用して半教師あり学習を行う方法を実証します。手書き数字データセットのサブセットを使用し、これらのサンプルのうち 40 個のみにラベルを付けます。その後、ラベル拡散アルゴリズムを使用して残りの 300 個のサンプルを予測します。

VM のヒント

VM の起動が完了したら、左上隅をクリックしてNotebookタブに切り替え、Jupyter Notebook を開いて練習を行ってください。

時には、Jupyter Notebook の読み込みが完了するまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

学習中に問題が発生した場合は、いつでも Labby に質問してください。セッション終了後にフィードバックを提供していただければ、迅速に問題を解決します。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills ml/sklearn -.-> lab-49185{{"ラベル拡散による半教師あり学習"}} end

データの読み込みとシャッフル

まず、数字データセットを読み込み、データをランダムにシャッフルします。

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

ラベル拡散モデル(Label Spreading Model)の訓練

gamma=0.25 と max_iter=20 でラベル拡散モデルを訓練します。

lp_model = LabelSpreading(gamma=0.25, max_iter=20)
lp_model.fit(X, y_train)

モデルの性能評価

分類レポート(classification report)と混同行列(confusion matrix)を生成することで、モデルの性能を評価します。

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 algorithm)を使用して半教師あり学習を行う方法を実証しました。少量のラベル付きデータでモデルを訓練し、残りのサンプルのラベルを予測するために使用しました。モデルは良好な性能を発揮し、ほとんどのサンプルのラベルを正しく予測しました。