VotingClassifier 를 이용한 클래스 확률 시각화

Beginner

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

소개

이 실습에서는 Scikit-Learn 의 VotingClassifier 가 계산한 클래스 확률을 시각화하는 방법을 배웁니다. LogisticRegression, GaussianNB, 그리고 RandomForestClassifier 를 포함한 세 가지 다른 분류기를 사용하고, VotingClassifier 를 통해 예측된 확률을 평균화합니다. 그런 다음 각 분류기를 학습 데이터 세트에 맞추고 데이터 세트의 첫 번째 샘플에 대한 예측된 클래스 확률을 플롯하여 확률 가중치를 시각화합니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근합니다.

때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.

학습 중 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.

분류기 및 데이터셋 초기화

먼저 세 가지 분류기와 하나의 예제 데이터셋을 초기화합니다. 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\n가중치 1",
        "GaussianNB\n가중치 1",
        "RandomForestClassifier\n가중치 5",
        "VotingClassifier\n(평균 확률)",
    ],
    rotation=40,
    ha="right",
)
plt.ylim([0, 1])
plt.title("다양한 분류기의 샘플 1 에 대한 클래스 확률")
plt.legend([p1[0], p2[0]], ["클래스 1", "클래스 2"], loc="upper left")
plt.tight_layout()
plt.show()

요약

이 실습에서는 Scikit-Learn 의 VotingClassifier 가 계산한 클래스 확률을 시각화하는 방법을 배웠습니다. LogisticRegression, GaussianNB, RandomForestClassifier 등 세 가지 다른 분류기를 사용하고, VotingClassifier 를 통해 예측된 확률을 평균화했습니다. 그런 다음 각 분류기를 학습 데이터 세트에 맞추고 데이터 세트의 첫 번째 샘플에 대한 예측된 클래스 확률을 플롯하여 확률 가중치를 시각화했습니다.