【TensorFlow】使用双向LSTM对MNIST进行分类

import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn
from tensorflow.examples.tutorials.mnist import input_data

加载数据

mnist = input_data.read_data_sets('/tmp/data',one_hot=True)
Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz

参数

# 训练参数
learning_rate = 0.001
training_steps = 10000
display_step = 200
batch_size = 128

# 网络参数
num_input = 28 # input的维度
timesteps = 28 # timestep的长度
num_hidden = 128 # 每个LSTM cell输出的维度
num_classes = 10

定义计算图

# Graph Input
X = tf.placeholder(tf.float32,[None,timesteps,num_input])
Y = tf.placeholder(tf.float32,[None,num_classes])

# 权重
weights = {
    'out':tf.Variable(tf.random_normal([2*num_hidden,num_classes]))
}
biases = {
    'out':tf.Variable(tf.random_normal([num_classes]))
}

def BiLSTM(x,weights,biases):
    # unstack前x.shape == (batch_size,timesteps,num_inputs)
    # unstack后x是一个tensor的list,其长度为timesteps,每一个tensor的shape == (batch_size,num_inputs)
    x = tf.unstack(x,timesteps,1)
    # 前向
    lstm_fw_cell = tf.nn.rnn_cell.LSTMCell(num_hidden,forget_bias=1.0)
    # 后向
    lstm_bw_cell = tf.nn.rnn_cell.LSTMCell(num_hidden,forget_bias=1.0)
    outputs,states_fw,states_bw = rnn.static_bidirectional_rnn(lstm_fw_cell,lstm_bw_cell,x,dtype = tf.float32)
    
    # 将最后一个cell的output全连接后输出
    return tf.matmul(outputs[-1],weights['out']) + biases['out']

logits = BiLSTM(X,weights,biases)
prediction = tf.nn.softmax(logits)

# 定义loss和优化器
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = logits,labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)

# 评估模型
correct_pred = tf.equal(tf.argmax(prediction,1),tf.argmax(Y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred,tf.float32))

init = tf.global_variables_initializer()

训练

with tf.Session() as sess:
    sess.run(init)
    
    for step in range(1,training_steps+1):
        batch_x,batch_y = mnist.train.next_batch(batch_size)
        batch_x = batch_x.reshape(batch_size,timesteps,num_input)
        sess.run(train_op,feed_dict={X:batch_x,Y:batch_y})
        
        if step % display_step == 0 or step == 1:
            loss,acc = sess.run([loss_op,accuracy],feed_dict={X:batch_x,Y:batch_y})
            loss = np.mean(loss)
            acc = np.mean(acc)
            print("Step " + str(step) + ", Minibatch Loss= " + "{:.4f}".format(loss) + ", Training Accuracy= " + "{:.3f}".format(acc))
            
    print('Optimization Finished!')
    
    test_size = 128
    test_data = mnist.test.images[:test_size].reshape((-1, timesteps, num_input))
    test_label = mnist.test.labels[:test_size]
    test_acc = sess.run(accuracy, feed_dict={X: test_data, Y: test_label})
    print("Testing Accuracy:", np.mean(test_acc))
Step 1, Minibatch Loss= 3.1331, Training Accuracy= 0.117
Step 200, Minibatch Loss= 1.9988, Training Accuracy= 0.414
Step 400, Minibatch Loss= 1.8180, Training Accuracy= 0.461
......
Step 9800, Minibatch Loss= 0.4329, Training Accuracy= 0.828
Step 10000, Minibatch Loss= 0.4194, Training Accuracy= 0.844
Optimization Finished!
Testing Accuracy: 0.890625

你可能感兴趣的:(TensorFlow)