はじめに
手書き文字認識(MNIST)による多クラス識別問題をやってみる。
前回に引き続きこの資料を基に理解していく。
MNISTとは
手書きの文字列を認識するもので、画像認識では定番と言えるテーマだ。
手書き文字の認識データは、機械学習の著名な研究者であるYann LeCun氏のwebsiteで公開しており、0-9のいずれかの数字が学習用、テスト用それぞれで60000枚と10000枚含まれている。
各数字画像の大きさは28×28ピクセルの単色画像で、RGBではなくGray-scaleの色空間となっている。
多クラス識別問題
前回の八百屋の識別問題が、買えるか買えないかの2クラスの分類であったが、今回は手書き文字を0-9と多クラスの分類となる。
手書き文字認識
one-hot ベクトル (one-of-K表現)
案1: ロジスティック回帰を拡張
ソフトマックス関数と呼ばれており、シグモイド関数を多クラス問題に対応させた活性化関数である。
ソフトマックス関数を使うと出力層の各ユニットの和が1になります。つまり、出力値が各クラスである確率と見なせるようになります。
案2: さらに中間層を追加
1. 予測式(モデル)を記述
TensorFlowによる実装
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
W1 = tf.Variable(tf.truncated_normal([784, 100]))
b1 = tf.Variable(tf.zeros([100]))
W2 = tf.Variable(tf.truncated_normal([100, 10]))
b2 = tf.Variable(tf.zeros([10]))
h = tf.sigmoid(tf.matmul(x, W1) + b1)
u = tf.matmul(h, W2) + b2
y = tf.nn.softmax(u)
2. 誤差関数と最適化手法を記述
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(u, y_))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
- 誤差関数を変更
多クラス識別(分類)問題
→多クラス用クロスエントロピー(softmax_cross_entropy_with_logits)
3. 学習実行
for i in range(10000):
batch_xs, batch_ys = mnist.train.next_batch(100)
_, l = sess.run([train_step, loss], feed_dict={x: batch_xs, y_: batch_ys})
if (i + 1) % 1000 == 0:
print "step=%3d, loss=%.2f" % (i + 1, l)
- 大規模なデータで学習する時の工夫
各ステップで、100個の訓練データをランダムに取り出して学習 (確率的勾配降下法)
→速く学習が進む
参考: 学習結果
4. 予測
new_x = mnist.test.images[0:1000]
new_y_ = mnist.test.labels[0:1000]
accuracy, new_y = sess.run([acc, y], feed_dict={x:new_x , y_:new_y_ })
print "Accuracy (for test data): %6.2f%%" % accuracy
print "True Label:", np.argmax(new_y_[0:15,], 1)
print "Est Label:", np.argmax(new_y[0:15, ], 1)
ここはこれまでと同様
【実行結果例】
Accuracy(test data): 80.0%
True Label: [7 2 1 0 4 1 4 9 5 9 0 6 9 0 1]
Est Label: [7 2 1 0 9 1 4 9 2 9 0 6 9 0 1]
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
W1 = tf.Variable(tf.truncated_normal([784, 100]))
b1 = tf.Variable(tf.zeros([100]))
W2 = tf.Variable(tf.truncated_normal([100, 10]))
b2 = tf.Variable(tf.zeros([10]))
h = tf.sigmoid(tf.matmul(x, W1) + b1)
u = tf.matmul(h, W2) + b2
y = tf.nn.softmax(u)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(u, y_))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)
for i in range(10000):
batch_xs, batch_ys = mnist.train.next_batch(100)
_, l = sess.run([train_step, loss], feed_dict={x: batch_xs, y_: batch_ys})
if (i + 1) % 1000 == 0:
print("step=%3d, loss=%.2f" % (i + 1, l))
new_x = mnist.test.images[0:1000]
new_y_ = mnist.test.labels[0:1000]
accuracy, new_y = sess.run([acc, y], feed_dict={x:new_x , y_:new_y_ })
print("Accuracy (for test data): %6.2f%%" % accuracy)
print("True Label:", np.argmax(new_y_[0:15,], 1))
print("Est Label:", np.argmax(new_y[0:15, ], 1))
sess.close()
最終結果
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
step=1000, loss=2.03
step=2000, loss=1.43
step=3000, loss=0.90
step=4000, loss=0.84
step=5000, loss=1.04
step=6000, loss=0.76
step=7000, loss=0.63
step=8000, loss=0.66
step=9000, loss=0.48
step=10000, loss=0.77
Accuracy (for test data): 0.79%
True Label: [7 2 1 0 4 1 4 9 5 9 0 6 9 0 1]
Est Label: [7 2 1 0 4 1 4 4 6 7 0 6 9 0 1]
チュートリアルのMNIST For ML Beginners用の本来のソースリストは使わず、今回は、株式会社ブレインパッドの技術エントリーTensorFlowを遊び倒す! 1-1. MNIST For ML Beginnersのソースリストを動くように変更したものを使います。
※チュートリアルは2015年11月時点の記事を参考にしても、ディレクトリ配置が変わってしまったようなので注意が必要です。
tensorflow/g3doc/tutorials/mnist/ → tensorflow/examples/tutorials/mnist/
import input_data → from tensorflow.examples.tutorials.mnist import input_data
tf.device("/gpu:1") → tf.device("/cpu:0")
print → print()
ソースリスト
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def main():
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
with tf.device("/cpu:0"):
x = tf.placeholder("float", [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder("float", [None, 10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
if __name__ == "__main__":
main()
実行結果
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting MNIST_data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
0.9139
参照
チュートリアルのMNIST For ML Beginners用の本来のソースリストは使わず、株式会社ブレインパッドの技術エントリーTensorFlowを遊び倒す! 2-1. MNIST For Expertsのソースリストを動くように変更したものを使います。
import input_data → from tensorflow.examples.tutorials.mnist import input_data
tf.device("/gpu:1") → tf.device("/cpu:0")
strides=[1, 1, 1, 1],
strides=[1, 2, 2, 1],
print → print()
ソースリスト
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
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):
"""2次元畳み込み関数
strides 真ん中2つが縦横のストライド
"""
return tf.nn.conv2d(x,
W,
strides=[1, 1, 1, 1],
padding='SAME')
def max_pool_2x2(x):
"""2x2マックスプーリング関数
strides 真ん中2つが縦横のストライド
"""
return tf.nn.max_pool(x,
ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1],
padding='SAME')
def main():
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
sess = tf.InteractiveSession()
with tf.device("/cpu:0"):
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
x_image = tf.reshape(x, [-1, 28, 28, 1])
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
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)
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)
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
sess.run(tf.initialize_all_variables())
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("test accuracy %g"%accuracy.eval(feed_dict={
x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
if __name__ == "__main__":
main()
実行結果 CPUのみとしたため、3時間程度かかりました。
自PCは「Intel Core i7-4700MQ 2.4GHz」です。
akiraakさんのブログには「Intel Core i7-6700K 4GHz」で30分、「NVIDIA TITAN X」のGPU実行では1分30秒に短縮されますとのこと。速いは正義!
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
step 0, training accuracy 0.1
step 100, training accuracy 0.78
step 200, training accuracy 0.94
step 300, training accuracy 0.88
(中略)
step 19800, training accuracy 1
step 19900, training accuracy 1
test accuracy 0.9926
実行前の注意点(2016/05/28追記)
Docker上で実行した場合、"The Kernel appears to have died."という表示とともに計算が停止したとのコメントを頂きました。
TensorFlowコトハジメ Automatic Colorization(白黒画像の自動彩色)の記事内のメモリ不足を参考に、VirtualBoxのdefaultを4GByteに、docker runに「-m 4g」のオプションを付けて実行してください。
実行後にfreeコマンドでメモリ状況を参照したところ使用メモリが「1138420」となっていました。defaultマシンの初期メモリは1GByteなのでメモリが足りなかったのでしょう。
total used free shared buffers cached
Mem: 4045692 1138420 2907272 91824 10164 108692
-/+ buffers/cache: 1019564 3026128
Swap: 1946364 244772 1701592
参照