5.1.注意力机制

注意力机制

​ "随意"就是随着自己意愿去做一些事,比如有一系列白色的东西,有一个红色的杯子在里面,非常引人注目,那么你的视线看向他,就是不随意线索,因为这不是你主观去看的,只是杯子很显眼。而如果你想读书了,你就在这些东西里面找到书,将注意力放在不那么显眼的书上,这就是随意线索。

​ 卷积、全连接、池化层都只考虑不随意线索,注意力机制则显示的考虑随意线索:

  • 随意线索被称之为查询(query)
  • 每个输入是一个值(value)和不随意线索(key)的对
  • 通过注意力池化层来有偏向性的选择某些输入

在这里插入图片描述

1.非参注意力池化层

​ 给定数据 ( x i , y i ) , i = 1 , ⋯   , n (x_i,y_i),i=1,\cdots,n (xi,yi),i=1,,n,平均池化是最简单的方案: f ( x ) = 1 n ∑ i y i f(x)=\frac 1n \sum_i y_i f(x)=n1iyi

​ 更好的方案是60年代提出来的Nadaraya-Watson核回归
f ( x ) = ∑ j = 1 n K ( x − x i ) ∑ j = 1 n K ( x − x j ) y i f(x) =\sum ^n_{j=1} \frac{K(x-x_i)}{\sum^n_{j=1}K(x-x_j)}y_i f(x)=j=1nj=1nK(xxj)K(xxi)yi
​ 其中 f ( x ) f(x) f(x)是查询(query), x j x_j xj是不随意线索(key), y i y_i yi是值(value),K是一个衡量 x x x x i x_i xi的距离的一个函数。一除就得到了类似概率的东西,再和 y i y_i yi相乘求和,离 x i x_i xi越近,权重越大。

