K-fold cross-validation
โจทย์นี้เป็นปัญหา binary classification โดยใช้ข้อมูลตัวอย่างจากการแข่งขัน Kaggle playground เป้าหมายของการแข่งขันคือการทำนายว่านักบาสเกตบอลชื่อดัง Kobe Bryant จะทำคะแนนได้หรือพลาดในแต่ละช็อต
ข้อมูล train พร้อมใช้งานในรูปแบบ DataFrame ชื่อ bryant_shots ซึ่งมีข้อมูลช็อตทั้งหมด 10,000 รายการ พร้อมคุณสมบัติของแต่ละช็อตและตัวแปร target "shot\_made\_flag" ที่บอกว่าช็อตนั้นทำคะแนนได้หรือไม่
หนึ่งในฟีเจอร์ของข้อมูลคือ "game_id" ซึ่งระบุเกมที่ทำช็อตนั้น โดยมีเกมที่ไม่ซ้ำกันถึง 541 เกม นั่นหมายความว่าเราต้องจัดการกับฟีเจอร์ categorical ที่มี cardinality สูง ลองเข้ารหัสด้วย target mean กัน!
สมมติว่าใช้ 5-fold cross-validation และต้องการประเมินฟีเจอร์ที่ผ่านการ encode ด้วย mean target บน local validation
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การแข่งขัน Kaggle ด้วย Python
คำแนะนำการฝึกหัด
- ในการทำเช่นนี้ ต้องทำขั้นตอนการ encode ฟีเจอร์ categorical
"game_id"ซ้ำภายในแต่ละ fold split แยกกัน เป้าหมายคือระบุพารามิเตอร์ที่ขาดหายไปทั้งหมดสำหรับการเรียกฟังก์ชันmean_target_encoding()ภายในแต่ละ fold split - พารามิเตอร์
trainและtestรับ DataFrame ของ train และ test ตามลำดับ - ส่วนพารามิเตอร์
targetและcategoricalรับชื่อของตัวแปร target และฟีเจอร์ categorical ที่ต้องการ encode
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Create 5-fold cross-validation
kf = KFold(n_splits=5, random_state=123, shuffle=True)
# For each folds split
for train_index, test_index in kf.split(bryant_shots):
cv_train, cv_test = bryant_shots.iloc[train_index], bryant_shots.iloc[test_index]
# Create mean target encoded feature
cv_train['game_id_enc'], cv_test['game_id_enc'] = mean_target_encoding(train=cv_train,
test=____,
target='shot_made_flag',
categorical='____',
alpha=5)
# Look at the encoding
print(cv_train[['game_id', 'shot_made_flag', 'game_id_enc']].sample(n=1))