真・全力失踪

全力で道を見失うブログ

TensorFlowの使い方がよく分からない

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

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

init_operations = tf.initialize_all_variables()
with tf.Session() as sess:
  sess.run(init_operations)
  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}))

このpythonスクリプトは、TensorFlowのチュートリアルプログラムを少し弄ったものです。パッケージへのパスが通ってれば動くはずです(パスを通すのに少し苦労した…)。スクリプトの詳細については次のポストへ続きます。

このページを見ながら、チュートリアルを動かしてライブラリの中を少し見てみたものの、見通しがまだイマイチ。なんとなく分かった気になっているのは、

  • tensorflowモジュールを介してDNNのノードや重みパラメータをセットし、
    ハンドル的なオブジェクトを受けとる
  • それらのパラメータに対する操作をするためにはSessionを開く必要がある
  • 開いたSessionはデフォルトセッションとしてセットされ、
    デフォルトセッションを介して操作できる
    (むしろセッションを明示する方法はないのだろうか…そういう使い方は想定していないのかも)

この場合ネットワークの構造ってどうなるんだろう。