본문 바로가기
Naver Clould with BitCamp/Aartificial Intelligence

Data Preprocessing: StandardScaler, MinMaxScaler

by HJ0216 2023. 1. 23.

기본 환경: IDE: VS code, Language: Python

 

⭐ 데이터 전 처리(Data Preprocessing)
→ 모델 구축 후 성능을 올리기 위한 데이터 처리

 

⭐ Feature Scaling

: 서로 다른 변수의 값 범위를 일정한 수준으로 맞춰주는 작업

 

1. Standard Scaler(표준화)

: (x-avg(x)) / std(x)

: 데이터의 치우침 현상이 발생했을 때, 데이터의 피처 각각이 평균이 0이고 분산이 1인 정규분포로 변환하는것
: 정규화의 경우 특이치(극단값)의 영향을 크게 받기 때문에, 해당하는 경우에는 표준화를 시키는 것이 좋음

# standardScaler_boston.py

import numpy as np

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.callbacks import EarlyStopping


# 1. Data
dataset = load_boston()
x = dataset.data # for training
y = dataset.target # for predict

x_train, x_test, y_train, y_test = train_test_split(
    x, y,
    train_size=0.7,
    random_state=123
)

scaler = StandardScaler()
# scaler = MinMaxScaler()
scaler.fit(x_train)
# x_train을 기준으로 scaling -> scaler에 훈련된 가중치 저장
x_train = scaler.transform(x_train)
# 가중치가 저장된 scaler로 x_train data를 transform 후 x_train에 저장
x_test = scaler.transform(x_test)
# train data의 가중치가 저장된 scaler로 x_test data를 transform 후 x_test에 저장
# train data로만 fit 후 가중치 저장


# 2. Model
model = Sequential()
model.add(Dense(64, input_dim=13, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(1))


# 3. compile and train
model.compile(loss='mae', optimizer='adam')
earlyStopping = EarlyStopping(monitor='val_loss', mode='min', patience=32, restore_best_weights=True, verbose=1)
model.fit(x_train, y_train,
          epochs=512,
          batch_size=32,
          validation_split=0.2,
          callbacks=[earlyStopping],
          verbose=1)

# 4. evaluate and predict
loss = model.evaluate(x_test, y_test)
y_predict = model.predict(x_test)


from sklearn.metrics import mean_squared_error, r2_score

def RMSE (y_test, y_predict):
    return np.sqrt(mean_squared_error(y_test, y_predict))
print("RMSE: ", RMSE(y_test, y_predict))

r2 = r2_score(y_test, y_predict)
print("R2: ", r2)



'''
Result
RMSE:  3.9774667461538487
R2:  0.7499457664401593

'''

 

2. MinMax Scaler(정규화)
: (x-min(x))/(max(x)-min(x))

: 서로 다른 피처의 크기를 제한하기 위해 값의 크기를 변환하는 것

: 원 데이터의 분포를 유지시킬 필요가 있을 때 사용하기 좋음

# minMaxScaler_california.py

import numpy as np

from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.callbacks import EarlyStopping


# 1. Data
datasets = fetch_california_housing()
x = datasets.data
y = datasets.target

x_train, x_test, y_train, y_test = train_test_split(
    x, y,
    test_size=0.2,
    shuffle= True,
    random_state = 333
)

# scaler = StandardScaler()
scaler = MinMaxScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)


# 2. Model Construction
model = Sequential()
model.add(Dense(64, input_shape=(8,)))
model.add(Dense(64))
model.add(Dense(32))
model.add(Dense(1))


# 3. Compile and train
model.compile(loss='mae', optimizer='adam')
earlyStopping = EarlyStopping(monitor='val_loss', mode='min', patience=32, restore_best_weights=True, verbose=1)
hist = model.fit(x_train, y_train,
          epochs=512,
          batch_size=16,
          validation_split=0.2,
          callbacks=[earlyStopping],
          verbose=1)


# 4. evaluate and predict
loss = model.evaluate(x_test, y_test)
y_predict = model.predict(x_test)


from sklearn.metrics import mean_squared_error, r2_score

def RMSE (y_test, y_predict):
    return np.sqrt(mean_squared_error(y_test, y_predict))
print("RMSE: ", RMSE(y_test, y_predict))

r2 = r2_score(y_test, y_predict)
print("R2: ", r2)



'''
Result
RMSE:  0.7262463681006281
R2:  0.586027099412155

'''

 

⭐ Scaling 대상

⚠️ Raw data에 scaler를 진행 할 경우,
training data와 test data의 scaler에 공백이 발생(예: 0~0.8)
→ total data가 아닌 training data를 scaler 처리(training: 0~1)
→ scaling 처리 된 train data의 가중치를 따르며 해당 가중치를 test data에 적용

예시
train set: 0 2 3 4 6 7 8
scaler: 0 0.25 .... 1
Test set: 1 5 9
scaler: 0.125 .... 1.125
-> train weight를 test, validation, predict로 끌고 들어옴

validaion data(학습지) 사용 시, 같이 weight가 저장된 scaler로 transform이 필요하나 fit()에서 validation_split을 한 경우, scaling된 train data를 이용했기 때문에 따로 transform 처리 필요 X

# 1. Data
x_tmp, x_test, y_tmp, y_test = train_test_split(
    x, y,
    test_size=0.2,
    shuffle= True,
    random_state = 333
)
x_train, x_val, y_train, y_val = train_test_split(
    x_tmp, y_tmp,
    test_size=0.2,
    shuffle= True,
    random_state = 333
)

scaler = MinMaxScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)
x_val = scaler.transform(x_val)

# scaling되지 않은 train data로 validation data를 만들 경우,
# train data로 만들어진 weight가 저장되어있는 scaler로 val data를 transform 해줘야 함
# 3. Compile and train
model.fit(x_train, y_train,
   epochs=300,
   batch_size=16,
   validation_split=0.2,
   verbose=1)
   
# scaling된 train data에서 validation을 split -> val_data scaling 필요 없음

 

 

 

소스 코드

🔗 HJ0216/TIL

 

참고 자료

📑 머신러닝 StandardScaler(표준화)

📑 피처 스케일링(StandardScaler,MinMaxScaler)

📑 싸이킷런 데이터 전처리 스케일 조정(스케일러)

 

 

'Naver Clould with BitCamp > Aartificial Intelligence' 카테고리의 다른 글

Save model and weights  (0) 2023.01.24
CNN Model Construction  (0) 2023.01.24
Classification Model Construction  (0) 2023.01.23
Pandas pkg and Numpy pkg  (1) 2023.01.23
Classification and One-Hot Encoding  (0) 2023.01.23