Transformer 模型中的位置编码(Positional Encoding)

位置编码通常用于给输入序列中的每个位置分配一个独特的向量,以便模型能够区分不同位置的信息。将学习到的位置编码添加到输入序列中。

两个具体实现:

1. 可学习型位置编码:(位置权重参数可学习)

class LearnedPositionEncoding(nn.Embedding):
    def __init__(self, d_model, dropout=0.1, max_len=140):
        super().__init__(max_len, d_model)
        self.dropout = nn.Dropout(p=dropout)

    def forward(self, x):
        weight = self.weight.data.unsqueeze(1)
        a = weight[:x.size(0), :]
        x = x + weight[:x.size(0), :]
        return self.dropout(x)

2. 正弦函数型硬编码:

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, dropout=0.1, max_len=140):
        super(PositionalEncoding, self).__init__()
        self.dropout = nn.Dropout(p=dropout)

        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0).transpose(0, 1)
        self.register_buffer('pe', pe)

    def forward(self, x):
        x = x + self.pe[:x.size(0), :]
        return self.dropout(x)

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用PyTorch实现Transformer位置编码的示例代码: ``` import torch import torch.nn as nn import math class PositionalEncoding(nn.Module): """ Positional encoding module for Transformer """ def __init__(self, d_model, max_seq_len=200, dropout=0.1): """ Args: d_model (int): The number of expected features in the input max_seq_len (int): The maximum length of the sequence dropout (float): The probability of an element to be zeroed """ super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) # Compute the positional encodings once in log space. pe = torch.zeros(max_seq_len, d_model) position = torch.arange(0, max_seq_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): """ Args: x: The input sequence of shape (seq_len, batch_size, d_model) Returns: The sequence with positional encoding """ x = x + self.pe[:x.size(0), :] return self.dropout(x) ``` 在这段代码,我们定义了一个名为PositionalEncoding的类,该类是Transformer模型的一部分,并用于对输入序列进行位置编码。在__init__方法,我们首先计算位置编码,即将正弦和余弦函数应用于不同频率的位置。然后,我们将位置编码作为一个buffer注册到模型,以便在前向传递过程使用。 在forward方法,我们将输入序列与位置编码相加,并将结果传递给Dropout层,以便在训练过程随机丢弃一些元素。最后,我们返回具有位置编码的序列。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温柔的行子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值