Tensorflow
学習記録
by yuji38kwmt 2017/08/19
MNIST:Mixed National Institute of Standards and Technology. 手書き数字画像データベース
訓練データで学習(適切なパラメータを決定)し、テストデータでモデルの精度を確認する。
下記サイトのコードを実行した。
Tensorflow Tutorial mnist_softmax.py
※一部修正
# xは特定の値ではない
# 数値「784」: MNISデータ1個のサイズ(28px×28px=784)
x = tf.placeholder(tf.float32, [None, 784])
# 重みをゼロで初期化
# 数値「10」:画像から判断する結果の数(数字0~9)
W = tf.Variable(tf.zeros([784,10]))
# バイアスをゼロで初期化
b = tf.Variable(tf.zeros([10]))
# モデルの実装
y = tf.nn.softmax(tf.matmul(x, W) + b)
[0.2, 0.7, 0, 0, 0, 0, 0, 0, 0, 0.1 ]
のような配列。画像から判定した数字の確率を表す。この場合、数字「1」の確率が0.7で最も高い。# 交差エントロピー誤算を算出
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
# 最適化方法を定義。降下勾配法。
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
交差エントロピー誤差の数式:
\(H_{y'}(y) = -\sum_i y'_i \log(y_i)\)
降下勾配法を使って、交差エントロピー誤差を最小化するパラメータを探す。
"0.01"は学習率。どれだけパラメータを更新するかを決める。
# セッションを定義して、パラメータを初期化する
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
# 訓練ステップを 1000 回実行する
# 訓練セットから 100 個のランダムなデータポイントの「バッチ」を取得する
# 確率的訓練
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# テストデータを使って、精度を検証
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({x: mnist.test.images, y_: mnist.test.labels}))
精度の計算には訓練データを用いる。
# 精度のモデルを定義
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 訓練開始
loss_list = [] #誤差のリスト
accuracy_list = [] #精度のリスト
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# 誤差と精度(訓練データ)を計算
loss_val, accuracy_val = sess.run([cross_entropy, accuracy], feed_dict={x: batch_xs, y_: batch_ys})
loss_list.append(loss_val)
accuracy_list.append(accuracy_val)
import matplotlib.pylab as plt
# 誤差のグラフを表示
plt.plot(loss_list)
plt.show()
# 精度のグラフを表示
plt.plot(accuracy_list)
plt.show()
AdamOptimizerも確率的勾配降下法のひとつであるが、他の方法より新しい(2015年に発表)
特徴的なことは、収束が指数関数的ではないことである。
下記サイトより引用
TensorFlowのOptimizerを比較する(ベジェ曲線編)
# 学習率を決める必要がない
train_step = tf.train.AdamOptimizer().minimize(cross_entropy)
Gistにアップしました。
mnist_降下勾配法.py