เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การเข้ารหัสคอลัมน์ 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_)
แก้ไขและรันโค้ด