You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
2.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import torch
from torch import nn
import math
import config
class PositionalEncoding(nn.Module):
"""实现Positional Encoding功能"""
def __init__(self, d_model=config.input_dim, dropout=config.dropout, max_len=config.seq_len):
"""
位置编码器的初始化函数
:param d_model: 词向量的维度与输入序列的特征维度相同512
:param dropout: 置零比率
:param max_len: 句子最大长度,5000
"""
super(PositionalEncoding, self).__init__()
# 初始化一个nn.Dropout层设置给定的dropout比例
self.dropout = nn.Dropout(p=dropout)
# 初始化一个位置编码矩阵
# (5000,512)矩阵保持每个位置的位置编码一共5000个位置每个位置用一个512维度向量来表示其位置编码
pe = torch.zeros(max_len, d_model)
# 偶数和奇数在公式上有一个共同部分使用log函数把次方拿下来方便计算
# position表示的是字词在句子中的索引如max_len是128那么索引就是从012...,127
# 论文中d_model是5122i符号中i从0取到255那么2i对应取值就是0,2,4...510
# (5000) -> (5000,1)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
# 计算用于控制正余弦的系数确保不同频率成分在d_model维空间内均匀分布
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
# 根据位置和div_term计算正弦和余弦值分别赋值给pe的偶数列和奇数列
pe[:, 0::2] = torch.sin(position * div_term) # 从0开始到最后面补长为2其实代表的就是偶数位置
pe[:, 1::2] = torch.cos(position * div_term) # 从1开始到最后面补长为2其实代表的就是奇数位置
# 上面代码获取之后得到的pe:[max_len * d_model]
# 下面这个代码之后得到的pe形状是[1 * max_len * d_model]
# 多增加1维是为了适应batch_size
# (5000, 512) -> (1, 5000, 512)
pe = pe.unsqueeze(0)
# 将计算好的位置编码矩阵注册为模块缓冲区buffer这意味着它将成为模块的一部分并随模型保存与加载但不会被视为模型参数参与反向传播
self.register_buffer('pe', pe)
def forward(self, x):
"""
x: [seq_len, batch_size, d_model] 经过词向量的输入
"""
x = x + self.pe[:, :x.size(1)].clone().detach() # 经过词向量的输入与位置编码相加
# Dropout层会按照设定的比例随机“丢弃”置零一部分位置编码与词向量相加后的元素
# 以此引入正则化效果,防止模型过拟合
return self.dropout(x)