가우시안 프로세스 분류

Beginner

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

소개

이 실습에서는 파이썬의 scikit-learn 라이브러리에서 Gaussian Process Classification (GPC) 를 사용하는 방법을 보여줍니다. 목표는 GPC 모델을 학습하고 테스트하는 방법, 등확률선을 플롯하는 방법, 그리고 분류 성능을 평가하는 방법을 보여주는 것입니다.

VM 팁

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

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

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

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

먼저 필요한 라이브러리를 가져와야 합니다.

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import DotProduct, ConstantKernel as C

데이터 준비

분류를 위한 합성 데이터를 생성합니다. 분류할 함수는 다음과 같이 정의됩니다.

def g(x):
    """예측할 함수 (분류는 그러면 g(x) <= 0 인지 아닌지 예측하는 것으로 구성됩니다)"""
    return 5.0 - x[:, 1] - 0.5 * x[:, 0] ** 2.0

그런 다음 실험 설계와 관측값을 생성해야 합니다.

## 몇 가지 상수
lim = 8

## 실험 설계
X = np.array(
    [
        [-4.61611719, -6.00099547],
        [4.10469096, 5.32782448],
        [0.00000000, -0.50000000],
        [-6.17289014, -4.6984743],
        [1.3109306, -6.93271427],
        [-5.03823144, 3.10584743],
        [-2.87600388, 6.74310541],
        [5.21301203, 4.26386883],
    ]
)

## 관측값
y = np.array(g(X) > 0, dtype=int)

모델 학습

데이터를 분류하기 위해 GPC 모델을 사용할 것입니다. 먼저 커널 함수를 지정해야 합니다.

kernel = C(0.1, (1e-5, np.inf)) * DotProduct(sigma_0=0.1) ** 2

그런 다음 GPC 모델을 생성하고 데이터를 사용하여 학습시킬 수 있습니다.

gp = GaussianProcessClassifier(kernel=kernel)
gp.fit(X, y)

모델 평가

학습된 GPC 모델의 분류 성능을 평가할 것입니다. 점들의 그리드를 생성하고 학습된 모델을 사용하여 각 점에 대한 예측 확률을 계산할 것입니다.

## 실제 함수와 예측 확률 평가
res = 50
x1, x2 = np.meshgrid(np.linspace(-lim, lim, res), np.linspace(-lim, lim, res))
xx = np.vstack([x1.reshape(x1.size), x2.reshape(x2.size)]).T

y_true = g(xx)
y_prob = gp.predict_proba(xx)[:, 1]
y_true = y_true.reshape((res, res))
y_prob = y_prob.reshape((res, res))

결과 플롯

GPC 모델의 등확률선과 분류 경계를 플롯할 것입니다.

## 확률적 분류 등값선 플롯
fig = plt.figure(1)
ax = fig.gca()
ax.axes.set_aspect("equal")
plt.xticks([])
plt.yticks([])
ax.set_xticklabels([])
ax.set_yticklabels([])
plt.xlabel("$x_1$")
plt.ylabel("$x_2$")

cax = plt.imshow(y_prob, cmap=cm.gray_r, alpha=0.8, extent=(-lim, lim, -lim, lim))
norm = plt.matplotlib.colors.Normalize(vmin=0.0, vmax=0.9)
cb = plt.colorbar(cax, ticks=[0.0, 0.2, 0.4, 0.6, 0.8, 1.0], norm=norm)
cb.set_label(r"${\rm \mathbb{P}}\left[\widehat{G}(\mathbf{x}) \leq 0\right]$")
plt.clim(0, 1)

plt.plot(X[y <= 0, 0], X[y <= 0, 1], "r.", markersize=12)

plt.plot(X[y > 0, 0], X[y > 0, 1], "b.", markersize=12)

plt.contour(x1, x2, y_true, [0.0], colors="k", linestyles="dashdot")

cs = plt.contour(x1, x2, y_prob, [0.666], colors="b", linestyles="solid")
plt.clabel(cs, fontsize=11)

cs = plt.contour(x1, x2, y_prob, [0.5], colors="k", linestyles="dashed")
plt.clabel(cs, fontsize=11)

cs = plt.contour(x1, x2, y_prob, [0.334], colors="r", linestyles="solid")
plt.clabel(cs, fontsize=11)

plt.show()

요약

이 실험에서 파이썬의 scikit-learn 라이브러리에서 가우시안 프로세스 분류 (GPC) 를 사용하는 방법을 배웠습니다. GPC 모델을 학습하고 테스트하는 방법, 등확률선을 플롯하는 방법, 그리고 분류 성능을 평가하는 방법을 보여주었습니다.