真・全力失踪

全力で道を見失うブログ

TensorFlowのチュートリアルスクリプトを理解する

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

このread_data_setsメソッドの実装は、
tensorflow/examples/tutorials/mnist/input_data.py
の中でインポートされている
tensorflow/examples/tutorials/mnist/mnist.py
の中にいます(ややこしい)。mnistにはDataSetというサンプル用の便利クラスのオブジェクトが返ります。カレントディレクトリにフォルダを作ってMNISTデータの圧縮ファイルがダウンロードされるので注意。

import tensorflow as tf
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]))

ここで入力ベクトルxおよび教師ベクトルy_を格納する領域の確保と、DNNの重みベクトルとバイアスベクトルをセットしている模様。重み行列が1つしか無いということは、もしかして単層のネットワークなのか…?

init_operations = tf.initialize_all_variables()
with tf.Session() as sess:
  sess.run(init_operations)

ここがよく分からないところ。セッションをwithブロックで開いて、Sessionクラスのrunを実行しています。initialize_all_variablesの戻り値は、全ての変数に対する(Initialize?)Operationのようなのですが、なぜrunを介して実行する必要があるのかがよく分からない…。

参照)
tensorflow/python/ops/variables.py
tensorflow/python/ops/control_flow_ops.py
tensorflow/python/framework/ops.py

  y = tf.nn.softmax(tf.matmul(x,W) + b)

入力に重みを掛けてバイアスを足してソフトマックス取ったのがy。あれ、活性化関数は…?

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

後半はなんとなく何をやっているのか分かりますが、相互情報量とかもう忘れてしまったなあ。

うーむ。他のチュートリアルも見てみよう。