Author : tmlab / Date : 2017. 2. 17. 14:21 / Category : Analytics
# 데이터 준비
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
trX = trX.reshape(-1, 28, 28, 1) # 28x28x1 input img
teX = teX.reshape(-1, 28, 28, 1) # 28x28x1 input img
# 데이터 플레이스홀더 생성
X = tf.placeholder("float", [None, 28, 28, 1])
Y = tf.placeholder("float", [None, 10])
# 컨볼루션레이어 가중치, 바이어스
w = tf.Variable(tf.random_normal([3,3,1,32], stddev=0.01)) # 컨볼루션 필터사이즈 3*3크기 필터로 32개 컨볼루션 레이어만들기
w2 = tf.Variable(tf.random_normal([3,3,32,64], stddev=0.01)) # 컨볼루션 필터사이즈 3*3크기, 32개 필터로 64개 컨볼루션 레이어만들기
w3 = tf.Variable(tf.random_normal([3,3,64,128], stddev=0.01)) # 컨볼루션 필터사이즈 3*3크기, 64개 필터로 128개 컨볼루션 레이어만들기
# 풀리 커넥티드레이어 생성을 위한 가중치
w4 = tf.Variable(tf.random_normal([128*4*4, 625], stddev=0.01)) # 128*4*4 인풋, 625개 아웃풋
w_o = tf.Variable(tf.random_normal([625, 10], stddev=0.01)) # 625개 인풋, 10개 아웃풋(라벨)
# 드랍아웃 파라미터 플레이스 홀더
p_keep_conv = tf.placeholder("float")
p_keep_hidden = tf.placeholder("float")
# 컨볼루션 모델 생성
l1a = tf.nn.relu(tf.nn.conv2d(X, w, [1,1,1,1], 'SAME')) # 28*28 컨볼루션에 relu 활성화함수 적용 / [N,28,28,32]
l1 = tf.nn.max_pool(l1a, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') # 2*2사이즈 맥스풀링 적용 / 아웃풋 [N,14,14,32]
l1 = tf.nn.dropout(l1, p_keep_conv)
l2a = tf.nn.relu(tf.nn.conv2d(l1, w2, [1,1,1,1], 'SAME')) # relu 활성화함수 적용 / [N,14,14, 64]
l2 = tf.nn.max_pool(l2a, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') # 2*2사이즈 맥스풀링 적용 / [N, 7, 7, 64]
l2 = tf.nn.dropout(l2, p_keep_conv)
l3a = tf.nn.relu(tf.nn.conv2d(l2, w3, [1,1,1,1], 'SAME')) # relu 활성화함수 적용 / [N, 7, 7, 128]
l3 = tf.nn.max_pool(l3a, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') # 2*2사이즈 맥스풀링 적용 / [N, 4, 4, 128]
l3 = tf.reshape(l3, [-1, w4.get_shape().as_list()[0]]) #풀리커넥티드 인풋 형태로 바꿈
l3 = tf.nn.dropout(l3, p_keep_conv)
# 풀리 커넥티드 레이어
l4 = tf.nn.relu(tf.matmul(l3, w4))
l4 = tf.nn.dropout(l4, p_keep_conv)
pyx = tf.matmul(l4, w_o)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pyx, Y))
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
predict_op = tf.argmax(pyx, 1)
with tf.Session() as sess:
tf.initialize_all_variables().run()
for i in range(100):
for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)): # 0~128개 / 128~256개 즉 128개씩 뽑아서 학습
sess.run(train_op, feed_dict={X:trX[start:end], Y:trY[start:end],
p_keep_conv:0.8, p_keep_hidden:0.5})
test_indices = np.arange(len(teX)) # 테스트 데이터 배치
np.random.shuffle(test_indices)
test_indices = test_indices[0:256]
print i, np.mean(np.argmax(teY[test_indices], axis=1) == sess.run(predict_op, feed_dict={X: teX[test_indices],
Y: teY[test_indices],
p_keep_conv: 1.0,
p_keep_hidden: 1.0}))