강건한 선형 추정기 적합

Beginner

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

소개

이 실습에서는 파이썬의 scikit-learn 라이브러리를 사용하여 강력한 선형 추정자 적합을 수행하는 방법을 배웁니다. 0 에 가까운 값에 대해 3 차 다항식으로 사인 함수를 적합하고, 다양한 상황에서 강력한 적합을 시연합니다. 중앙 절대 편차를 사용하여 새 데이터를 오염시키지 않고 예측의 품질을 판단합니다.

VM 팁

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

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

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

필요한 라이브러리 가져오기 및 데이터 생성

먼저 필요한 라이브러리를 가져오고 적합을 위한 데이터를 생성해야 합니다. 약간의 노이즈가 있는 사인 함수를 생성하고 X 와 y 모두에 오류를 도입하여 데이터를 손상시킬 것입니다.

from matplotlib import pyplot as plt
import numpy as np

from sklearn.linear_model import (
    LinearRegression,
    TheilSenRegressor,
    RANSACRegressor,
    HuberRegressor,
)
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline

np.random.seed(42)

X = np.random.normal(size=400)
y = np.sin(X)
## X 가 2 차원이 되도록 합니다.
X = X[:, np.newaxis]

X_test = np.random.normal(size=200)
y_test = np.sin(X_test)
X_test = X_test[:, np.newaxis]

y_errors = y.copy()
y_errors[::3] = 3

X_errors = X.copy()
X_errors[::3] = 3

y_errors_large = y.copy()
y_errors_large[::3] = 10

X_errors_large = X.copy()
X_errors_large[::3] = 10

3 차 다항식으로 사인 함수 적합

0 에 가까운 값에 대해 3 차 다항식으로 사인 함수를 적합합니다.

x_plot = np.linspace(X.min(), X.max())

다양한 상황에서의 강건한 적합 데모

이제 OLS, Theil-Sen, RANSAC, HuberRegressor 네 가지 다른 추정기를 사용하여 다양한 상황에서 강건한 적합을 데모합니다.

estimators = [
    ("OLS", LinearRegression()),
    ("Theil-Sen", TheilSenRegressor(random_state=42)),
    ("RANSAC", RANSACRegressor(random_state=42)),
    ("HuberRegressor", HuberRegressor()),
]
colors = {
    "OLS": "turquoise",
    "Theil-Sen": "gold",
    "RANSAC": "lightgreen",
    "HuberRegressor": "black",
}
linestyle = {"OLS": "-", "Theil-Sen": "-.", "RANSAC": "--", "HuberRegressor": "--"}
lw = 3

결과 플롯

이제 각 상황에 대한 결과를 플롯합니다.

for title, this_X, this_y in [
    ("Modeling Errors Only", X, y),
    ("Corrupt X, Small Deviants", X_errors, y),
    ("Corrupt y, Small Deviants", X, y_errors),
    ("Corrupt X, Large Deviants", X_errors_large, y),
    ("Corrupt y, Large Deviants", X, y_errors_large),
]:
    plt.figure(figsize=(5, 4))
    plt.plot(this_X[:, 0], this_y, "b+")

    for name, estimator in estimators:
        model = make_pipeline(PolynomialFeatures(3), estimator)
        model.fit(this_X, this_y)
        mse = mean_squared_error(model.predict(X_test), y_test)
        y_plot = model.predict(x_plot[:, np.newaxis])
        plt.plot(
            x_plot,
            y_plot,
            color=colors[name],
            linestyle=linestyle[name],
            linewidth=lw,
            label="%s: error = %.3f" % (name, mse),
        )

    legend_title = "Error of Mean\nAbsolute Deviation\nto Non-corrupt Data"
    legend = plt.legend(
        loc="upper right", frameon=False, title=legend_title, prop=dict(size="x-small")
    )
    plt.xlim(-4, 10.2)
    plt.ylim(-2, 10.2)
    plt.title(title)
plt.show()

요약

이 실험에서 파이썬의 scikit-learn 라이브러리를 사용하여 강건한 선형 추정기 적합을 수행하는 방법을 배웠습니다. 0 에 가까운 값에 대해 3 차 다항식으로 사인 함수를 맞추고 다양한 상황에서 강건한 적합을 데모했습니다. 비교 데이터에 대한 중앙값 절대 편차를 사용하여 예측의 품질을 판단했습니다.