MY MEMO

[MACHINE LEARNING] Logistic classifier 본문

MACHINE LEARNING/Sung Kim - 실습

[MACHINE LEARNING] Logistic classifier

l_j_yeon 2017. 4. 19. 02:42

Logistic algorithm을 구현한 코드이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 = 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 = tf.sigmoid(tf.matmul(X,W)+b)
 
cost = -tf.reduce_mean(Y*tf.log(hypothesis)+(1-Y)*tf.log(1-hypothesis))
 
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
 
predicted = tf.cast(hypothesis>0.5,dtype = tf.float32)
#cast -> True나 False
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted,Y),dtype=tf.float32))
#예측한 값 = predicted와 정답 Y가 같은지 True or False
 
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})
  print("\nhypothesis: ",h,"\nCorrect (Y):",c,"\nAccuracy: ",a)

이 코드의 결과는


이것이다. 보면 cost는 계속 줄어들고 0에 가까워지고 있다.

hypothesis를 보면 0.03 0.1 0.3 0.7 0.9 0.9가 나오는 것을 볼 수 있다.

0.5이상이면 1로 나타나고 0.5이하이면 0으로 나타난다.

Accuracy는 1.0 즉 완벽하게 맞아떨어졌다.


코드의 간단한 설명은 강의자료로 첨부한다! 아주 잘 설명되어있다!



tf.cast는 0과 1로 나타내어 주는 것이다. True or False이다.

accuracy는 predicted = 예측된 값과 Y = 정답을 비교해서 tf.cast = 0과 1로 계산하여 tf.reduce_mean = 평균을 낸다!


+) tf.reduce_mean 관련 코드는 참고 : http://ljs93kr.tistory.com/33 여기에 굉장히 잘 설명되어있다!

 

그렇다면 이제 파일로 저장된 코드를 불러와 실행시켜보자


data-03-diabetes.csv코드이며 8개의 데이터를 가지고 왔다


-0.294118,0.487437,0.180328,-0.292929,0,0.00149028,-0.53117,-0.0333333,0

-0.882353,-0.145729,0.0819672,-0.414141,0,-0.207153,-0.766866,-0.666667,1

-0.0588235,0.839196,0.0491803,0,0,-0.305514,-0.492741,-0.633333,0

-0.882353,-0.105528,0.0819672,-0.535354,-0.777778,-0.162444,-0.923997,0,1

0,0.376884,-0.344262,-0.292929,-0.602837,0.28465,0.887276,-0.6,0

-0.411765,0.165829,0.213115,0,0,-0.23696,-0.894962,-0.7,1

-0.647059,-0.21608,-0.180328,-0.353535,-0.791962,-0.0760059,-0.854825,-0.833333,0

0.176471,0.155779,0,0,0,0.052161,-0.952178,-0.733333,1


이제 이 데이터를 저장해서 Logistic classifier를 해보자!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import tensorflow as tf
import numpy as np
xy = np.loadtxt("C:\Code\Python_Workspace\Machine Learning\data-03-diabetes.csv",delimiter=',',dtype=np.float32)
x_data = xy[:,0:-1]
y_data = xy[:,[-1]]
 
X = tf.placeholder(tf.float32,shape=[None,8])
Y = tf.placeholder(tf.float32,shape=[None,1])
 
W = tf.Variable(tf.random_normal([8,1]),name='weight')
#the number of x_datat is 8 and the number of y_data is 1
b = tf.Variable(tf.random_normal([1]),name = 'bias')
 
hypothesis = tf.sigmoid(tf.matmul(X,W)+b)
 
cost = -tf.reduce_mean(Y*tf.log(hypothesis)+(1-Y)*tf.log(1-hypothesis))
 
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
 
predicted = tf.cast(hypothesis>0.5,dtype = tf.float32)
#cast -> True나 False
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted,Y),dtype=tf.float32))
#예측한 값 = predicted와 정답 Y가 같은지 True or False
 
with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  for step in range(10001):
    sess.run(train,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}))
  h,c,a = sess.run([hypothesis,predicted,accuracy],feed_dict={X:x_data,Y:y_data})
  print("\nhypothesis: ",h,"\nCorrect (Y):",c,"\nAccuracy: ",a)


이 코드의 결과는



이것이다! 마찬가지로 정답과 100% 일치하게 결과값이 도출되었다!!!!


Comments