rueki

5. Mnist 예제 본문

Tensorflow

5. Mnist 예제

륵기 2019. 7. 18. 09:07
728x90
반응형

딥러닝을 공부할 때 'Hello, world!' 와 같은 존재인 Mnist를 통해 실습해보자.

Mnist는 손글씨 이미지이며, 0부터 9까지의 숫자에 대한 데이터가 있다.

28x28픽셀로서 특징은 784개인데, 즉 입력이 784라는 것을 캐치해야한다. 

그럼 출력값은? 당연히 0부터 9까지 10이 되겠다.

import tensorflow as tf
import numpy as np

먼저 텐서플로우 라이브러리를 불러오자

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/.mnist/data/", one_hot = True)

mnist 데이터는 텐서플로우 안에 내장되어 있어 쉽게 불러올 수가 있으며,

데이터 형태을 원-핫 인코딩 상태로 불러올 것이다. 그래야 Classification이 쉬울테니까.

이미지를 불러왔으니 이제 신경망 모델을 만들 차례이다.

X = tf.placeholder(tf.float32, [None, 784])
Y = tf.placeholder(tf.float32, [None, 10])

W1 = tf.Variable(tf.random_normal([784, 256],stddev = 0.01))
L1 = tf.nn.relu(tf.matmul(X, W1))

W2 = tf.Variable(tf.random_normal([256, 256],stddev=0.01))
L2 = tf.nn.relu(tf.matmul(L1, W2))

W3 = tf.Variable(tf.random_normal([256, 10], stddev=0.01))
model = tf.matmul(L2, W3)

입력층 값은 784로 시작해서, 은닉층을 2개를 넣었다. 은닉층의 각 Layer의 값은 256을 갖고있다.

Neural network 모델을 만들었으니 비용 함수를 만들고 최적화를 해보자.

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=model, labels=Y))
optimizer = tf.train.AdamOptimizer(0.001).minimize(cost)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

세션까지 초기화를 하였다. 이제 학습을 시켜야하는데, 수많은 Mnist의 데이터를 다 사용하기에는

너무 무리이지 않을까? 그래서 임의로 데이터를 뽑기로 했으며  이것을 미니 배치라고 한다.

뽑을 배치의 크기는 100으로 설정하고, 전체 배치는 mnist 수에서 배치 크기인 100을 나누도록 하겠다.

batch_size= 100
total_batch = int(mnist.train.num_examples / batch_size)

이제 비용함수가 최소로 되게끔 훈련을 시켜보자.

for epoch in range(15):
    total_cost = 0
    
    for i in range(total_batch):
        batch_x,batch_y = mnist.train.next_batch(batch_size)
        _,cost_val = sess.run([optimizer, cost], feed_dict = {X: batch_x, Y : batch_y})
        total_cost += cost_val
        
    print("epoch:", '%4d' % (epoch + 1), 
         'Avg. cost=', '{:.3f}'.format(total_cost/total_batch))
    
print("최적화 완료!")
#결과
epoch:    1 Avg. cost= 0.387
epoch:    2 Avg. cost= 0.145
epoch:    3 Avg. cost= 0.094
epoch:    4 Avg. cost= 0.069
epoch:    5 Avg. cost= 0.051
epoch:    6 Avg. cost= 0.039
epoch:    7 Avg. cost= 0.030
epoch:    8 Avg. cost= 0.023
epoch:    9 Avg. cost= 0.022
epoch:   10 Avg. cost= 0.018
epoch:   11 Avg. cost= 0.017
epoch:   12 Avg. cost= 0.014
epoch:   13 Avg. cost= 0.014
epoch:   14 Avg. cost= 0.010
epoch:   15 Avg. cost= 0.011
최적화 완료!

cost 값이 현저히 줄어든 것을 볼 수 있었다.

훈련까지 다 했으니, 실제 데이터와 비교를 하고 정확도를 알아내보자

is_corr = tf.equal(tf.argmax(model, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(is_corr, tf.float32))
print('정확도:', sess.run(accuracy,
                        feed_dict={X: mnist.test.images,
                                   Y: mnist.test.labels}))
                                   
#결과
정확도: 0.9796
728x90
반응형

'Tensorflow' 카테고리의 다른 글

Tensorflow 02. mnist dataset 알아보기  (0) 2019.12.03
TensorFlow 01. 사용법 알아보기  (0) 2019.12.03
4.신경망 구현 - Hidden layer 추가  (5) 2019.07.17
3. 신경망 구현  (0) 2019.07.16
2. 선형회귀 구현  (0) 2019.07.16
Comments