渋谷駅前で働くデータサイエンティストのブログ

元祖「六本木で働くデータサイエンティスト」です / 道玄坂→銀座→東京→六本木→渋谷駅前

生TensorFlow七転八倒記(5):ようやくCNNまでたどり着いた

前回の記事でようやくDeepっぽいところまで来たので、そのままさっさとDeepらしさの象徴でもあるCNN (Convolutional Neural Network)にいってしまおうと思います。ちなみに今回も大して参照していませんが、参考文献として深層学習青本を掲げておきます。

深層学習 (機械学習プロフェッショナルシリーズ)

深層学習 (機械学習プロフェッショナルシリーズ)

それでは、いよいよCNNをやってみましょう。


生TensorFlowでLeNetを回してみる


ようやくCNNをやってみるわけですが、実はTensorFlow公式に立派なチュートリアルがあります(Deep MNIST for Experts  |  TensorFlow)。というか、MNIST + CNNというところまで来ればweb上の至るところにいくらでも「やってみました」系の記事が大量に転がっています。むしろこれまではどこにも参考になる資料がなくて困ったというのが実態だったりします(笑)。ということで、これをなぞればおしまいです*1。使ったデータは前回同様簡易版MNISTです。


import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

d_train = pd.read_csv("short_prac_train.csv", sep=',')
d_test = pd.read_csv("short_prac_test.csv", sep=',')

train_X = d_train.iloc[:, 1:785]/255
train_Y = d_train[[0]]
test_X = d_test.iloc[:, 1:785]/255
test_Y = d_test[[0]]

# Define input
x = tf.placeholder(tf.float32, [None, 784])

# Turn into CNN
# For simplicity, just follow "Deep MNIST for Experts"

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides = [1, 1, 1, 1], padding = 'SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME')

# Just accumulate layers as GoogeLenet

# 1st layer
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

x_image = tf.reshape(x, [-1, 28, 28, 1])

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

# 2nd layer
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

# Dense
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# Dropout
keep_prob = tf.placeholder(tf.float32) # set 1.0 if inference
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# Readout
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2

# Define label & momentum optimizer
y = tf.placeholder(tf.int64, [None, 1])
y_ = tf.one_hot(indices = y, depth = 10)
global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.01
learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,
                                           10000, 1 - 1e-6, staircase=True)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y_conv))
optimizer = tf.train.MomentumOptimizer(learning_rate, momentum = 0.9, use_nesterov=True).minimize(cost, global_step = global_step)

# WITH minibatch
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

num_epochs = 30
num_data = train_X.shape[0]
batch_size = 50
for epoch in range(num_epochs):
  s_idx = np.random.permutation(num_data)
  for idx in range(0, num_data, batch_size):
    batch_x = train_X.iloc[s_idx[idx: idx + batch_size].tolist(),:]
    batch_y = train_Y.iloc[s_idx[idx: idx + batch_size].tolist()]
    sess.run(optimizer, feed_dict={x:batch_x, y:batch_y, keep_prob:0.5})

pred = sess.run(y_conv, feed_dict = {x: test_X, keep_prob:1.0})
pred_d = tf.argmax(pred,1)
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
print confusion_matrix(test_Y, sess.run(pred_d)), accuracy_score(test_Y, sess.run(pred_d))
[[ 97   0   0   0   0   0   2   0   1   0]
 [  0  99   0   0   0   0   0   0   1   0]
 [  0   0  99   0   0   0   0   1   0   0]
 [  0   0   0  99   0   0   0   0   1   0]
 [  0   2   0   0  97   0   0   0   0   1]
 [  0   0   0   0   0 100   0   0   0   0]
 [  0   0   0   0   0   1  98   0   1   0]
 [  0   0   0   0   0   0   0 100   0   0]
 [  0   0   1   0   1   0   0   0  98   0]
 [  0   0   0   0   1   0   0   0   0  99]] 0.986

いとも簡単にACC 0.986が出ました(驚)。このチュートリアルのコードはKerasで書いたりするのに比べればまだるっこしいんですが、それでもconv層のところを書きやすくするために事前に関数を定義して簡単に書けるようにしてあったり、keep_probの値次第でtrainingとinferenceを分けられるようにしてあったり、そこそこ親切だという印象です。


Keras in Rで同じくLeNetを回してみる


