북극곰의 개발일기

모두를 위한 딥러닝 lecture5 logistic classfication(실습)





posted by purplebeen on Thu Feb 07 2019 22:18:52 GMT+0900 (KST) in AI


Logistic regression

Logistic regression

import tensorflow as tf
# 공부한 시간
x_data = [[1,2], [2, 3], [3,1], [4,3], [5,3], [6,2]]
# pass / fail 여부
y_data = [[0], [0], [0], [1], [1], [1]]
#placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 2])
Y = tf.placeholder(tf.float32, shape=[None, 1])
W = tf.Variable(tf.random_normal([2,1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')
# Hypothesis using sigmoid : tf.div(1., 1. + tf.exp(tf.matmul(X, W) + b))
hypothesis = tf.sigmoid(tf.matmul(X, W) + b)
#cost / loss function
cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))
#Accuracy computation
#True if hyopothesis > 0.5 else False
predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))
#Launch graph
with tf.Session() as sess:
    #Initialize Tensorflow variables
    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)
    # Accuracy report 
    h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict={X : x_data, Y : y_data})
    print("\nHypothesis : " , h, "\n correct (Y) : " , c, "\nAccuracy : ", a)

cost가 점점 줄어들고 있고, Y의 값이 원본 결과와 100% 일치하기 때문에 accuracy가 1.0이 나오는 것을 볼 수 있다.