在交叉验证期间更改测试和训练的大小

问题描述

我执行了10倍交叉验证的回归模型。

for train,test in kf.split(X,Y):
   print ("Fold ",cv)
   print("Train",X[train].shape)
   print("Test",X[test].shape)
   # define the model
   Breg = BayesianRidge(n_iter = 500,tol=0.0000000001)
   # fit the data to the model
   Breg.fit(X[train],Y[train])
   # calculate R2 for each fold and save the value into a file
   R2.append(Breg.score(X[test],Y[test]))
   # predict in test set
   ypred_test = Breg.predict(X[test])
   Y_pred_test.append(ypred_test)
   # calculate mean squared error for each fold and save into a list
   mae.append(mean_absolute_error(Y[test],ypred_test))

运行模型时,我观察到训练和测试的大小发生了变化。

Fold  1
Train (14754,9)
Test (1640,9)
Fold  2
Train (14754,9)
Fold  3
Train (14754,9)
Fold  4
Train (14754,9)
Fold  5
Train (14755,9)
Test (1639,9)
Fold  6
Train (14755,9)
Fold  7
Train (14755,9)
Fold  8
Train (14755,9)
Fold  9
Train (14755,9)
Fold  10
Train (14755,9) 
Test (1639,9)

您可以看到5折后训练的大小增加了1,而测试的大小减少了1
知道这可能如何发生并可以解决吗?
预先感谢

解决方法

答案可以在KFold的{​​{3}}中找到,我认为这就是您在kf中的kf.split所代表的意思。

在注释中说:

n_samples % n_splits折的尺寸为n_samples // n_splits + 1,其他折的尺寸为n_samples // n_splits,其中n_samples是 样本数。

通过插入数字,您可以看到前4个分割的大小为n_samples // n_splits + 1,其余的大小为n_samples // n_splits,因此大小差为+1