กรณีศึกษาโรคไต I: Categorical Imputer
ต่อจากนี้จะสำรวจการใช้ pipeline กับชุดข้อมูลที่ต้องการการจัดเตรียมข้อมูลมากขึ้น ชุดข้อมูลโรคไตเรื้อรัง มีทั้งฟีเจอร์ประเภทหมวดหมู่และตัวเลข แต่มีค่าที่ขาดหายไปจำนวนมาก เป้าหมายคือการทำนายว่าใครเป็นโรคไตเรื้อรัง โดยใช้ค่าตัวชี้วัดทางเลือดต่าง ๆ เป็นฟีเจอร์
ดังที่ Sergey กล่าวถึงในวิดีโอ เราจะแนะนำไลบรารีใหม่ชื่อ sklearn_pandas ซึ่งช่วยให้เชื่อมขั้นตอนการประมวลผลได้หลากหลายมากขึ้นภายใน pipeline เกินกว่าที่ scikit-learn รองรับในปัจจุบัน โดยเฉพาะอย่างยิ่ง สามารถใช้คลาส DataFrameMapper() เพื่อนำ transformer ที่เข้ากันได้กับ sklearn ไปใช้กับคอลัมน์ใน DataFrame โดยผลลัพธ์ที่ได้จะเป็น NumPy array หรือ DataFrame ก็ได้
นอกจากนี้ยังมี transformer ที่สร้างขึ้นชื่อ Dictifier ซึ่งทำหน้าที่แปลง DataFrame โดยใช้ .to_dict("records") โดยที่ไม่ต้องเรียกใช้โดยตรง (และทำให้ใช้งานใน pipeline ได้) อีกทั้งยังกำหนดรายชื่อฟีเจอร์ไว้ใน kidney_feature_names ชื่อ target ใน kidney_target_name ฟีเจอร์ใน X และ target ใน y
ในแบบฝึกหัดนี้ ให้ใช้ SimpleImputer ของ sklearn เพื่อเติมค่าที่ขาดหายไปในคอลัมน์ประเภทหมวดหมู่ทั้งหมดในชุดข้อมูล อ้างอิงวิธีสร้าง numeric imputation mapper เป็นแม่แบบได้ สังเกต keyword arguments input_df=True และ df_out=True ที่ระบุไว้ เพื่อให้ทำงานกับ DataFrame แทน array โดยค่าเริ่มต้น transformer จะรับ numpy array ของคอลัมน์ที่เลือกเป็น input และผลลัพธ์จาก DataFrame mapper ก็จะเป็น array เช่นกัน ทั้งนี้เนื่องจาก transformer ของ scikit-learn ถูกออกแบบมาให้ทำงานกับ numpy array ไม่ใช่ pandas DataFrame แม้ว่าอินเทอร์เฟซการ index พื้นฐานจะคล้ายกันก็ตาม
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Extreme Gradient Boosting with XGBoost
คำแนะนำการฝึกหัด
- ใช้
DataFrameMapper()และSimpleImputer()เพื่อทำ categorical imputation โดยSimpleImputer()ไม่ต้องส่ง argument ใด ๆ คอลัมน์ต่าง ๆ อยู่ในcategorical_columnsอย่าลืมระบุinput_df=Trueและdf_out=Trueและใช้category_featureเป็นตัวแปร iterator ใน list comprehension
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import necessary modules
from sklearn_pandas import DataFrameMapper
from sklearn.impute import SimpleImputer
# Check number of nulls in each feature column
nulls_per_column = X.isnull().sum()
print(nulls_per_column)
# Create a boolean mask for categorical columns
categorical_feature_mask = X.dtypes == object
# Get list of categorical column names
categorical_columns = X.columns[categorical_feature_mask].tolist()
# Get list of non-categorical column names
non_categorical_columns = X.columns[~categorical_feature_mask].tolist()
# Apply numeric imputer
numeric_imputation_mapper = DataFrameMapper(
[([numeric_feature], SimpleImputer(strategy="median")) for numeric_feature in non_categorical_columns],
input_df=True,
df_out=True
)
# Apply categorical imputer
categorical_imputation_mapper = ____(
[(category_feature, ____) for ____ in ____],
input_df=____,
df_out=____
)