クロス検証python

2875 ワード

以下、クロス検証(Cross Validation)と略すCVとする.CVは分類器の性能を検証するための統計分析方法であり、基本思想はある意味で元のデータ(dataset)をグループ化し、一部を訓練セット(train set)、もう一部を検証セット(validation set)とし、まず訓練セットで分類器を訓練し、検証セットを利用して訓練したモデル(model)をテストすることである.これを評価分類器の性能指標とする.一般的なCVの方法は以下の通りである:K回交差検査(K-Fold Cross Validation):K回交差検査の大まかな考え方はデータを大まかにKサブサンプルに分け、毎回1つのサンプルを検証データとし、残りのK-1つのサンプルを訓練データとする
from sklearn.model_selection import KFold
import numpy as np
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([1, 2, 3, 4])
kf = KFold(n_splits=2)

for train_index, test_index in kf.split(X):
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

Stratified k-fold:StratifiedKFold()という関数はよく使われています.KFoldよりも、k割引データをパーセンテージでデータセットに分割することが利点です.各カテゴリのパーセンテージはトレーニングセットとテストセットで同じです.これにより、あるカテゴリのデータがトレーニングセットにあり、テストセットにこのような状況がないことを保証することができます.同じように、トレーニングセットにテストセットにありません.これは結果を最悪にする.
from sklearn.model_selection import StratifiedKFold
import numpy as np

X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([0, 0, 1, 1])
skf = StratifiedKFold(n_splits=2)
for train_index, test_index in skf.split(X, y):
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

train_test_split:(これは現在多く使われています)
トレーニングセットとテストセットをランダムにスケールに基づいて割り当てます.この関数はランダムシードを調整できます.
import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=42)

参照先:https://blog.csdn.net/ztchun/article/details/71169530