함께 배워가는 학생개발자

Softmax function 본문

머신러닝

Softmax function

Hgrace 2017. 5. 15. 00:55

Softmax Function


식 : 

tensorflow 코드 : 

* cost 식 직접 구할 때

hypothesis = tf.nn.softmax(tf.matmul(X,W)+b)

cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis = 1)

optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1).minimize(cost)


* cost cross_entropy_with_logits 함수 사용할 때

Y_one_hot = tf.one_hot(Y, nb_classes)                         # shape = (?, 1, 7)

Y_one_hot = tf.reshape(Y_one_hot, [-1, nb_classes])        # shape = (?, 7)

logits = tf.matmul(X,W)+b

hypothesis = tf.nn.softmax(logits)

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)



Logistic classifier를 이용해 나온 hypothesis 값을 softmax 함수에 인수 값으로 넣어주면
모든 클래스의 값의 합이 1이고 각 값의 범위가 0 < softmax(hypothesis) < 1인 값으로 나온다.


그 이후에 one-hot encoding을 사용해 하나의 값만 1이 나오고 나머지는 0으로 나온다.


* one_hot, reshape 예시

Y = [[0],[3]]                                 # (2, 1)

Y_one_hot = tf.one_hot(Y, 7)           # (2, 1, 7)    [[[1000000]],[[0001000]]]

Y_one_hot = tf.reshape(Y_one_hot, [-1, 7])    #(2, 7) [[1000000],[0001000]]



* 테스트

prediction = tf.argmax(hypothesis, argmax = 1)

correct_prediction = tf.equal(prediction, tf.argmax(Y_one_hot, 1))        # tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y_one_hot, 1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


pred = sess.run(prediction, feed_dict={x_data})

for p, y in zip (pred, y_data.flatten()):

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


참고 : 모두를위한딥러닝

'머신러닝' 카테고리의 다른 글

Faster R-CNN  (0) 2019.06.17
MNIST 숫자 인식  (0) 2017.05.15
Normalization  (0) 2017.05.15
Comments