KFold#

class sklearn.model_selection.KFold(n_splits=5, *, shuffle=False, random_state=None)[source]#

K-Fold 交叉验证器。

提供训练/测试索引以将数据拆分为训练/测试集。将数据集拆分为 k 个连续的折叠(默认情况下不打乱)。

然后,每个折叠被用作一次验证集,而剩余的 k - 1 个折叠构成训练集。

用户指南中了解更多信息。

有关交叉验证行为的可视化以及常见 scikit-learn 拆分方法的比较,请参阅scikit-learn 中的交叉验证行为可视化

参数:
n_splitsint, default=5

折叠数。必须至少为 2。

版本 0.22 中已更改: n_splits 的默认值从 3 更改为 5。

shufflebool, default=False

是否在拆分成批次之前打乱数据。请注意,每个拆分中的样本不会被打乱。

random_stateint, RandomState instance or None, default=None

shuffle 为 True 时,random_state 会影响索引的顺序,从而控制每个折叠的随机性。否则,此参数无效。传递一个整数可在多次函数调用中实现可复现的输出。请参阅词汇表

另请参阅

StratifiedKFold

考虑类别信息以避免构建类别分布不平衡的折叠(适用于二分类或多分类任务)。

GroupKFold

具有非重叠组的 K 折迭代器变体。

RepeatedKFold

重复 K-Fold n 次。

注意事项

n_samples % n_splits 个折叠的大小为 n_samples // n_splits + 1,其他折叠的大小为 n_samples // n_splits,其中 n_samples 是样本数。

随机 CV 拆分器在每次调用 split 时可能会返回不同的结果。您可以通过将 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()
2
>>> print(kf)
KFold(n_splits=2, random_state=None, shuffle=False)
>>> for i, (train_index, test_index) in enumerate(kf.split(X)):
...     print(f"Fold {i}:")
...     print(f"  Train: index={train_index}")
...     print(f"  Test:  index={test_index}")
Fold 0:
  Train: index=[2 3]
  Test:  index=[0 1]
Fold 1:
  Train: index=[0 1]
  Test:  index=[2 3]
get_metadata_routing()[source]#

获取此对象的元数据路由。

请查阅 用户指南,了解路由机制如何工作。

返回:
routingMetadataRequest

封装路由信息的 MetadataRequest

get_n_splits(X=None, y=None, groups=None)[source]#

返回在实例化交叉验证器时使用 n_splits 参数设置的拆分迭代次数。

参数:
Xarray-like of shape (n_samples, n_features), default=None

始终忽略,存在是为了保持 API 兼容性。

yshape 为 (n_samples,), default=None 的 array-like

始终忽略,存在是为了保持 API 兼容性。

groups形状为 (n_samples,) 的类数组对象,默认=None

始终忽略,存在是为了保持 API 兼容性。

返回:
n_splitsint

返回交叉验证器中的拆分迭代次数。

split(X, y=None, groups=None)[source]#

生成索引以将数据拆分为训练集和测试集。

参数:
Xshape 为 (n_samples, n_features) 的 array-like

训练数据,其中 n_samples 是样本数,n_features 是特征数。

yshape 为 (n_samples,), default=None 的 array-like

用于监督学习问题的目标变量。

groups形状为 (n_samples,) 的类数组对象,默认=None

始终忽略,存在是为了保持 API 兼容性。

生成:
trainndarray

该拆分的训练集索引。

testndarray

该拆分的测试集索引。