使用K折交叉验证来反应模型的平均性能,首先应该保证每次数据集的划分是一样的,即第一个模型的训练集应该与第二个模型的训练集应该相同,这样得出来的对比结果才更有说服力。那么下面就是介绍如何使得输入到不同的模型时保证数据集是一样的。
令shuffle=True和random_state=某个整数
from sklearn.model_selection import KFold
import numpy as np
X = np.arange(24).reshape(12,2)
kf = KFold(n_splits=5,shuffle=True,random_state=1)
for train_index , test_index in kf.split(X):
print(f'train_index:{train_index} , test_index: {test_index} ')
运行几次,实验结果均如下所示,所以,划分数据集在每次送到不同的模型时,每个fold的结果是一样的。