yshr10ic’s Blog

備忘録

TensorFlowのNNでMNISTをやってみた。

「ゼロから作るDeep Learning②」を読了しました。

t.co

前作の「ゼロから作るDeep Learning」に引き続き、分かりやすく丁寧な説明でした。 私としては、「ゼロから作るDeep Learning③」で画像処理や異常検知などの書籍が出ることを期待しています!

さて、「ゼロから作るDeep Learning」「ゼロから作るDeep Learning②」と読んで、Deep Learningの概要は理解することができたのですが、numpyだけで実装することって、まず無いですよね?そこで、本で理解した内容をTensorFlowを用いて、実装してみたいと思います!(すでにいろんな人がやっていることはおいておいて・・・)

TensorFlowでの実装

今回は、2層ニューラルネットワーク(隠れ層が1層)の実装です。

import tensorflow as tf
import math
from tensorflow.examples.tutorials.mnist import input_data

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

# input data/output data
X = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])

# input image
img = tf.reshape(X, [-1, 28, 28, 1])

# hidden layer
with tf.name_scope('hidden'):
    hidden_w = tf.Variable(tf.truncated_normal([784, 64], stddev=0.1), name='hidden_w')
    # He の初期値
    # stddev = math.sqrt(2.0 / (784 * 64))
    # hidden_w = tf.Variable(tf.truncated_normal([784, 64], stddev=stddev), name='hidden_w')
    hidden_b = tf.Variable(tf.zeros([64]), name='hidden_b')
    hidden_o = tf.nn.relu(tf.matmul(X, hidden_w) + hidden_b)

# output layer
with tf.name_scope('output'):
    output_w = tf.Variable(tf.truncated_normal([64, 10], stddev=0.1), name='output_w')
    output_b = tf.Variable(tf.zeros([10]), name='output_b')
    output_o = tf.nn.softmax(tf.matmul(hidden_o, output_w) + output_b)

# loss function
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.square(y - output_o))

# training
with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(loss)
    # Adam
    # train_step = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)

# evaluation
with tf.name_scope('accuracy'):
    correct = tf.equal(tf.argmax(output_o, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))

# init
init = tf.global_variables_initializer()
saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(init)

    # test data
    test_images = mnist.test.images
    test_labels = mnist.test.labels

    for i in range(1000):
        step = i + 1
        train_images, train_labels = mnist.train.next_batch(50)
        sess.run(train_step, feed_dict={X: train_images, y: train_labels})

        if step % 100 == 0:
            accuracy_val = sess.run(accuracy, feed_dict={X: test_images, y: test_labels})
            print('Step %4d: accuracy = %.2f' % (step, accuracy_val))

    saver.save(sess, 'models/mnist_nn_model', write_meta_graph=False)

簡単な実装ですが、これでaccuracyは0.90前後になりました。

ポイント

特に難しいことはしてませんが、ポイントとしては、

  • ReLUを使用しているところで、「He の初期値」を使用できるようにしている

  • パラメータの更新に関してでは、SGDとAdamを用意

今後に向けて

TensorFlowを用いて2層ニューラルネットワークを実装しました。 今後やっていきたいことは↓です。