TensorFlow始めの一歩

## 環境構築(on OSX10.11.4)

python3を[homebrew](http://brew.sh/)でインストールします。

```bash
$ brew update && brew install python3
```

virtualenvをインストールします。

```bash
$ pip3.5 install --upgrade virtualenv
```

開発用のディレクトリを作成して、virtualenvを作成します。
virtualenv内にtensorflowをインストールします。
動作や簡単な計算確認のためにipythonもインストールします。

```bash
$ mkdir -p /path/to/develop
$ cd /path/to/develop
$ virtualenv --system-site-packages tensorflow
$ source tensorflow/bin/activate
(tensorflow)$ pip3.5 install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.8.0-py3-none-any.whl
(tensorflow)$ pip3.5 install ipython
```

正常に動作するかを確認します。

```bash
$ ipython
Python 3.5.1 (default, Apr 18 2016, 11:46:32)
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import tensorflow as tf

In [2]:
```

何もエラーが出ないならばOKです。

## Tutorial

まず、テストデータを取り込むディレクトリを作成します。

```bash
(tensorflow)$ pwd
/path/to/develop/tensorflow
(tensorflow)$ mkdir -p src/MNIST_data
```

[Tutorial](https://www.tensorflow.org/versions/r0.8/tutorials/mnist/pros/index.html)をやってみます。

```bash
In [1]: from tensorflow.examples.tutorials.mnist import input_data

In [2]: mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
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

In [3]: import tensorflow as tf

In [4]: sess = tf.Session()

In [5]: sess = tf.InteractiveSession()

In [6]: x = tf.placeholder(tf.float32, shape=[None, 784])

In [7]: y_ = tf.placeholder(tf.float32, shape=[None, 10])

In [8]: W = tf.Variable(tf.zeros([784, 10]))

In [9]: b = tf.Variable(tf.zeros([10]))

In [10]: sess.run(tf.initialize_all_variables())

In [11]: y = tf.nn.softmax(tf.matmul(x,W) + b)

In [12]: cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

In [13]: train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

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

In [15]: correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

In [16]: accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

In [17]: print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
0.9092
```

約91%と出力されました。これは良くない結果みたい(92%が正しい)なので、改善する必要があります。
ipythonを実行しているディレクトリにファイルを作ります。

```py:mnist_tutorial.py
# -*- coding: utf-8 -*-

import tensorflow as tf


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')
```

書いたコードをipythonにロードします。

```bash
In [18]: %load mnist_tutorial.py
```

作成した関数を使用して再度計算します。

```bash
In [19]: W_conv1 = weight_variable([5, 5, 1, 32])

In [20]: b_conv1 = bias_variable([32])

In [21]: x_image = tf.reshape(x, [-1, 28, 28, 1])

In [22]: h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

In [23]: h_pool1 = max_pool_2x2(h_conv1)

In [24]: W_conv2 = weight_variable([5, 5, 32, 64])

In [25]: b_conv2 = bias_variable([64])

In [26]: h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

In [27]: h_pool2 = max_pool_2x2(h_conv2)

In [28]: W_fc1 = weight_variable([7 * 7 * 64, 1024])

In [29]: b_fc1 = bias_variable([1024])

In [30]: h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])

In [31]: h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

In [32]: keep_prob = tf.placeholder(tf.float32)

In [33]: h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

In [34]: W_fc2 = weight_variable([1024, 10])

In [35]: b_fc2 = bias_variable([10])

In [36]: y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

In [37]: cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))

In [38]: train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

In [39]: correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))

In [40]: accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

In [41]: sess.run(tf.initialize_all_variables())

In [42]: 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}))
```

これ、CPUものすごく使いますね。積んでいるCPU次第では20000回は多そうです。
試しに1000回としたところ0.9598でした。改善はされているようです。
ちなみに私のCPUは`2.7 GHz Intel Core i5`で70%近く使用していました。

## さっくり試す人向け

```python:mnist_tutorial_all.py
# -*- coding: utf-8 -*-

import tensorflow as tf

sess = tf.Session()
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
sess.run(tf.initialize_all_variables())
y = tf.nn.softmax(tf.matmul(x, W) + b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ *
                                              tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

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

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

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


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


W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
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)
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(tf.float32)
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_mean(-tf.reduce_sum(y_ *
                                              tf.log(y_conv), reduction_indices=[1]))
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, tf.float32))
sess.run(tf.initialize_all_variables())

for i in range(1000):
    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}))
```

`from tensorflow.examples.tutorials.mnist import input_data`と`mnist = input_data.read_data_sets('MNIST_data', one_hot=True)`を事前に行ってから`%load mnist_tutorial_all.py`でファイルをロードしてください。

## 参考文献
* http://colah.github.io/posts/2015-09-Visual-Information/
* http://michaelnielsen.org/reinventing_explanation/
* http://colah.github.io/posts/2015-08-Backprop/
* http://neuralnetworksanddeeplearning.com/chap1.html

続く・・・（完）