Scikit-Learn を使ったマルチラベルデータセットの生成

Machine LearningMachine LearningBeginner
今すぐ練習

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

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

はじめに

この実験では、Scikit-Learnライブラリのmake_multilabel_classification関数を使ってマルチラベルデータセットを生成する方法を学びます。この関数は、マルチラベルデータのランダムサンプルを生成します。各サンプルは2つの特徴量のカウントを持ち、それぞれ2つのクラスのそれぞれで異なる分布を持ちます。

VMのヒント

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

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

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/UtilitiesandDatasetsGroup -.-> sklearn/datasets("Datasets") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/datasets -.-> lab-49255{{"Scikit-Learn を使ったマルチラベルデータセットの生成"}} ml/sklearn -.-> lab-49255{{"Scikit-Learn を使ったマルチラベルデータセットの生成"}} end

必要なライブラリをインポートして定数を定義する

まず、必要なライブラリをインポートし、マルチラベルデータセットを生成するための色と乱数シードの定数を定義する必要があります。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_multilabel_classification as make_ml_clf

COLORS = np.array(
    [
        "!",
        "#FF3333",  ## red
        "#0198E1",  ## blue
        "#BF5FFF",  ## purple
        "#FCD116",  ## yellow
        "#FF7216",  ## orange
        "#4DBD33",  ## green
        "#87421F",  ## brown
    ]
)

## Use same random seed for multiple calls to make_multilabel_classification to
## ensure same distributions
RANDOM_SEED = np.random.randint(2**10)

プロット関数を定義する

次に、ランダムに生成されたマルチラベルデータセットをプロットする関数plot_2dを定義します。この関数には、n_labelsn_classeslengthの3つの引数が必要です。

def plot_2d(ax, n_labels=1, n_classes=3, length=50):
    X, Y, p_c, p_w_c = make_ml_clf(
        n_samples=150,
        n_features=2,
        n_classes=n_classes,
        n_labels=n_labels,
        length=length,
        allow_unlabeled=False,
        return_distributions=True,
        random_state=RANDOM_SEED,
    )

    ax.scatter(
        X[:, 0], X[:, 1], color=COLORS.take((Y * [1, 2, 4]).sum(axis=1)), marker="."
    )
    ax.scatter(
        p_w_c[0] * length,
        p_w_c[1] * length,
        marker="*",
        linewidth=0.5,
        edgecolor="black",
        s=20 + 1500 * p_c**2,
        color=COLORS.take([1, 2, 4]),
    )
    ax.set_xlabel("Feature 0 count")
    return p_c, p_w_c

この関数は、指定されたパラメータを使ってmake_multilabel_classification関数を使ってデータセットを生成します。その後、Matplotlibライブラリのscatter関数を使ってデータセットをプロットします。この関数は、クラス確率と特徴確率を返します。

データセットをプロットする

ここでは、plot_2d関数を使ってランダムに生成されたマルチラベルデータセットをプロットします。2つのサブプロットを持つ図を作成し、それぞれのサブプロットに異なるパラメータ値を使ってplot_2d関数を呼び出します。

_, (ax1, ax2) = plt.subplots(1, 2, sharex="row", sharey="row", figsize=(8, 4))
plt.subplots_adjust(bottom=0.15)

p_c, p_w_c = plot_2d(ax1, n_labels=1)
ax1.set_title("n_labels=1, length=50")
ax1.set_ylabel("Feature 1 count")

plot_2d(ax2, n_labels=3)
ax2.set_title("n_labels=3, length=50")
ax2.set_xlim(left=0, auto=True)
ax2.set_ylim(bottom=0, auto=True)

plt.show()

クラスと特徴の確率を表示する

最後に、plot_2d関数が返すクラス確率と特徴確率を使って、各クラスのクラスと特徴の確率を表示します。

print("The data was generated from (random_state=%d):" % RANDOM_SEED)
print("Class", "P(C)", "P(w0|C)", "P(w1|C)", sep="\t")
for k, p, p_w in zip(["red", "blue", "yellow"], p_c, p_w_c.T):
    print("%s\t%0.2f\t%0.2f\t%0.2f" % (k, p, p_w[0], p_w[1]))

まとめ

この実験では、Scikit-Learnライブラリのmake_multilabel_classification関数を使ってマルチラベルデータセットを生成する方法を学びました。また、データセットをプロットし、クラスと特徴の確率を表示する方法も学びました。