import tensorflow as tf
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
# Set the hyperparameters of training, including learning rate, training times and data size of each round of training
# Set training hyperparameters
lr = 0.001
training_iters = 100000
batch_size = 128
# To classify images using RNN, we treat the rows of each image as a sequence of pixels. Because MNIST images are 28 by 28 pixels in size,
# So we treat each image sample as a sequence of rows. Therefore, there is a total of (sequence of 28 elements) × (28 rows), and then the sequence length of each input step is 28, and the number of input steps is 28
# Parameters of neural network
n_inputs = 28  # input layer n
n_steps = 28  # 28 length
n_hidden_units = 128   # Number of neurons in the hidden layer
n_classes = 10   The number of numbers in the output, i.e. the category of the classification, 0 ~ 9 numbers, a total of 10
Define input data and weights
# Input data placeholder
x = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
y = tf.placeholder(tf.float32, [None, n_classes])

# define weight
weights = {
    # (28, 128)
    'in': tf.Variable(tf.random_normal([n_inputs, n_hidden_units])),
    # (128, 10)
    'out': tf.Variable(tf.random_normal([n_hidden_units, n_classes]))
}
biases = {
    # (128),
    'in': tf.Variable(tf.constant(0.1, shape=[n_hidden_units, ])),
    # (10),
    'out': tf.Variable(tf.constant(0.1, shape=[n_classes, ]))
}
# Define the RNN model
def RNN(X, weights, biases) :
    Batch * 28 steps, 28 inputs ==> (batch * 28 inputs, 28 inputs)
    X = tf.reshape(X, [-1, n_inputs])

    Enter the hidden layer
    # X_in = (128 batch * 28 steps, 128 hidden)
    X_in = tf.matmul(X, weights['in']) + biases['in']
    # X_in ==> (128 batch, 28 steps, 128 hidden)
    X_in = tf.reshape(X_in, [-1, n_steps, n_hidden_units])
    # The basic LSTM loop network unit is used here: basic LSTM Cell
    lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden_units, forget_bias=1.0,
                                             state_is_tuple=True)
    The LSTM unit consists of two parts :(c_state, h_state)
    init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32)

    # dynamic_rnn accepts the tensor (batch, steps, inputs) or (steps, Batch, inputs) as X_in
    outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, X_in, initial_state=init_state, time_major=False)
    results = tf.matmul(final_state[1], weights['out']) + biases['out']
    return results
Define loss function and optimizer, optimizer uses AdamOptimizer
pred = RNN(x, weights, biases)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
train_op = tf.train.AdamOptimizer(lr).minimize(cost)
Define model prediction results and accuracy calculation methods
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Start the graph in a session, start the training, output the accuracy size every 20 times
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    step = 0
    while step * batch_size < training_iters:
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        batch_xs = batch_xs.reshape([batch_size, n_steps, n_inputs])
        sess.run([train_op], feed_dict={
            x: batch_xs,
            y: batch_ys,
        })
        if step % 20= =0:
            print(sess.run(accuracy, feed_dict={
                x: batch_xs,
                y: batch_ys,
            }))
        step += 1
Copy the code

\