attention包含两种,一种是空间上的,一种是时序上的
seq2seq:
encoder-decoder存在的问题:中间的存储向量的尺寸固定
通过attention机制解决
计算每个时刻的输出与最后时刻输出的相似度,再进行softmax得到一个向量
https://www.cnblogs.com/hiyoung/p/9860561.html
fw_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden)##正向的LSTM
bw_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden)##反向的LSTM
hidden_outputs, final_state = tf.nn.bidirectional_dynamic_rnn(fw_cell, bw_cell, cell_in, dtype=tf.float32)
# hidden_outputs[2,batch_size,n_step,hidden_size]
# final_state [2,2,batch_size,hidden_size]
output = tf.concat([hidden_outputs[0], hidden_outputs[1]], 2) # 6,3,10 第一个step和第二个step 的隐藏层输出
final_state = tf.concat([final_state[1][0], final_state[1][1]], 1) # 6,10 正反向最后时刻输出
final_state = tf.expand_dims(final_state, 2)
attn_weight = tf.squeeze(tf.matmul(output, final_state), 2) # 6,3
soft_attn_weights = tf.nn.softmax(attn_weight, 1) # 6,3
context = tf.matmul(tf.transpose(output, [0, 2, 1]), tf.expand_dims(soft_attn_weights, 2)) # 6,10,1
context = tf.squeeze(context, 2) # 6,10
model = tf.matmul(context, out) # batch n_class