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

การเข้ารหัสคอลัมน์ประเภท Categorical I: LabelEncoder

ตอนนี้เราได้เห็นแล้วว่าต้องทำอะไรบ้างเพื่อเตรียมข้อมูลด้านที่อยู่อาศัยให้พร้อมสำหรับ XGBoost ต่อไปมาดำเนินการทีละขั้นตอนกัน

ขั้นแรก ต้องเติมค่าที่หายไป (missing values) เนื่องจากคอลัมน์ LotFrontage มีค่าที่หายไปจำนวนมากตามที่เห็นก่อนหน้านี้ จากนั้นต้องเข้ารหัสคอลัมน์ประเภท categorical ในชุดข้อมูลด้วย one-hot encoding เพื่อแปลงให้เป็นตัวเลข ดูวิดีโอนี้ จากคอร์ส Supervised Learning with scikit-learn เพื่อทบทวนแนวคิดนี้ได้

ข้อมูลมีคอลัมน์ประเภท categorical ทั้งหมด 5 คอลัมน์ ได้แก่ MSZoning, PavedDrive, Neighborhood, BldgType และ HouseStyle scikit-learn มีฟังก์ชัน LabelEncoder ที่แปลงค่าในแต่ละคอลัมน์ประเภท categorical ให้เป็นจำนวนเต็ม ในแบบฝึกหัดนี้จะได้ฝึกใช้งานฟังก์ชันดังกล่าว

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Extreme Gradient Boosting with XGBoost

ดูคอร์ส

คำแนะนำการฝึกหัด

  • นำเข้า LabelEncoder จาก sklearn.preprocessing
  • เติมค่าที่หายไปในคอลัมน์ LotFrontage ด้วย 0 โดยใช้ .fillna()
  • สร้าง boolean mask สำหรับคอลัมน์ประเภท categorical โดยตรวจสอบว่า df.dtypes มีค่าเท่ากับ object หรือไม่
  • สร้างออบเจ็กต์ LabelEncoder ซึ่งทำได้เช่นเดียวกับการสร้าง estimator ของ scikit-learn ทั่วไป
  • เข้ารหัสคอลัมน์ประเภท categorical ทั้งหมดให้เป็นจำนวนเต็มด้วย LabelEncoder() โดยใช้เมธอด .fit_transform() ของ le ในฟังก์ชัน lambda ที่เตรียมไว้ให้

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Import LabelEncoder
____

# Fill missing values with 0
df.LotFrontage = ____

# Create a boolean mask for categorical columns
categorical_mask = (____ == ____)

# Get list of categorical column names
categorical_columns = df.columns[categorical_mask].tolist()

# Print the head of the categorical columns
print(df[categorical_columns].head())

# Create LabelEncoder object: le
le = ____

# Apply LabelEncoder to categorical columns
df[categorical_columns] = df[categorical_columns].apply(lambda x: ____(x))

# Print the head of the LabelEncoded categorical columns
print(df[categorical_columns].head())
แก้ไขและรันโค้ด