注意力的可视化

1. 注意力热力图

mport torch
from d2l import torch as d2l
import matplotlib.pyplot as plt


def show_heatmaps(matrics, xlabel, ylabel, titles=None, figsize=(2.5, 2.5),
				  cmap="Reds"):
	"""
	
	:param matrics: 输入的矩阵值;例matrics.shape=(1,1,10,10)
	:param xlabel: 设置x轴的标签
	:param ylabel: 设置y轴的标签
	:param titles: 设置表头
	:param figsize: 设置图片的大小
	:param cmap: 设置热力图的颜色
	:return: 
	"""
	# 设置图片的显示格式为'svg'
	d2l.use_svg_display()
	# 根据输入矩阵获取行数和列数
	num_rows, num_cols = matrics.shape[0], matrics.shape[1]
	# 设置画布fig和画布区域axes
	fig, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize,
								 sharex=True, sharey=True, squeeze=False)
	# 得到axes,和数据matrix
	for i, (row_axes, row_matrix) in enumerate(zip(axes, matrics)):
		for j, (ax, matrix) in enumerate(zip(row_axes, row_matrix)):
			# 将matrix的值传入到坐标系中
			pcm = ax.imshow(matrix.detach().numpy(), cmap=cmap)
			# 设置x轴的标签
			if i == num_rows - 1:
				ax.set_xlabel(xlabel)
			# 设置y轴的标签
			if j == 0:
				ax.set_ylabel(ylabel)
			# 设置表格的抬头
			if titles:
				ax.set_title(titles[j])
	# 给画布添加新的渐变跳
	fig.colorbar(pcm, ax=axes, shrink=0.6)

# 设置注意力权重值,torch.eye表示的对角线值为1,其他位置值为0
attention_weights = torch.eye(10).reshape((1, 1, 10, 10))
show_heatmaps(attention_weights, xlabel="keys", ylabel="queries", titles=['fuckyou'])
plt.show()

在这里插入图片描述

2. 平均汇聚

平均汇聚就是求得训练值的均值
f ( x ) = 1 n ∑ i = 1 n y i f(x)=\frac{1}{n}\sum_{i=1}^{n}y_i f(x)=n1i=1nyi

# 1.导入相关数据库
import torch
from d2l import torch as d2l
import matplotlib.pyplot as plt

# 2.随机生成数据,随机生成数值并排序
n_train = 50
x_train, _ = torch.sort(torch.rand(n_train) * 5)


# 3.定义函数
def f(x):
	return 2 * torch.sin(x) + x ** 0.8


# 4.生成x轴值
x_test = torch.arange(0, 5, 0.1)

# 5.生成y_train,y_truth
y_train = f(x_train) + torch.normal(0, 0.5, (n_train,))
y_truth = f(x_test)


# 6.画图
def plot_kernel_reg(y_hat):
	# 画曲线图
	d2l.plot(x_test, [y_truth, y_hat], xlabel='x', ylabel='y', legend=['truth', 'preds'],
			 xlim=[0, 5], ylim=[-1, 5])
	# 画点图
	plt.plot(x_train, y_train, 'o', alpha=0.5)

# 7.求得均值,并复制相关值
y_hat = torch.repeat_interleave(y_train.mean(), n_train)
plot_kernel_reg(y_hat)
plt.show()

在这里插入图片描述

  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
在PyTorch中,我们可以使用TensorBoard来可视化注意力图。以下是一些步骤: 1. 安装TensorBoard ```python pip install tensorboard ``` 2. 添加注释 在模型中,添加一个函数来生成注意力图,并将其作为注释添加到TensorBoard中。例如: ```python import torch from torch.utils.tensorboard import SummaryWriter # 定义一个简单的注意力模型 class AttentionModel(torch.nn.Module): def __init__(self): super(AttentionModel, self).__init__() self.linear = torch.nn.Linear(10, 10) self.attention = torch.nn.Linear(10, 1) def forward(self, x): h = self.linear(x) a = torch.softmax(self.attention(h), dim=1) c = torch.sum(a * h, dim=1) return c, a # 生成注意力图并将其添加到TensorBoard中 def visualize_attention(model, writer, inputs): model.eval() with torch.no_grad(): outputs, attention = model(inputs) attention = attention.squeeze(1) for i in range(inputs.size(0)): input_seq = inputs[i].tolist() attention_weights = attention[i].tolist() writer.add_attention("Attention/AttentionMap", torch.Tensor([attention_weights]), torch.Tensor([input_seq]), global_step=i) ``` 在这个例子中,我们定义了一个简单的注意力模型,并在`visualize_attention()`函数中生成注意力图。注意力图是一个热力图,其中每个单元格的颜色代表模型注重哪些输入。 3. 启动TensorBoard 在您的终端中运行以下命令以启动TensorBoard: ```python tensorboard --logdir=<path_to_your_tensorboard_logs> ``` 其中`<path_to_your_tensorboard_logs>`是您保存TensorBoard日志的路径。 4. 查看注意力图 在您的浏览器中输入`localhost:6006`,然后单击“Attention/AttentionMap”选项卡即可查看注意力图。您可以通过单击“Step”滑块来查看每个输入的注意力图。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值