「这是我参与11月更文挑战的第12天,活动详情查看:2021最后一次更文挑战」
K-fold
KFold(): k折交叉验证,KFold 将所有的样例划分为 k 个组,称为折叠 (fold) ,每组数据都具有相同的大小。每一次分割会将其中的 K-1 组作为训练数据,剩下的一组用作测试数据,一共会分割K次。
可以通过这张图直观的体现出来。(这是四折交叉验证,即K取4)
上手K-fold戳这篇👉让我看看是谁还不会交叉验证?
StratifiedKFold()方法
StratifiedKFold:分层交叉验证。 它是KFold()的变种, 使每个分组中各类别的比例同整体数据中各类别的比例尽可能的相同。(比如说:原始数据有3类,比例为1:2:1,采用3折分层交叉验证,那么划分的3折中,每一折中的数据类别保持着1:2:1的比例,这样的验证结果更加可信。)
StratifiedKFold()方法和KFold()代码的区别就在于cv
strKFold = StratifiedKFold(n_splits=3,shuffle=False,random_state=0)
scores = cross_val_score(logreg,iris.data,iris.target,cv=strKFold)
StratifiedKFold参数:
n_splits:折叠次数,默认为3,至少为2。
shuffle:是否在每次分割之前打乱顺序。
random_state:随机种子,在shuffle=True时使用,默认使用np.random。
怎么用起来?当然还是从万能的sklearn导入啦✌
栗子🚩
from sklearn.datasets import load_iris
from sklearn.model_selection import StratifiedKFold,cross_val_score #导入
from sklearn.linear_model import LogisticRegression
iris = load_iris()
print('Iris labels:\n{}'.format(iris.target))
logreg = LogisticRegression()
strKFold = StratifiedKFold(n_splits=3,shuffle=False,random_state=0)
scores = cross_val_score(logreg,iris.data,iris.target,cv=strKFold)
print("straitified cross validation scores:{}".format(scores))
print("Mean score of straitified cross validation:{:.2f}".format(scores.mean()))
输出👇
Iris labels:
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2]
straitified cross validation scores:[0.96078431 0.92156863 0.95833333]
Mean score of straitified cross validation:0.95
接我机器学习的demo,怎么用呢?
来看来看👀
效果:
k折交叉验证优点是可以降低由一次随机划分带来的偶然性,提高其泛化能力。但K折存在的问题就是因为是随机划分,很有可能划分的过程中刚好把类别都划分开了,比如第1折训练集里全是0标签,第2折测试集里全是1标签,这样对模型训练就不太好,这样的话会导致某个模型学习的时候就没有学习到测试集的分类特征。对于不均衡数据集使用k折交叉验证就不太合适。
所以对非平衡数据可以用分层采样StratifiedKFold,就是在每一份子集中都保持和原始数据集相同的类别比例,它相对于k折交叉验证更完善。
欢迎随时指导~
具体代码可戳👉gitee.com/xin-yue-qin…
参考资料