Deep Learning study

Convolutional Neural Network(CNN)으로 MNIST 99%이상 해보기 본문

AI/Tensorflow

Convolutional Neural Network(CNN)으로 MNIST 99%이상 해보기

HwaniL.choi 2018. 1. 8. 16:54
반응형

저번에 CNN 을 tensorflow으로 기본적인 개념들을 맛보았고 이번에는 그것들을 활용하여 MNIST를 학습시켜 보자!

(https://www.youtube.com/watch?v=pQ9Y9ZagZBk&t=18s)



1
2
3
= tf.placeholder(tf.float32, [None, 784])
X_img = tf.reshape(X, [-128281])
= tf.placeholder(tf.float32, [None,10])
cs


먼저 MNIST data set은 28*28이미지 이기 때문에 X를 784(28*28)로 잡아와 준다. 

그리고 이미지를 받아올 X_img 와 Label을 받아올 Y이다.


1
2
3
4
5
W1 = tf.Variable(tf.random_normal([3,3,1,32], stddev=0.01))
L1 = tf.nn.conv2d(X_img, W1, strides=[1,1,1,1],padding='SAME')
L1 = tf.nn.relu(L1)
L1 = tf.nn.max_pool(L1, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
L1 = tf.nn.dropout(L1, keep_prob=keep_prob)
cs


W1은 weight로 사용할 필터를 정해준다. [3,3,1,32] 는 3*3*1 필터 32개를 쓰겠다는 뜻이다. 그렇다면 결과로는 28*28*32의 channel이 나오게 되겠다.

conv2d layer를 만든다. 차례대로 이미지, 필터, stride, padding 이다. strides = [batch_size, image_rows, image_cols, number_of_colors] 이라 [0],[3] 인덱스에는 1이들어가고 , [1],[2]는 1이 들어간다. 어쨋든 [1]또는 [2] 를 보면 몇칸씩 이동할 것인지 알 수 있다. 여기서는 1칸씩 간다는 뜻이다. 


참고로 padding='SAME' 일때는 (이미지 크기 - 필터크기)/stride 이고 

padding = 'VALID' 일때 (이미지크기 - 필터크기)/stride + 1이라고 한다.

여기서는 max_pool을 거치면서 14*14*32가 된다.


1
2
3
4
5
W2 = tf.Variable(tf.random_normal([3,3,32,64], stddev=0.01))
L2 = tf.nn.conv2d(L1, W2, strides=[1,1,1,1],padding='SAME')
L2 = tf.nn.relu(L2)
L2 = tf.nn.max_pool(L2, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
L2 = tf.nn.dropout(L2, keep_prob=keep_prob)
cs


2번째 layer를 보면 다른건 바뀌지 않았고 , 위에서 14*14*32이가 되었으므로, 필터사이즈를 3*3*32로 설정해주었다.

conv를 거치고나면 14*14*64 크기의 channel이 나오게 되겠다.

위와 같은 방법으로 여기서 결과는 7*7*64가 된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
W3 = tf.Variable(tf.random_normal([3,3,64,128], stddev=0.01))
L3 = tf.nn.conv2d(L2, W3, strides=[1,1,1,1],padding='SAME')
L3 = tf.nn.relu(L3)
L3 = tf.nn.max_pool(L3, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
L3 = tf.nn.dropout(L3, keep_prob=keep_prob)
L3_flat = tf.reshape(L3, [-1128*4*4])
 
W4 = tf.get_variable("W4", shape=[128*4*4625], initializer = tf.contrib.layers.xavier_initializer())
b4 = tf.Variable(tf.random_normal([625]))
L4 = tf.nn.relu(tf.matmul(L3_flat, W4) + b4)
L4 = tf.nn.dropout(L4, keep_prob=keep_prob)
 
W5 = tf.get_variable("W5", shape = [625,10], initializer = tf.contrib.layers.xavier_initializer())
b5 = tf.Variable(tf.random_normal([10]))
logits = tf.matmul(L4,W5) + b5
cs


이제 마지막으로 FC(fully connected layer)를 거친다.


FC layer를 만들기 위해서 이미지 형태의 데이터를 1차원 배열형태로 펴준다. (L3_flat)

그뒤 w4에서 [input, output] 형태를 만들어 주고, 1차원 배열 형태로 펴준 L3_flat을 input으로 받아오고 output을 625로 정해준다. 그리고 relu함수를 통과시키고 dropout도 설정해준다.

마찬가지로 w5에서도 625개의 input을 받아 결과갑인 0-9중 하나의 출력을내기 때문에 output은 10이 된다.


전체코드는 아래에 있다.


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
64
65
66
67
68
69
70
71
72
73
74
75
76
import tensorflow as tf
import random
from tensorflow.examples.tutorials.mnist import input_data
 
tf.set_random_seed(777)
 
mnist = input_data.read_data_sets("MINST_data/",one_hot=True)
 
learning_rate = 0.001
training_epochs = 15
batch_size = 100
 
keep_prob = tf.placeholder(tf.float32)
 
= tf.placeholder(tf.float32, [None, 784])
X_img = tf.reshape(X, [-128281])
= tf.placeholder(tf.float32, [None,10])
 
W1 = tf.Variable(tf.random_normal([3,3,1,32], stddev=0.01))
L1 = tf.nn.conv2d(X_img, W1, strides=[1,1,1,1],padding='SAME')
L1 = tf.nn.relu(L1)
L1 = tf.nn.max_pool(L1, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
L1 = tf.nn.dropout(L1, keep_prob=keep_prob)
 
W2 = tf.Variable(tf.random_normal([3,3,32,64], stddev=0.01))
L2 = tf.nn.conv2d(L1, W2, strides=[1,1,1,1],padding='SAME')
L2 = tf.nn.relu(L2)
L2 = tf.nn.max_pool(L2, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
L2 = tf.nn.dropout(L2, keep_prob=keep_prob)
 
W3 = tf.Variable(tf.random_normal([3,3,64,128], stddev=0.01))
L3 = tf.nn.conv2d(L2, W3, strides=[1,1,1,1],padding='SAME')
L3 = tf.nn.relu(L3)
L3 = tf.nn.max_pool(L3, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
L3 = tf.nn.dropout(L3, keep_prob=keep_prob)
L3_flat = tf.reshape(L3, [-1128*4*4])
 
W4 = tf.get_variable("W4", shape=[128*4*4625], initializer = tf.contrib.layers.xavier_initializer())
b4 = tf.Variable(tf.random_normal([625]))
L4 = tf.nn.relu(tf.matmul(L3_flat, W4) + b4)
L4 = tf.nn.dropout(L4, keep_prob=keep_prob)
 
W5 = tf.get_variable("W5", shape = [625,10], initializer = tf.contrib.layers.xavier_initializer())
b5 = tf.Variable(tf.random_normal([10]))
logits = tf.matmul(L4,W5) + b5
 
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)
 
 
sess = tf.Session()
sess.run(tf.global_variables_initializer())
 
print("Learning started, It takes sometime.")
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, 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))
 
print('Learning Finished')
 
correct_prediction = tf.equal(tf.argmax(logits,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}))
 
= 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(logits, 1), feed_dict={X: mnist.test.images[r:r+1],keep_prob: 1}))
 
cs


간단하게 layers 패키지를 사용하여 코드를 간소화 시킨 것도 소개해 주셨지만, 좀더 공부하기 좋은 코드를 선택해서 짜보았다. 이미지 크기가 자꾸 변해서 이부분에서 크기를 정해주는게 헷갈린다. 잘 외워둬야겠다. 



여튼 결과는 , 무려 99.38%의 정확도를 보여주고있다. 하지만 시간이.. 43분이나 걸렸다 . 노트북으로 실행시키다보니 너무오래걸렸다. 빨리 컴퓨터 사야지 .. 



점점 코드도 복잡해지고 이해하는데 시간이 걸린다. 책을 사서 좀더 읽어보고 자세히 공부해보아야겠다. ㅠㅠ

반응형
Comments