Tensorflow-recurrent-neural-networks

提供:Dev Guides
移動先:案内検索

TensorFlow-リカレントニューラルネットワーク

リカレントニューラルネットワークは、深層学習指向のアルゴリズムの一種で、シーケンシャルアプローチに従います。 ニューラルネットワークでは、各入力と出力が他のすべてのレイヤーから独立していることを常に想定しています。 これらのタイプのニューラルネットワークは、数学的計算を逐次的に実行するため、リカレントと呼ばれます。

リカレントニューラルネットワークを訓練するために次の手順を検討してください-

  • ステップ1 *-データセットから特定の例を入力します。
  • ステップ2 *-ネットワークは例をとり、ランダムに初期化された変数を使用していくつかの計算を計算します。
  • ステップ3 *-予測結果が計算されます。
  • ステップ4 *-生成された実際の結果と期待値を比較すると、エラーが発生します。
  • ステップ5 *-エラーをトレースするために、変数も調整された同じパスを介して伝播されます。
  • ステップ6 *-出力を取得するために宣言された変数が適切に定義されていると確信できるまで、1から5までのステップが繰り返されます。
  • ステップ7 *-これらの変数を適用して、新しい見えない入力を取得することにより、体系的な予測が行われます。

リカレントニューラルネットワークを表すための模式的なアプローチは以下に説明されています-

リカレントニューラルネットワーク

TensorFlowを使用したリカレントニューラルネットワークの実装

このセクションでは、TensorFlowでリカレントニューラルネットワークを実装する方法を学習します。

  • ステップ1 *-TensorFlowには、リカレントニューラルネットワークモジュールの特定の実装のためのさまざまなライブラリが含まれています。
#Import necessary modules
from __future__ import print_function

import tensorflow as tf
from tensorflow.contrib import rnn
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot = True)

前述のように、ライブラリは入力データの定義に役立ちます。入力データは、リカレントニューラルネットワーク実装の主要部分を形成します。

  • ステップ2 *-主な動機は、リカレントニューラルネットワークを使用して画像を分類することです。ここでは、すべての画像行をピクセルのシーケンスと見なします。 MNIST画像の形状は、特に28 * 28ピクセルとして定義されています。 ここで、記載されている各サンプルに対して28ステップの28シーケンスを処理します。 入力パラメーターを定義して、シーケンシャルパターンを完成させます。
n_input = 28 # MNIST data input with img shape 28*28
n_steps = 28
n_hidden = 128
n_classes = 10

# tf Graph input
x = tf.placeholder("float", [None, n_steps, n_input])
y = tf.placeholder("float", [None, n_classes]
weights = {
   'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))
}
biases = {
   'out': tf.Variable(tf.random_normal([n_classes]))
}
  • ステップ3 *-RNNで定義された関数を使用して結果を計算し、最良の結果を取得します。 ここでは、各データ形状が現在の入力形状と比較され、結果が計算されて精度が維持されます。
def RNN(x, weights, biases):
   x = tf.unstack(x, n_steps, 1)

   # Define a lstm cell with tensorflow
   lstm_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)

   # Get lstm cell output
   outputs, states = rnn.static_rnn(lstm_cell, x, dtype = tf.float32)

   # Linear activation, using rnn inner loop last output
   return tf.matmul(outputs[-1], weights['out']) + biases['out']

pred = RNN(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = pred, labels = y))
optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)

# Evaluate model
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
init = tf.global_variables_initializer()
  • ステップ4 *-このステップでは、グラフを起動して計算結果を取得します。 これは、テスト結果の精度の計算にも役立ちます。
with tf.Session() as sess:
   sess.run(init)
   step = 1
   # Keep training until reach max iterations

   while step * batch_size < training_iters:
      batch_x, batch_y = mnist.train.next_batch(batch_size)
      batch_x = batch_x.reshape((batch_size, n_steps, n_input))
      sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})

      if step % display_step == 0:
         # Calculate batch accuracy
         acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})

         # Calculate batch loss
         loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})

         print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
            "{:.6f}".format(loss) + ", Training Accuracy= " + \
            "{:.5f}".format(acc))
      step += 1
   print("Optimization Finished!")
      test_len = 128
   test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))

   test_label = mnist.test.labels[:test_len]
   print("Testing Accuracy:", \
      sess.run(accuracy, feed_dict={x: test_data, y: test_label}))

以下のスクリーンショットは、生成された出力を示しています-

リカレントニューラルネットワーク実装出力

リカレントニューラルネットワーク実装出力TransFlow