Scikit-Learn 을 이용한 비모수적 등가선형 회귀

Beginner

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

소개

이 튜토리얼에서는 등척성 회귀 (isotonic regression) 에 대해 배웁니다. 등척성 회귀는 비모수적 회귀 기법으로, 학습 데이터의 평균 제곱 오차를 최소화하면서 함수의 비감소 근사값을 찾습니다. 파이썬의 인기 머신러닝 라이브러리인 scikit-learn 을 사용하여 등척성 회귀를 구현하고 선형 회귀와 비교해 보겠습니다.

VM 팁

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

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

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

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

이 튜토리얼에서는 NumPy, Matplotlib, 그리고 scikit-learn 과 같은 필요한 라이브러리를 가져와 시작합니다.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

from sklearn.linear_model import LinearRegression
from sklearn.isotonic import IsotonicRegression
from sklearn.utils import check_random_state

데이터 생성

다음으로, 회귀에 사용할 데이터를 생성합니다. 이 데이터는 이분산 (homoscedastic) 균일 노이즈를 가진 비선형 단조 추세를 갖도록 생성됩니다.

n = 100
x = np.arange(n)
rs = check_random_state(0)
y = rs.randint(-50, 50, size=(n,)) + 50.0 * np.log1p(np.arange(n))

등가선형 및 선형 회귀 모델 적합

이제 생성된 데이터에 등가선형 회귀 모델과 선형 회귀 모델을 모두 적합합니다.

ir = IsotonicRegression(out_of_bounds="clip")
y_ = ir.fit_transform(x, y)

lr = LinearRegression()
lr.fit(x[:, np.newaxis], y)  ## LinearRegression 을 위해 x 를 2 차원으로 변환해야 함

결과 플롯

마지막으로, 두 회귀 모델의 결과를 플롯하여 데이터에 대한 적합도를 시각화합니다.

segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
lc = LineCollection(segments, zorder=0)
lc.set_array(np.ones(len(y)))
lc.set_linewidths(np.full(n, 0.5))

fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 6))

ax0.plot(x, y, "C0.", markersize=12)
ax0.plot(x, y_, "C1.-", markersize=12)
ax0.plot(x, lr.predict(x[:, np.newaxis]), "C2-")
ax0.add_collection(lc)
ax0.legend(("Training data", "Isotonic fit", "Linear fit"), loc="lower right")
ax0.set_title("잡음 데이터에 대한 등가선형 회귀 적합 (n=%d)" % n)

x_test = np.linspace(-10, 110, 1000)
ax1.plot(x_test, ir.predict(x_test), "C1-")
ax1.plot(ir.X_thresholds_, ir.y_thresholds_, "C1.", markersize=12)
ax1.set_title("예측 함수 (%d 임계값)" % len(ir.X_thresholds_))

plt.show()

요약

이 튜토리얼에서는 등가선형 회귀, 즉 훈련 데이터의 평균 제곱 오차를 최소화하면서 함수의 비감소 근사값을 찾는 비모수적 회귀 기법에 대해 배웠습니다. 또한 scikit-learn 을 사용하여 등가선형 회귀를 구현하고 선형 회귀와 비교했습니다.