본문 바로가기

파이썬/머신러닝

[#E15] MNIST 데이터란?

MNIST 데이터란 필기 숫자의 분류를 위한 학습 데이터 집합입니다. 즉, 이 데이터는 어지럽게 필기된 숫자가 어떤 숫자에 해당하는지 정확하게 맞추기 위한 학습을 위한 것입니다.


해당 데이터는 다음과 같이 이미지와 해당하는 라벨로 구성되어 있습니다.




또한 이것은 다음과 같이 파이썬 폴더의 MNIST_data 폴더에서도 확인할 수 있습니다.

 

 

train- 파일은 학습데이터입니다. 이것은 전체 데이터의 70퍼센트로, t10k- 파일은 테스트용 데이터로 30퍼센트를 사용합니다. ( 기본적으로 학습은 70퍼센트, 테스트는 30퍼센트를 사용합니다 )

 

이 포스트에서는 세 가지의 다른 방법으로 학습을 진행합니다.


1. FANCY SOFTMAX REGRESSION [#E8 : FANCY SOFTMAX REGRESSION이란?]


2. NN with XAVIER INITIALIZER [#E12 : W 변수 (Weights) 초기화 방법]


3. NN with DROP OUT [#E13 : DROP OUT 이란?]

 

먼저 MNIST 데이터를 가져오는 방법은 세 가지 모두 아래와 같습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import tensorflow as tf
import random
 
from tensorflow.examples.tutorials.mnist import input_data
 
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
 
# parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
total_batch = int(mnist.train.num_examples / batch_size)
 
# input place holders
= tf.placeholder(tf.float32, [None, 784])
= tf.placeholder(tf.float32, [None, 10])
cs


mnist 변수는 데이터의 위치를 가리키는데, 해당 코드는 파이썬 폴더를 기준으로 합니다.


또한, MNIST 데이터는 총 784개의 데이터로 이루어져 있습니다. 따라서 X의 Shape는 [None, 784]이며 학습은 batch를 이용해 효율적으로 100개씩 진행합니다. (batch_size=100)

 

(1) FANCY SOFTMAX REGRESSION


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
# weights & bias for nn layers
= tf.Variable(tf.random_normal([78410]))
= tf.Variable(tf.random_normal([10]))
 
logits = tf.matmul(X, W) + b
 
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
 
# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
# train my model
for epoch in range(training_epochs):
    avg_cost = 0
 
    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        feed_dict = {X: batch_xs, Y: batch_ys}
        c, _ = sess.run([cost, optimizer], feed_dict=feed_dict)
        avg_cost += c / total_batch
 
    print('Epoch:''%04d' % (epoch + 1), 'cost =''{:.9f}'.format(avg_cost))
cs


FANCY SOFTMAX REGRESSION에서는 logits, 그리고 cost 함수 중 하나인 Cross-Entropy를 사용합니다.


해당 코드는 1epoch 마다 784개의 데이터를 학습하고, 이를 15epoch 반복합니다.


(2) NN with XAVIER INITIALIZER


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
# weights & bias for nn layers
# http://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
W1 = tf.get_variable("W1", shape=[784256],
                     initializer=tf.contrib.layers.xavier_initializer())
b1 = tf.Variable(tf.random_normal([256]))
L1 = tf.nn.relu(tf.matmul(X, W1) + b1)
 
W2 = tf.get_variable("W2", shape=[256256],
                     initializer=tf.contrib.layers.xavier_initializer())
b2 = tf.Variable(tf.random_normal([256]))
L2 = tf.nn.relu(tf.matmul(L1, W2) + b2)
 
W3 = tf.get_variable("W3", shape=[25610],
                     initializer=tf.contrib.layers.xavier_initializer())
b3 = tf.Variable(tf.random_normal([10]))

logits = tf.matmul(L2, W3) + b3
 
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
 
# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
# train my model
for epoch in range(training_epochs):
    avg_cost = 0
    total_batch = int(mnist.train.num_examples / batch_size)
 
    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        feed_dict = {X: batch_xs, Y: batch_ys}
        c, _ = sess.run([cost, optimizer], feed_dict=feed_dict)
        avg_cost += c / total_batch
 
    print('Epoch:''%04d' % (epoch + 1), 'cost =''{:.9f}'.format(avg_cost))
cs


Xavier initializer을 이용한 NN은 여러 개의 레이어를 쌓아 학습합니다. 여기서는 마찬가지로 logits와 cost 함수로 Cross-Entropy 함수를 이용합니다.


여기가 Xavier Initializer을 적용한 부분입니다.

 

(3) NN with DROP OUT


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
# dropout (keep_prob) rate  0.7 on training, but should be 1 for testing
keep_prob = tf.placeholder(tf.float32)
 
# weights & bias for nn layers
# http://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
W1 = tf.get_variable("W1", shape=[784512],
                     initializer=tf.contrib.layers.xavier_initializer())
b1 = tf.Variable(tf.random_normal([512]))
L1 = tf.nn.relu(tf.matmul(X, W1) + b1)
L1 = tf.nn.dropout(L1, keep_prob=keep_prob)
 
W2 = tf.get_variable("W2", shape=[512512],
                     initializer=tf.contrib.layers.xavier_initializer())
b2 = tf.Variable(tf.random_normal([512]))
L2 = tf.nn.relu(tf.matmul(L1, W2) + b2)
L2 = tf.nn.dropout(L2, keep_prob=keep_prob)
 
W3 = tf.get_variable("W3", shape=[512512],
                     initializer=tf.contrib.layers.xavier_initializer())
b3 = tf.Variable(tf.random_normal([512]))
L3 = tf.nn.relu(tf.matmul(L2, W3) + b3)
L3 = tf.nn.dropout(L3, keep_prob=keep_prob)
 
W4 = tf.get_variable("W4", shape=[512512],
                     initializer=tf.contrib.layers.xavier_initializer())
b4 = tf.Variable(tf.random_normal([512]))
L4 = tf.nn.relu(tf.matmul(L3, W4) + b4)
L4 = tf.nn.dropout(L4, keep_prob=keep_prob)
 
W5 = tf.get_variable("W5", shape=[51210],
                     initializer=tf.contrib.layers.xavier_initializer())
b5 = tf.Variable(tf.random_normal([10]))
logits= tf.matmul(L4, W5) + b5
 
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
 
# initialize
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
# train my model
for epoch in range(training_epochs):
    avg_cost = 0
 
    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        feed_dict = {X: batch_xs, Y: batch_ys, keep_prob: 0.7}
        c, _ = sess.run([cost, optimizer], feed_dict=feed_dict)
        avg_cost += c / total_batch
 
    print('Epoch:''%04d' % (epoch + 1), 'cost =''{:.9f}'.format(avg_cost))
cs

 

여기가 Droip out을 적용한 부분입니다. 학습에는 주로 0.7 값을, 테스트 시에는 반드시 1 값을 사용합니다.

 

또한 여러 개의 레이어는 DEEP하게 연결되어있습니다.

 

각각의 학습 모델들은 다음과 같이 테스트할 수 있습니다.

 

(1. FANCY SOFTMAX REGRESSION, 2. XAVIER INITIALIZER)

 

1
2
3
4
5
6
7
8
9
10
11
# Test model and check accuracy
correct_prediction = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('Accuracy:', sess.run(accuracy, feed_dict={
      X: mnist.test.images, Y: mnist.test.labels}))
 
# Get one and predict
= 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]}))
cs

 

(3. DROP OUT)

 

1
2
3
4
5
6
7
8
9
10
11
# Test model and check accuracy
correct_prediction = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('Accuracy:', sess.run(accuracy, feed_dict={
      X: mnist.test.images, Y: mnist.test.labels, keep_prob: 1}))
 
# Get one and predict
= 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], keep_prob: 1}))
cs

 

(참고)

 

각 모델의 학습 정확도는 0.9035 -> 0.9783 -> 0.9804 입니다.


전체 소스코드는 다음에서 볼 수 있습니다.


[1: FANCY SOFTMAX REGRESSION]


[2: NN with XAVIER INITIALIZER]


[3: NN with DROP OUT]