腎臟疾病案例研究 I:類別型補值器
現在你要在需要更多前處理的資料集上,繼續練習如何使用 pipeline。這個慢性腎臟疾病資料集同時包含類別型與數值型特徵,但有許多遺漏值。目標是根據各種血液指標等特徵,預測哪些人罹患慢性腎臟疾病。
正如 Sergey 在影片中提到的,你會接觸一個新的函式庫 sklearn_pandas,它讓你在 pipeline 中串接比 scikit-learn 目前原生支援更多的前處理步驟。特別是你可以使用 DataFrameMapper() 類別,將任何與 sklearn 相容的轉換器套用到 DataFrame 的欄位上,而且輸出可以是 NumPy 陣列或 DataFrame。
我們也建立了一個名為 Dictifier 的轉換器,將 DataFrame 轉成 .to_dict("records"),而且不需要你手動呼叫(並確保可在 pipeline 中運作)。最後,我們也提供了特徵名稱清單 kidney_feature_names、目標名稱 kidney_target_name、特徵 X,以及目標 y。
在本練習中,你的任務是套用 sklearn 的 SimpleImputer,對資料集中所有類別型欄位進行補值。你可以參考數值型補值 mapper 的建立方式作為範本。注意關鍵參數 input_df=True 與 df_out=True。這樣你才能以 DataFrame(而不是陣列)進行操作。預設情況下,轉換器會接收所選欄位組成的 numpy 陣列作為輸入,因此 DataFrame mapper 的輸出也會是陣列。歷史上,scikit-learn 的轉換器主要是為 numpy 陣列設計,而非 pandas DataFrame,儘管它們在基本索引介面上很相似。
本練習屬於課程
使用 XGBoost 的極端梯度提升
練習說明
- 使用
DataFrameMapper()與SimpleImputer()套用類別型補值器。SimpleImputer()不需要傳入任何參數。欄位已包含在categorical_columns。請記得指定input_df=True與df_out=True,並在串列推導中使用category_feature作為迭代變數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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=____
)