参考来源:python中sklearn实现交叉验证
在实验数据分析中,有些算法需要用现有的数据构建模型,如卷积神经网络(CNN),这类算法称为监督学习。
构建模型需要的数据称为训练数据。
模型的构建的过程中,也需要检验模型,辅助模型构建。
所以会将训练数据分为两个部分,1)训练数据;2)验证数据。
将数据分类就要采用交叉验证的方法。Stratified k-fold
StratifiedKFold()这个函数较常用,比KFold的优势在于将k折数据按照百分比划分数据集,每个类别百分比在训练集和测试集中都是一样,这样能保证不会有某个类别的数据在训练集中而测试集中没有这种情况,同样不会在训练集中没有全在测试集中,这样会导致结果糟糕透顶。
from sklearn.model_selection import StratifiedKFold
import numpy as np
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([0, 0, 1, 1])
skf = StratifiedKFold(n_splits=2)
for train_index, validation_index in skf.split(X, y):
print("TRAIN:", train_index, "TEST:", validation_index)
X_train, X_test = X[train_index], X[validation_index]
y_train, y_test = y[train_index], y[validation_index]
#**注意!!!X,y是数组(数据框.values形式),直接[index]筛选行**
#如果X、y是数据框,则用.loc[index,:]筛选特定行
for train_index, validation_index in folds.split(X_train, y_train):
print("TRAIN:", train_index, "TEST:", validation_index)
fold_xtrain,fold_ytrain=X_train.loc[train_index,:],y_train.loc[train_index,:]
fold_xtest,fold_ytest=X_train.loc[validation_index,:],y_train.loc[validation_index,:]
from sklearn.model_selection import KFold
import numpy as np
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([1, 2, 3, 4])
kf = KFold(n_splits=2)
for train_index, validation_index in kf.split(X):
print("TRAIN:", train_index, "TEST:",validation_index)
X_train, X_test = X[train_index], X[validation_index]
y_train, y_test = y[train_index], y[validation_index]
参考来源:Python-sklearn包中StratifiedKFold和KFold生成交叉验证数据集的区别
StratifiedKFold分层采样,用于交叉验证:与KFold最大的差异在于,StratifiedKFold方法是根据标签中不同类别占比来进行拆分数据的。
利用StratifiedKFold方法分层采样:依照标签的比例来抽取数据,本案例集标签0和1的比例是1:1,因此在抽取数据时也是按照标签比例1:1来提取的
#依照标签的比例来抽取数据,本案例集标签0和1的比例是1:1
#因此在抽取数据时也是按照标签比例1:1来提取的
from sklearn.model_selection import StratifiedKFold
import numpy as np
sfolder = StratifiedKFold(n_splits=4,random_state=0)
for train, test in sfolder.split(X,y):
print('Train: %s | test: %s' % (train, test))
>>>
Train: [1 3 4 5 6 7] | test: [0 2]
Train: [0 2 4 5 6 7] | test: [1 3]
Train: [0 1 2 3 5 7] | test: [4 6]
Train: [0 1 2 3 4 6] | test: [5 7]
利用KFold方法交叉采样:按顺序分别取第1-2、3-4、5-6和7-8的数据
#按顺序分别取第1-2、3-4、5-6和7-8的数据。
kfolder = KFold(n_splits=4,random_state=1)
for train, test in kfolder.split(X,y):
print('Train: %s | test: %s' % (train, test),'\n')
>>>
Train: [2 3 4 5 6 7] | test: [0 1]
Train: [0 1 4 5 6 7] | test: [2 3]
Train: [0 1 2 3 6 7] | test: [4 5]
Train: [0 1 2 3 4 5] | test: [6 7]