การเข้ารหัสคอลัมน์ categorical ขั้นที่ 3: DictVectorizer
เกือบพร้อมแล้ว ขอแนะนำเทคนิคสุดท้ายก่อนเริ่มใช้ pipeline กระบวนการสองขั้นตอนที่ผ่านมา ได้แก่ LabelEncoder ตามด้วย OneHotEncoder นั้น สามารถรวมเป็นขั้นตอนเดียวได้โดยใช้ DictVectorizer
การใช้ DictVectorizer กับ DataFrame ที่แปลงเป็น dictionary แล้ว ช่วยให้ได้ทั้ง label encoding และ one-hot encoding ในครั้งเดียว
ในแบบฝึกหัดนี้ ลองนำกลยุทธ์นี้ไปใช้งานจริงกัน!
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Extreme Gradient Boosting with XGBoost
คำแนะนำการฝึกหัด
- นำเข้า
DictVectorizerจากsklearn.feature_extraction - แปลง
dfให้เป็น dictionary ชื่อdf_dictโดยใช้เมธอด.to_dict()พร้อมระบุ"records"เป็นอาร์กิวเมนต์ - สร้างออบเจกต์
DictVectorizerชื่อdvโดยกำหนด keyword argument เป็นsparse=False - นำ
DictVectorizerไปใช้กับdf_dictโดยเรียกเมธอด.fit_transform() - คลิก 'ส่งคำตอบ' เพื่อแสดงผลลัพธ์ 5 แถวแรกและ vocabulary
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import DictVectorizer
____
# Convert df into a dictionary: df_dict
df_dict = ____
# Create the DictVectorizer object: dv
dv = ____
# Apply dv on df: df_encoded
df_encoded = ____
# Print the resulting first five rows
print(df_encoded[:5,:])
# Print the vocabulary
print(dv.vocabulary_)