AI & BigData/모두를 위한 딥러닝(정리)

텐서플로우(Tensor Flow) #10_ MNIST data

Tigercow.Door 2018. 4. 10. 14:05


안녕하세요. 문범우입니다.

오늘 포스팅에서는 실전데이터를 이용해서 모델을 만들어 보도록 하겠습니다.


* 해당 포스트의 모든 내용은 김성훈 교수님의 '모두를 위한 딥러닝'을 바탕으로 제작되었습니다.

관련한 상세 내용은 아래 링크를 참고해주세요.

https://hunkim.github.io/ml/



1. MNIST data



오늘 우리가 사용해볼 데이터는 위의 그림과 같은 MNIST dataset 입니다.

보시면 아시듯이 손으로 쓴 숫자들 입니다.

이 데이터들은 아래 주소에서 손쉽게 다운받을 수 있습니다.


http://yann.lecun.com/exdb/mnist/


위의 사이트에서 4개의 알집을 모두 다운받았습니다.

그럼 각 데이터가 어떤 형태를 가지고 있는지 좀 더 자세히 알아보도록 하겠습니다.


MNIST의 데이터들은 위와 같이 28x28 픽셀로 이루어져 있습니다.

하나의 데이터에 총 784개의 픽셀이 존재합니다.

즉 우리는 784 개의 shape의 데이터를 이용하는 것 입니다.

그리고 결과 값 y 로는 0~9까지 10개의 출력이 될 것입니다.


이러한 MNIST 데이터는 많이 이용되기 때문에, 우리가 보다 쉽게 다룰 수 있도록 라이브러리를 지원해주고 있습니다.


from tensorflow.examples.tutorials.mnist import input_data


위와 같은 코드로 라이브러리를 불러올 수 있습니다.


먼저 전체적인 코드는 아래와 같습니다.


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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import tensorflow as tf
import matplotlib.pyplot as plt
import random
from tensorflow.examples.tutorials.mnist import input_data
 
# loading data
mnist = input_data.read_data_sets("/Users/doorbw/Desktop/Beomwoo/deep_learning_zeroToAll/", one_hot=True)
 
nb_classes = 10
 
= tf.placeholder(tf.float32,[None,784])
= tf.placeholder(tf.float32,[None,nb_classes])
 
# using softmax classifier
= tf.Variable(tf.random_normal([784, nb_classes]))
= tf.Variable(tf.random_normal([nb_classes]))
 
# Hypothesis(using Softmax)
hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)
 
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
 
# Test model
is_correct = tf.equal(tf.arg_max(hypothesis,1), tf.arg_max(Y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(is_correct,tf.float32))
 
# parameters
# Training epoch/batch
training_epochs = 15
batch_size = 100
 
with tf.Session() as sess:
    # Init Tensorflow variables
    sess.run(tf.global_variables_initializer())
    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0
        total_batch = int(mnist.train.num_examples / batch_size)
 
        for i in range(batch_size):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            c, _= sess.run([cost,optimizer], feed_dict={X: batch_xs, Y: batch_ys})
            avg_cost += c / total_batch
 
        print('Epoch:''%04d' %(epoch+1), 'cost = ''{:.9f}'.format(avg_cost))
 
    print("Learning finished")
    print("Accuracy: ", accuracy.eval(session=sess,feed_dict={X: mnist.test.images, Y: mnist.test.labels}))
 
    # Get one and predict using matplotlib
    r = random.randint(0, mnist.test.num_examples - 1)
    print("Label: ", sess.run(tf.argmax(mnist.test.labels[r:r + 1], 1)))
    print("Prediction: ", sess.run(
        tf.argmax(hypothesis, 1), feed_dict={X: mnist.test.images[r:r + 1]}))
 
    plt.imshow(
        mnist.test.images[r:r + 1].reshape(2828),
        cmap='Greys',
        interpolation='nearest')
    plt.show()
 
cs


전체적인 학습 부분에 있어서는 그동안 실습을 진행했던 내용과 동일합니다.

그렇지만 중간에 새롭게 다루는 개념이 하나 있는데 epoch이라는 개념입니다.

먼저 정의는 아래와 같습니다.



epoch이라는 것은 전체 데이터셋을 한번 학습하는 것이라고 합니다.

하지만 우리가 메모리상의 문제등이 있기 때문에 하나의 epoch을 나누어서 학습하는데 그 때의 단위가 batch size입니다.


위의 코드에서는 15번의 epoch을 진행하며 batch size는 100으로 잡아서 학습을 진행합니다.


50번째 줄까지 진행하면 각 epoch 당 cost 가 출력되며 마지막에는 accuracy 가 출력되도록 하였습니다. 

그리고 이후 52번째 줄에서는 matplotlib를 이용하여 하나의 x 데이터를 랜덤하게 뽑아내서 이를 matplotlib 을 통해 출력하고 우리가 만들었던 모델이 예측하게 합니다.


결과를 확인하니 accuracy 는 약 82~88% 정도가 나오는 듯 합니다.



728x90