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

IT/파이썬

[for loop 활용] 최적화된 feature set 찾기

sarah0518 2021. 6. 25. 15:53

 

오늘은 다양한 모델을 돌릴 때, 

어떤 feature set에서 성능이 가장 성능이 좋은지 확인하는 방법을 소개하려고 합니다.

 


예를 들어 feature1~10까지 10개의 feature가 있을 때, 

"feature 5, 10 " 의  조합이 "feature 1, 2, 4, 7" 의 조합보다 
더 나은지 모든 조합에 대해 비교분석 하실 때 유용한 코드를 공유하고자 해요.

 


학생때 배웠던 조합을 잠깐 회상해보자고 하면,
10개의 숫자중에서 3개만 뽑는 경우의 수는 (순서 상관없이)

 

위의 값으로 120가지의 경우의 수가 있습니다.

 


알고리즘 진행 시, 심지어 몇개의 조합이 최적인지도 알 수 없기 때문에

위의 값 될텐데, 그렇다면 더 많은 경우의 수가 존재하죠.

 


이걸 다 손으로 돌리기엔 너무나 비효율적이니
for loop을 활용하여 모든 조합의 분석결과를 비교하고자 합니다.

 

 

1
2
3
from itertools import combinations
from sklearn.svm import OneClassSVM
 
cs

 

우선!

combination계산에 필요한 itertools과 사용할 알고리즘인 sklearn의 svm을 불러옵니다.

 

 

 

1
2
3
4
5
6
7
8
9
ocsvm=OneClassSVM( verbose=True, nu=0.00195889, kernel = 'rbf', gamma=0.0009)
 
def oc_model(model, x_train_df, x_test_df, y_test_df):
    model.fit(x_train_df)
    p=model.predict(x_test_df)
    cm = metrics.confusion_matrix(y_test_df, p)
    cm0=cm[0,0]
    cm1=cm[1,1]
    return cm0, cm1
cs

위에 ocsvm이라는 모델을 생성해주고,

그 모델을 불러서 fit과 predict 그리고 성능으로 볼 결과를 return해 주는 함수를 만들었습니다.



 

말씀드린 대로 변수가 10개가 있다고 가정해보죠.

1
2
3
4
5
6
7
8
9
10
11
12
feature_list=['f1''f2' ,'f3''f4''f5''f6''f7''f8''f9''f10']
 
cm0_l=[]
cm1_l=[]
temp_list_l=[]
for i in range(3len(feature_list)):
    temp_list=list(combinations(feature_list, i))
    for j in range(len(temp_list)):
        cm0, cm1 = oc_model(ocsvm, train[list(temp_list[j])], test[list(temp_list[j])], test['target'])
        cm0_l.append(cm0)
        cm1_l.append(cm1)
        temp_list_l.append(list(temp_list[j]))
cs

 

for loop의 결과는

True Negative개수(cm0_l) 와, True Postive의 개수(cm1_1)

그리고 그때의 feature set(temp_list_l)으로 table을 만들었습니다.

 

 

1
2
frames={'TN':cm0_l,'TP':cm1_l, 'features':temp_list_l}
result_tb=pd.DataFrame(frames)
cs

result_tb의 결과치를 보면 아래와 같습니다.

 

True Negative와 True Positive값이 제일 max가 되는

features set을 확인 하실 수 있겠죠!

 

 

참고로..18개의 feature가 들어가니 끝도 없이 돌아가더군요...

15개 이하로 돌리시는걸 추천합니다! 

3만개정도 이상의 데이터를 가지고 계신다면..