Scikit-Learnの多クラスSGD分類器

Machine LearningMachine LearningBeginner
今すぐ練習

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

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

はじめに

この実験では、Scikit-LearnのSGDClassifierを使って、有名なアイリスデータセットに対する多クラス分類モデルを実装します。データセット上のモデルの決定面をプロットし、3つのone-versus-all(OVA)分類器に対応するハイパープレーンを可視化します。

VMのヒント

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

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

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) sklearn(("Sklearn")) -.-> sklearn/ModelSelectionandEvaluationGroup(["Model Selection and Evaluation"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/linear_model("Linear Models") sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/inspection("Inspection") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/linear_model -.-> lab-49288{{"Scikit-Learnの多クラスSGD分類器"}} sklearn/inspection -.-> lab-49288{{"Scikit-Learnの多クラスSGD分類器"}} ml/sklearn -.-> lab-49288{{"Scikit-Learnの多クラスSGD分類器"}} end

データの読み込みと準備

必要なライブラリをインポートし、アイリスデータセットを読み込んで始めます。その後、データをシャッフルし、訓練に使用するために標準化します。

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.linear_model import SGDClassifier

## アイリスデータセットを読み込む
iris = datasets.load_iris()

## 最初の2つの特徴量を取得する
X = iris.data[:, :2]
y = iris.target
colors = "bry"

## データをシャッフルする
idx = np.arange(X.shape[0])
np.random.seed(13)
np.random.shuffle(idx)
X = X[idx]
y = y[idx]

## データを標準化する
mean = X.mean(axis=0)
std = X.std(axis=0)
X = (X - mean) / std

モデルの訓練

ここでは、fit()メソッドを使ってアイリスデータセット上でSGDClassifierモデルを訓練します。このメソッドは、入力データとターゲット値を入力として受け取り、与えられたデータでモデルを訓練します。

clf = SGDClassifier(alpha=0.001, max_iter=100).fit(X, y)

決定面を可視化する

ここでは、訓練済みモデルの決定面をアイリスデータセット上にプロットします。モデルの決定境界を可視化するために、DecisionBoundaryDisplayクラスを使用します。

from sklearn.inspection import DecisionBoundaryDisplay

ax = plt.gca()
DecisionBoundaryDisplay.from_estimator(
    clf,
    X,
    cmap=plt.cm.Paired,
    ax=ax,
    response_method="predict",
    xlabel=iris.feature_names[0],
    ylabel=iris.feature_names[1],
)
plt.axis("tight")

訓練ポイントをプロットする

ここでは、決定面上に訓練ポイントをプロットします。異なるターゲット値に対して異なる色で訓練ポイントをプロットするために、scatter()メソッドを使用します。

for i, color in zip(clf.classes_, colors):
    idx = np.where(y == i)
    plt.scatter(
        X[idx, 0],
        X[idx, 1],
        c=color,
        label=iris.target_names[i],
        cmap=plt.cm.Paired,
        edgecolor="black",
        s=20,
    )
plt.title("Decision surface of multi-class SGD")
plt.axis("tight")

全対一(OVA)分類器をプロットする

ここでは、決定面上に3つの全対一(OVA)分類器をプロットします。訓練済みモデルのcoefおよびintercept属性を使用して、OVA分類器に対応する超平面をプロットします。

xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()
coef = clf.coef_
intercept = clf.intercept_


def plot_hyperplane(c, color):
    def line(x0):
        return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1]

    plt.plot([xmin, xmax], [line(xmin), line(xmax)], ls="--", color=color)


for i, color in zip(clf.classes_, colors):
    plot_hyperplane(i, color)
plt.legend()
plt.show()

まとめ

この実験では、Scikit-LearnのSGDClassifierを使ってアイリスデータセット上で多クラス分類モデルを実装する方法を学びました。訓練済みモデルの決定面をデータセット上に可視化し、3つの全対一(OVA)分類器に対応する超平面をプロットしました。