Stratified K-fold
จะเห็นว่าการกระจายตัวของตัวแปรเป้าหมายในแต่ละ fold นั้นแตกต่างกันค่อนข้างมาก เนื่องจากการแบ่งข้อมูลแบบสุ่ม ปัญหานี้อาจไม่ส่งผลกระทบมากนักในการแข่งขันนี้ แต่หากเป็นโจทย์ classification ที่มีตัวแปรเป้าหมายไม่สมดุลอย่างมาก ก็อาจเป็นปัญหาสำคัญได้
เพื่อแก้ปัญหานี้ ลองนำกลยุทธ์ stratified K-fold มาใช้โดยอ้างอิงการแบ่งชั้นจากตัวแปรเป้าหมาย DataFrame train พร้อมใช้งานแล้วใน workspace ของคุณ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การแข่งขัน Kaggle ด้วย Python
คำแนะนำการฝึกหัด
- สร้างออบเจ็กต์
StratifiedKFoldที่มี 3 folds พร้อมเปิดใช้งาน shuffling - วนลูปผ่านแต่ละ split โดยใช้ออบเจ็กต์
str_kfโดยใช้คอลัมน์ "interest_level" เป็นเกณฑ์ในการแบ่งชั้นข้อมูล - สำหรับแต่ละ split ให้เลือก fold สำหรับฝึกและทดสอบโดยใช้
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