マルチラベルドキュメント分類

Beginner

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

はじめに

この実験では、scikit-learn を使ってマルチラベルドキュメント分類問題を示します。データセットは、次のプロセスに基づいてランダムに生成されます。

  • ラベルの数を選ぶ:n ~ ポアソン分布 (n_labels)
  • N 回、クラス c を選ぶ:c ~ 多項分布 (theta)
  • ドキュメントの長さを選ぶ:k ~ ポアソン分布 (length)
  • K 回、単語 w を選ぶ:w ~ 多項分布 (theta_c)

このプロセスでは、拒否サンプリングを使って n が 2 以上であり、ドキュメントの長さが決してゼロでないことを保証します。同様に、既に選択されたクラスは拒否されます。2 つのクラスに割り当てられたドキュメントは、2 つの色付きの円で囲まれて描画されます。

VM のヒント

VM の起動が完了した後、左上隅をクリックしてノートブックタブに切り替えて、Jupyter Notebook を使った練習を行います。

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

学習中に問題に遭遇した場合は、Labby にお問い合わせください。セッション終了後にフィードバックを提供してください。そうすれば、迅速に問題を解決します。

ライブラリのインポート

このステップでは、必要なライブラリをインポートします。numpymatplotlibsklearn.datasets からの make_multilabel_classificationsklearn.multiclass からの OneVsRestClassifierSVCsklearn.decomposition からの PCACCA です。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_multilabel_classification
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.cross_decomposition import CCA

プロット関数の定義

このステップでは、plot_hyperplaneplot_subfigure 関数を定義します。plot_hyperplane 関数は分離超平面を取得するために使用され、plot_subfigure 関数はサブプロットを描画するために使用されます。

def plot_hyperplane(clf, min_x, max_x, linestyle, label):
    ## get the separating hyperplane
    w = clf.coef_[0]
    a = -w[0] / w[1]
    xx = np.linspace(min_x - 5, max_x + 5)  ## make sure the line is long enough
    yy = a * xx - (clf.intercept_[0]) / w[1]
    plt.plot(xx, yy, linestyle, label=label)


def plot_subfigure(X, Y, subplot, title, transform):
    if transform == "pca":
        X = PCA(n_components=2).fit_transform(X)
    elif transform == "cca":
        X = CCA(n_components=2).fit(X, Y).transform(X)
    else:
        raise ValueError

    min_x = np.min(X[:, 0])
    max_x = np.max(X[:, 0])

    min_y = np.min(X[:, 1])
    max_y = np.max(X[:, 1])

    classif = OneVsRestClassifier(SVC(kernel="linear"))
    classif.fit(X, Y)

    plt.subplot(2, 2, subplot)
    plt.title(title)

    zero_class = np.where(Y[:, 0])
    one_class = np.where(Y[:, 1])
    plt.scatter(X[:, 0], X[:, 1], s=40, c="gray", edgecolors=(0, 0, 0))
    plt.scatter(
        X[zero_class, 0],
        X[zero_class, 1],
        s=160,
        edgecolors="b",
        facecolors="none",
        linewidths=2,
        label="Class 1",
    )
    plt.scatter(
        X[one_class, 0],
        X[one_class, 1],
        s=80,
        edgecolors="orange",
        facecolors="none",
        linewidths=2,
        label="Class 2",
    )

    plot_hyperplane(
        classif.estimators_[0], min_x, max_x, "k--", "Boundary\nfor class 1"
    )
    plot_hyperplane(
        classif.estimators_[1], min_x, max_x, "k-.", "Boundary\nfor class 2"
    )
    plt.xticks(())
    plt.yticks(())

    plt.xlim(min_x - 0.5 * max_x, max_x + 0.5 * max_x)
    plt.ylim(min_y - 0.5 * max_y, max_y + 0.5 * max_y)
    if subplot == 2:
        plt.xlabel("First principal component")
        plt.ylabel("Second principal component")
        plt.legend(loc="upper left")

データセットの生成

このステップでは、sklearn.datasets からの make_multilabel_classification 関数を使ってデータセットを生成します。

X, Y = make_multilabel_classification(
    n_classes=2, n_labels=1, allow_unlabeled=True, random_state=1
)

サブプロットの描画

このステップでは、plot_subfigure 関数を使ってサブプロットを描画します。

plt.figure(figsize=(8, 6))

plot_subfigure(X, Y, 1, "With unlabeled samples + CCA", "cca")
plot_subfigure(X, Y, 2, "With unlabeled samples + PCA", "pca")

X, Y = make_multilabel_classification(
    n_classes=2, n_labels=1, allow_unlabeled=False, random_state=1
)

plot_subfigure(X, Y, 3, "Without unlabeled samples + CCA", "cca")
plot_subfigure(X, Y, 4, "Without unlabeled samples + PCA", "pca")

plt.subplots_adjust(0.04, 0.02, 0.97, 0.94, 0.09, 0.2)
plt.show()

まとめ

この実験では、scikit-learn を使ってマルチラベルドキュメント分類問題を示しました。データセットの生成には make_multilabel_classification 関数を、サブプロットの描画には plot_subfigure 関数を使用しました。