가우시안 프로세스 회귀 모델 학습

Beginner

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

소개

이 실습에서는 가우시안 프로세스 회귀를 사용하여 데이터 세트에 모델을 맞추는 방법을 배웁니다. 합성 데이터 세트를 생성하고 가우시안 프로세스 회귀를 사용하여 모델을 맞춥니다. scikit-learn 라이브러리를 사용하여 가우시안 프로세스 회귀를 수행합니다.

VM 팁

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

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

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

Dataset Generation

We will generate a synthetic dataset. The true generative process is defined as f(x) = x sin(x).

import numpy as np

X = np.linspace(start=0, stop=10, num=1_000).reshape(-1, 1)
y = np.squeeze(X * np.sin(X))

import matplotlib.pyplot as plt

plt.plot(X, y, label=r"$f(x) = x \sin(x)$", linestyle="dotted")
plt.legend()
plt.xlabel("$x$")
plt.ylabel("$f(x)$")
_ = plt.title("True generative process")

데이터 생성

합성 데이터 세트를 생성합니다. 참 생성 과정은 f(x) = x sin(x) 로 정의됩니다.

import numpy as np

X = np.linspace(start=0, stop=10, num=1_000).reshape(-1, 1)
y = np.squeeze(X * np.sin(X))

import matplotlib.pyplot as plt

plt.plot(X, y, label=r"$f(x) = x \sin(x)$", linestyle="dotted")
plt.legend()
plt.xlabel("$x$")
plt.ylabel("$f(x)$")
_ = plt.title("True generative process")

잡음 없는 대상

이 단계에서는 잡음을 추가하지 않고 참 생성 과정을 사용합니다. 가우시안 프로세스 회귀를 학습시키기 위해 몇 개의 샘플만 선택합니다.

rng = np.random.RandomState(1)
training_indices = rng.choice(np.arange(y.size), size=6, replace=False)
X_train, y_train = X[training_indices], y[training_indices]

from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF

kernel = 1 * RBF(length_scale=1.0, length_scale_bounds=(1e-2, 1e2))
gaussian_process = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=9)
gaussian_process.fit(X_train, y_train)
gaussian_process.kernel_

예측 및 신뢰 구간

모델을 맞춘 후, 커널의 하이퍼파라미터가 최적화되었음을 확인합니다. 이제 전체 데이터 세트의 평균 예측을 계산하고 95% 신뢰 구간을 플롯합니다.

mean_prediction, std_prediction = gaussian_process.predict(X, return_std=True)

plt.plot(X, y, label=r"$f(x) = x \sin(x)$", linestyle="dotted")
plt.scatter(X_train, y_train, label="Observations")
plt.plot(X, mean_prediction, label="Mean prediction")
plt.fill_between(
    X.ravel(),
    mean_prediction - 1.96 * std_prediction,
    mean_prediction + 1.96 * std_prediction,
    alpha=0.5,
    label=r"95% confidence interval",
)
plt.legend()
plt.xlabel("$x$")
plt.ylabel("$f(x)$")
_ = plt.title("잡음 없는 데이터 세트에 대한 가우시안 프로세스 회귀")

잡음이 있는 대상

이번에는 대상에 추가적인 잡음을 추가하여 유사한 실험을 반복할 수 있습니다. 이렇게 하면 잡음이 맞춰진 모델에 미치는 영향을 볼 수 있습니다.

noise_std = 0.75
y_train_noisy = y_train + rng.normal(loc=0.0, scale=noise_std, size=y_train.shape)

gaussian_process = GaussianProcessRegressor(
    kernel=kernel, alpha=noise_std**2, n_restarts_optimizer=9
)
gaussian_process.fit(X_train, y_train_noisy)
mean_prediction, std_prediction = gaussian_process.predict(X, return_std=True)

plt.plot(X, y, label=r"$f(x) = x \sin(x)$", linestyle="dotted")
plt.errorbar(
    X_train,
    y_train_noisy,
    noise_std,
    linestyle="None",
    color="tab:blue",
    marker=".",
    markersize=10,
    label="Observations",
)
plt.plot(X, mean_prediction, label="Mean prediction")
plt.fill_between(
    X.ravel(),
    mean_prediction - 1.96 * std_prediction,
    mean_prediction + 1.96 * std_prediction,
    color="tab:orange",
    alpha=0.5,
    label=r"95% confidence interval",
)
plt.legend()
plt.xlabel("$x$")
plt.ylabel("$f(x)$")
_ = plt.title("잡음이 있는 데이터 세트에 대한 가우시안 프로세스 회귀")

요약

이 실험에서 우리는 가우시안 프로세스 회귀를 사용하여 데이터 세트에 모델을 맞추는 방법을 배웠습니다. 합성 데이터 세트를 생성하고 가우시안 프로세스 회귀를 사용하여 모델을 맞췄습니다. Scikit-learn 라이브러리를 사용하여 가우시안 프로세스 회귀를 수행하고 평균 예측 및 95% 신뢰 구간을 플롯했습니다.