前回も紹介した以前の記事に、ほぼ同じ設定のCNNをKerasで回した例があります。

以下そのまま転載しておきます。

library(keras)

train <- read.csv('short_mnist_train.csv', header=T, sep=',')
test <- read.csv('short_mnist_test.csv', header=T, sep=',')

x_train <- array(<span style="color: #ff0000">as.matrix</span>(train[,-1]/255), dim=c(5000, 28, 28, 1))
y_train <- train[,1] %>% 
    to_categorical(num_classes = 10)
x_test <- array(<span style="color: #ff0000">as.matrix</span>(test[,-1]/255), dim=c(1000, 28, 28, 1))
y_test <- test[,1] %>% 
    to_categorical(num_classes = 10)

# create model
model <- keras_model_sequential()

model %>% 
    layer_conv_2d(filters = 32, kernel_size = c(3,3), activation = 'relu', 
                  input_shape = c(28,28, 1)) %>% 
    layer_conv_2d(filters = 64, kernel_size = c(3,3), activation = 'relu') %>% 
    layer_max_pooling_2d(pool_size = c(2,2)) %>% 
    layer_dropout(rate = 0.25) %>% 
    layer_conv_2d(filters = 64, kernel_size = c(3,3), activation = 'relu') %>% 
    layer_conv_2d(filters = 64, kernel_size = c(3,3), activation = 'relu') %>% 
    layer_max_pooling_2d(pool_size = c(2,2)) %>% 
    layer_dropout(rate = 0.25) %>% 
    layer_flatten() %>% 
    layer_dense(units = 128, activation = 'relu') %>% 
    layer_dropout(rate = 0.25) %>% 
    layer_dense(units = 10, activation = 'softmax') %>% 
    compile(
        loss = 'categorical_crossentropy', 
        optimizer = optimizer_sgd(lr = 0.01, decay = 1e-6, momentum = 0.9, nesterov = TRUE)
    )

# train
model %>% fit(x_train, y_train, batch_size = 32, epochs = 10)

# evaluate
score <- model %>% evaluate(x_test, y_test, batch_size = 32)
Epoch 1/10
5000/5000 [==============================] - 20s - loss: 1.1239    
Epoch 2/10
5000/5000 [==============================] - 25s - loss: 0.2766    
Epoch 3/10
5000/5000 [==============================] - 23s - loss: 0.1871    
Epoch 4/10
5000/5000 [==============================] - 21s - loss: 0.1420    
Epoch 5/10
5000/5000 [==============================] - 23s - loss: 0.1142    
Epoch 6/10
5000/5000 [==============================] - 23s - loss: 0.1089    
Epoch 7/10
5000/5000 [==============================] - 22s - loss: 0.0929    
Epoch 8/10
5000/5000 [==============================] - 22s - loss: 0.0819    
Epoch 9/10
5000/5000 [==============================] - 22s - loss: 0.0674    
Epoch 10/10
5000/5000 [==============================] - 21s - loss: 0.0616    
> 
> # evaluate
> score <- model %>% evaluate(x_test, y_test, batch_size = 32)
 992/1000 [============================>.] - ETA: 0s
> score
[1] 0.05340803
> pred_class <- model %>% predict(x_test, batch_size=100)
> pred_label <- t(max.col(pred_class))
> table(test[,1], pred_label)
   pred_label
      1   2   3   4   5   6   7   8   9  10
  0  98   0   0   0   0   0   2   0   0   0
  1   0 100   0   0   0   0   0   0   0   0
  2   0   0  99   0   0   0   0   1   0   0
  3   0   0   0 100   0   0   0   0   0   0
  4   0   2   0   0  97   0   1   0   0   0
  5   0   0   0   0   0 100   0   0   0   0
  6   1   0   0   0   0   2  97   0   0   0
  7   0   0   0   1   0   0   0  99   0   0
  8   0   1   1   1   0   1   0   0  96   0
  9   0   0   0   0   1   1   0   1   0  97
> sum(diag(table(test[,1], pred_label)))/nrow(test)
[1] 0.983

ACC 0.983ということで、生TensorFlowでやってみてもほぼ同じ結果になったことが分かります。

*1:ただしチュートリアル中ではADAMで最適化しているのに対して、今回のコードでは精度が出なかったので前回に引き続きMomentumを使っています