Scikit-Learn 반복적 누락값 보간법

Beginner

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

소개

이 실습에서는 Scikit-Learn 의 IterativeImputer 클래스를 사용하여 데이터 세트에서 누락된 값을 대체하는 방법을 배웁니다. 캘리포니아 주택 데이터 세트에서 각 행에서 임의의 하나의 값을 제거한 후 BayesianRidge 추정기를 사용할 때 IterativeImputer에 가장 적합한 추정기를 비교해 보겠습니다.

VM 팁

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

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

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

라이브러리 가져오기

먼저 이 실습에 필요한 라이브러리를 가져옵니다.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

from sklearn.experimental import enable_iterative_imputer
from sklearn.datasets import fetch_california_housing
from sklearn.impute import SimpleImputer
from sklearn.impute import IterativeImputer
from sklearn.linear_model import BayesianRidge, Ridge
from sklearn.kernel_approximation import Nystroem
from sklearn.ensemble import RandomForestRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_score

데이터셋 로드

Scikit-Learn 에서 캘리포니아 주택 데이터셋을 로드합니다. 계산 시간을 줄이기 위해 2,000 개의 샘플만 사용합니다.

N_SPLITS = 5

rng = np.random.RandomState(0)

X_full, y_full = fetch_california_housing(return_X_y=True)
X_full = X_full[::10]
y_full = y_full[::10]
n_samples, n_features = X_full.shape

누락된 값 추가

데이터셋의 각 행에 하나의 누락된 값을 추가합니다.

X_missing = X_full.copy()
y_missing = y_full
missing_samples = np.arange(n_samples)
missing_features = rng.choice(n_features, n_samples, replace=True)
X_missing[missing_samples, missing_features] = np.nan

단순 임퓨터를 이용한 누락 값 보간

Scikit-Learn 의 SimpleImputer 클래스를 사용하여 평균 및 중앙값 전략으로 누락된 값을 보간합니다.

score_simple_imputer = pd.DataFrame()
for strategy in ("mean", "median"):
    estimator = make_pipeline(
        SimpleImputer(missing_values=np.nan, strategy=strategy), BayesianRidge()
    )
    score_simple_imputer[strategy] = cross_val_score(
        estimator, X_missing, y_missing, scoring="neg_mean_squared_error", cv=N_SPLITS
    )

반복적 임퓨터를 이용한 누락 값 보간

Scikit-Learn 의 IterativeImputer 클래스를 사용하여 다양한 추정기를 활용하여 누락된 값을 보간합니다.

estimators = [
    BayesianRidge(),
    RandomForestRegressor(
        n_estimators=4,
        max_depth=10,
        bootstrap=True,
        max_samples=0.5,
        n_jobs=2,
        random_state=0,
    ),
    make_pipeline(
        Nystroem(kernel="polynomial", degree=2, random_state=0), Ridge(alpha=1e3)
    ),
    KNeighborsRegressor(n_neighbors=15),
]
score_iterative_imputer = pd.DataFrame()
tolerances = (1e-3, 1e-1, 1e-1, 1e-2)
for impute_estimator, tol in zip(estimators, tolerances):
    estimator = make_pipeline(
        IterativeImputer(
            random_state=0, estimator=impute_estimator, max_iter=25, tol=tol
        ),
        BayesianRidge(),
    )
    score_iterative_imputer[impute_estimator.__class__.__name__] = cross_val_score(
        estimator, X_missing, y_missing, scoring="neg_mean_squared_error", cv=N_SPLITS
    )

결과 비교

다양한 누락 값 보간 전략의 결과를 막대 차트를 통해 비교합니다.

scores = pd.concat(
    [score_full_data, score_simple_imputer, score_iterative_imputer],
    keys=["Original", "SimpleImputer", "IterativeImputer"],
    axis=1,
)

fig, ax = plt.subplots(figsize=(13, 6))
means = -scores.mean()
errors = scores.std()
means.plot.barh(xerr=errors, ax=ax)
ax.set_title("캘리포니아 주택 회귀 분석 - 서로 다른 누락 값 보간 방법 비교")
ax.set_xlabel("MSE (값이 작을수록 좋음)")
ax.set_yticks(np.arange(means.shape[0]))
ax.set_yticklabels([" w/ ".join(label) for label in means.index.tolist()])
plt.tight_layout(pad=1)
plt.show()

요약

이 실습에서는 Scikit-Learn 의 IterativeImputer 클래스를 사용하여 데이터셋에서 누락된 값을 보간하는 방법을 배웠습니다. SimpleImputer를 사용한 평균 및 중앙값 보간과 IterativeImputer를 사용한 다양한 추정기들을 비교했습니다. 캘리포니아 주택 데이터셋의 특정 누락 패턴에 대해 BayesianRidgeRandomForestRegressor가 가장 좋은 결과를 보여주었습니다.