使用 Python matplotlib 绘制 nn.multiheadattention 的注意力权重热力图
要画出 'nn.multiheadattention' 函数返回值的 'attn_output_weights_sum' 矩阵的热力图,可以使用 Python 中的 'matplotlib' 库。以下是一个示例代码:
import matplotlib.pyplot as plt
import torch.nn as nn
# 假设你已经有了一个 nn.MultiheadAttention 的实例,名为 attention
# 假设你已经有了一个输入张量 x,形状为 (seq_len, batch_size, input_dim)
# 假设你已经有了一个输出张量 output,形状为 (seq_len, batch_size, output_dim)
# 注意:seq_len 和 batch_size 的值必须相同
# 调用 attention 函数
_, attn_output_weights = attention(x, x, x)
# 取出 attn_output_weights_sum 矩阵
attn_output_weights_sum = attn_output_weights.sum(dim=0).squeeze().detach().numpy()
# 使用 matplotlib 画出热力图
plt.imshow(attn_output_weights_sum, cmap='hot', interpolation='nearest')
plt.colorbar()
plt.show()
解释一下上面的代码:
- 首先调用 'attention' 函数,得到两个返回值,我们只需要第二个返回值 'attn_output_weights';
- 对 'attn_output_weights' 进行求和,得到 'attn_output_weights_sum';
- 将 'attn_output_weights_sum' 转换为 numpy 数组,并使用 'imshow' 函数画出热力图;
- 最后使用 'colorbar' 和 'show' 函数显示热力图。
需要注意的是,'attn_output_weights_sum' 的形状是 '(batch_size, seq_len, seq_len)',因此要先对第一个维度求和(即 'sum(dim=0)'),然后挤压掉第一个维度(即 'squeeze()')。另外,要将 'attn_output_weights_sum' 转换为 numpy 数组,才能用 'imshow' 函数画出热力图。
原文地址: https://www.cveoy.top/t/topic/oJ6j 著作权归作者所有。请勿转载和采集!