다중 로지스틱 회귀 및 One-vs-Rest 로지스틱 회귀 시각화

Beginner

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

소개

로지스틱 회귀는 이진 및 다중 클래스 분류 문제에 사용할 수 있는 분류 알고리즘입니다. 이 실습에서는 scikit-learn 라이브러리를 사용하여 다항 로지스틱 회귀와 일대다 로지스틱 회귀라는 두 가지 로지스틱 회귀 모델의 결정 경계를 시각화합니다. 3 개의 클래스로 구성된 데이터셋을 사용하여 두 모델의 결정 경계를 시각화하고 성능을 비교합니다.

VM 팁

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

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

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

라이브러리 가져오기

이 실습에서는 필요한 라이브러리를 가져오는 것으로 시작합니다. scikit-learn 라이브러리를 사용하여 데이터셋을 생성하고 로지스틱 회귀 모델을 학습하며, matplotlib 라이브러리를 사용하여 결정 경계를 시각화합니다.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.linear_model import LogisticRegression
from sklearn.inspection import DecisionBoundaryDisplay

데이터셋 생성

scikit-learn 의 make_blobs 함수를 사용하여 3 개의 클래스로 구성된 데이터셋을 생성합니다. 샘플 수는 1000 개이며, 클러스터 중심은 [-5, 0], [0, 1.5], [5, -1]로 설정합니다. 그런 다음 변환 행렬을 사용하여 데이터셋을 변환하여 분류하기 더 어렵게 만듭니다.

centers = [[-5, 0], [0, 1.5], [5, -1]]
X, y = make_blobs(n_samples=1000, centers=centers, random_state=40)
transformation = [[0.4, 0.2], [-0.4, 1.2]]
X = np.dot(X, transformation)

다항 로지스틱 회귀 모델 학습

이제 scikit-learn 의 LogisticRegression 함수를 사용하여 다항 로지스틱 회귀 모델을 학습합니다. solver 를 "sag"로, 최대 반복 횟수를 100 으로, random state 를 42 로, multi-class 옵션을 "multinomial"로 설정합니다. 그런 다음 모델의 학습 점수를 출력합니다.

clf = LogisticRegression(
        solver="sag", max_iter=100, random_state=42, multi_class="multinomial"
    ).fit(X, y)

print("training score : %.3f (%s)" % (clf.score(X, y), "multinomial"))

다항 로지스틱 회귀 모델의 결정 경계 시각화

이제 scikit-learn 의 DecisionBoundaryDisplay 함수를 사용하여 다항 로지스틱 회귀 모델의 결정 경계를 시각화합니다. response 메서드를 "predict"로, 컬러맵을 "plt.cm.Paired"로 설정하고, 학습 데이터 포인트도 함께 플롯합니다.

_, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(
        clf, X, response_method="predict", cmap=plt.cm.Paired, ax=ax
    )
plt.title("LogisticRegression (multinomial) 의 결정 경계")
plt.axis("tight")

colors = "bry"
for i, color in zip(clf.classes_, colors):
        idx = np.where(y == i)
        plt.scatter(
            X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired, edgecolor="black", s=20
        )

One-vs-Rest 로지스틱 회귀 모델 학습

이제 3 단계와 동일한 매개변수를 사용하여, multi-class 옵션을 "ovr"로 설정한 One-vs-Rest 로지스틱 회귀 모델을 학습합니다. 그런 다음 모델의 학습 점수를 출력합니다.

clf = LogisticRegression(
        solver="sag", max_iter=100, random_state=42, multi_class="ovr"
    ).fit(X, y)

print("training score : %.3f (%s)" % (clf.score(X, y), "ovr"))

One-vs-Rest 로지스틱 회귀 모델의 결정 경계 시각화

이제 4 단계와 동일한 매개변수를 사용하여 one-vs-rest 로지스틱 회귀 모델의 결정 경계를 시각화합니다. 하지만 세 개의 one-vs-rest 분류기의 초평면을 점선으로 플롯합니다.

_, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(
        clf, X, response_method="predict", cmap=plt.cm.Paired, ax=ax
    )
plt.title("LogisticRegression (ovr) 의 결정 경계")
plt.axis("tight")

colors = "bry"
for i, color in zip(clf.classes_, colors):
        idx = np.where(y == i)
        plt.scatter(
            X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired, edgecolor="black", s=20
        )

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.subplot(1,2,1)
_, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(
        clf, X, response_method="predict", cmap=plt.cm.Paired, ax=ax
    )
plt.title("다중 로지스틱 회귀")
plt.axis("tight")

colors = "bry"
for i, color in zip(clf.classes_, colors):
        idx = np.where(y == i)
        plt.scatter(
            X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired, edgecolor="black", s=20
        )

plt.subplot(1,2,2)
_, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(
        clf, X, response_method="predict", cmap=plt.cm.Paired, ax=ax
    )
plt.title("One-vs-Rest 로지스틱 회귀")
plt.axis("tight")

colors = "bry"
for i, color in zip(clf.classes_, colors):
        idx = np.where(y == i)
        plt.scatter(
            X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired, edgecolor="black", s=20
        )

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.subplots_adjust(wspace=0.5)
plt.show()

요약

이 실습에서는 다중 로지스틱 회귀와 One-vs-Rest 로지스틱 회귀라는 두 가지 로지스틱 회귀 모델의 결정 경계를 시각화하는 방법을 배웠습니다. 3 개의 클래스로 구성된 데이터셋을 사용하여 두 모델의 성능을 비교하고, 각 모델의 결정 경계를 시각화했습니다. 결과적으로 다중 로지스틱 회귀 모델은 더 매끄러운 결정 경계를 보였고, One-vs-Rest 로지스틱 회귀 모델은 각 클래스마다 분리된 세 개의 결정 경계를 가졌습니다.