KFold、StratifiedKFold、GroupKFold的区别
一、問題來源:
在kaggle代碼中第一次看到GroupKFold,不太清楚和KFold的區(qū)別,所以才想著去搞清楚這個(gè)問題
二、KFold
>>> import numpy as np >>> from sklearn.model_selection import KFold>>> X = ["a", "b", "c", "d"] >>> kf = KFold(n_splits=2) >>> for train, test in kf.split(X): ... print("%s %s" % (train, test)) [2 3] [0 1] [0 1] [2 3]三、Stratified k-fold
StratifiedKFold是k-fold的一個(gè)變體,它會(huì)根據(jù)數(shù)據(jù)集的分布來劃分,使得 劃分后的數(shù)據(jù)集的目標(biāo)比例和原始數(shù)據(jù)集近似。
>>> from sklearn.model_selection import StratifiedKFold>>> X = np.ones(10) >>> y = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1] >>> skf = StratifiedKFold(n_splits=3) >>> for train, test in skf.split(X, y): ... print("%s %s" % (train, test)) [2 3 6 7 8 9] [0 1 4 5] [0 1 3 4 5 8 9] [2 6 7] [0 1 2 4 5 6 7] [3 8 9]四、Group k-fold
GroupKFold 會(huì)保證同一個(gè)group的數(shù)據(jù)不會(huì)同時(shí)出現(xiàn)在訓(xùn)練集和測(cè)試集上。因?yàn)槿绻?xùn)練集中包含了每個(gè)group的幾個(gè)樣例,可能訓(xùn)練得到的模型能夠足夠靈活地從這些樣例中學(xué)習(xí)到特征,在測(cè)試集上也會(huì)表現(xiàn)很好。但一旦遇到一個(gè)新的group它就會(huì)表現(xiàn)很差。
>>> from sklearn.model_selection import GroupKFold>>> X = [0.1, 0.2, 2.2, 2.4, 2.3, 4.55, 5.8, 8.8, 9, 10] >>> y = ["a", "b", "b", "b", "c", "c", "c", "d", "d", "d"] >>> groups = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]>>> gkf = GroupKFold(n_splits=3) >>> for train, test in gkf.split(X, y, groups=groups): ... print("%s %s" % (train, test)) [0 1 2 3 4 5] [6 7 8 9] [0 1 2 6 7 8 9] [3 4 5] [3 4 5 6 7 8 9] [0 1 2]問題:應(yīng)用中還未發(fā)現(xiàn)GroupKFold的使用價(jià)值,后續(xù)發(fā)現(xiàn)補(bǔ)上……
來源:https://zhuanlan.zhihu.com/p/52515873
圖片參考:https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_indices.html#sphx-glr-auto-examples-model-selection-plot-cv-indices-py
總結(jié)
以上是生活随笔為你收集整理的KFold、StratifiedKFold、GroupKFold的区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pip国内镜像源速度几十倍于官方及如何设
- 下一篇: jupyter notebook妙用之%