原理:
模型在验证数据中的评估常用的是交叉验证,又称循环验证。它将原始数据分成K组(K-Fold),将每个子集数据分别做一次验证集,其余的K-1组子集数据作为训练集,这样会得到K个模型。这K个模型分别在验证集中评估结果,最后的误差MSE(Mean Squared Error)加和平均就得到交叉验证误差。交叉验证有效利用了有限的数据,并且评估结果能够尽可能接近模型在测试集上的表现,可以做为模型优化的指标使用。
KFold(n_splits=’warn’, shuffle=False, random_state=None)
参数:
n_splits 表示划分为几块(至少是2)
shuffle 表示是否打乱划分,默认False,即不打乱
random_state 表示是否固定随机起点,Used when shuffle == True.
方法
1,get_n_splits([X, y, groups]) 返回分的块数
2,split(X[,Y,groups]) 返回分类后数据集的index
例子:
import numpy as np
from sklearn.model_selection import KFold
a = np.arange(27).reshape(9, 3)
print(a)
b = np.arange(9).reshape(9, 1)
kfold = KFold(n_splits=3, shuffle=False)
index = kfold.split(X=a)
print(list(index))
print(type(index))
index = kfold.split(X=a, y=b)
for train_index, test_index in index:
print("-------------------------------------------------")
print(a[train_index]) # 注意如果a是datafram类型就得用a.iloc[tain_index], 因为a[train_index]会被认为是访问列
print(a[test_index])
输出:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]
[24 25 26]]
[(array([3, 4, 5, 6, 7, 8]), array([0, 1, 2])), (array([0, 1, 2, 6, 7, 8]), array([3, 4, 5])), (array([0, 1, 2, 3, 4, 5]), array([6, 7, 8]))]
<class 'generator'>
-------------------------------------------------
[[ 9 10 11]
[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]
[24 25 26]]
[[0 1 2]
[3 4 5]
[6 7 8]]
-------------------------------------------------
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[18 19 20]
[21 22 23]
[24 25 26]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
-------------------------------------------------
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]