nn.TransformerEncoderLayer
用于定义编码器中的一个层,它由多个子层组成,包括自注意力机制(self-attention)、前馈神经网络和残差连接(residual connection)等。
以下是 nn.TransformerEncoderLayer
类的主要参数和功能:
- d_model (int) – the number of expected features in the input (required) 输入特征的维度大小
-
nhead(int) – the number of heads in the multiheadattention models (required). 自注意力机制中注意力头的数量,每个头对应一个不同的权重。
-
dim_feedforward(int) – the dimension of the feedforward network model (default=2048). 前馈神经网络中隐藏层的维度。
-
dropout (float) – the dropout value (default=0.1).用于控制模型的过拟合程度的 dropout 比例。
下面是一个示例使用 nn.TransformerEncoderLayer
创建编码器层的简单代码:
import torch
import torch.nn as nn
# 定义一个 Transformer 编码器层
encoder_layer= nn.TransformerEncoderLayer(d_model=512, nhead=8, dim_feedforward=2048)
# 创建输入张量
src = torch.rand((10, 32, 512)) # 输入序列的形状:(sequence length, batch size, feature size)
# 执行编码器层的正向传播计算
output = encoder_layer(src)
print(output.shape) # 输出编码后的特征张量的形状
打印结果:torch.Size([10,32,512])