TensorFlow递归神经网络

递归神经网络是一种面向深度学习的算法,遵循顺序方法。在神经网络中,我们总是假设每个输入和输出都独立于所有其他层。这些类型的神经网络称为循环,因为它们以顺序方式执行数学计算。

考虑以下步骤来训练递归神经网络 -

第1步 - 从数据集输入特定示例。
第2步 - 网络将举例并使用随机初始化变量计算一些计算。
第3步 - 然后计算预测结果。
第4步 - 生成的实际结果与期望值的比较将产生错误。
第5步 - 为了跟踪错误,它通过相同的路径传播,其中也要调整变量。
第6步 - 重复从1到5的步骤,直到声明获得输出的变量正确定义。
第7步 - 通过应用这些变量来获得新的看不见的输入来进行系统预测。

表示递归神经网络的示意方法如下所述 -

TensorFlow递归神经网络

使用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}))

下面的屏幕截图显示了生成的输出 -


上一篇:TensorFlow卷积神经网络

下一篇:TensorFlow TensorBoard可视化

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程