배깅을 이용한 편향 - 분산 분해

Beginner

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

소개

이 실습에서는 편향 - 분산 분해 개념과 단일 추정자 대 바깅 앙상블의 관계를 탐구합니다. Scikit-learn 을 사용하여 예제 회귀 문제를 생성하고 시각화하고, 단일 추정자와 의사결정 트리의 바깅 앙상블의 예상 평균 제곱 오차를 비교합니다.

VM 팁

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

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

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

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

먼저, 데이터 생성, 모델 학습 및 결과 시각화를 위해 필요한 라이브러리를 가져와야 합니다.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import BaggingRegressor
from sklearn.tree import DecisionTreeRegressor

매개변수 설정

데이터셋 크기, 반복 횟수, 노이즈의 표준 편차를 제어하는 매개변수를 설정해야 합니다.

n_repeat = 50  ## 기대값 계산을 위한 반복 횟수
n_train = 50  ## 학습 데이터셋 크기
n_test = 1000  ## 테스트 데이터셋 크기
noise = 0.1  ## 노이즈의 표준 편차
np.random.seed(0)

데이터 생성

알려진 함수를 사용하여 1 차원 회귀 문제를 생성하고, 학습 및 테스트 데이터셋에 랜덤 노이즈를 추가합니다. 기대 평균 제곱 오차를 계산하기 위해 여러 학습 데이터셋을 생성합니다.

def f(x):
    x = x.ravel()
    return np.exp(-(x**2)) + 1.5 * np.exp(-((x - 2) ** 2))

def generate(n_samples, noise, n_repeat=1):
    X = np.random.rand(n_samples) * 10 - 5
    X = np.sort(X)

    if n_repeat == 1:
        y = f(X) + np.random.normal(0.0, noise, n_samples)
    else:
        y = np.zeros((n_samples, n_repeat))

        for i in range(n_repeat):
            y[:, i] = f(X) + np.random.normal(0.0, noise, n_samples)

    X = X.reshape((n_samples, 1))

    return X, y

X_train = []
y_train = []

for i in range(n_repeat):
    X, y = generate(n_samples=n_train, noise=noise)
    X_train.append(X)
    y_train.append(y)

X_test, y_test = generate(n_samples=n_test, noise=noise, n_repeat=n_repeat)

비교할 모델 정의

비교할 두 가지 모델을 정의합니다: 단일 의사결정 트리와 의사결정 트리의 배깅 앙상블입니다.

estimators = [
    ("Tree", DecisionTreeRegressor()),
    ("Bagging(Tree)", BaggingRegressor(DecisionTreeRegressor())),
]
n_estimators = len(estimators)

모델 학습 및 기대 평균 제곱 오차 계산

여러 학습 데이터셋에서 모델들을 반복적으로 학습하고, 편향, 분산, 노이즈 항으로 분해하여 기대 평균 제곱 오차를 계산합니다. 또한, 모델 예측과 편향 - 분산 분해를 시각화합니다.

plt.figure(figsize=(10, 8))

## 비교할 추정자 반복
for n, (name, estimator) in enumerate(estimators):
    ## 예측 계산
    y_predict = np.zeros((n_test, n_repeat))

    for i in range(n_repeat):
        estimator.fit(X_train[i], y_train[i])
        y_predict[:, i] = estimator.predict(X_test)

    ## 평균 제곱 오차의 편향^2 + 분산 + 노이즈 분해
    y_error = np.zeros(n_test)

    for i in range(n_repeat):
        for j in range(n_repeat):
            y_error += (y_test[:, j] - y_predict[:, i]) ** 2

    y_error /= n_repeat * n_repeat

    y_noise = np.var(y_test, axis=1)
    y_bias = (f(X_test) - np.mean(y_predict, axis=1)) ** 2
    y_var = np.var(y_predict, axis=1)

    print(
        "{0}: {1:.4f} (오차) = {2:.4f} (편향^2) "
        " + {3:.4f} (분산) + {4:.4f} (노이즈)".format(
            name, np.mean(y_error), np.mean(y_bias), np.mean(y_var), np.mean(y_noise)
        )
    )

    ## 그림 출력
    plt.subplot(2, n_estimators, n + 1)
    plt.plot(X_test, f(X_test), "b", label="$f(x)$")
    plt.plot(X_train[0], y_train[0], ".b", label="LS ~ $y = f(x)+noise$")

    for i in range(n_repeat):
        if i == 0:
            plt.plot(X_test, y_predict[:, i], "r", label=r"$\^y(x)$")
        else:
            plt.plot(X_test, y_predict[:, i], "r", alpha=0.05)

    plt.plot(X_test, np.mean(y_predict, axis=1), "c", label=r"$\mathbb{E}_{LS} \^y(x)$")

    plt.xlim([-5, 5])
    plt.title(name)

    if n == n_estimators - 1:
        plt.legend(loc=(1.1, 0.5))

    plt.subplot(2, n_estimators, n_estimators + n + 1)
    plt.plot(X_test, y_error, "r", label="$오차 (x)$")
    plt.plot(X_test, y_bias, "b", label="$편향^2(x)$"),
    plt.plot(X_test, y_var, "g", label="$분산 (x)$"),
    plt.plot(X_test, y_noise, "c", label="$노이즈 (x)$")

    plt.xlim([-5, 5])
    plt.ylim([0, 0.1])

    if n == n_estimators - 1:
        plt.legend(loc=(1.1, 0.5))

plt.subplots_adjust(right=0.75)
plt.show()

결과 해석

각 모델의 기대 평균 제곱 오차의 편향 - 분산 분해와 모델 예측을 관찰할 수 있습니다. 또한, 두 모델의 총 오차와 편향과 분산 간의 트레이드오프를 비교할 수 있습니다.

요약

이 실험에서는 편향 - 분산 분해의 개념과 단일 추정자 대 앙상블 (bagging) 의 관계를 탐구했습니다. Scikit-learn 을 사용하여 가상 회귀 문제를 생성하고 시각화했으며, 단일 의사결정 트리와 의사결정 트리의 앙상블 (bagging) 의 기대 평균 제곱 오차를 비교했습니다. 결과적으로 앙상블 (bagging) 은 편향 항을 약간 증가시키지만 분산을 더 크게 줄일 수 있어 전체 평균 제곱 오차를 낮추는 데 더 효과적인 트레이드오프를 보여주었습니다.