교차검증을 하는 이유는 과적합을 피하면서 파라미터를 튜닝하고 일반적인 모델을 만들고 더 신뢰성 있는 모델 평가를 진행하기 위해서입니다.
교차 검증은 train set을 train set + validation set으로 분리한 뒤, validation set을 사용해 검증하는 방식이다.
머신러닝 모델을 만들때 중요한 이슈는 최적화(optimization)와 일반화(generalization) 입니다.
smoothing
파라미터를 설정하여 줄 수 있다.# 예시
from category_encoders import TargetEncoder
target_enc=TargetEncoder(min_samples_leaf=1, smoothing=1)
target_enc.fit_transform(X_train,y_train)
from sklearn.model_selection import RandomizedSearchCV
pipe = make_pipeline(
OneHotEncoder(use_cat_names=True)
, SimpleImputer()
, StandardScaler()
, SelectKBest(f_regression)
, Ridge()
)
# 튜닝할 하이퍼파라미터의 범위를 지정해 주는 부분
dists = {
'simpleimputer__strategy': ['mean', 'median'],
'selectkbest__k': range(1, len(X_train.columns)+1),
'ridge__alpha': [0.1, 1, 10],
}
clf = RandomizedSearchCV(
pipe,
param_distributions=dists,
n_iter=50,
cv=3,
scoring='neg_mean_absolute_error',
verbose=1,
n_jobs=-1
)
clf.fit(X_train, y_train);
from sklearn.model_selection import GridSearchCV
pipe = make_pipeline(
OrdinalEncoder(cols=cols_enc,mapping=mapping_enc,handle_unknown='return_nan'),
SimpleImputer(),
RandomForestClassifier(oob_score=True)
)
dists = {
'randomforestclassifier__n_estimators': [300,400,500,600,700,800,900,1000],
'randomforestclassifier__max_depth': [3,4,5,6],
'randomforestclassifier__criterion': ['gini','entropy']
}
clf = GridSearchCV(
pipe,
param_grid=dists,
cv=3,
scoring='roc_auc',
verbose=1,
n_jobs=-1
)
clf.fit(X_train, y_train);
sklearn
에서는 이 기능을 제공하지 않으며, 일반적으로 hyperopt
등의 라이브러리를 추가 사용해서 탐색을 진행하게 됩니다.