NeuroWhAI의 잡블로그

[TensorFlow] MNIST CNN 예제 고수준 API로 바꾸기 본문

개발 및 공부/라이브러리&프레임워크

[TensorFlow] MNIST CNN 예제 고수준 API로 바꾸기

NeuroWhAI 2018. 1. 21. 14:22


책에서 짤막하게 고수준 API를 알려주더라고요!
편하긴 편한데 역시 저수준 API를 쓰는게 원리를 배우는데엔 더 좋은것 같아요.

코드:
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
#-*- coding: utf-8 -*-
 
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)
 
# 입력X는 28x28 크기의 이미지들이며 그레이스케일 포맷이므로 채널은 1개
# 출력 Y는 원 핫 인코딩된 텐서들이며 [0,0,1,0,0,0,0,0,0,0]는 2를 뜻함.
= tf.placeholder(tf.float32, [None, 28281])
= tf.placeholder(tf.float32, [None, 10])
is_training = tf.placeholder(tf.bool)
 
L1 = tf.layers.conv2d(X, 32, [33])
L1 = tf.layers.max_pooling2d(L1, [22], [22])
L1 = tf.layers.dropout(L1, 0.7, is_training)
 
L2 = tf.layers.conv2d(L1, 64, [33])
L2 = tf.layers.max_pooling2d(L2, [22], [22])
L2 = tf.layers.dropout(L2, 0.7, is_training)
 
L3 = tf.contrib.layers.flatten(L2)
L3 = tf.layers.dense(L3, 256, activation=tf.nn.relu)
L3 = tf.layers.dropout(L3, 0.5, is_training)
 
model = tf.layers.dense(L3, 10, activation=None)
 
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    labels=Y, logits=model
))
 
optimizer = tf.train.AdamOptimizer(0.001).minimize(cost)
 
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
 
    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_xs, batch_ys = mnist.train.next_batch(batch_size)
            batch_xs = batch_xs.reshape(-128281)
 
            _, cost_val = sess.run([optimizer, cost],
                feed_dict={X: batch_xs, Y: batch_ys, is_training: True})
 
            total_cost += cost_val
 
        print('Epoch:''%04d' % (epoch + 1),
            'Avg. cost =''{:.3f}'.format(total_cost / total_batch))
 
    print('완료!')
 
    is_correct = tf.equal(tf.argmax(model, 1), tf.argmax(Y, 1))
    accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
    print('정확도: %.2f' % sess.run(accuracy * 100,
        feed_dict={X: mnist.test.images.reshape(-128281),
            Y: mnist.test.labels, is_training: False}))
 
    

Google Cloud ML이란 서비스에 있는 콘솔에서 코드를 돌려보려고 했는데
결론적으론 고성능 머신이 유료인것 같아서 포기했습니다. (아님 제가 못찾았...)
다만 #-*- coding: utf-8 -*- 이 코멘트를 달지 않으니까 인코딩 관련 오류가 뜨길래 붙혀뒀습니다 ㅋㅋ...

결과:
Extracting ./mnist/data/train-images-idx3-ubyte.gz
Extracting ./mnist/data/train-labels-idx1-ubyte.gz
Extracting ./mnist/data/t10k-images-idx3-ubyte.gz
Extracting ./mnist/data/t10k-labels-idx1-ubyte.gz
Epoch: 0001 Avg. cost = 0.177
Epoch: 0002 Avg. cost = 0.051
Epoch: 0003 Avg. cost = 0.033
Epoch: 0004 Avg. cost = 0.023
Epoch: 0005 Avg. cost = 0.017
Epoch: 0006 Avg. cost = 0.013
Epoch: 0007 Avg. cost = 0.012
Epoch: 0008 Avg. cost = 0.009
Epoch: 0009 Avg. cost = 0.010
Epoch: 0010 Avg. cost = 0.008
Epoch: 0011 Avg. cost = 0.006
Epoch: 0012 Avg. cost = 0.007
Epoch: 0013 Avg. cost = 0.006
Epoch: 0014 Avg. cost = 0.004
Epoch: 0015 Avg. cost = 0.006
완료!
정확도: 98.89

23분 걸렸습니다 ㅠㅠ
GPU 쓰고싶어요오오오오오---

tf.layers.*
tf.contrib.layers.*
여기에 있는게 고수준 API 중 하나인것 같습니다.
말그대로 레이어를 제공해주네요.

conv2d : 합성곱 계층. 입력, 필터 개수, 커널 크기 정도만 설정해줬습니다.
max_pooling2d : 풀링 계층. 차례로 입력, 풀 크기, 스트라이드를 설정해줬습니다.
dropout : 드롭아웃 계층. 입력, 뉴런 활성화 확률, 학습중 여부
flatten : 이전 예제에서 이전 레이어의 출력값을 reshape으로 펴줬던 역할을 하는 레이어입니다.
dense : 완전 연결 계층. 입력, 출력 개수, 활성화 함수를 설정해줬습니다.

나머진 이전 예제랑 동일!








Comments