tensorlfow的雙向lstm的幾種情況

雙向rnn

關于雙向rnn有好幾種情況,雖然可以組合,但是一定要考慮loss優化時是否能夠收斂。
1.單層雙向(靜態)
2.單層雙向(動態)
3.多層雙向(靜態)
4.多層雙向(動態)

代碼示例

1.單層雙向(靜態)

lstm_fw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)
lstm_bw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)
x1 = tf.unstack(x, n_steps, 1)
outputs, _, _ = rnn.static_bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x1,dtype=tf.float32)
pred = tf.contrib.layers.fully_connected(outputs[-1],n_classes,activation_fn = None)

2.單層雙向(動態)

lstm_fw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)
lstm_bw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)
outputs, _, _ = rnn.stack_bidirectional_dynamic_rnn([mcell],[mcell_bw], x, dtype=tf.float32)
outputs = tf.concat(outputs, 2)
outputs = tf.transpose(outputs, [1, 0, 2]) 
pred = tf.contrib.layers.fully_connected(outputs[-1],n_classes,activation_fn = None)

3.多層雙向(靜態)

x1 = tf.unstack(x, n_steps, 1)
stacked_rnn = []
stacked_bw_rnn = []
for i in range(3):
    stacked_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))
     stacked_bw_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))
mcell = tf.contrib.rnn.MultiRNNCell(stacked_rnn)
mcell_bw = tf.contrib.rnn.MultiRNNCell(stacked_bw_rnn)
outputs, _, _ = rnn.stack_bidirectional_rnn([mcell],[mcell_bw], x1,dtype=tf.float32)

4.多層雙向(動態)

stacked_rnn = []
stacked_bw_rnn = []
for i in range(3):
    stacked_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))
     stacked_bw_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))
mcell = tf.contrib.rnn.MultiRNNCell(stacked_rnn)
mcell_bw = tf.contrib.rnn.MultiRNNCell(stacked_bw_rnn)
outputs, _, _ = rnn.stack_bidirectional_dynamic_rnn([mcell],[mcell_bw], x,dtype=tf.float32)
outputs = tf.transpose(outputs, [1, 0, 2]) 

全部代碼

https://blog.csdn.net/u012436149/article/details/71080601

# -*- coding: utf-8 -*-

import tensorflow as tf
from tensorflow.contrib import rnn
# 導入 MINST 數據集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("c:/user/administrator/data/", one_hot=True)

#參數設置
learning_rate = 0.001
training_iters = 100000
batch_size = 128
display_step = 10

# Network Parameters
n_input = 28 # MNIST data 輸入 (img shape: 28*28)
n_steps = 28 # timesteps
n_hidden = 128 # hidden layer num of features
n_classes = 10  # MNIST 列別 (0-9 ,一共10類)

tf.reset_default_graph()

# tf Graph input
x = tf.placeholder("float", [None, n_steps, n_input])
y = tf.placeholder("float", [None, n_classes])

#tf.nn.bidirectional_dynamic_rnn,雙向RNN

lstm_fw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)
#dropout
#lstm_fw_cell=rnn.DropoutWrapper(lstm_fw_cell,output_keep_prob=0.5)
# 反向cell
lstm_bw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)
#lstm_bw_cell=rnn.DropoutWrapper(lstm_bw_cell,input_keep_prob=0.5)
#單層動態雙向
#outputs, output_states = tf.nn.bidirectional_dynamic_rnn(lstm_fw_cell,lstm_bw_cell,x,
#                                         dtype=tf.float32)
#print(len(outputs),outputs[0].shape,outputs[1].shape)
#outputs = tf.concat(outputs, 2)
#outputs = tf.transpose(outputs, [1, 0, 2])
#單層靜態雙向   
x1 = tf.unstack(x, n_steps, 1)
#outputs, _, _ = rnn.static_bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x1,
#                                              dtype=tf.float32)
#print(outputs[0].shape,len(outputs))
#print(outputs)
#多層雙向
#outputs, _, _ = rnn.stack_bidirectional_rnn([lstm_fw_cell],[lstm_bw_cell], x1,
#                                              dtype=tf.float32)
#print(outputs[0].shape,len(outputs))

#LIST多層靜態雙向
#stacked_rnn = []
#stacked_bw_rnn = []
#for i in range(3):
#    stacked_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))
#    stacked_bw_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))
#    
#outputs, _, _ = rnn.stack_bidirectional_rnn(stacked_rnn,stacked_bw_rnn, x1,
#                                             dtype=tf.float32)    
#MultiRNNCell多層靜態雙向
stacked_rnn = []
stacked_bw_rnn = []
for i in range(3):
    stacked_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))
    stacked_bw_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))
   
  
#
mcell = tf.contrib.rnn.MultiRNNCell(stacked_rnn)
mcell_bw = tf.contrib.rnn.MultiRNNCell(stacked_bw_rnn)
#
#outputs, _, _ = rnn.stack_bidirectional_rnn([mcell],[mcell_bw], x1,
#                                              dtype=tf.float32)
#MultiRNNCell多層動態雙向
outputs, _, _ = rnn.stack_bidirectional_dynamic_rnn([mcell],[mcell_bw], x,
                                              dtype=tf.float32)
outputs = tf.transpose(outputs, [1, 0, 2])                                              
print(outputs[0].shape,outputs.shape)

pred = tf.contrib.layers.fully_connected(outputs[-1],n_classes,activation_fn = None)

# 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))



# 啟動session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    step = 1
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        batch_x, batch_y = mnist.train.next_batch(batch_size)
        # Reshape data to get 28 seq of 28 elements
        batch_x = batch_x.reshape((batch_size, n_steps, n_input))
        # Run optimization op (backprop)
        sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
        if step % display_step == 0:
            # 計算批次數據的準確率
            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 (" Finished!")

    # 計算準確率 for 128 mnist test images
    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}))


?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容