hello, world!

[ML lab 06-1] TensorFlow로 Softmax Classification 구현하기 본문

AI/모두를 위한 ML (SungKim)

[ML lab 06-1] TensorFlow로 Softmax Classification 구현하기

ferozsun 2021. 2. 18. 11:56

Softmax Classification: 여러 개의 class 중에서 결과를 예측해야 할 때 유용하다.

    (ex. 학점 A, B, C, D, F 등 n개의 항목이 있는 경우)


▷ Hypothesis => Softmax function을 통과시킨다.

특징

1. a, b, c의 hypothesis는 0과 1 사이의 값이다.

2. a, b, c의 hypothesis 총합은 1이다. 따라서 확률로 볼 수 있다.

    (one-hot encoding: 확률이 가장 큰 것을 100%, 나머지를 0%로 판단하여 구현하는 방법)


▷ Cost function => Cross-entropy

실제 값 Y와 softmax의 결과값의 차이


Gradient descent => cost function의 미분


import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

x_data = [[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_data = [[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 = tf.placeholder("float", [None, 4])
Y = tf.placeholder("float", [None, 3]) # Y element 개수는 label(class)의 개수
nb_classes = 3

W = tf.Variable(tf.random_normal([4, nb_classes]), name = 'weight')
b = tf.Variable(tf.random_normal([nb_classes]), name = 'bias')

# tf.nn.softmax computes softmax activations
# softmax = exp(logits) / reduce_sum(exp(logits), dim)
hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)

# cross entropy coss/loss
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis = 1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1).minimize(cost)

# Launch graph
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    
    for step in range(2001):
        sess.run(optimizer, feed_dict = {X: x_data, Y: y_data})
        if step % 200 == 0:
            print(step, sess.run(cost, feed_dict = {X: x_data, Y: y_data}))
    print("\n");
    
    # 잘 학습 되었는지 확인!
    # Test & one-hot encoding
    a = sess.run(hypothesis, feed_dict = {X: [[1, 11, 7, 9]]})
    print(a, sess.run(tf.arg_max(a, 1)), "\n")
    
    all = sess.run(hypothesis, feed_dict = {X: [[1, 11, 7, 9], [1, 3, 4, 3], [1, 1, 0, 1]]})
    print(all, sess.run(tf.arg_max(all, 1)))

[출력]

학습 후 테스트도 잘 작동한다.

각각의 hypothesis도 출력하고, one-hot encoding을 통해 가장 확률이 높은 label도 출력한다.

Comments