分層 K 折
你應該已經注意到,因為是隨機切分,每一折的目標變數分佈差異很大。對這個比賽本身影響不大,但在目標變數高度不平衡的分類型比賽中就可能造成問題。
為了改善這點,來實作在目標變數上進行分層的 K 折驗證策略。train DataFrame 已經在你的工作空間中可用。
本練習屬於課程
用 Python 拿下 Kaggle 競賽
練習說明
- 建立一個具有 3 折且啟用隨機抽樣的
StratifiedKFold物件。 - 使用
str_kf物件迴圈走訪每個切分。分層依據欄位「interest_level」。 - 對於每個切分,使用
train_index與test_index選出訓練與測試折。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import StratifiedKFold
from sklearn.model_selection import StratifiedKFold
# Create a StratifiedKFold object
str_kf = ____(n_splits=____, shuffle=____, random_state=123)
# Loop through each split
fold = 0
for train_index, test_index in ____.____(train, train['interest_level']):
# Obtain training and testing folds
cv_train, cv_test = ____.iloc[____], ____.iloc[____]
print('Fold: {}'.format(fold))
print('CV train shape: {}'.format(cv_train.shape))
print('Medium interest listings in CV train: {}\n'.format(sum(cv_train.interest_level == 'medium')))
fold += 1