이상치 탐지 Isolation Forest

Beginner

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

소개

이 실습에서는 이상 탐지에 Isolation Forest 를 사용하는 과정을 살펴봅니다. 먼저 두 개의 클러스터와 몇 개의 이상치를 포함하는 데이터셋을 생성한 후, Isolation Forest 모델을 학습하여 이상치를 식별합니다. 마지막으로 모델의 결정 경계를 시각화하여 내부 데이터 포인트와 이상치를 어떻게 분리하는지 확인합니다.

VM 팁

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

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

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

데이터 생성

두 개의 클러스터와 몇 개의 이상치를 포함하는 데이터셋을 생성합니다. 클러스터는 표준 정규 분포에서 무작위로 샘플링하여 생성됩니다. 하나는 구형이고 다른 하나는 약간 변형된 형태입니다. 이상치는 균일 분포에서 무작위로 샘플링하여 생성합니다.

import numpy as np
from sklearn.model_selection import train_test_split

n_samples, n_outliers = 120, 40
rng = np.random.RandomState(0)
covariance = np.array([[0.5, -0.1], [0.7, 0.4]])
cluster_1 = 0.4 * rng.randn(n_samples, 2) @ covariance + np.array([2, 2])  ## 일반적인 형태
cluster_2 = 0.3 * rng.randn(n_samples, 2) + np.array([-2, -2])  ## 구형
outliers = rng.uniform(low=-4, high=4, size=(n_outliers, 2))

X = np.concatenate([cluster_1, cluster_2, outliers])
y = np.concatenate(
    [np.ones((2 * n_samples), dtype=int), -np.ones((n_outliers), dtype=int)]
)

X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)

데이터셋 시각화

생성된 클러스터를 시각화하여 데이터셋의 모습을 확인할 수 있습니다.

import matplotlib.pyplot as plt

scatter = plt.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor="k")
handles, labels = scatter.legend_elements()
plt.axis("square")
plt.legend(handles=handles, labels=["이상치", "내부 데이터 포인트"], title="실제 클래스")
plt.title("가우시안 내부 데이터 포인트와 \n균일 분포된 이상치")
plt.show()

모델 학습

훈련 데이터로 Isolation Forest 모델을 학습합니다.

from sklearn.ensemble import IsolationForest

clf = IsolationForest(max_samples=100, random_state=0)
clf.fit(X_train)

이산 결정 경계 시각화

DecisionBoundaryDisplay 클래스를 사용하여 이산 결정 경계를 시각화합니다. 배경색은 해당 영역의 샘플이 이상치로 예측되는지 여부를 나타냅니다. 산점도는 실제 레이블을 표시합니다.

import matplotlib.pyplot as plt
from sklearn.inspection import DecisionBoundaryDisplay

disp = DecisionBoundaryDisplay.from_estimator(
    clf,
    X,
    response_method="predict",
    alpha=0.5,
)
disp.ax_.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor="k")
disp.ax_.set_title("IsolationForest 의 이진 결정 경계")
plt.axis("square")
plt.legend(handles=handles, labels=["이상치", "내부 데이터 포인트"], title="실제 클래스")
plt.show()

경로 길이 결정 경계 시각화

response_method="decision_function"을 설정하면 DecisionBoundaryDisplay의 배경은 관측치의 정상성 척도를 나타냅니다. 이러한 점수는 무작위 트리의 숲에서 평균화된 경로 길이에 의해 주어지며, 이는 특정 샘플을 분리하는 데 필요한 리프의 깊이 (또는 동등하게 분할 횟수) 에 의해 결정됩니다.

disp = DecisionBoundaryDisplay.from_estimator(
    clf,
    X,
    response_method="decision_function",
    alpha=0.5,
)
disp.ax_.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor="k")
disp.ax_.set_title("IsolationForest 의 경로 길이 결정 경계")
plt.axis("square")
plt.legend(handles=handles, labels=["이상치", "내부 데이터 포인트"], title="실제 클래스")
plt.colorbar(disp.ax_.collections[1])
plt.show()

요약

이 실습에서는 이상치 탐지에 Isolation Forest 를 사용하는 방법을 배웠습니다. 두 개의 클러스터와 몇 개의 이상치가 있는 데이터 세트를 생성하고, Isolation Forest 모델을 학습하여 이상치를 식별하고, 모델의 결정 경계를 시각화하여 내부 데이터 포인트와 이상치를 어떻게 분리하는지 확인했습니다.