讲解了交叉验证的基本思想之后,接下来将学习几个常用的交叉迭代器及其使用方法。
K 折交叉验证(KFold)会将数据集划分为 k 个分组,成为折叠(fold)。如果 k 的值等于数据集实例的个数,那么每次的测试集就只有一个,这种处理方式称为“留一”。
Scikit 中提供了 KFold 方法进行分组。
- #导入相关模块
- In [1]: from sklearn.model_selection import KFold
- #导入相关数据
- In [2]: X = ["a", "b", "c", "d", "e", "f"]
- #设置分组这里选择分成3份。
- In [3]: kf = KFold(n_splits=3)
- #查看分组结果
- In [4]: for train, test in kf.split(X):
- ...: print("%s-%s" % (train, test))
- [2 3 4 5]-[0 1]
- [0 1 4 5]-[2 3]
- [0 1 2 3]-[4 5]
KFold 方法采用的是不放回的抽样方法,Scikit 中还提供了重复 K 折交叉验证(RepeatedKFold)方法进行重复抽样。
- #导入相关模块
- In [1]: from sklearn.model_selection import RepeatedKFold
- #导入相关数据
- In [2]: X = ["a", "b", "c", "d", "e", "f"]
- #创建重复K折交叉验证对象
- In [3]: rkf = RepeatedKFold(n_splits=3, n_repeats=2,)
- #查看分组结果
- In [4]: for train, test in rkf.split(X):
- ...: print("%s-%s" % (train, test))
- [1 3 4 5]-[0 2]
- [0 1 2 3]-[4 5]
- [0 2 4 5]-[1 3]
- [0 2 4 5]-[1 3]
- [0 1 3 4]-[2 5]
- [1 2 3 5]-[0 4]
和 KFold 不同的地方是,RepeatedKFold 可以进行有放回的抽取。
留一交叉验证(LeaveOneOut)是 KFold 的特殊情况,它的 k 值等于数据集实例的个数。留一交叉验证的优点是每次训练的训练集都包含除了一个样本之外的所有样本,所以保证了训练集尽可能大。
- #导入相关模块
- In [1]: from sklearn.model_selection import LeaveOneOut
- #导入相关数据
- In [2]: X = ["a", "b", "c", "d", "e", "f"]
- #创建留一交叉验证对象
- In [3]: loo = LeaveOneOut()
- #查看输出结果
- In [4]: for train, test in loo.split(X):
- ...: print("%s-%s" % (train, test))
- [1 2 3 4 5]-[0]
- [0 2 3 4 5]-[1]
- [0 1 3 4 5]-[2]
- [0 1 2 4 5]-[3]
- [0 1 2 3 5]-[4]
- [0 1 2 3 4]-[5]
-
留 P交叉验证是指选定 P个样本作测试集,然后输出所有可能的训练-测试集对。与 LeaveOneOut 和 KFold 不同的地方是,当 P>1 时,该验证的测试集会有重叠。
- #导入相关模块
- In [1]: from sklearn.model_selection import LeavePOut
- #导入相关数据
- In [2]: X = ["a", "b", "c", "d", "e", "f"]
- #创建留P交叉验证模型
- In [3]: lpo = LeavePOut(p=2)
- #查看分组结果
- In [4]: for train, test in lpo.split(X):
- ...: print("%s-%s" % (train, test))
- [2 3 4 5]-[0 1]
- [1 3 4 5]-[0 2]
- [1 2 4 5]-[0 3]
- [1 2 3 5]-[0 4]
- [1 2 3 4]-[0 5]
- [0 3 4 5]-[1 2]
- [0 2 4 5]-[1 3]
- [0 2 3 5]-[1 4]
- [0 2 3 4]-[1 5]
- [0 1 4 5]-[2 3]
- [0 1 3 5]-[2 4]
- [0 1 3 4]-[2 5]
- [0 1 2 5]-[3 4]
- [0 1 2 4]-[3 5]
- [0 1 2 3]-[4 5]
随机排列交叉验证会将数据集分散,然后随机排列,划分为一对测试集和训练集。
- #导入相关模块
- In [1]: from sklearn.model_selection import ShuffleSplit
- #导入相关数据
- In [2]: X = ["a", "b", "c", "d", "e", "f"]
- #创建随机排列交叉验证对象
- In [3]: ss = ShuffleSplit(n_splits=3, test_size=0.25)
- #查看分组结果
- In [4]: for train_index, test_index in ss.split(X):
- ...: print("%s-%s" % (train_index, test_index))
- [4 5 1 0]-[3 2]
- [3 1 4 2]-[0 5]
- [0 3 1 4]-[2 5]