การเข้ารหัสด้วยค่าเฉลี่ยของ Target
ขั้นแรก เราจะสร้างฟังก์ชันที่ใช้การเข้ารหัสด้วยค่าเฉลี่ยของ target โดยต้องดำเนินการ 2 ขั้นตอนต่อไปนี้:
- คำนวณค่าเฉลี่ยจากชุดข้อมูล train แล้วนำไปใช้กับชุดข้อมูล test
- แบ่ง train ออกเป็น K folds แล้วคำนวณค่าเฉลี่ย out-of-fold สำหรับแต่ละ fold จากนั้นนำค่าที่ได้ไปใช้กับ fold นั้น
แต่ละขั้นตอนจะถูก implement แยกกันในฟังก์ชัน test_mean_target_encoding() และ train_mean_target_encoding() ตามลำดับ
ฟังก์ชันหลัก mean_target_encoding() รับอาร์กิวเมนต์ได้แก่: DataFrame ของ train และ test, ชื่อคอลัมน์ categorical ที่ต้องการเข้ารหัส, ชื่อคอลัมน์ target และพารามิเตอร์ smoothing alpha โดยจะคืนค่า 2 ค่า ได้แก่ feature ใหม่สำหรับ DataFrame ของ train และ test ตามลำดับ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การแข่งขัน Kaggle ด้วย Python
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
def test_mean_target_encoding(train, test, target, categorical, alpha=5):
# Calculate global mean on the train data
global_mean = train[target].mean()
# Group by the categorical feature and calculate its properties
train_groups = train.groupby(categorical)
category_sum = train_groups[target].sum()
category_size = train_groups.size()
# Calculate smoothed mean target statistics
train_statistics = (category_sum + global_mean * alpha) / (category_size + ____)
# Apply statistics to the test data and fill new categories
test_feature = test[categorical].map(train_statistics).fillna(____)
return test_feature.values