python金融風控評分卡模型和數據分析微專業課(博主親自錄制視頻):http://dwz.date/b9vv
原文鏈接
https://blog.csdn.net/wqh_jingsong/article/details/77896449
StratifiedKFold用法類似Kfold,但是他是分層采樣,確保訓練集,測試集中各類別樣本的比例與原始數據集中相同。
例子:
import numpy as np
from sklearn.model_selection import KFold,StratifiedKFold
X=np.array([ [1,2,3,4], [11,12,13,14], [21,22,23,24], [31,32,33,34], [41,42,43,44], [51,52,53,54], [61,62,63,64], [71,72,73,74] ]) y=np.array([1,1,0,0,1,1,0,0]) #n_folds這個參數沒有,引入的包不同, floder = KFold(n_splits=4,random_state=0,shuffle=False) sfolder = StratifiedKFold(n_splits=4,random_state=0,shuffle=False) for train, test in sfolder.split(X,y): print('Train: %s | test: %s' % (train, test)) print(" ") for train, test in floder.split(X,y): print('Train: %s | test: %s' % (train, test)) print(" ")
結果:
1.
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]
2.
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]
分析:可以看到StratifiedKFold 分層采樣交叉切分,確保訓練集,測試集中各類別樣本的比例與原始數據集中相同。
python機器學習生物信息學系列課(博主錄制):http://dwz.date/b9vw
歡迎關注博主主頁,學習python視頻資源