machine learning code

Finding the outliers — isolation forest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# GridSearchCV(모델, param_grid, cv, scoring, n_jobs, verbose)
from sklearn.ensemble import IsolationForest
param_grid = {
'n_estimators':[50, 100, 150],
'max_samples':[50, 100, 150, 200],
'contamination':[float(0.004), float(0.1), float(0.5), 'auto']
}

# 전처리를 거친 x_train으로 grid search cross validation 수행
grid_search = GridSearchCV(IsolationForest(max_features=1.0, bootstrap=False, random_state=42,),
param_grid=param_grid, cv=10, n_jobs=-1, verbose=0, scoring = 'accuracy')
grid_search.fit(dataset)

# 가장 좋은 성능을 보인 파라미터 조합의 estimator을 model에 저장
model = grid_search.best_estimator_

# dataset 데이터를 예측 및 성능 평가
data_pred = model.predict(dataset)

#이상치 값 개수
-data_pred[data_pred == -1].sum() #1038개

## 그리드 서치 결과
# IsolationForest(contamination=0.004, max_samples=50, n_estimators=50, random_state=42)

Filling with the values using KNN imputer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from sklearn.impute import KNNImputer
param_grid = [
{'n_neighbors': range(3, 11, 2)}
]

imputer = KNNImputer(missing_values=np.nan, add_indicator=True)
gs = GridSearchCV(imputer, param_grid = param_grid,
cv=10, n_jobs = -1, scoring = 'f1')
gs.fit(df)

# 가장 좋은 성능을 보인 파라미터 조합의 estimator을 model에 저장
model = gs.best_estimator_

#f1 scoring일 때 최적 모델 값
KNNImputer(add_indicator=True, n_neighbors=3)

## imputer 결과(f1 score)
# KNNImputer(add_indicator=True, n_neighbors=3)

# f1 score일 때 결측값 채운 부분 확인하기
df[(df.category_id_1 == 0)]
  • 모델링을 할 때 데이터 양이 많으면 시간이 오래 걸림 (2~3시간 기본)
  • 구글 코랩에서 GPU로 돌려도 마찬가지 (딥러닝이 아니면 GPU로 잘 안돌아감.)