[ML] 데이터 정규화 (Normalization)

youngchae·2022년 9월 5일
1

ML

목록 보기
3/4
post-thumbnail

Q. 정규화를 왜 해야할까요? 정규화의 방법은 무엇이 있나요?

데이터 정규화 (Data Normalization)

: 데이터를 특정 구간으로 바꾸는 척도법

  • 서로 다른 feature의 크기를 통일하기 위해서 크기를 변환
  • 모두 동일한 크기 단위로 비교하기 위해 값을 변환

1. Min-Max Scaling

: 모든 feature가 0과 1 사이에 위치하도록 데이터를 변경하는 방법

  • 이상치의 영향을 많이 받음
  • 모든 feature 들의 스케일이 동일
  • 분포에 대해서 알지 못할 때 유용
xnew=xxminxmaxxminx_{new} = \frac{x-x_{min}}{x_{max}-x_{min}}
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.datasets import load_iris

# sklearn dataset에서 iris data 불러오기
iris = load_iris()
iris_data = iris.data
iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)

print('feature들의 최소 값')
print(iris_df.min())
print('\nfeature들의 최대 값')
print(iris_df.max())

---------------------
<결과>
feature들의 최소 값
sepal length (cm)    4.3
sepal width (cm)     2.0
petal length (cm)    1.0
petal width (cm)     0.1
dtype: float64

feature들의 최대 값
sepal length (cm)    7.9
sepal width (cm)     4.4
petal length (cm)    6.9
petal width (cm)     2.5
dtype: float64

# MinMaxScaler객체 생성
scaler = MinMaxScaler()
# MinMaxScaler 로 데이터 셋 변환. fit() 과 transform() 호출.  
scaler.fit(iris_df) # fit = 데이터 변환을 위한 기준 정보 설정
iris_scaled = scaler.transform(iris_df) # transform = 설정된 정보를 이용한 데이터 변환

# iris_df_scaled DataFrame 생성
iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)
print('feature들의 최소 값')
print(iris_df_scaled.min())
print('\nfeature들의 최대 값')
print(iris_df_scaled.max())

---------------------
<결과>
feature들의 최소 값
sepal length (cm)    0.0
sepal width (cm)     0.0
petal length (cm)    0.0
petal width (cm)     0.0
dtype: float64

feature들의 최대 값
sepal length (cm)    1.0
sepal width (cm)     1.0
petal length (cm)    1.0
petal width (cm)     1.0
dtype: float64

2. Z-Score Normalization = Standardization(표준화)

: 각 피처의 표준편차와 평균으로 값을 정규화 (평균이 0, 분산이 1인 값으로 변환)

  • 이상치를 잘 처리함 (이상치의 영향을 덜 받음)
  • feature 들의 스케일이 동일하지 않음
  • 데이터가 정규분포를 따라야할 때 유용 (SVM, Linear Regression, Logistic Regression은 데이터가 정규분포를 가지고 있다고 가정하고 구현했기에 성능 향상에 중요한 요소가 될 수 있음)
xnew=ximean(x)stdev(x)x_{new} = \frac{x_i-mean(x)}{stdev(x)}
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler

# sklearn dataset에서 iris data 불러오기 
iris = load_iris()
iris_data = iris.data
iris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)

print('feature 들의 평균 값')
print(iris_df.mean())
print('\nfeature 들의 분산 값')
print(iris_df.var())

---------------------
<결과>
feature 들의 평균 값
sepal length (cm)    5.843333
sepal width (cm)     3.057333
petal length (cm)    3.758000
petal width (cm)     1.199333
dtype: float64

feature 들의 분산 값
sepal length (cm)    0.685694
sepal width (cm)     0.189979
petal length (cm)    3.116278
petal width (cm)     0.581006
dtype: float64
# StandardScaler객체 생성
scaler = StandardScaler()
# StandardScaler 로 데이터 셋 변환. fit( ) 과 transform( ) 호출.  
scaler.fit(iris_df) # fit = 데이터 변환을 위한 기준 정보 설정
iris_scaled = scaler.transform(iris_df) # transform = 설정된 정보를 이용한 데이터 변환

# iris_df_scaled DataFrame 생성
iris_df_scaled = pd.DataFrame(data=iris_scaled, columns=iris.feature_names)
print('feature 들의 평균 값')
print(iris_df_scaled.mean())
print('\nfeature 들의 분산 값')
print(iris_df_scaled.var())

---------------------
<결과>
feature 들의 평균 값
sepal length (cm)   -1.690315e-15
sepal width (cm)    -1.842970e-15
petal length (cm)   -1.698641e-15
petal width (cm)    -1.409243e-15
dtype: float64

feature 들의 분산 값
sepal length (cm)    1.006711
sepal width (cm)     1.006711
petal length (cm)    1.006711
petal width (cm)     1.006711
dtype: float64

3. Robust Scaling

: median과 IQR(Interquartile range = Q3-Q1)를 사용하여 스케일링

  • 이상치의 영향을 덜받음 (robust to outliers)
xnew=ximedian(x)Q3Q1x_{new} = \frac{x_i-median(x)}{Q3-Q1}

4. Max Absolute Scaling

: 최대절대값과 0이 각각 1,0이 되도록 스케일링

  • 모든 feature의 범위가 -1과 1 사이에 위치
xnew=ximax(x)x_{new} = \frac{x_i}{max(|x|)}

데이터 스케일링을 해야하는 때 (스케일링이 중요한 알고리즘)

  • Gradient Descent 기반 알고리즘
    • mini-batch Gradient Descent
    • Stochastic Gradient Descent
  • 거리 기반 알고리즘
    • KNN
    • K-means
    • SVM
  • PCA를 사용한 feature engineering

[참고]

profile
we_need_to_talk_about_ds

0개의 댓글