학습(구)/AI

Multinomial classification - SoftMax 실습

잉아당 2020. 11. 10. 23:54
728x90

Sung Kim님(김성훈 교수님)의 유튜브를 보고 공부한 AI 입니다.

Sung Kim님(김성훈 교수님)의 유튜브 주소 : www.youtube.com/channel/UCML9R2ol-l0Ab9OXoNnr7Lw

 

Sung Kim

컴퓨터 소프트웨어와 딥러닝, 영어등 다양한 재미있는 이야기들을 나누는 곳입니다.

www.youtube.com

import tensorflow as tf
import numpy as np

먼저 필요한 모듈인 tensorlow와 numpy 를 import 시켜 줍니다.

 

x_raw = [[1, 2, 1, 1],
          [2, 1, 3, 2],
          [3, 1, 3, 4],
          [4, 1, 5, 5],
          [1, 7, 5, 5],
          [1, 2, 5, 6],
          [1, 6, 6, 6],
          [1, 7, 7, 7]]
y_raw = [[0, 0, 1],
          [0, 0, 1],
          [0, 0, 1],
          [0, 1, 0],
          [0, 1, 0],
          [0, 1, 0],
          [1, 0, 0],
          [1, 0, 0]]

Training Data로 사용할 x와 y의 배열을 준비합니다. 이때 y는 one - hot 인코딩이 되어진 형태입니다.

 

x_data = np.array(x_raw, dtype=np.float32)
y_data = np.array(y_raw, dtype=np.float32)

그런다음 해당 Training Data를 Matrix 형태로 변영합니다. 

 

nb_classes = 3

클래스가 3개인 것을 변수 형태로 만듭니다.

 

tf.model = tf.keras.Sequential()
tf.model.add(tf.keras.layers.Dense(input_dim=4, units=nb_classes, use_bias=True))

4개의 input이 들어가면 3으로 설정한 nb_classes의 개수 만큼 output이 나오게 설정합니다.

use_bias를 true로 설정하여 bias를 사용합니다.

 

# softmax 함수 활성화 : softmax = exp(logits) / reduce_sum(exp(logits), dim)
tf.model.add(tf.keras.layers.Activation('softmax'))

Activation을 활용하여 softmax 함수를 활성화 시킵니다.

sotfmax는 0~1사이의 값으로 확률을 나타내주는 함수입니다.

 

tf.model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.SGD(lr=0.1), metrics=['accuracy'])
tf.model.summary()

loss로 categorical_crossentropy를 사용하면 결과값이 one-hot encoding이 되어져 나옵니다. sgd를 이용하여 하강 기울기를 사용하고 learning rate를 0.1로 설정하여 모델을 완성합니다.

 

history = tf.model.fit(x_data, y_data, epochs=2000)

준비한 데이터를 이용하여 2000회 학습시킵니다.

 

 

a = tf.model.predict(np.array([[1, 11, 7, 9]]))
print(a, tf.keras.backend.eval(tf.argmax(a, axis=1)))

예측을 수행하고 ont-hot encoding을 통해 어느 클래스가 예측값인지 알 수 있습니다.

 

 

 

전체 코드 

import tensorflow as tf
import numpy as np

x_raw = [[1, 2, 1, 1],
          [2, 1, 3, 2],
          [3, 1, 3, 4],
          [4, 1, 5, 5],
          [1, 7, 5, 5],
          [1, 2, 5, 6],
          [1, 6, 6, 6],
          [1, 7, 7, 7]]
y_raw = [[0, 0, 1],
          [0, 0, 1],
          [0, 0, 1],
          [0, 1, 0],
          [0, 1, 0],
          [0, 1, 0],
          [1, 0, 0],
          [1, 0, 0]]

x_data = np.array(x_raw, dtype=np.float32)
y_data = np.array(y_raw, dtype=np.float32)

nb_classes = 3

tf.model = tf.keras.Sequential()
tf.model.add(tf.keras.layers.Dense(input_dim=4, units=nb_classes, use_bias=True)) 

tf.model.add(tf.keras.layers.Activation('softmax'))

tf.model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.SGD(lr=0.1), metrics=['accuracy'])
tf.model.summary()

history = tf.model.fit(x_data, y_data, epochs=2000)

a = tf.model.predict(np.array([[1, 11, 7, 9]]))
print(a, tf.keras.backend.eval(tf.argmax(a, axis=1)))

 

 

 

 

출처 : github.com/hunkim/DeepLearningZeroToAll/blob/master/tf2/tf2-06-1-softmax_classifier.py

'학습(구) > AI' 카테고리의 다른 글

Learning rate, Data preprocessing, Overfitting  (0) 2020.11.26
Multinomial classification - SoftMax  (0) 2020.11.10
Logistic classification 실습  (0) 2020.10.04
Logistic classification  (0) 2020.10.04
Multi-variable linear regression 실습  (0) 2020.10.04