這篇博客不是一篇講解原理的博客,這篇博客主要講解tnesorlfow的RNN代碼結(jié)構(gòu),通過代碼來學(xué)習(xí)RNN,以及講解time_steps,如果這篇博客沒有讓你明白time_steps,歡迎博客下面評論交流。
我曾翻閱各大網(wǎng)站,各大博客,他們的對RNN中time_steps的講解,都沒有一個讓人醍醐灌頂?shù)拇鸢?,甚至讓人越看模糊。有的博主在博客中講的看似他懂了,一問他自己他答不上來。在這里,我向全中國還迷糊在time_step的學(xué)者答疑,立此博文。
RNNCell
想要看懂tensorflow RNN代碼,我們必須要先了解RNNCell,RNNcell 是
tensorlfow中實(shí)現(xiàn)RNN的基本單元。我們平時在代碼中用的是RNNcell的子類,BasicRNNCell(RNN的基礎(chǔ)類)和BasicLSTMCell(LSTM的基礎(chǔ)類)。為了方便,我用cell對這兩個類進(jìn)行統(tǒng)稱。
使用方式是:(output, next_state) = call(input, state)
理解例子:輸入序列是:$x_1、x_2、x_3$,RNN的初始狀態(tài)為$h_0$
t=1時刻,$(output_1, h_1) = cell(x_1,h_0)$
t=2時刻,$(output_2, h_2) = cell(x_2,h_1)$
t=3時刻,$(output_3, h_3) = cell(x_3,h_2)$
每調(diào)用一次RNNCell的call方法,就相當(dāng)于在時間上推進(jìn)了一步。
RNNCell中還有兩個輸出比較重要,state_size(隱層的大小),output_size(輸出的大小)。
設(shè)輸入數(shù)據(jù)的形狀為(batch_size, input_size),那么計(jì)算時得到的隱層狀態(tài)就是(batch_size,
state_size),輸出就是(batch_size, output_size)。
import tensorflow as tf cell = tf.nn.rnn_cell.BasicRNNCell(num_units=128) #
state_size = 128 # cell = tf.keras.layers.SimpleRNNCell(units=128) print
(cell.state_size)# 128 # 32 是 batch_size inputs = tf.placeholder(tf.float32,
shape=(32, 100)) # 通過zero_state得到一個全0的初始狀態(tài),形狀為(batch_size, state_size) h0 =
cell.zero_state(32, tf.float32)# (32, 128) # 調(diào)用call函數(shù) output, h1 = cell.__call__
(inputs, h0)print(h1.shape) # (32, 128)
對于BasicLSTMCell,因?yàn)長STM可以看做有兩個隱狀態(tài)h和c,對應(yīng)的隱層就是一個Tuple,每個都是(batch_size,
state_size)的形狀:
import tensorflow as tf lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(num_units=128
) inputs= tf.placeholder(tf.float32, shape=(32, 100)) # 32 是 batch_size h0 =
lstm_cell.zero_state(32, tf.float32)# (32,128) output, h1 = lstm_cell.__call__
(inputs, h0)print(h1.h.shape) # shape=(32, 128) print(h1.c.shape) # shape=(32,
128)
tf.nn.static_rnn
tf.nn.static_rnn——隨時間靜態(tài)展開。static_rnn() 返回兩個對象,第一個是每一時刻time_steps RNN輸出的列表
,另一個是RNN網(wǎng)絡(luò)的最終狀態(tài)state。下面代碼舉例time_steps=2的輸入。
X0 = tf.placeholder(tf.float32, [None, n_inputs]) X1 =
tf.placeholder(tf.float32, [None, n_inputs]) basic_cell=
tf.contrib.rnn.BasicRNNCell(num_units=n_neurons) output_seqs, states =
tf.contrib.rnn.static_rnn(basic_cell, [X0, X1], dtype=tf.float32) Y0, Y1 =
output_seqs
如果有50個tiime_steps時刻,操作50個輸入占位符實(shí)在太繁瑣了,假如輸入shape=(None, time_steps,
imput_size),可以用如下方法一并輸入
X = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) X = tf.transpose(X,
perm=[1, 0, 2])# shape=(n_steps, batchs ,n_inputs) X_seqs = tf.unstack(X) #
time_steps個(batchs, n_inputs)的列表 basic_cell =
tf.contrib.rnn.BasicRNNCell(num_units=n_neurons) output_seqs, states =
tf.contrib.rnn.static_rnn(basic_cell, X_seqs, dtype=tf.float32) outputs =
tf.transpose(tf.stack(output_seqs), perm=[1, 0, 2])
最終的outputs是一個包含所有實(shí)例、任一時刻、所有神經(jīng)元的輸出的張量。幸運(yùn)的是,還有更好的解決方案,那就是dynamic_rnn()函數(shù)。
tf.nn.dynamic_rnn
tf.nn.dynamic_rnn——隨時間動態(tài)展開
?;A(chǔ)的RNNCell有一個很明顯的問題:對于單個的RNNCell,我們使用它的call函數(shù)進(jìn)行運(yùn)算時,只是在序列時間上前進(jìn)了一步
。如果我們的序列長度為10,就要調(diào)用10次call函數(shù),比較麻煩。對此,TensorFlow提供了一個tf.nn.dynamic_rnn函數(shù),該函數(shù)就相當(dāng)于調(diào)用了n(輸入數(shù)據(jù)的格式為(batch_size,?
time_steps, input_size),其中time_steps表示序列本身的長度,如在Char
RNN中,長度為10的句子對應(yīng)的time_steps就等于10。最后的input_size就表示輸入數(shù)據(jù)單個序列單個時間維度上固有的長度。另外我們已經(jīng)定義好了一個RNNCell,調(diào)用該RNNCell的call函數(shù)time_steps次,對應(yīng)的代碼就是:)次call函數(shù)。即通過${h_0,x_1,
x_2, …., x_n}$直接得${h_1,h_2…,h_n}$。
舉個例子:假設(shè)輸入數(shù)據(jù)的格式為(batch_size, time_steps,
input_size),其中time_steps表示序列本身的長度,如在NLP中,一句話有25個字,每個字的向量維度為300,那么time_steps就是句子的長度=25,input_size=300。另外我們已經(jīng)定義好了一個RNNCell,調(diào)用該RNNCell的call函數(shù)time_steps次,對應(yīng)的代碼就是:
outputs, state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state)
參數(shù):
* inputs: 輸入序列 shape = (batch_size, time_steps, input_size)
* cell: RNNCell
* initial_state: 初始狀態(tài)。一般可以取零矩陣shape = (batch_size, cell.state_size)。
返回:
* outputs:time_steps步里所有輸出,shape=(batch_size, time_steps, cell.output_size)
* state:最后一步的隱狀態(tài),它的形狀為(batch_size, cell.state_size) X =
tf.placeholder(tf.float32, [None, n_steps, n_inputs])# (batch_size,
time_steps,input_size) basic_cell = tf.contrib.rnn.BasicRNNCell(num_units=
n_neurons) outputs, states= tf.nn.dynamic_rnn(basic_cell, X, dtype=tf.float32)
變長輸入序列
前面我們處理的輸入shape=(batch_size, time_step,
input_size),輸入序列是定長的,拿我們做自然一樣處理為例子,如果數(shù)據(jù)有1000段時序的句子,每句話有25個字,對每個字進(jìn)行向量化,每個字的向量維度為300,那么batch_size=1000,time_steps=25,input_size=300。但是每句話的句子長度都是不一樣的,這時候我們就需要在調(diào)用dynamic_rnn()(或者static_rnn)時使用sequence_length參數(shù)。指明了每一實(shí)例輸入序列的長度。例如:
X = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) # (batch_size,
time_steps,input_size) seq_length = tf.placeholder(tf.int32, [None]) basic_cell
= tf.contrib.rnn.BasicRNNCell(num_units=n_neurons) outputs, states =
tf.nn.dynamic_rnn(basic_cell, X,sequence_length=seq_length, dtype=tf.float32)
假設(shè)我們輸入的第二個實(shí)例只有一個時刻的輸入,表示該實(shí)例張量的第二維需要補(bǔ)零,如下所示:
X_batch = np.array([ # step 0 step 1 [[0, 1, 2], [9, 8, 7]], # instance 0 [[3,
4, 5], [0, 0, 0]],# instance 1 (padded with a zero vector) [[6, 7, 8], [6, 5,
4]],# instance 2 [[9, 0, 1], [3, 2, 1]], # instance 3 ]) seq_length_batch =
np.array([2, 1, 2, 2]) with tf.Session() as sess: init.run() outputs_val,
states_val= sess.run([outputs, states], feed_dict={X: X_batch, seq_length:
seq_length_batch})
tf.nn.rnn_cell.MultiRNNCell
單層RNN能力有限,我們需要多層的RNN
。將x輸入第一層RNN的后得到隱層狀態(tài)h,這個隱層狀態(tài)就相當(dāng)于第二層RNN的輸入,第二層RNN的隱層狀態(tài)又相當(dāng)于第三層RNN的輸入,以此類推。在TensorFlow中,可以使用tf.nn.rnn_cell.MultiRNNCell函數(shù)對RNNCell進(jìn)行堆疊
import tensorflow as tf # 每調(diào)用一次這個函數(shù)就返回一個BasicRNNCell def get_a_cell(): return
tf.nn.rnn_cell.BasicRNNCell(num_units=128) # 用tf.nn.rnn_cell MultiRNNCell創(chuàng)建3層RNN
cell = tf.nn.rnn_cell.MultiRNNCell([get_a_cell()for _ in range(3)]) # 3層RNN #
得到的cell實(shí)際也是RNNCell的子類 # 它的state_size是(128, 128, 128) # (128, 128,
128)并不是128x128x128的意思 # 而是表示共有3個隱層狀態(tài),每個隱層狀態(tài)的大小為128 print(cell.state_size) #
(128, 128, 128) # 使用對應(yīng)的call函數(shù) inputs = tf.placeholder(tf.float32, shape=(32,
100))# 32 是 batch_size h0 = cell.zero_state(32, tf.float32) #
通過zero_state得到一個全0的初始狀態(tài) output, h1 = cell.__call__(inputs, h0) print(h1) #
tuple中含有3個32x128的向量 # (<tf.Tensor 'multi_rnn_cell/cell_0/basic_rnn_cell/Tanh:0'
shape=(32, 128) dtype=float32>, # <tf.Tensor
'multi_rnn_cell/cell_1/basic_rnn_cell/Tanh:0' shape=(32, 128) dtype=float32>, #
<tf.Tensor 'multi_rnn_cell/cell_2/basic_rnn_cell/Tanh:0' shape=(32, 128)
dtype=float32>)
RNN的其他變種
### ------------ LSTM ------------- ### lstm_cell =
tf.contrib.rnn.BasicLSTMCell(num_units=n_neurons) # peephole connections #
讓長期記憶也參與控制門的管理可能會更好 lstm_cell = tf.contrib.rnn.LSTMCell(num_units=n_neurons,
use_peepholes=True) ### ------------ GRU ------------- ### gru_cell =
tf.contrib.rnn.GRUCell(num_units=n_neurons)
time_steps專欄
有的人學(xué)習(xí)到RNN的時候,死活都弄不清batch、input_size、time_steps。在這篇博文中,我做一個專欄。
文字?jǐn)?shù)據(jù)
如果數(shù)據(jù)有1000段時序的句子,每句話有25個字,對每個字進(jìn)行向量化,每個字的向量維度為300,那么batch_size=1000,time_steps=25,input_size=300。
解析:time_steps一般情況下就是等于句子的長度,input_size等于字量化后向量的長度。
圖片數(shù)據(jù)
拿MNIST手寫數(shù)字集來說,訓(xùn)練數(shù)據(jù)有6000個手寫數(shù)字圖像,每個數(shù)字圖像大小為28*28,batch_size=6000沒的說,time_steps=28,input_size=28,我們可以理解為把圖片圖片分成28份,每份shape=(1,
28)。
音頻數(shù)據(jù)
如果是單通道音頻數(shù)據(jù),那么音頻數(shù)據(jù)是一維的,假如shape=(8910,)。使用RNN的數(shù)據(jù)必須是二維的,這樣加上batch_size,數(shù)據(jù)就是三維的,第一維是batch_size,第二維是time_steps,第三位是數(shù)據(jù)input_size。我們可以把數(shù)據(jù)reshape成三維數(shù)據(jù)。這樣就能使用RNN了。
參考文獻(xiàn)
知乎-何之源:TensorFlow中RNN實(shí)現(xiàn)的正確打開方式 <https://zhuanlan.zhihu.com/p/28196873>
學(xué)習(xí)RNN練手項(xiàng)目 Char-RNN
<https://link.zhihu.com/?target=https%3A//github.com/hzy46/Char-RNN-TensorFlow>
royhoo的博客園——循環(huán)神經(jīng)網(wǎng)絡(luò)
<https://www.cnblogs.com/royhoo/p/Recurrent-Neural-Networks-1.html>
熱門工具 換一換