LoginSignup
12
14

More than 5 years have passed since last update.

今度こそ理解するTensorFlow (MNISTを題材に)

Last updated at Posted at 2016-11-03

タイトルは釣りですw
TensorFlowのMNISTチュートリアル(for Beginner)の解説は数あれど、精度をちょろっと出してお終いで、その学習したモデルを使ってどう予測を行えば良いかを書いている記事が見当たらなかったので記事にしてみます。あと、良い入門記事を見つけたので、それも紹介します。

はじめに読んでおくと良い記事

こちらの連載を読むとTensorFlowの理解が深まるのでまずは読んでおくことを強くお勧めします。
http://www.buildinsider.net/small/booktensorflow/0001
http://msyksphinz.hatenablog.com/entry/2015/11/19/022254

TensorFlowのMNISTチュートリアル(for Beginner)の解説

こちらの記事が大変分かりやすいです (丸投げ)
http://qiita.com/tuno-tky/items/cf7068f14ceea08802e8

学習したモデルを使った予測

以下の最後の3行で学習結果を使った予測を行っています。
やっていることは、テスト用のデータを引っ張ってきて、定義済みのyというオペレーションを、argmaxでラップしたオペレーションを作成し、それを実行しています。
実行すると、テストデータそれぞれのラベルが得られます。

mnist_beginner.py
import input_data
import tensorflow as tf

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

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

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

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.005).minimize(cross_entropy)

sess = tf.Session()

init = tf.initialize_all_variables()
sess.run(init)

# 実行時間短縮のため10000回から100回に減らしている
for i in range(100):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

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

# prediction
batch_xs, batch_ys = mnist.train.next_batch(5)
pred_rslt = sess.run(tf.argmax(y, 1), feed_dict={x: batch_xs})

print(pred_rslt)

実行結果

(省略)
0.8672
0.8766
0.889
0.8943
[5 1 1 3 6]

その他参考

http://qiita.com/tawago/items/c977c79b76c5979874e8
http://qiita.com/tawago/items/931bea2ff6d56e32d693

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14