LSTM公式
- 原理圖:http://colah.github.io/posts/2015-08-Understanding-LSTMs/漫雕,并參考了github上這份代碼實現(xiàn):https://github.com/jonnykira/Tensorflow_mLSTM
- 公式:
- 更新細胞狀態(tài):
- 更新隱層:
定義需要用到Variable
先來個初始化用的對象,玄學(xué)初始化:
initializer = tf.contrib.layers.xavier_initializer()
全局變量:seq_length, embedding_size, rnn_size
定義那些矩陣
##tensorflow中的實現(xiàn)好像是把x_t和h_t-1拼起來了峰鄙,這里簡單點浸间,分開算
Wi=tf.get_variable('Wi', shape=(embedding_size, rnn_size), initializer=initializer)
Ui=tf.get_variable('Ui', shape=(rnn_size, rnn_size), initializer=initializer)
Wf=tf.get_variable('Wf', shape=(embedding_size, rnn_size), initializer=initializer)
Uf=tf.get_variable('Uf', shape=(rnn_size, rnn_size), initializer=initializer)
Wo=tf.get_variable('Wo', shape=(embedding_size, rnn_size), initializer=initializer)
Uo=tf.get_variable('Uo', shape=(rnn_size, rnn_size), initializer=initializer)
Wc=tf.get_variable('Wc', shape=(embedding_size, rnn_size), initializer=initializer)
Uc=tf.get_variable('Uc', shape=(rnn_size, rnn_size), initializer=initializer)
# 如果要做weight normalization可以接著寫.....
LSTM Cell
def lstm_cell(x, h, c):
it = tf.sigmoid(tf.matmul(x, Wi) + tf.matmul(h, Ui))
ft = tf.sigmoid(tf.matmul(x, Wf) + tf.matmul(h, Uf))
ot = tf.sigmoid(tf.matmul(x, Wo) + tf.matmul(h, Uo))
ct = tf.tanh(tf.matmul(x, Wc) + tf.matmul(h, Wc))
c_new = (ft * c) + (it * ct)
h_new = ot * tf.tanh(c_new)
return c_new, h_new
展開LSTM
在tensorflow中這個過程是用tf.nn.static_rnn
和tf.nn.dynamic_rnn
實現(xiàn),實際上寫個循環(huán)就行了吟榴。(ps: tf.nn.dynamic_rnn
是用tf.while
實現(xiàn)的魁蒜,不同batch可以有不同的seq_length,而tf.nn.static_rnn
的time_step數(shù)量定義好了就不能改了)
def transform(x):
# 處理一下輸入數(shù)據(jù)煤墙,rnn的batch和cnn有些不同
embedding_outputs = embedding(x) # embedding函數(shù)梅惯,需自己定義
shape = tf.shape(embedding_outputs)
embedding_inputs = tf.nn.dropout(embedding_outputs, 0.5,
noise_shape=[1, shape[1], shape[2]])
# (batch_size, seq_length, embeding_size)
inputs_split = tf.split(embedding_inputs, seq_length, axis=1)
# it's a list: seq_length x (batch_size, embedding_size)
list_inputs = [tf.squeeze(input_, [1]) for input_ in inputs_split]
return list_inputs
def unroll_lstm(lstm_cell, x, length):
# length是序列的真實長度
# x.shape = (batch_size, seq_length), 這個seq_length是padding后的
batch_size = tf.shape(x)[0]
# 對x做embedding
input_list = transform(x)
outputs = []
# unrolled lstm loop
# 定義output & state來接輸出結(jié)果
output = tf.tile(tf.expand_dims(tf.Variable(tf.zeros(cell_size),
trainable=False), 0), [batch_size, 1])
state = tf.tile(tf.expand_dims(tf.Variable(tf.zeros(cell_size),
trainable=False), 0), [batch_size, 1])
for ipt in input_list:
state, output = lstm_cell(ipt, output, state)
outputs.append(output)
# 使用mask來截掉大于序列真實長度的部分(置為0)
mask = tf.sequence_mask(length, seq_length)
out_tensor = tf.stack(outputs, axis=1)
outputs = tf.where(tf.stack([mask] * cell_size, axis=-1), out_tensor,
tf.zeros_like(out_tensor))
return outputs, state
輸出的截取
前面lstm輸出的結(jié)果為(batch_size, seq_length, rnn_size)
,batch中某些句子的長度可能比seq_length要短仿野,這時需要使用tf.gather_nd
函數(shù)去截取真實長度的輸出铣减。
# 計算真實輸出部分的indices
# 這里我添加了一個記錄batch中句子長度的placehoder: ph_length, shape: (batch_size, )
output_indices = tf.stack([tf.range(tf.shape(ph_length)[0]),
ph_length - 1], 1)
# (batch_size, rnn_size)
lstm_out_with_len = tf.gather_nd(lstm_outs, output_indices)
關(guān)于Language Model的Loss
基于LSTM的Language Model就是對于句子(其中
是句子的分詞結(jié)果),使用
去預(yù)測第
個詞
是什么脚作。如果是一整片文章葫哗,沒有加Padding和句子末尾標(biāo)記<EOS>,那這個工作還是比較簡單的球涛;若加上Padding劣针,在計算loss的時候需要對輸入和輸出做一些處理,Padding部分需要截取掉亿扁。
Loss參考代碼:https://github.com/sherjilozair/char-rnn-tensorflow/blob/master/model.py捺典,其中l(wèi)oss函數(shù)用了sequence_loss_by_example
有點迷,感覺用cross_entropy就夠了从祝,看了下API:https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py襟己。sequence_loss_by_example計算了batch_size x sequece_length
個sparse_softmax_cross_entropy_with_logits
,最后放在了一個list里面牍陌。直接寫的話擎浴,這樣子:
# 輸入:
# outputs: LSTM每個timestep的輸出,shape = (batch_size, sequence_len, lstm_cell_size)
# length: 這個batch_size中每個句子的實際長度毒涧,shape = (batch_size, )
# max_seq_len: 最大句子長度
# (optional) embed_mat: embedding使用的Lookup Table矩陣 (vocabulary_size, lstm_cell_size)
# mask tensor representing the first N positions of each cell
mask = tf.sequence_mask(length, max_seq_len)
# 提取非Padding位置的LSTM輸出
output = tf.boolean_mask(outputs, mask) # (?, lstm_cell_size)
# 構(gòu)造預(yù)測的target部分贮预,例如 “落 霞 與 孤 鶩 齊 飛”其對應(yīng)的target為
# "霞 與 孤 鶩 齊 飛 <EOS>" → [20, 11, 38, 79, 3, 7, 0] (假設(shè)"<EOS>"的id表示為0)
# 這個工具最好預(yù)處理的時候做,tensorflow的tensor不支持assignment操作,不好實現(xiàn)仿吞。滑频。
# input_y: 這個batch句子處理后的id化表示 shape = (batch_size, max_seq_len)
target = tf.boolean_mask(input_y, mask)
decoder_matrix = tf.get_variable(shape=[lstm_cell_size, vocabulary_size], initializer=
tf.random_uniform_initializer(-1., 1.))
logits = tf.matmul(output, decoder_matrix)
# 如果想要節(jié)約內(nèi)存,減少一些參數(shù)茫藏,可以復(fù)用embedding matrix
logits = tf.matmul(output, tf.transpose(embed_mat))
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=target))