sklearn.model_selection.KFold?
class sklearn.model_selection.KFold(n_splits=5, *, shuffle=False, random_state=None)
[源碼]
K折交叉驗證器。
提供訓練集或測試集索引以將數據切分為訓練集或測試集。將數據集切分為k個連續的交叉(默認情況下不打亂數據)。
然后將每折交叉用作一次驗證,而剩下的k-1折交叉形成訓練集。
在用戶指南中閱讀更多內容。
參數 | 說明 |
---|---|
n_splits | int, default=5 折數。必須至少為2。 0.22版本中: n_splits 默認值從3更改為5。) |
shuffle | bool, default=False 在切分之前是否打亂數據。注意,每次切分內的樣本都不會被打亂。 |
random_state | int or RandomState instance, default=None 當 shuffle 為True時,random_state 會影響索引的順序,從而控制每折交叉的隨機性。否則,此參數無效。為多個函數調用傳遞可重復輸出的int值。請參閱詞匯表。 |
另見:
StratifiedKFold
考慮組信息,以避免因類分布不均衡而造成交叉(對于二進制或多類分類任務)。
GroupKFold
具有非重疊組的K折迭代器變體。
RepeatedKFold
重復K折n次。
注
第一個n_samples % n_splits
的大小為 n_samples // n_splits + 1
,其他幾折的大小為n_samples // n_splits
,其中n_samples
為樣本數。
隨機CV切分器可能會為每個切分調用返回不同的結果。您可以通過將random_state
設置為整數使結果相同。
示例
>>> import numpy as np
>>> from sklearn.model_selection import KFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([1, 2, 3, 4])
>>> kf = KFold(n_splits=2)
>>> kf.get_n_splits(X)
2
>>> print(kf)
KFold(n_splits=2, random_state=None, shuffle=False)
>>> 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]
TRAIN: [2 3] TEST: [0 1]
TRAIN: [0 1] TEST: [2 3]
方法
方法 | 說明 |
---|---|
get_n_splits (self[, X, y, groups]) |
返回交叉驗證器中的切分迭代次數。 |
split (self, X[, y, groups]) |
生成索引以將數據切分為訓練集和測試集。 |
__init__(self,n_splits = 5,*,shuffle = False,random_state = None )
[源碼]
初始化self。詳情可參閱 type(self)的幫助。
get_n_splits(self,X = None,y = None,groups = None )
[源碼]
返回交叉驗證器中的切分迭代次數。
參數 | 說明 |
---|---|
X | object 始終被忽略,為了兼容性而存在。 |
y | object 始終被忽略,為了兼容性而存在。 |
groups | object 始終被忽略,為了兼容性而存在。 |
返回值 | 說明 |
---|---|
n_splits | int 返回交叉驗證器中拆分迭代的次數。 |
split(self,X,y = None,groups = None )
[源碼]
生成索引以將數據切分為訓練集和測試集。
參數 | 說明 |
---|---|
X | object 用于訓練的數據,其中n_samples是樣本數量,n_features是特征數量。 |
y | object 監督學習問題的目標變量。 |
groups | object 將數據集切分為訓練集或測試集時使用的樣本的分組標簽。 |
輸出 | 說明 |
---|---|
train | ndarray 切分的訓練集索引。 |
test | ndarray 切分的測試集索引。 |