Kaggle을 보다보면 Cross-Validation의 함수인 train_test_split를 자주 사용하는 것을 볼 수 있다. 이러한 취지의 기본적인 목적은 Overfitting(과적합) 을 피하는 것이다.
과적합을 피하는 것은 최적의 매개변수를 구하는 것이라고 할 수 있다.
X, y = datasets.load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)
clf = smv.SVC(kernel='linear', C=1).fit(X_train, y_train)
clf.score(X_test, y_test)
k=5 일 때
1. train_set을 5개로 나눠 5번을 순환해 test_set을 늘려주는 방식이다.
2. k-fold 교차검증이라고 부르면 반복과정에 평균 값을 사용하게 된다.
3. 비용이 크지만 데이터가 크지 않을 때 사용하면 좋다.
from sklearn.model_selection import cross_val_score
clf = svm.SVC(kernel='linear', C=1, random_state=42)
scores = cross_val_score(clf, X, y, cv=5)
scores
1. scores.mean()과 scores.std()를 출력하며 성능을 나타낼 수 있다.
2. metrics 지정을 통한 성능 도출
scores = cross_val_score(clf, X, y, cv=5, scoring='f1_macro')
scores
from sklearn.model_selection import ShuffleSplit
cv = ShuffleSplit(n_splits=5, test_size=0.3, random_state=0)
cross_val_score(clf, X, y, cv=cv)
def custom_cv_2folds(X):
n = X.shape[0]
while i <= 2:
idx = np.arange(n * (i-1)/2, n*i/2, dtype=int)
yield idx, idx
i += 1
custom_cv = custom_cv_2folds(X)
cross_val_score(clf, X, y, cv=custom_cv)
K-fold는 앞서 설명한 것처럼 샘플을 K개의 그룹으로 나눠 K-1개를 훈련할 때 사용하고 나머지 하나는 테스트를 위해 사용한다.
from sklearn.model_selection import KFold
kf = KFold(n_splits=2)
for train, test in kf.split(X):
print("%s %s" % (train, test))
import numpy as np
from sklearn.model_selection import RepeatedKFold
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
random_state = 12883823
rkf = RepeatedKFold(n_splits=2, n_repeats=2, random_state=random_state)
for train, test in rkf.split(X):
print("%s %s" % (train, test))
LOO는 하나를 제외한 모든 샘플을 생성하는 방식으로 가장 간단한 교차검증 방식이다.
from sklearn.model_selection import LeaveOneOut
X = [1, 2, 3, 4]
loo = LeaveOneOut()
for train, test in loo.split(X):
print(train, test)
기존 K-Fold 방식과 거의 비슷하지만
LPO는 One -> P가 된 것으로 P=2이면 2개를 아웃시킨다는 의미이다. (p > 1)
from sklearn.model_selection import LeavePOut
X = np.ones(4)
lpo = LeavePOut(p=2)
for train, test in lpo.split(X):
print(train, test)
from sklearn.model_selection import ShuffleSplit
X = np.arange(10)
ss = ShuffleSplit(n_splits=5, test_size=0.25, random_state=0)
for train_index, test_index in ss.split(X):
print(train_index, test_index)
상기 내용은 기존 Scikit-Learn을 참고하여 정리하였습니다.