Big data & AI
Deep learning 예제: MNIST
z2soo
2020. 1. 13. 09:08
반응형
목차
MNIST with Neuron Network
tensorflow가 기본으로 제공해주는 예제를 이용해서 MNIST multi-layer (deep learning)을 진행해보자.
- 모듈 삽입
- Data set
- Placeholder
- Weight, bias
- Hypothesis
- Cost function
- Train
- Session, 초기화
- 학습
- 예측
모듈 삽입
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import warnings
warnings.filterwarnings(action='ignore')
# 불필요한 warning 알림을 끈다.
Data set
mnist = input_data.read_data_sets('./data/mnist', one_hot=True)
Placeholder
X = tf.placeholder(shape=[None, 784], dtype=tf.float32)
Y = tf.placeholder(shape=[None, 10], dtype=tf.float32)
Weight, bias
# deep learning을 위해 여러 layer, loogistics를 만들 것 (deep&wide)
# 처음 layer의 logistic은 256개, bias도 따라가야 됨
W1 = tf.Variable(tf.random_normal(shape=[784,256]), name='weight1')
b1 = tf.Variable(tf.random_normal(shape=[256]), name='bias1')
# 앞의 layer에서 나온 값이 sigmoid 된 값이 다음 layer에 들어가게 된다.
layer1 = tf.sigmoid(tf.matmul(X,W1) + b1)
# 두번째 layer 생성
W2 = tf.Variable(tf.random_normal(shape=[256, 256]), name='weight2')
b2 = tf.Variable(tf.random_normal(shape=[256]), name='bias2')
layer2 = tf.sigmoid(tf.matmul(layer1,W2) + b2)
# 세번째 layer 생성
W3 = tf.Variable(tf.random_normal(shape=[256, 10]), name='weight3')
b3 = tf.Variable(tf.random_normal(shape=[10]), name='bias3')
Hypothesis
마지막 layer 에서는 layer 값을 따로 뽑지 않고, 그 값으로 가설을 생성한다.
sigmoid를 쓰면 각각의 확률이 나오고, softmax는 전체에 대한 확률이 나온다.
아직까지는 두 개가 큰 상관이 없지만, 그래도 배운대로 사용하기로 한다.
- tf.nn : nn 은 neuron network 약자, deep learning 과정을 의미하며, 그 때 사용되는 함수 앞에 붙는다.
logit = tf.matmul(layer2, W3) + b3
H = tf.nn.softmax(logit)
Cost function
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logit, labels=Y))
Train
train = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
Session, 초기화
sess = tf.Session()
sess.run(tf.global_variables_initializer())
학습
num_of_epoch = 30
batch_size = 100
for step in range(num_of_epoch):
cost_val = 0
for i in range(num_of_iter):
batch_x, batch_y = mnist.train.next_batch(batch_size)
num_of_iter = int(mnist.train.num_examples / batch_size)
_, cost_val = sess.run([train, cost], feed_dict={X: batch_x,
Y: batch_y})
if step % 3 == 0:
print(f'cost: {cost_val}')
정확도 및 예측
predict = tf.argmax(H,1)
correct = tf.equal(predict, tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct, dtype=tf.float32))
print(f'정확도:{sess.run(accuracy, feed_dict={X:mnist.test.images, Y: mnist.test.labels})}')
반응형