티스토리 뷰

Logistic Classification



크기와 길이를 통해 해당 상품이 참치(0)인지 꽁치(1) 인지 판별 해보자. 아래 소스는 Logistic Classfication을 사용하여 분류하는 코드이다.


기본의 Linear regression과는 다른 부분들이 보인다.


sigmoid는 그래프로서 최대값은 1, 최소값은 0인 그래프 함수 이다. 해당 부분의 API를 사용하여 데이터를 정규화 한다.


기존에 사용하던 cost 함수와는 조금 다른 형태의 cost 함수 이다. 간단하게 설명하면 참이면 loss는 0이고 거짓이면 loss는 무한대가 되는 그래프를 나타낸다.



데이터를 대입해보면 Y = 0 일 경우, H(x)가 1이면 해당 cost는 무한대가 되지만 H(x)가 0이되면 cost값은 0이 된다. cost값이 0에 가까울 수록 신뢰도가 높아 지므로 해당 값들을 신뢰할 수 있다. 또는 반대로 이해해도 가능하겠다.


반대로 Y = 1 일 경우, H(x)가 1이면 해당 cost값은 0이지만, H(x)가 0이면 해당 cost값은 1이 된다. 나머지 부분은 기존의 Linear regression과 유사하다.

import tensorflow as tf
import numpy as np


def normalize(input):
max = np.max(input, axis=0)
min = np.min(input, axis=0)
out = (input - min) / (max - min)
return out


# 참치(0) / 꽁치(1) | 길이 / 무게
x = [[50, 15], [40, 20], [10, 5], [10, 5], [45, 22], [15, 13]]
y = [[0], [0], [1], [1], [0], [1]]
x = normalize(x)
y = normalize(y)

testM = 2
m = len(x) - testM
print('m: ', m)

x_train = x[0:m, :]
y_train = y[0:m, :]

x_test = x[m:, :]
y_test = y[m:, :]

X = tf.placeholder(tf.float32, [None, 2])
Y = tf.placeholder(tf.float32, [None, 1])
w = tf.Variable(tf.ones([2, 1], dtype=tf.float32))
b = tf.Variable(0.0)

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

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

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train = optimizer.minimize(loss)

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

sess = tf.Session()
sess.run(tf.global_variables_initializer())

for iter in range(10000):
t_, w_, l_, h = sess.run([train, w, loss, hypothesis], feed_dict={X: x_train, Y: y_train})

if iter % 1000 == 0:
print('iter:%d. loss:%f' % (iter, l_))

predict = sess.run(predicted, feed_dict={X: x_test, Y: y_test})
print('class predict', predict)


결과값:




댓글
공지사항
최근에 올라온 글
링크
«   2024/05   »
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
글 보관함