Skip to content

Instantly share code, notes, and snippets.

@yujuwon
Created June 3, 2019 09:25
Show Gist options
  • Save yujuwon/3a0032b1760a981269c6fab5f18e8e0a to your computer and use it in GitHub Desktop.
Save yujuwon/3a0032b1760a981269c6fab5f18e8e0a to your computer and use it in GitHub Desktop.
dl 분류 기초
import tensorflow as tf
import numpy as np
x_data = np.array([[0, 0], [1, 0], [1, 1], [0, 0], [0, 0], [0, 1]])
y_data = np.array([
[1, 0, 0], # 기타
[0, 1, 0], # 포유류
[0, 0, 1], # 조류
[1, 0, 0],
[1, 0, 0],
[0, 0, 1]
])
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# tf.random_uniform : 정규분포 난수를 생성하는 함수로 배열의 shape, 최소, 최대 값을 파라미터로 받는다.
# -1 ~ 1 사이의 난수를 2x3개 생성한다.
W = tf.Variable(tf.random_uniform([2, 3], -1., 1.))
b = tf.Variable(tf.zeros([3]))
# ex) [1, 0] x [[0.2, 0.3, 0.4] + [0.1, 0.2, 0.3] = [0.3, 0.5, 0.7]
# [0.1, 0.2, 0.1]]
# 1x2 matmul 2x3 + 1x3 = 1x3
L = tf.add(tf.matmul(X, W), b)
L = tf.nn.relu(L)
model = tf.nn.softmax(L)
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(model), axis=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(cost)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for step in range(100):
sess.run(train_op, feed_dict={X: x_data, Y: y_data})
if (step + 1) % 10 == 0:
print(step + 1, sess.run(cost, feed_dict={X: x_data, Y: y_data}))
prediction = tf.argmax(model, 1)
target = tf.argmax(Y, 1)
print('예측값:', sess.run(prediction, feed_dict={X: x_data}))
print('실제값:', sess.run(target, feed_dict={Y: y_data}))
is_correct = tf.equal(prediction, target)
print(sess.run(is_correct, feed_dict={X: x_data, Y: y_data}))
print(sess.run(accuracy, feed_dict={X: x_data, Y: y_data})) # 2/6
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
print('정확도: %.2f' % sess.run(accuracy * 100, feed_dict={X: x_data, Y: y_data}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment