VotingClassifier を用いたクラス確率

Beginner

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

はじめに

この実験では、Scikit-Learn の VotingClassifier によって計算されるクラス確率をプロットする方法を学びます。LogisticRegression、GaussianNB、RandomForestClassifier を含む 3 つの異なる分類器を使用し、VotingClassifier を使ってそれらの予測確率を平均化します。その後、各分類器を訓練セットにフィットさせることで確率の重み付けを可視化し、データセットの最初のサンプルの予測クラス確率をプロットします。

VM のヒント

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

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

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

分類器とデータセットの初期化

まず、3 つの分類器と玩具データセットを初期化します。分類器として LogisticRegression、GaussianNB、RandomForestClassifier を使用し、玩具データセットとして X と y を使用します。

import numpy as np
import matplotlib.pyplot as plt

from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier

clf1 = LogisticRegression(max_iter=1000, random_state=123)
clf2 = RandomForestClassifier(n_estimators=100, random_state=123)
clf3 = GaussianNB()
X = np.array([[-1.0, -1.0], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]])
y = np.array([1, 1, 2, 2])

VotingClassifier の初期化

次に、重み付け [1, 1, 5] を持つソフト投票の VotingClassifier を初期化します。これは、平均確率を計算する際に、RandomForestClassifier の予測確率が他の分類器の重みの 5 倍の重みを持つことを意味します。

eclf = VotingClassifier(
    estimators=[("lr", clf1), ("rf", clf2), ("gnb", clf3)],
    voting="soft",
    weights=[1, 1, 5],
)

すべての分類器に対するクラス確率の予測

predict_proba() 関数を使用して、すべての分類器に対するクラス確率を予測します。

probas = [c.fit(X, y).predict_proba(X) for c in (clf1, clf2, clf3, eclf)]

データセットの最初のサンプルに対するクラス確率の取得

データセットの最初のサンプルに対するクラス確率を取得し、class1_1 と class2_1 に格納します。

class1_1 = [pr[0, 0] for pr in probas]
class2_1 = [pr[0, 1] for pr in probas]

クラス確率のプロット

棒グラフを使って、各分類器と VotingClassifier のクラス確率をプロットします。

N = 4  ## グループの数
ind = np.arange(N)  ## グループの位置
width = 0.35  ## 棒の幅

fig, ax = plt.subplots()

## 分類器 1 - 3 用の棒
p1 = ax.bar(ind, np.hstack(([class1_1[:-1], [0]])), width, color="green", edgecolor="k")
p2 = ax.bar(
    ind + width,
    np.hstack(([class2_1[:-1], [0]])),
    width,
    color="lightgreen",
    edgecolor="k",
)

## VotingClassifier 用の棒
p3 = ax.bar(ind, [0, 0, 0, class1_1[-1]], width, color="blue", edgecolor="k")
p4 = ax.bar(
    ind + width, [0, 0, 0, class2_1[-1]], width, color="steelblue", edgecolor="k"
)

## プロットの注釈
plt.axvline(2.8, color="k", linestyle="dashed")
ax.set_xticks(ind + width)
ax.set_xticklabels(
    [
        "LogisticRegression\nweight 1",
        "GaussianNB\nweight 1",
        "RandomForestClassifier\nweight 5",
        "VotingClassifier\n(average probabilities)",
    ],
    rotation=40,
    ha="right",
)
plt.ylim([0, 1])
plt.title("Class probabilities for sample 1 by different classifiers")
plt.legend([p1[0], p2[0]], ["class 1", "class 2"], loc="upper left")
plt.tight_layout()
plt.show()

まとめ

この実験では、Scikit-Learn の VotingClassifier によって計算されたクラス確率をプロットする方法を学びました。LogisticRegression、GaussianNB、RandomForestClassifier を含む 3 つの異なる分類器を使用し、VotingClassifier を使ってそれらの予測確率を平均化しました。そして、各分類器を訓練セットにフィットさせることで確率の重み付けを可視化し、データセットの最初のサンプルに対する予測クラス確率をプロットしました。