KZKY memo

自分用メモ.

TensorFlow: Deep MNIST for Experts

ここではinteractive sessionでCNNを書くチュートリアル

Setup

Load MNIST Data

git clone https://github.com/tensorflow/tensorflow.git

してきて,ここに移動.

cd tensorflow/tensorflow/examples/tutorials/mnist

こんな感じでmnistデータを読み込み

import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

interactive sessionを立ち上げる.

import tensorflow as tf
sess = tf.InteractiveSession()
Computation Graph

pythonでnumerical computinをするとなると,普通numpyを使う.numpyはイケてるが,operation毎にいちいちpythonに戻るのは結構overheadになる.特にGPUを使う場合はgpu/cpu間のメモリのトランスファーがかなりネックになってしまう.

なので,TFではgraphでopsを構築して実際の実行は別途python外で行う.Theano/Torchとかと一緒.pythonでgraphを作って,どの部分グラフを実行するのかを決める.

Build a Softmax Regression Model

ここではLogistic Regressionの例をinteractiveに説明する.

Placeholders

modelへのinput

x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])

784はinputの次元,Noneはbatchサイズで,どんなサイズでも良い.

Variables

graph上のパラメータ有りのインプット.機械学習のコンテキストではモデルパラメータと思っておけばいい.初めの引数にっているのは,init value.そのshapeの[784, 10]は,[input feature dim, output feature dim].この例ではoutput feature dim= num. of classes

W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

実際にグラフを実行する前にinitする.TFでは,このinitもopになっている.

sess.run(tf.initialize_all_variables())

Predicted Class and Cost Function

Logistic Regressionなので,Affineしてからsoftmax.

y = tf.nn.softmax(tf.matmul(x,W) + b)

コスト関数は分類問題なので,クロスエントロピー.reduce_sumは,minibatch内のすべてのサンプルで和をとる.

cross_entropy = -tf.reduce_sum(y_*tf.log(y))

Train the Model

optimization opの追加

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

これはGradientDescentだけど,抑えるべきものはある.

  • momentum
  • adam
  • adagrad
  • rmsprop

optimizerで,実際に追加しているopsは,

  • compute_gradients
  • apply_gradients


これらをbatch単位で実行

for i in range(1000):
  batch = mnist.train.next_batch(50)
  train_step.run(feed_dict={x: batch[0], y_: batch[1]})

Evaluate the Model

予測する.argmaxは便利関数で第2引数で持していした軸で最大値をとるindexを返してくれる.tf.equalでboolを返す.

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

interactiveにチェックしたかったら,tensor.eval(feed_dict={...})でfeedする.

boolをfloatにキャストして,平均をとる.

accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

最後にevalしてチェック

print accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})

91%くらいの精度がでる.

Build a Multilayer Convolutional Network

CNNを使ったREPLの例.
ネットワークのアーキテクチャは,


(conv + relu + maxpooling) * 2
\+ (affine + relu)
\+ dropout
\+ (affine + softmax)

これらを一気に書くと(xをreshapeしているので注意),

# Helper func
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')

# Parameter at conv1 (kernel_size, kernel_size, in_map, out_map)
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

# Reshape image 
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)

# Parameter at conv2
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)

# Parameter at affine 1
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

# Reshape to [batch, feature]
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("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# Parameter at affine 2
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

# Softmax
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

# Loss
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))

# Train op
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# Eavl op
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

# Init
sess.run(tf.initialize_all_variables())

# Train
st = time.time()
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i %100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print "step %d, training accuracy %g" % (i, train_accuracy)

  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

print "elapsed time %f [s]" % (time.time() - st)
  
# Evalute
print "test accuracy %g" % accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})

結果 (GPU/cudnnあり)99%くらいの精度になる.

APIの説明をみると,コードに出てくる4D tesorは,[batch, height, width, channels]だと思う.なので,maxpoolingではksize=[1, 2, 2, 1], strdies=[1, 2, 2, 1]でheight, width方向に重複なしでpoolするということ.4Dなのでbatch/in_map方向にもstrideできると考えていいのか.