본문 바로가기
DNN with Keras/Machine Learning

결측치 (Missing Values) / 특이치 (Outliers)

by goatlab 2023. 5. 1.
728x90
반응형
SMALL

결측치 (Missing Values)

 

결측치는 기계 학습의 현실이다. 모든 데이터 행에는 모든 열에 대한 값이 있는 것이 이상적이다. 하지만, 이것은 거의 그렇지 않다. 일반적인 방법은 결측값을 해당 열의 중앙값으로 바꾸는 것이다. 이 프로그램은 중앙값 (median)을 계산한다. csv 파일을 다운받는다.

 

import os
import pandas as pd

df = pd.read_csv('auto-mpg.csv', na_values = ['NA', '?'])

print(f"horsepower has na? {pd.isnull(df['horsepower']).values.any()}")
print("Filling missing values ...")

med = df['horsepower'].median()
df['horsepower'] = df['horsepower'].fillna(med)

# df = df.dropna() # you can also simply drop NA values
print(f"horsepower has na? {pd.isnull(df['horsepower']).values.any()}")
horsepower has na? True
Filling missing values ...
horsepower has na? False

 

특이치 (Outliers)

 

특이치는 비정상적으로 높거나 낮은 값이다. 특이치는 일반적으로 평균에서 몇 가지 표준 편차가 있는 값으로 간주한다. 때때로 특이치는 단순한 오차이다. 이는 관측치 오차의 결과이다. 특이치는 실제로 크거나 작은 값일 수 있으며 이 값은 다루기 어려울 수 있다. 다음 함수는 이러한 값을 제거할 수 있다.

 

# Remove all rows where the specified column is +/− sd standard deviations
def remove_outliers(df, name, sd):
  drop_rows = df.index[(np.abs(df[name] − df[name].mean()) >= (sd ∗ df[name].std()))]
  df.drop(drop_rows, axis = 0, inplace = True)
# create feature vector
med = df['horsepower'].median()
df['horsepower'] = df['horsepower'].fillna(med)

# Drop the name column
df.drop('name', 1, inplace = True)

# Drop outliers in horsepower
print("Length before MPG outliers dropped : {}".format(len(df)))

remove_outliers(df, 'mpg', 2)
print("Length after MPG outliers dropped : {}".format(len(df)))

pd.set_option('display.max_columns', 0)
pd.set_option('display.max_rows', 5)

display(df)
728x90
반응형
LIST