​ 使用高斯核 K ( u ) = 1 2 π e x p ( − u 2 2 ) K(u) =\frac 1{\sqrt{2\pi}} exp(-\frac{u^2}2) K(u)=2π 1exp(2u2),那么有:
f ( x ) = ∑ j = 1 n e x p ( − 1 2 ( x − x i ) 2 ∑ j = 1 n e x p ( − 1 2 ( x − x j ) 2 ) y i = ∑ i = 1 n s o f t m a x ( − 1 2 ( x − x i ) 2 ) y i f(x) =\sum ^n_{j=1} \frac{exp(-\frac 12(x-x_i)^2}{\sum^n_{j=1}exp(-\frac 12(x-x_j)^2)}y_i\\ =\sum ^n_{i=1} softmax(-\frac 12(x-x_i)^2)y_i f(x)=j=1nj=1nexp(21(xxj)2)exp(21(xxi)2yi=i=1nsoftmax(21(xxi)2)yi
​ 在此基础上引入可以学习的 w w w,就是参数化的注意力机制:
f ( x ) = ∑ i = 1 n s o f t m a x ( − 1 2 ( ( x − x i ) w ) 2 ) y i f(x)=\sum ^n_{i=1} softmax(-\frac 12((x-x_i)w)^2)y_i f(x)=i=1nsoftmax(21((xxi)w)2)yi
​ 注意力机制中,通过query(随意线索)和key(不随意线索)来对输入进行有偏向性的选择,可以一般的写作 f ( x ) = ∑ i α ( x , x i ) y i f(x)= \sum_i \alpha(x,x_i)y_i f(x)=iα(x,xi)yi ,这里的 α ( x , x i ) \alpha (x,x_i) α(x,xi)是注意力权重。

2.代码实现Nadaraya-Watson核回归

简单的实现一下:给定的成对的输入-输出数据集 { ( x 1 , y 1 ) , ⋯   , ( x n , y n ) } \{(x_1,y_1),\cdots,(x_n,y_n)\} {(x1,y1),,(xn,yn)},如何学习 f f f来预测任意输入 x x x的输出 y ^ = f ( x ) \hat{y}=f(x) y^=f(x).

​ 先生成人工数据集,加入噪声项为 ϵ \epsilon ϵ:
y i = 2 s i n ( x i ) + x i 0.8 + ϵ y_i = 2sin(x_i)+x_i^{0.8}+\epsilon yi=2sin(xi)+xi0.8+ϵ
​ 其中 ϵ \epsilon ϵ服从均值为0,标准差为0.5的正态分布。

import torch
from torch import nn
from d2l import torch as d2l

n_train = 50  # 训练样本数
x_train, _ = torch.sort(torch.rand(n_train) * 5)   # 排序后的训练样本

def f(x):
    return 2 * torch.sin(x) + x**0.8

y_train = f(x_train) + torch.normal(0.0, 0.5, (n_train,))  # 训练样本的输出
x_test = torch.arange(0, 5, 0.1)  # 测试样本
y_truth = f(x_test)  # 测试样本的真实输出
n_test = len(x_test)  # 测试样本数
n_test

# 绘制训练样本(用源泉表示),不带噪声项的真实数据生成函数(标记为“Truth”), 以及学习得到的预测函数(标记为“Pred”)。
def plot_kernel_reg(y_hat):
    d2l.plot(x_test, [y_truth, y_hat], 'x', 'y', legend=['Truth', 'Pred'],
             xlim=[0, 5], ylim=[-1, 5])
    d2l.plt.plot(x_train, y_train, 'o', alpha=0.5);
    d2l.plt.show()
  
# 平均汇聚,就算一下平均值
y_hat = torch.repeat_interleave(y_train.mean(), n_test)
plot_kernel_reg(y_hat)


'''非参数注意力池化'''
# X_repeat的形状:(n_test,n_train),
# 每一行都包含着相同的测试输入(例如:同样的查询)
X_repeat = x_test.repeat_interleave(n_train).reshape((-1, n_train))
# x_train包含着键。attention_weights的形状:(n_test,n_train),
# 每一行都包含着要在给定的每个查询的值(y_train)之间分配的注意力权重
attention_weights = nn.functional.softmax(-(X_repeat - x_train)**2 / 2, dim=1)
# y_hat的每个元素都是值的加权平均值,其中的权重是注意力权重
y_hat = torch.matmul(attention_weights, y_train)
plot_kernel_reg(y_hat)

'''看一下注意哪些值'''
d2l.show_heatmaps(attention_weights.unsqueeze(0).unsqueeze(0),
                  xlabel='Sorted training inputs',
                  ylabel='Sorted testing inputs')



'''带参数的注意力池化'''

X = torch.ones((2, 1, 4))
Y = torch.ones((2, 4, 6))
torch.bmm(X, Y).shape 
# bmm批量矩阵乘法:例如X有两个(1,4)矩阵,Y有两个(4,6)矩阵,则第一个和第一个相乘,第二个和第二个相乘,结果的批量也是2,形状为(2,1,6)


weights = torch.ones((2, 10)) * 0.1
values = torch.arange(20.0).reshape((2, 10))
torch.bmm(weights.unsqueeze(1), values.unsqueeze(-1))

'''定义模型'''
class NWKernelRegression(nn.Module):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.w = nn.Parameter(torch.rand((1,), requires_grad=True))

    def forward(self, queries, keys, values):
        # queries和attention_weights的形状为(查询个数,“键-值”对个数)
        queries = queries.repeat_interleave(keys.shape[1]).reshape((-1, keys.shape[1]))
        self.attention_weights = nn.functional.softmax(
            -((queries - keys) * self.w)**2 / 2, dim=1)
        # values的形状为(查询个数,“键-值”对个数),多乘一个可学习的w
        return torch.bmm(self.attention_weights.unsqueeze(1),
                         values.unsqueeze(-1)).reshape(-1)


'''训练'''

# X_tile的形状:(n_train,n_train),每一行都包含着相同的训练输入
X_tile = x_train.repeat((n_train, 1))
# Y_tile的形状:(n_train,n_train),每一行都包含着相同的训练输出
Y_tile = y_train.repeat((n_train, 1))
# keys的形状:('n_train','n_train'-1)
keys = X_tile[(1 - torch.eye(n_train)).type(torch.bool)].reshape((n_train, -1))
# values的形状:('n_train','n_train'-1)
values = Y_tile[(1 - torch.eye(n_train)).type(torch.bool)].reshape((n_train, -1))

net = NWKernelRegression()
loss = nn.MSELoss(reduction='none')
trainer = torch.optim.SGD(net.parameters(), lr=0.5)
animator = d2l.Animator(xlabel='epoch', ylabel='loss', xlim=[1, 5])

for epoch in range(5):
    trainer.zero_grad()
    l = loss(net(x_train, keys, values), y_train)
    l.sum().backward()
    trainer.step()
    print(f'epoch {epoch + 1}, loss {float(l.sum()):.6f}')
    animator.add(epoch + 1, float(l.sum()))


# keys的形状:(n_test,n_train),每一行包含着相同的训练输入(例如,相同的键)
keys = x_train.repeat((n_test, 1))
# value的形状:(n_test,n_train)
values = y_train.repeat((n_test, 1))
y_hat = net(x_test, keys, values).unsqueeze(1).detach()
plot_kernel_reg(y_hat)

d2l.show_heatmaps(net.attention_weights.unsqueeze(0).unsqueeze(0),
                  xlabel='Sorted training inputs',
                  ylabel='Sorted testing inputs')
d2l.ply.show()

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

​ 分别为非参数化注意力池化,和参数化注意力池化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值