시작하기무료로 시작하기

신장 질환 사례 연구 I: 범주형 Imputer

이제 전처리가 훨씬 더 필요한 데이터셋으로 파이프라인 활용을 계속 연습해 보겠습니다. 만성 신장 질환 데이터셋은 범주형과 수치형 특성이 모두 있지만, 결측치가 매우 많습니다. 목표는 여러 혈액 지표를 특성으로 사용하여 만성 신장 질환 보유 여부를 예측하는 것입니다.

영상에서 Sergey가 언급했듯이, 이번에는 파이프라인 안에서 scikit-learn이 기본적으로 지원하는 것보다 훨씬 더 다양한 처리 단계를 연결할 수 있게 해주는 새로운 라이브러리 sklearn_pandas를 사용합니다. 특히 DataFrameMapper() 클래스를 통해 DataFrame 열에 임의의 sklearn 호환 변환기를 적용할 수 있으며, 결과는 NumPy 배열 또는 DataFrame이 될 수 있습니다.

또한 .to_dict("records")를 사용한 DataFrame 변환을 명시적으로 호출하지 않고도 수행하도록 캡슐화한 Dictifier라는 변환기도 만들어 두었습니다(파이프라인에서 동작하도록 하기 위함입니다). 마지막으로, 특성 이름 목록은 kidney_feature_names, 타깃 이름은 kidney_target_name, 특성은 X, 타깃은 y로 제공되어 있습니다.

이 연습 문제에서는 sklearn의 SimpleImputer를 사용하여 데이터셋의 모든 범주형 열을 대치(Impute)하는 것이 목표입니다. 수치형 대치 매퍼가 어떻게 만들어졌는지 템플릿으로 참고하세요. 키워드 인수 input_df=Truedf_out=True가 보이시나요? 이는 배열 대신 DataFrame으로 작업할 수 있도록 하기 위함입니다. 기본적으로는 선택된 열들이 numpy 배열로 변환기에 전달되며, 그 결과 DataFrame 매퍼의 출력도 배열이 됩니다. 역사적으로 scikit-learn 변환기는 pandas DataFrame이 아닌 numpy 배열을 대상으로 설계되어 왔으며, 비록 기본 인덱싱 인터페이스는 유사합니다.

이 연습은 강의의 일부입니다

XGBoost로 익히는 Extreme Gradient Boosting

강의 보기

연습 안내

  • DataFrameMapper()SimpleImputer()를 사용해 범주형 imputer를 적용하세요. SimpleImputer()에는 인수를 전달할 필요가 없습니다. 열 목록은 categorical_columns에 들어 있습니다. input_df=Truedf_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=____
                                               )
코드 편집 및 실행