用于attention可视化的一个效果

# encoding=utf-8

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# 中文显示
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 模拟数据及数据的注意力计算结果
tokens = ["[CLS]", "我", "爱", "北", "京", "天安门", "[SEP]"]
n = len(tokens)
a = np.random.rand(n, n) * 0.3
a[0, :] = 0.8
a[2, 3:5] = 0.9        # “爱” → “北京”
a[5, 5] = 0.95
a += np.eye(n) * 0.4
a = np.clip(a, 0, 1)

# 绘图
fig, ax = plt.subplots(figsize=(7, 6))
sns.heatmap(a, cmap="Reds", square=True, cbar=True,
            xticklabels=tokens, yticklabels=tokens,
            annot=True, fmt=".2f", annot_kws={"size": 9}, ax=ax)

# 标题
ax.set_title("Attention Map模拟:我爱北京天安门", fontsize=14, pad=30)

# X/Y 轴标签
ax.set_xlabel("X 轴 → Key:表示当前词正在看的词",
              fontsize=11, labelpad=10, color='darkblue')
ax.set_ylabel("Y 轴 → Query:表示正在进行关注的词",
              fontsize=11, labelpad=10, color='darkred')

# 旋转标签
plt.xticks(rotation=0, ha='center')
plt.yticks(rotation=0)

plt.tight_layout()
plt.show()