tensorflow勉強会

tensorflow勉強会用の資料

tensorflow勉強会④ MNIST(難しい方)

mint_deep.pyを動かす

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

やはりよくわからないので、やはりこの上なくバカっぽく書き直していきます。

新しく出てくる概念
①畳み込み
②プーリング
 このページがわかりやすいかも!!!動くし。
deepage.net

ドロップアウト
 密結合層のノードを、ある確率で(普通は50%)使わないようにして学習していきます。
 理屈はもろもろありますが、結果的に過学習しづらくなります。

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

import tensorflow as tf
import numpy as np

# 0.よく使う記述は関数に
def conv2d(x, W): # 畳み込み
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x): # プーリング
"""max_pool_2x2 downsamples a feature map by 2X."""
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')


def weight_variable(shape):
"""weight_variable generates a weight variable of a given shape."""
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)


def bias_variable(shape):
"""bias_variable generates a bias variable of a given shape."""
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)


# 1.モデルを作成
x = tf.placeholder(tf.float32, [None, 784])

# Reshape to use within a convolutional neural net.
# Last dimension is for "features" - there is only one here, since images are
# grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
x_image = tf.reshape(x, [-1, 28, 28, 1])

# First convolutional layer - maps one grayscale image to 32 feature maps.
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

# Pooling layer - downsamples by 2X.
h_pool1 = max_pool_2x2(h_conv1)

# Second convolutional layer -- maps 32 feature maps to 64.
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)

# Second pooling layer.
h_pool2 = max_pool_2x2(h_conv2)

# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
# is down to 7x7x64 feature maps -- maps this to 1024 features.
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)

# Dropout - controls the complexity of the model, prevents co-adaptation of
# features. ドロップアウト
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# Map the 1024 features to 10 classes, one for each digit
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2

y_ = tf.placeholder(tf.float32, [None, 10])

# 2.学習方法を指定
cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv) )
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))

# 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.学習 & 6.学習結果のテスト
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, keep_prob:0.5})
    print("test accuracy : " + str(sess.run(accuracy, feed_dict={x: test_data, y_: test_label, keep_prob:1.0})))

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

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

tensorflow勉強会② tensorflow超ざっくり書き方

今日はtensorflowチュートリアルにあるMNISTのコードを見ていきますが、
次のような流れでいけるようにもろもろ書き直します。
1.モデルを作成
2.学習方法を指定
3.コンパイル(と言っていいのやら)
4.データをロード
5.学習
6.学習結果のテスト

 

モデルを作成

ひとまず今日出てくるのはこんな感じの概念。

①placeholder
 学習の際にデータを流し込むところ。
②variable
 モデルが賢くなるように学習していく重み。
③relu
 活性化関数の一つ。
 他にもいっぱいあります。

 

その他の概念

こちらのサイトに説明がある通り、5つくらいのコンセプトを理解すれば大丈夫です。
(理解してなくても大丈夫だと思いますが。)

developers.gnavi.co.jp

tensorflow勉強会① 超ざっくり機械学習

機械学習の流れ

おおまかな流れはこんな感じになってます。

1.学習用の「答えありデータ」を用意します。

2.学習する
データを入れる → マシーンが何やら計算する → アウトプットが出てくる → 答えと比べる → ズレてる → ズレが小さくなるようにマシーンを教育 → データを入れる → ・・・
ズレが十分小さくなるまで何度も繰り返します。

3.テストする
学習に使わなかった「答えありデータ」でテストします。

4.予測する
学習・テストに使ったデータ以外の、新しい「答えなしデータ」に対して、答えを予測します。
 ← これが本当にやりたいことですね。

 

学習について

ズレが小さくなるようにマシーンを教育」
ズレが小さくなる方向にパラメータ(Wとb)を少し動かしてやります。
どれだけ動かせばズレが最小となるW・bとなるかはわからないため、
少し動かす → ズレを計算する → 少し動かす → ・・・
を何回も繰り返す事になります。

「少し動かす」
この「少し動かす」にも様々な工夫があります。
今日のtensorflowのコードでは、一番簡単な(何の工夫もない)方法を使います。
このページに「少し動かす」方法がやたらとまとまっています。

postd.cc



テストについて

例えばこのサイトを参照してください。

tjo.hatenablog.com

「答えありデータ」を適当に(適切に)分割します。
mnistの場合は、学習用データ60,000 vs テスト用データ10,000
学習用データでモデルの学習を行い、テスト用データで「過学習」していないことをチェックします。
(←今日はやりませんが。)