728x90
변수 중요도를 기준으로 변수를 하나씩 늘려가며 Kfold 교차검증을 진행하는 코드입니다.
모듈 import 및 data load
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split, StratifiedKFold
import pandas as pd
# data load
df = pd.read_csv('train.csv')
trian set 설정
# object column 제외
df = df.select_dtypes(exclude= 'object')
# Nan 값 평균 값으로 처리
df.fillna(df.Age.mean(), inplace = True)
model 학습 후 feature importance 내림차순으로 column list로 출력 및 li 변수로 저장
# 모델 학습
X = df.drop('Survived', axis = 1)
y = df.Survived
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, stratify = y)
rf = RandomForestClassifier(random_state = 10)
rf.fit(x_train, y_train)
pred = rf.predict(x_test)
print(accuracy_score(pred, y_test))
# feature importance 저장
fi = pd.DataFrame(rf.feature_importances_, index = X.columns, columns = ['score'])
fi.sort_values(by = 'score', ascending = False, inplace = True)
# 내림차순 기준 column list로 변수 설정
li = fi.reset_index()['index']
from sklearn.model_selection import StratifiedKFold
import warnings
warnings.filterwarnings('ignore')
n_splits = 3
acc_all = []
# feature importance 내림차순 기준으로 변수 늘리면서 accuracy 비교
for i in range(1, len(li)+1):
skf = StratifiedKFold(n_splits = n_splits)
X = df[li[:i]]
y = df[['Survived']]
acc = 0
# StratifiedKFold 진행
for train_idx, test_idx in skf.split(X, y):
x_train, x_test = X.iloc[train_idx], X.iloc[test_idx]
y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]
rf = RandomForestClassifier(random_state = 10)
rf.fit(x_train, y_train)
pred = rf.predict(x_test)
acc += accuracy_score(y_test, pred)
acc_all.append(acc/n_splits)
print(f'----- number of features: {i} -----')
print(acc_all[i-1])
print('\n')
print(max(acc_all), acc_all.index(max(acc_all))+1)
이렇게 진행하면 결과가 이렇게 나옵니다.
가장 높은 accuracy는 5개를 사용할 때네요.
728x90
'Machine Learning' 카테고리의 다른 글
[Machine Learning] SMOTETomek (0) | 2022.11.23 |
---|---|
[Machine Learning] imblearn 라이브러리 undersampling (0) | 2022.11.21 |
[Machine Learning] imblearn 라이브러리 oversampling (0) | 2022.11.18 |
[Machine Learning]PCA로 cluster 그래프 그리기 (0) | 2022.11.11 |
[Machine Learning]변수 중요도 출력(feature importance) (0) | 2022.11.01 |