2,456 바이트 추가됨
, 2021년 9월 2일 (목) 02:23
== 개요 ==
수집한 데이터 안에 결측치가 있는 경우가 있다. 이런 경우 어떻게 다룰 것인가?
# 버리기. 결측치가 있는 행을 버리거나 열을 버리는 것.
# 채우기. 결측치를 특정 값으로 채운다. 정확한 데이터는 아니지만, 열을 통째로 버리는 경우보단 유용.
# 새로운 행 만들기. 위 두 과정의 절충. 특정 값으로 채우되, 결측값을 새로 채웠다는 정보를 알려주는 행을 새로 만든다.
== 결측치 다루기 예시 ==
Kaggle의 'Missing Values'에서 제공한 코드를 약간 변형.
{| class="wikitable"
!전략
!예시
|-
|버리기
|<syntaxhighlight lang="python">
# 결측치가 하나라도 있는 열을 찾는다.
cols_with_missing = [col for col in X_train.columns if X_train[col].isnull().any()]
# 해당 행 버리기.
reduced_X_train = X_train.drop(cols_with_missing, axis=1)
reduced_X_valid = X_valid.drop(cols_with_missing, axis=1)
</syntaxhighlight>
|-
|채우기
|<syntaxhighlight lang="python">
from sklearn.impute import SimpleImputer
imputer = SimpleImputer()
imputed_train_X = pd.DataFrame(imputer.fit_transform(train_X)) # 학습용 자료에 결측치 채워넣기.
test_train_X = pd.DataFrame(imputer.fit_transform(test_X)) # 테스트용 데이터에 결측치 채워넣기.
</syntaxhighlight>[어떤 값으로 채우는 걸까?]
|-
|채우고, 표시하기
|<syntaxhighlight lang="python">
X_train_plus = X_train.copy()
X_valid_plus = X_valid.copy()
# 해당 값이 원랜 비어있었다는 것을 표시하기 위한 열 만들기.
for col in cols_with_missing:
X_train_plus[col + '_was_missing'] = X_train_plus[col].isnull()
X_valid_plus[col + '_was_missing'] = X_valid_plus[col].isnull()
# 채우기
my_imputer = SimpleImputer()
imputed_X_train_plus = pd.DataFrame(my_imputer.fit_transform(X_train_plus))
imputed_X_valid_plus = pd.DataFrame(my_imputer.transform(X_valid_plus))
# imputer가 열 이름을 다 지워버리기 때문에 열을 다시 복사한다.
imputed_X_train_plus.columns = X_train_plus.columns
imputed_X_valid_plus.columns = X_valid_plus.columns
print("MAE from Approach 3 (An Extension to Imputation):")
print(score_dataset(imputed_X_train_plus, imputed_X_valid_plus, y_train, y_valid))
</syntaxhighlight>복잡한 작업을 했기 때문에 단순 채우기보다 성능이 좋아질 것 같지만.. 오히려 나빠지는 경우도 있다.
|}
[[분류:인공지능 이론]]