位置编码通常用于给输入序列中的每个位置分配一个独特的向量,以便模型能够区分不同位置的信息。将学习到的位置编码添加到输入序列中。
两个具体实现:
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)