케이스윔의 개발 블로그

[Lab05] Logistic classification 구현하기 본문

모두를 위한 딥러닝

[Lab05] Logistic classification 구현하기

kswim 2018. 5. 7. 14:21

학습을 통해서 cost를 작게 하는 W를 구해보자! cost를 최소화하고자 하는 방법은 Linear regression과 마찬가지로 기울기를 변화시키면서 W를 조정하게 된다!


import tensorflow as tf


x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]

y_data = [[0],[0],[0], [1], [1], [1]]

#x_data는 공부한시간, y_data는 0아니면 1로 주어진다! 


#None으로 주는 이유는 데이터가 몇개 주어질지 몰라서 n개임을 표시한당

X = tf.placeholder(tf.float32, shape=[None,2])

Y = tf.placeholder(tf.float32, shape=[None,1])

#shape에 주의를 합시다!!!!! Multi-variable이니까!!!!


W = tf.Variable(tf.random_normal([2, 1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')


#matmul -> matrix끼리 곱하기! shape를 맞춰야 한다.

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


cost = -tf.reduce_mean(Y*tf.log(hypothesis) + (1-Y)*tf.log(1-hypothesis))

#reduce_mean은 평균을 만들어주는 부분!


train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)


#예측한 값이 hypothesis이고 그 값이 0.5을 기준으로 cast하면 true나 false가 나온다!

predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)

accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))


with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())

    

    for step in range(10001):

        cost_val, _ = sess.run([cost, train], feed_dict={X: x_data, Y:y_data})

        if step % 200 == 0:

            print(step, cost_val)

    

    h, c, a = sess.run([hypothesis, predicted, accuracy],feed_dict={X: x_data, Y:y_data})

    #위에 학습한 모델에 x_data를 넣어서 예측값을 출력해본다!

    print("\nhypothesis:\n", h, "\nCorrect(Y):\n", c, "\nAccuracy: ", a)



생각보다 코드가 너무 간단하다! 이론에서 봐도 알 수 있듯이 대부분 수식으로 나타낼 수 있고, 그런 경우 tensorflow의 계산을 통해서 쉽게 값을 계산하고 학습을 시킬 수 있다! 신기하다!


Comments