1. 程式人生 > >交叉驗證 python

交叉驗證 python

以下簡稱交叉驗證(Cross Validation)為CV.CV是用來驗證分類器的效能一種統計分析方法,基本思想是把在某種意義下將原始資料(dataset)進行分組,一部分做為訓練集(train set),另一部分做為驗證集(validation set),首先用訓練集對分類器進行訓練,在利用驗證集來測試訓練得到的模型(model),以此來做為評價分類器的效能指標.常見CV的方法如下:
K次交叉檢驗(K-Fold Cross Validation):
K次交叉檢驗的大致思想是將資料大致分為K個子樣本,每次取一個樣本作為驗證資料,取餘下的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)