Keras 시작하기

TensorFlow 를 조금 더 쉽게 쓰기 위해 Keras를 배워보기로 했다. Keras는 오픈소스 Neural Network API이다. https://keras.io/ 이곳에서 더 자세하게 알 수 있다.

Keras를 어떻게 쓸지 전혀 몰라서 tutorial이 있길래 따라해보기로 했다. 이 예제에서는 softmax regression을 이용하여 MNIST를 학습한다.

import tensorflow as tf
sess = tf.Session()

from keras import backend as K
K.set_session(sess)
먼저 기존 tensorflow 에서 세션을 만든다. 그리고 그것을 keras에 등록시켜 keras가 해당 세션을 사용할 수 있도록 한다.

img = tf.placeholder(tf.float32, shape=(None, 784))
MNIST 이미지를 담을 변수를 선언한다.

from keras.layers import Dense
x = Dense(128, activation='relu')(img)  # fully-connected layer with 128 units and ReLU activation
x = Dense(128, activation='relu')(x)
preds = Dense(10, activation='softmax')(x)  # output layer with 10 units and a softmax activation
keras 레이어를 사용하여 모델을 정의한다. 128개의 뉴런으로 이루어진 완전연결계층을 만들고 그것을 ReLU 함수에 적용시키는 것이 단 한 줄로 이루어진다. TensorFlow를 이용해서 만드는 것보다 쉬울 뿐만 아니라 직관적이다.

labels = tf.placeholder(tf.float32, shape=(None, 10))

from keras.objectives import categorical_crossentropy
loss = tf.reduce_mean(categorical_crossentropy(labels, preds))
MNIST 데이터의 참값을 담을 labels를 선언한다. 그리고 cost function을 만들고 경사하강법을 이용해 최적화시킨다.

acc_value = accuracy(labels, preds)
sess.run(tf.global_variables_initializer())
 학습을 통해 나온 예측값이 얼마나 정확한지 알아보기 위한 변수를 선언하고, 위에서 사용될 variable들을 초기화 해준다.

mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)
with sess.as_default():
    for i in range(1000):
        batch = mnist_data.train.next_batch(50)
        train_step.run(feed_dict={img:batch[0], labels:batch[1]})
    
    correct_prediction = acc.eval(
            feed_dict={img:mnist_data.test.images, labels:mnist_data.test.labels})    

print(sess.run(tf.reduce_mean(correct_prediction)))
이제 학습을 시작한다. 훈련에 쓰일 MNIST 데이터를 읽어들인다. sess.as_default():는 위에서 선언한 sess를 현재의 Session으로 선언하겠다는 것이다. 학습은 1천번을 진행했다. 그리고 정확도 테스트를 위해 test 이미지와 label을 넣어주었다. 그 결과 약 95%의 정확도를 나타내었다.

아래는 전체 코드이다.
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from keras import backend as k
from keras.layers import Dense
from keras.objectives import categorical_crossentropy
from keras.metrics import categorical_accuracy as accuracy

sess = tf.Session()
k.set_session(sess)

img = tf.placeholder(tf.float32, shape = [None, 784]) # "shape =" 생략해도 됨.

# fully-connected layer with 128 units and ReLU activation
x = Dense(128, activation = 'relu')(img)
x = Dense(128, activation = 'relu')(x)

preds = Dense(10, activation = 'softmax')(x)
labels = tf.placeholder(tf.float32, [None, 10])

loss = tf.reduce_mean(categorical_crossentropy(labels, preds))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

acc = accuracy(labels, preds)

sess.run(tf.global_variables_initializer())

mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)
with sess.as_default():
    for i in range(1000):
        batch = mnist_data.train.next_batch(50)
        train_step.run(feed_dict={img:batch[0], labels:batch[1]})
    
    correct_prediction = acc.eval(
            feed_dict={img:mnist_data.test.images, labels:mnist_data.test.labels})    

print(sess.run(tf.reduce_mean(correct_prediction)))
import 부분을 모두 위로 모아서 깔끔하게 보이게 했다.

별 내용이 없지만 확실히 TensorFlow만 써서 하는 것보다는 더 쉽게 코드를 작성할 수 있는 듯하다.