sklearn.model_selection.GroupKFold?
class sklearn.model_selection.GroupKFold(n_splits=5)
[源碼]
具有非重疊組的K折迭代器變體。
在兩個不同的折疊中不會出現相同的組(不同組的數量必須至少等于折數)。
在每次折疊中不同組數大致相同的意義上,折疊大致平衡。
參數 | 說明 |
---|---|
n_splits | int, default=5 折數。必須至少為2。 0.22版中的更改:n_splits默認值從3更改為5。 |
另見
LeaveOneGroupOut
根據數據集明確的特定領域分層來切分數據。
示例
>>> import numpy as np
>>> from sklearn.model_selection import GroupKFold
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
>>> y = np.array([1, 2, 3, 4])
>>> groups = np.array([0, 0, 2, 2])
>>> group_kfold = GroupKFold(n_splits=2)
>>> group_kfold.get_n_splits(X, y, groups)
2
>>> print(group_kfold)
GroupKFold(n_splits=2)
>>> for train_index, test_index in group_kfold.split(X, y, groups):
... 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]
... print(X_train, X_test, y_train, y_test)
...
TRAIN: [0 1] TEST: [2 3]
[[1 2]
[3 4]] [[5 6]
[7 8]] [1 2] [3 4]
TRAIN: [2 3] TEST: [0 1]
[[5 6]
[7 8]] [[1 2]
[3 4]] [3 4] [1 2]
方法
方法 | 說明 |
---|---|
get_n_splits (self[, X, y, groups]) |
返回交叉驗證器中的切分迭代次數 |
split (self, X[, y, groups]) |
生成索引將數據分割成訓練集和測試集。 |
__init__(self,n_splits = 5 )
[源碼]
初始化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 | array-like of shape (n_samples, n_features) 用于訓練的數據,其中n_samples是樣本數量,n_features是特征數量。 |
y | array-like of shape (n_samples,), default=None 監督學習問題的目標變量。 |
groups | array-like of shape (n_samples,) 將數據集切分為訓練或測試集時使用的樣本的分組標簽。 |
返回值 | 說明 |
---|---|
train | ndarray 切分的訓練集索引。 |
test | ndarray 切分的測試集索引。 |