30.注意力汇聚:Nadaraya-Watson 核回归

1.平均汇聚

python 复制代码
import torch
from torch import nn
from d2l import torch as d2l
#需要拟合预测的函数:
def f(x):
    return 2 * torch.sin(x) + x**0.8
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)
n_train = 50
x_train, _ = torch.sort(torch.rand(n_train) * 5)  
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)
y_hat = torch.repeat_interleave(y_train.mean(), n_test)
plot_kernel_reg(y_hat)

2.非参数注意力汇聚

python 复制代码
import torch
from torch import nn
from d2l import torch as d2l
#需要拟合预测的函数:
def f(x):
    return 2 * torch.sin(x) + x**0.8
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)
n_train = 50
x_train, _ = torch.sort(torch.rand(n_train) * 5) 
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)
#相当于做Q
X_repeat = x_test.repeat_interleave(n_train).reshape((-1, n_train))
attention_weights=nn.functional.softmax(-(X_repeat-x_train)**2/2,dim=1)
y_hat=torch.matmul(attention_weights,y_train)
plot_kernel_reg(y_hat)
python 复制代码
d2l.show_heatmaps(attention_weights.unsqueeze(0).unsqueeze(0),
                  xlabel='Sorted training inputs',
                  ylabel='Sorted testing inputs')

3.带参数注意力汇聚

python 复制代码
import torch
from torch import nn
from d2l import torch as d2l
#需要拟合预测的函数:
def f(x):
    return 2 * torch.sin(x) + x**0.8
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)
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的形状为(查询个数,"键-值"对个数)
        return torch.bmm(self.attention_weights.unsqueeze(1),
                         values.unsqueeze(-1)).reshape(-1)
    
n_train = 50
x_train, _ = torch.sort(torch.rand(n_train) * 5) 
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)

# 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)
python 复制代码
d2l.show_heatmaps(net.attention_weights.unsqueeze(0).unsqueeze(0),
                  xlabel='Sorted training inputs',
                  ylabel='Sorted testing inputs')
相关推荐
数据大魔方6 分钟前
【期货量化入门】股指期货量化入门:IF/IC/IH交易全攻略(TqSdk完整教程)
开发语言·python
sunfove15 分钟前
空间几何的基石:直角、柱、球坐标系的原理与转换详解
人工智能·python·机器学习
<-->16 分钟前
pytorch vs ray
人工智能·pytorch·python
知乎的哥廷根数学学派17 分钟前
基于多尺度特征提取和注意力自适应动态路由胶囊网络的工业轴承故障诊断算法(Pytorch)
开发语言·网络·人工智能·pytorch·python·算法·机器学习
七夜zippoe23 分钟前
缓存策略:从本地到分布式架构设计与Python实战
分布式·python·缓存·lfu·lru
曲幽24 分钟前
重构FastAPI生产部署:用异步网关与无服务器计算应对高并发
python·serverless·fastapi·web·async·httpx·await·asyncio
郝学胜-神的一滴28 分钟前
《机器学习》经典教材全景解读:周志华教授匠心之作的技术深探
数据结构·人工智能·python·程序人生·机器学习·sklearn
知乎的哥廷根数学学派28 分钟前
基于物理约束与多源知识融合的浅基础极限承载力智能预测与工程决策优化(以模拟信号为例,Pytorch)
人工智能·pytorch·python·深度学习·神经网络·机器学习
yubo050929 分钟前
【无标题】
人工智能·深度学习
费弗里32 分钟前
新组件库fi发布,轻松实现新一代声明式信息图可视化
python·数据可视化·dash