관리 메뉴

Storage Gonie

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

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

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

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

# Softmax 구현방법 (라이브러리를 이용하는 방법)

- tf.nn.softmax_cross_entropy_with_logits(logits= , labels= ) 를 이용하면 크로스 엔트로피를 구하는 공식을 사용할 수 있다.

- 여기서 주의할 점은 Y는 label로 1개의1, 여러개의 0으로 이루어진 one_hot 벡터 이어야 한다.

- 그러면 각각의  logit에 대한 오차값이 결과로 나오고 그것을 tf.reduce_mean해주면 전체에 대한 평균오차값이 나온다.



# Y label을 one-hot 벡터로 변환하는 방법

- tf.one_hot()을 사용한 뒤 tf.reshape을 이용함(* tf.one_hot()은 입력으로 rank가 N 인 것을 넣어주면 rank가 N+1인 것을 결과값으로 내주므로 이를 다시 rank가 N인 것으로 변경하는 과정)

- ex) [ [0], [3] ] => [ [[1000000]], [[0001000]] ] =>  [ [1000000], [0001000] ]

- ex) { shape(2,1) , rank=2 } => { shape( 2,1,7), rank=3 } => { shape(2,7), rank=2}

y_data = xy[:, -1]  => [0, 1, 2, 0, 6]

y_data = xy[:, [-1]] => [[0], [1], [2], [0], [6]]

import tensorflow as tf
import numpy as np

# Predicting animal type based on various features
xy = np.loadtxt('data-04-zoo.csv', delimiter=',', dtype=np.float32) # 16개의 features, 1개의 label
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
print(x_data.shape, y_data.shape)

nb_classes = 7 # 0 ~ 6

X = tf.placeholder(tf.float32, [None, 16])
Y = tf.placeholder(tf.int32, [None, 1]) # 0 ~ 6, shape = (?, 1), ex)[[0], [3]] shape=(2,1) , rank=2

Y_one_hot = tf.one_hot(Y, nb_classes) # one hot shape = (?, 1, 7) ex)[[[1000000]], [[0001000]]] shape=(2,1,7), rank=3
print("one_hot", Y_one_hot)

# -1은 모든 것을 의미하며, 왼쪽인자를 오른쪽에서 지정한 모양으로 모양을 변경해주는 것
Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes]) # shape = (?, 7) ex)[[1000000], [0001000]] shape=(2,7) , rank=2
print("reshape", Y_one_hot)

'''
((101, 16), (101, 1))
('one_hot', <tf.Tensor 'one_hot:0' shape=(?, 1, 7) dtype=float32>)
('reshape', <tf.Tensor 'Reshape:0' shape=(?, 7) dtype=float32>)
'''

 

# Softmax를 이용한 classifier만들기

# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
tf.set_random_seed(777) # for reproducibility

# Predicting animal type based on various features
xy = np.loadtxt('data-04-zoo.csv', delimiter=',', dtype=np.float32) # 16개의 features, 1개의 label
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
print(x_data.shape, y_data.shape)

nb_classes = 7 # 0 ~ 6

X = tf.placeholder(tf.float32, [None, 16])
Y = tf.placeholder(tf.int32, [None, 1]) # 0 ~ 6, shape = (?, 1), ex)[[0], [3]] shape=(2,1) , rank=2

Y_one_hot = tf.one_hot(Y, nb_classes) # one hot shape = (?, 1, 7) ex)[[[1000000]], [[0001000]]] shape=(2,1,7), rank=3
print("one_hot", Y_one_hot)

# -1은 모든 것을 의미하며, 왼쪽인자를 오른쪽에서 지정한 모양으로 모양을 변경해주는 것
Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes]) # shape = (?, 7) ex)[[1000000], [0001000]] shape=(2,7) , rank=2
print("reshape", Y_one_hot)

W = tf.Variable(tf.random_normal([16, 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)
logits = tf.matmul(X, W) + b
hypothesis = tf.nn.softmax(logits)

# Cross entropy cost/loss
cost_i = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y_one_hot)
cost = tf.reduce_mean(cost_i)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)

prediction = tf.argmax(hypothesis, 1) # 가장 높은 값을 가지는 index반환
correct_prediction = tf.equal(prediction, tf.argmax(Y_one_hot, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Launch graph
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())

for step in range(2000):
sess.run(optimizer, feed_dict={X: x_data, Y: y_data})
if step % 100 == 0:
loss, acc = sess.run([cost, accuracy], feed_dict={X: x_data, Y: y_data})
print("Step: {:5}\tLoss: {:.3f}\tAcc: {:.2%}".format(step, loss, acc))

# Let's see if we can predict
pred = sess.run(prediction, feed_dict={X: x_data})
# y_data: (N,1) = flatten => (N, ) matches pred.shape
for p, y in zip(pred, y_data.flatten()): # [[0], [3]].flatten = [0, 3], zip은 두 리스트를 묶는 것으로 양쪽리스트에서 하나씩 뽑기위해 사용

print("[{}] Prediction: {} True Y: {}".format(p == int(y), p, int(y)))

'''
Step: 0 Loss: 5.106 Acc: 37.62%
Step: 100 Loss: 0.800 Acc: 79.21%
Step: 200 Loss: 0.486 Acc: 88.12%
Step: 300 Loss: 0.349 Acc: 90.10%
Step: 400 Loss: 0.272 Acc: 94.06%
...
Step: 1600 Loss: 0.068 Acc: 100.00%
Step: 1700 Loss: 0.064 Acc: 100.00%
Step: 1800 Loss: 0.060 Acc: 100.00%
Step: 1900 Loss: 0.057 Acc: 100.00%
[True] Prediction: 0 True Y: 0
[True] Prediction: 0 True Y: 0
[True] Prediction: 3 True Y: 3
[True] Prediction: 0 True Y: 0
[True] Prediction: 0 True Y: 0
...
[True] Prediction: 0 True Y: 0
[True] Prediction: 0 True Y: 0
[True] Prediction: 3 True Y: 3
[True] Prediction: 3 True Y: 3
[True] Prediction: 0 True Y: 0
'''


반응형
Comments