728x90
728x170

어떤 결과치의 합을 1로 나타내도록 하는 것

여러 결과를 나타내고자 할때 사용된다. (A,B,C...)

A,B,C 를 판별한다고 할때

X값일때  A 인지 물어보면 결과가 0.7(A), 0.2(B), 0.1(C) 이런 식으로 나오게 된다

그러므로 X 일때 A 결과가 맞다고 보면된다.

이를 1.0, 0.0, .0.0 으로 명확하게 구분지으려고 할때는 ONE-HOT ENCODING 을 사용하면된다.

 

코드

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 = [[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])
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 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}))

    # 학습된 결과로 결론을 도출해봅니다.
    a = sess.run(hypothesis, feed_dict={X: [[1, 11, 7, 9]]})
    # argmax 는 그중에 최고값을 가려냅니다.
    print(a, sess.run(tf.argmax(a, 1)))

 결과

(0, 5.048625)
(200, 0.5484252)
(400, 0.43214869)
(600, 0.35246667)
(800, 0.27682927)
(1000, 0.23268281)
(1200, 0.21055315)
(1400, 0.19221503)
(1600, 0.17675203)
(1800, 0.16353439)
(2000, 0.15210819)
--------------
(array([[  1.38904958e-03,   9.98601854e-01,   9.06129117e-06]], dtype=float32), array([1]))

 

마지막줄에서 중간의 9.98601854e-01 값이 0.9 로 가장 큰 값을 가지므로 몇번째 있는지 확인하여 1 을 리턴한다. (0,1,2)

 

아래처럼 단일 값이 아닌 여러 값을 가지고 예측할수 있다.

 

    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)))

728x90
그리드형
Posted by kjun
,