오답노트

[Keras] MultiClass - SoftMax 본문

Python/DL

[Keras] MultiClass - SoftMax

권멋져 2022. 9. 13. 21:56

MultiClass

로지스틱 회귀는 분류 모델로 0과 1로만 판단할 수 있다. 하지만 분류의 개수가 3개 이상이면 분류할 수 없게 된다.

그래서 로지스틱 회귀 결과에 *n 으로 분류의 개수를 늘린다는 아이디어는 존재했지만, 범주형 변수에 수학적인 계산은 의미가 없다.

 

그래서 등장한 개념이 one vs the others(one vs rest) 이다. 이 방식은 분류의 개수가 3개 이상일 경우, 분류 중 1개일 경우와 그 외일 경우를 3개로 나누어 생각하는 것이다. 하지만 이 방법으로 로지스틱 회귀를 3개를 만들면 확률로 계산되어 1을 넘어가버리게 된다.

 

이 확률을 노말라이즈 하여 확실하게 분류를 하는 것이 SoftMax이다.

 

SoftMax

One-Hot Encoding

to_categorical 함수를 통해 target 과 분류 개수를 입력하면 One-Hot Encoding을 할 수 있다.

 

import tensorflow as tf
from tensorflow import keras

from sklearn.datasets import load_iris

iris = load_iris()

x = iris.data
y = iris.target

print(x.shape, y.shape) # (150, 4), (150,)

print(y) 
'''
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
'''

#one-hot encoding
from tensorflow.keras.utils import to_categorical
y = to_categorical(y, 3)
print(x.shape, y.shape) # (150, 4), (150,3)

print(y[:10])
'''
array([[1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.],
       [1., 0., 0.]], dtype=float32)
'''

 

Sequential API

#케라스 세션 클리어
keras.backend.clear_session()

#모델 생성
model_seq = keras.models.Sequential()

#레이어 추가
model_seq.add(keras.layers.Input(shape=(4,)))
model_seq.add(keras.layers.Dense(3, activation='softmax'))

#모델 컴파일
model_seq.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])

#모델 학습
model_seq.fit(x,y,epochs=10,verbose=1)

#모델 예측
print(model_seq.predict(x)[:5])
print(y[:5])

'''

[[0.00327347 0.9714513  0.02527525]
 [0.00430241 0.9673483  0.02834945]
 [0.00518749 0.9609153  0.03389724]
 [0.00666014 0.95718485 0.03615502]
 [0.00370575 0.9686766  0.02761762]]
 
[[1. 0. 0.]
 [1. 0. 0.]
 [1. 0. 0.]
 [1. 0. 0.]
 [1. 0. 0.]]
 
 '''

 

Functional API

# 케라스 세션 클리어
keras.backend.clear_session()

#레이어 선언
il = keras.layers.Input(shape=(4,))
ol = keras.layers.Dense(3,activation='softmax')(il)

#모델 선언
model_fuc = keras.models.Model(il,ol)

#모델 컴파일
model_fuc.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])

#모델 학습
model_fuc.fit(x,y,epochs=10,verbose=1)

#모델 예측
print(y[:5])
print(model_fuc.predict(x)[:5])

'''

[[1. 0. 0.]
 [1. 0. 0.]
 [1. 0. 0.]
 [1. 0. 0.]
 [1. 0. 0.]]
 
[[5.2907735e-01 4.7062388e-01 2.9874884e-04]
 [5.3845602e-01 4.6103981e-01 5.0418189e-04]
 [5.2963108e-01 4.6982110e-01 5.4789055e-04]
 [4.9338010e-01 5.0594562e-01 6.7431619e-04]
 [5.1630509e-01 4.8338053e-01 3.1432847e-04]]

'''

'Python > DL' 카테고리의 다른 글

[Keras] EarlyStopping  (0) 2022.09.15
[Keras] Flatton Layer  (0) 2022.09.15
[Keras] ANN  (0) 2022.09.14
[Keras] Functional API  (0) 2022.09.13
[Keras] Sequential API  (0) 2022.09.13