tensorflow - 在 Tensorflow 中可视化注意力激活

标签 tensorflow deep-learning attention-model sequence-to-sequence

enter image description here

有没有办法在 TensorFlow 的 seq2seq 中可视化某些输入的注意力权重,例如上面链接中的图(来自 Bahdanau 等人,2014 年)楷模?我找到了 TensorFlow's github issue关于这一点,但我无法找到如何在 session 期间获取注意力掩码。

最佳答案

我还想为我的文本摘要任务可视化 Tensorflow seq2seq ops 的注意力权重。我认为临时解决方案是使用 session.run() 来评估上面提到的注意力掩码张量。有趣的是,原来的 seq2seq.py ops 被认为是遗留版本,在 github 中不容易找到,所以我只是使用了 0.12.0 wheel 发行版中的 seq2seq.py 文件并对其进行了修改。为了绘制热图,我使用了'Matplotlib'包,非常方便。

新闻标题文本的注意力可视化的最终输出如下所示:
enter image description here

我修改了代码如下:
https://github.com/rockingdingo/deepnlp/tree/master/deepnlp/textsum#attention-visualization

seq2seq_attn.py

# Find the attention mask tensor in function attention_decoder()-> attention()
# Add the attention mask tensor to ‘return’ statement of all the function that calls the attention_decoder(), 
# all the way up to model_with_buckets() function, which is the final function I use for bucket training.

def attention(query):
  """Put attention masks on hidden using hidden_features and query."""
  ds = []  # Results of attention reads will be stored here.

  # some code

  for a in xrange(num_heads):
    with variable_scope.variable_scope("Attention_%d" % a):
      # some code

      s = math_ops.reduce_sum(v[a] * math_ops.tanh(hidden_features[a] + y),
                              [2, 3])
      # This is the attention mask tensor we want to extract
      a = nn_ops.softmax(s)

      # some code

  # add 'a' to return function
  return ds, a

seq2seq_model_attn.py
# modified model.step() function and return masks tensor
self.outputs, self.losses, self.attn_masks = seq2seq_attn.model_with_buckets(…)

# use session.run() to evaluate attn masks
attn_out = session.run(self.attn_masks[bucket_id], input_feed)
attn_matrix = ...

predict_attn.pyeval.py
# Use the plot_attention function in eval.py to visual the 2D ndarray during prediction.

eval.plot_attention(attn_matrix[0:ty_cut, 0:tx_cut], X_label = X_label, Y_label = Y_label)

并且可能在 future tensorflow 将有更好的方法来提取和可视化注意力权重图。有什么想法吗?

关于tensorflow - 在 Tensorflow 中可视化注意力激活,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40601552/

相关文章:

python - TensorFlow:实现网络,其中所有一层的特征图未连接到下一层的所有特征图

machine-learning - 如何在 TensorFlow 中重复未知维度

python - 为什么 keras 模型编译但 fit_generator 命令抛出 'model not compiled runtime error' ?

python - 为什么在 Transformer 模型中嵌入向量乘以一个常数?

python - 为什么 Keras 不返回 lstm 层中细胞状态的完整序列?

python - 在 CNTK 中实现 Seq2Seq 时存在多个轴问题

tensorflow - 修改和组合使用 tensorflow 对象检测 API 生成的两个不同的卡住图进行推理

python-3.x - 我的简单损失函数导致 NAN

tensorflow - Keras ImageDataGenerator 预处理

machine-learning - Keras 神经网络模型精度始终为零