관리 메뉴

Storage Gonie

모두를 위한 딥러닝 제16강 ML lab 06-1: TensorFlow로 Softmax Classification의 구현하기 본문

데이터 사이언스/모두를 위한 딥러닝

모두를 위한 딥러닝 제16강 ML lab 06-1: TensorFlow로 Softmax Classification의 구현하기

Storage Gonie 2018. 9. 17. 21:48
반응형

# Softmax Classifier에서 Softmax함수를 텐서플로우에서 구현하는 코드

- Logistic classifier의 XW + b 의 값을 먼저 "tf.matmul(X,W)+b" 로 표현하고

- 위 식의 값을 Softmax 함수에 통과시킨 것을 "hypothesis = tf.nn.softmax(tf.matmul(X,W) + b)" 로 표현한다.

- Softmax 함수에 통과시키는 값을 logit이라 한다.


Softmax Classifier에서 Cost와 Gradientdescent를 텐서플로우에서 구현하는 코드

- Cost는 -L* log(hypothesis)를 다 더한뒤 개수로 나눠준것.

- Gradientdescent능 Cost함수를 그냥 최소화 시켜주는 W와 b 매개변수들을 찾아가는 것임.



# Softmax Classifier 구현

import tensorflow as tf

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는 one-hot 인코딩의 방식으로 표현된 데이터이다.
# one-hot 인코딩 : 하나만 1이고 나머지는 0인 표현방
# 각각의 자리는 0, 1, 2를 의미하고 그중 하나만 1로 선택되는 것이라고 생각하면 됨.
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_data는 feature가 4개이므로 4
# y_data는 3자리 이므로 3
X = tf.placeholder("float", [None, 4])
Y = tf.placeholder("float", [None, 3])

#label의 개수 -> y의 출력개수
nb_classes = 3

# W는 [X의 입력되는 feature의 수, y의 출력개수]
# b는 [y의 출력개수]
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
# logits : logistic classifier의 hypothesis 즉, WX + b
# softmax = exp(logits) / reduce_sum(exp(logits), dim)
# hypothesis는 결과가 [a, b, c] 이런식으로 나오게됨.
hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)

# Cross entropy cost/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('--------------')

# Testing & One-hot encoding
# tf.argmax(a, 1) 는 a에서 몇번째 인덱스가 가장 큰 숫자를 가지나요 하는 것에 대한 결과값을 반환함, 1은 가로축에 대해 연산을 한다는 의미
a = sess.run(hypothesis, feed_dict={X: [[1, 11, 7, 9]]})
print(a, sess.run(tf.argmax(a, 1)))

print('--------------')

b = sess.run(hypothesis, feed_dict={X: [[1, 3, 4, 3]]})
print(b, sess.run(tf.argmax(b, 1)))

print('--------------')

c = sess.run(hypothesis, feed_dict={X: [[1, 1, 0, 1]]})
print(c, sess.run(tf.argmax(c, 1)))

print('--------------')

# 한번에 물어보는 경우.
all = sess.run(hypothesis, feed_dict={X: [[1, 11, 7, 9], [1, 3, 4, 3], [1, 1, 0, 1]]})
print(all, sess.run(tf.argmax(all, 1)))

'''
--------------
[[ 1.38904958e-03 9.98601854e-01 9.06129117e-06]] [1]
--------------
[[ 0.93119204 0.06290206 0.0059059 ]] [0]
--------------
[[ 1.27327668e-08 3.34112905e-04 9.99665856e-01]] [2]
--------------
[[ 1.38904958e-03 9.98601854e-01 9.06129117e-06]
[ 9.31192040e-01 6.29020557e-02 5.90589503e-03]
[ 1.27327668e-08 3.34112905e-04 9.99665856e-01]] [1 0 2]
'''

그림 참고 : https://youtu.be/VRnubDzIy3A

반응형
Comments