분류 확률 시각화

Beginner

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

소개

이 실험은 Python Scikit-learn 을 사용하여 다양한 분류기의 분류 확률을 플롯하는 방법을 보여줍니다. 3 개의 클래스 데이터셋을 사용하고, 서포트 벡터 분류기, L1 및 L2 페널티가 적용된 로지스틱 회귀 (One-Vs-Rest 또는 다항 설정 포함), 그리고 가우시안 프로세스 분류를 사용하여 분류합니다.

VM 팁

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

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

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

필요한 라이브러리 가져오기

실험을 시작하기 위해 필요한 라이브러리를 가져옵니다.

import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn import datasets

데이터셋 로드

다음으로, Scikit-learn 에서 아이리스 (iris) 데이터셋을 로드합니다.

iris = datasets.load_iris()
X = iris.data[:, 0:2]  ## 시각화를 위해 처음 두 개의 특징만 사용
y = iris.target
n_features = X.shape[1]

분류기 정의

데이터셋에 대한 여러 분류기를 정의합니다.

C = 10
kernel = 1.0 * RBF([1.0, 1.0])  ## GPC 를 위한 커널

## 서로 다른 분류기를 만듭니다.
classifiers = {
    "L1 로지스틱 회귀": LogisticRegression(
        C=C, penalty="l1", solver="saga", multi_class="multinomial", max_iter=10000
    ),
    "L2 로지스틱 회귀 (다항 분류)": LogisticRegression(
        C=C, penalty="l2", solver="saga", multi_class="multinomial", max_iter=10000
    ),
    "L2 로지스틱 회귀 (OvR)": LogisticRegression(
        C=C, penalty="l2", solver="saga", multi_class="ovr", max_iter=10000
    ),
    "선형 SVC": SVC(kernel="linear", C=C, probability=True, random_state=0),
    "GPC": GaussianProcessClassifier(kernel),
}

분류 확률 시각화

각 분류기의 분류 확률을 시각화합니다.

n_classifiers = len(classifiers)

plt.figure(figsize=(3 * 2, n_classifiers * 2))
plt.subplots_adjust(bottom=0.2, top=0.95)

xx = np.linspace(3, 9, 100)
yy = np.linspace(1, 5, 100).T
xx, yy = np.meshgrid(xx, yy)
Xfull = np.c_[xx.ravel(), yy.ravel()]

for index, (name, classifier) in enumerate(classifiers.items()):
    classifier.fit(X, y)

    y_pred = classifier.predict(X)
    accuracy = accuracy_score(y, y_pred)
    print("Accuracy (train) for %s: %0.1f%% " % (name, accuracy * 100))

    ## 확률 보기:
    probas = classifier.predict_proba(Xfull)
    n_classes = np.unique(y_pred).size
    for k in range(n_classes):
        plt.subplot(n_classifiers, n_classes, index * n_classes + k + 1)
        plt.title("Class %d" % k)
        if k == 0:
            plt.ylabel(name)
        imshow_handle = plt.imshow(
            probas[:, k].reshape((100, 100)), extent=(3, 9, 1, 5), origin="lower"
        )
        plt.xticks(())
        plt.yticks(())
        idx = y_pred == k
        if idx.any():
            plt.scatter(X[idx, 0], X[idx, 1], marker="o", c="w", edgecolor="k")

ax = plt.axes([0.15, 0.04, 0.7, 0.05])
plt.title("확률")
plt.colorbar(imshow_handle, cax=ax, orientation="horizontal")

plt.show()

요약

이 실험에서는 Python Scikit-learn 을 사용하여 다양한 분류기의 분류 확률을 플롯하는 방법을 보여주었습니다. 우리는 아이리스 데이터셋을 로드하고, 서로 다른 분류기를 정의했으며, 각 분류기의 분류 확률을 시각화했습니다.