tensorflow勉強会

tensorflow勉強会用の資料

tensorflow勉強会③ MNIST(簡単な方)

mint_softmax.pyを動かす

もとのコードはこちら。
https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/examples/tutorials/mnist/mnist_softmax.py

mnist_softmax.pyの中身を見てみましょう。
→ よくわからない。。。
今日は、このコードをこの上なくバカっぽく書き直していきます。

mnist_softmax.pyの実行結果はこんな感じになっているはずです。

python mnist_softmax.py
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
0.915

/tmp/tensorflow/mnist/input_data にmnistデータがあるので持ってきましょう。

cp /tmp/tensorflow/mnist/input_data/* ./

で、解凍

gzip -d *.gz

でもこれはdataファイルになっていて読み取れない。。。
ので、こちらのページのやり方でテキストデータに変換しましょう。
y-uti.hatenablog.jp

od -An -v -tu1 -j16 -w784 train-images-idx3-ubyte | sed 's/^ *//' | tr -s ' ' > train-images.txt
od -An -v -tu1 -j16 -w784 t10k-images-idx3-ubyte | sed 's/^ *//' | tr -s ' ' > test-images.txt
od -An -v -tu1 -j8 -w1 train-labels-idx1-ubyte | tr -d ' ' > train-labels.txt
od -An -v -tu1 -j8 -w1 t10k-labels-idx1-ubyte | tr -d ' ' > test-labels.txt

どんなデータか見てみましょうか。
(もっといいやりかたあるはずですが。)

import numpy as np

data = np.loadtxt('test-images.txt')

for n in range(3): # 始めの3つ
  digit = data[n,].reshape([28, 28])
  for row in range(28):
    for col in range(27):
      if digit[row,col] > 100:
        print(digit[row,col], end='')
      elif digit[row,col] > 10:
        print(digit[row,col], end='0')
      else:
        print(digit[row,col], end='00')
    print(digit[row,27])
  print(' ')

この上なくバカっぽく書き直したコード

import tensorflow as tf
import numpy as np


# 1.モデルを作成
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b
y_ = tf.placeholder(tf.float32, [None, 10])

# 2.学習方法を指定
cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y) )
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# 3.コンパイル
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

# 4.データをロード
train_data = np.loadtxt('train-images.txt')
train_label_pre = np.loadtxt('train-labels.txt')
train_label = np.zeros([60000, 10], dtype=np.float32)
for i in range(60000):
  train_label[i, int(train_label_pre[i])] = 1

test_data = np.loadtxt('test-images.txt')
test_label_pre = np.loadtxt('test-labels.txt')
test_label = np.zeros([10000, 10], dtype=np.float32)
for i in range(10000):
  test_label[i, int(test_label_pre[i])] = 1

# 5.学習
for iter in range(100):
  print("iter : " + str(iter))
  for i in range( int(60000/100) ):
    batch_xs = train_data[i*100:(i+1)*100, ]
    batch_ys = train_label[i*100:(i+1)*100, ]
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

# 6.学習結果のテスト
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: test_data, y_: test_label}))

練習問題

上の簡単なMNISTは 784 → 10 の単純な構造でした。
これをニューラルネットワークに改造しましょう!!!
784 → 392 → 10 の構造にして、392の部分に活性化関数reluを入れましょう。

活性化関数はこちら
hokuts.com

活性化関数を使わないと、どんなに複雑な構造にしても普通の線形回帰分析と同じモデルになってしまいます!!!