Tensorflow を勉強するために用意されているチュートリアルをやってみようと思った。
Qiita の記事にも登場しているので先達さんたちの日本語記事を参考にやっていこう。

本家チュートリアル
https://www.tensorflow.org/versions/master/tutorials/index.html
では、以下が用意されている。下から3つ目のように学習データの落とし方も含んでいるのだが。

 MNIST For ML Beginners
 Deep MNIST for Experts
 TensorFlow Mechanics 101
 TensorFlow Serving
 Convolutional Neural Networks
 Vector Representations of Words
 Recurrent Neural Networks
 Sequence-to-Sequence Models
 Mandelbrot Set
 Partial Differential Equations
 MNIST Data Download
 Image Recognition
 Deep Dream Visual Hallucinations



まずは一番初級 MNIST For ML Beginners から


(tensorflow)take@ubuntu:~/tensorflow$ more mnist_for_ml_beginners.py
# -*- coding: utf-8 -*-
import tensorflow as tf
import input_data

# MNISTデータを取り出す。訓練データとテストデータで、画像と0-9のラベル
# mnist.train.images
# mnist.train.labels
# mnist.test.images
# mnist.test.labels
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# Training用の入れ物の準備
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# y_ : 正しい答え
# y  : 予測した答え
y_ = tf.placeholder(tf.float32, [None, 10])

#  x*W+b を softmax と通し、y にする。
y = tf.nn.softmax(tf.matmul(x, W) + b)

# Training指標の準備
# 訓練するために、悪い(or 良い)を定義する。ここでは悪い(費用:コストがかかる)ことを
# 交差エントロピーで計算する。
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)


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})

# 評価のために正解率を計算
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}))
(tensorflow)take@ubuntu:~/tensorflow$



走らせてみる。



(tensorflow)take@ubuntu:~/tensorflow$ python mnist_for_ml_beginners.py

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.9183
(tensorflow)take@ubuntu:~/tensorflow$

正解率は、91.8%