let us not love with words or tongue but actions and truth.

IT/파이썬

Isolation Forest와 One-Class SVM

sarah0518 2021. 2. 23. 17:25

우리의 현실 데이터는 Imbalanced 된 data가 많이 존재하죠.

 

그래서 오늘은 Imbalanced 된 데이터를 분석하는 모델링에 대해서 알아보려고 합니다.

 

1. Isolation Forest

2. One Class SVM

위의 두개에 대해서 알아보려고 해요.

 

이론에 대해서 deep하게 설명하는 것은 저의 능력을 벗어나므로,

간단히 설명하면 실제 모든 True인 데이터에 대해 분류기를 training을 시킵니다.

 

그러다가 그 데이터셋과 다른 특징을 나타내는 data들이 들어오면 "기존것과의 패턴이 다르다"고 판단하여

분류해 내는 모형이라고 생각하시면 될거같아요.

 

이것이 바로 One Class Classification 모델의 기본 idea입니다.

 

두 모델의 가장 중요한 것은 hyper parameter 수정인데, 정말 detail한 값까지 수정해줘야 된다는 거에요.

특히 imbalanced한 데이터 일때!

 

1
2
3
4
def clf2():
    ocsvm=OneClassSVM(gamma=0.0001, kernel='rbf', max_iter=1000, nu=0.009, verbose=True)
    isf=IsolationForest(contamination=0.08461, random_state=99, n_jobs=-1, behaviour= "new", max_features=2, max_samples=55,  n_estimators=2
    return ocsvm, isf
cs

 

 

위에 코드를 보시면 

One Class SVM모델은 kernel, gamma, nu값을 수정해주시면 됩니다.

kernel의 종류는

- sigmoid

- rbf

- poly

- linear

가 있는데요.

 

poly는 다항함수, linear는 선형함수, rbf방사형 함수, sigmoid는 0~1사이의 값을 갖는 함수라고 생각하시면 됩니다.

 

One Class SVM모델 자체가 다른 차원으로 데이터를 적합시켰을때

어떤 kernel을 가지고 분류해낼 것인가에 대해서 생각해보시고 선택하시면 될거 같아요.

 

그래도 제일 널리 쓰이고 성능이 좋다고 소문 난 kernel은 RBF커널이에요.

이 커널은 gamma와 nu값으로 곡선 경계율을 변경해준답니다.

 

 

 

 

 

 

 

그 다음은 IsolationForest모델로 Tree기반의 모델입니다.

 

contamination=0.1, random_state=9, n_jobs=-1, behaviour= "new", max_features=2, max_samples=5,  n_estimators=2

 

 

설정해줘야할 파라미터들은

- contamination값 (test데이터셋에서의 불량률과 동일하게 가져감)

- max_features값 (설명변수의 개수보다 같거나 작아야함)

- max_samples 값 (test 셋의 data sample 값보다 같거나 작아야함)

- n_estimators 값 들이 있습니다.

 

** 참고로 random_state값은 임의로 고정시켜두어 한번 더 돌렸을 때

고정된 모델이기때문에 설정된 paramete값에 대해 동일한 결과가 나옵니다.

 

 

이제 모델을 Fitting하는 함수를 짜보겠습니다.

1
2
3
4
5
6
7
8
def oc_model(model, x_train_df, x_test_df, y_test_df):
    model.fit(x_train_df)
    p=model.predict(x_test_df)
    print("f1: %.8f"%(f1_score(y_test_df, p)))
    print("accuracy: %.8f"%(accuracy_score(y_test_df, p)))
    print("recall: %.8f"%(recall_score(y_test_df, p)))
    print("precision: %.8f"%(precision_score(y_test_df, p)))
    return p
cs

 

 

위의 oc_model이라는 함수를 활용하여 아래와 같이

ocsvm모델로 예측된 p_ocsvm값과

isf모델로 예측된 p_isf값을 얻을 수 있습니다.

1
2
3
ocsvm, isf = clf2()
p_ocsvm=oc_model(ocsvm, train_scaled_x, test_scaled_x, test_y)
p_isf=oc_model(isf, train_scaled_x, test_scaled_x, test_y)
cs