TFT 模型由 Temporal Fusion Transformer (TFT) 和 Gated Residual Network (GRN) 两部分组成。其中,GRN 用于对时间序列数据进行特征提取。

GRN 的输入是经过 Embedding 和 Positional Encoding 处理后的时序数据。Embedding 将离散的时间步转换为连续的向量表示,Positional Encoding 则用于表示时间步之间的顺序关系。GRN 的输出是经过一系列卷积、门控线性单元 (Gated Linear Unit, GLU) 和残差连接得到的特征向量。

以下是 TFT 模型中 GRN 部分的 Pytorch 代码实现:

class GatedResidualNetwork(nn.Module):
    def __init__(self, input_size, hidden_size, output_size, dropout_rate):
        super(GatedResidualNetwork, self).__init__()
        self.conv1 = nn.Conv1d(input_size, hidden_size, kernel_size=2, stride=1, padding=1)
        self.conv2 = nn.Conv1d(hidden_size, hidden_size, kernel_size=2, stride=1, padding=1)
        self.conv3 = nn.Conv1d(hidden_size, hidden_size, kernel_size=2, stride=1, padding=1)
        self.gate1 = nn.GLU(dim=1)
        self.gate2 = nn.GLU(dim=1)
        self.dropout = nn.Dropout(dropout_rate)
        self.residual = nn.Linear(input_size, hidden_size)
        self.output_layer = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        # x shape: (batch_size, seq_len, input_size)
        residual = self.residual(x)
        # residual shape: (batch_size, seq_len, hidden_size)
        x = self.conv1(x.transpose(1, 2)).transpose(1, 2)
        # x shape: (batch_size, seq_len, hidden_size)
        x = self.gate1(x)
        # x shape: (batch_size, seq_len, hidden_size)
        x = self.dropout(x)
        x = self.conv2(x.transpose(1, 2)).transpose(1, 2)
        # x shape: (batch_size, seq_len, hidden_size)
        x = self.gate2(x)
        # x shape: (batch_size, seq_len, hidden_size)
        x = self.dropout(x)
        x = self.conv3(x.transpose(1, 2)).transpose(1, 2)
        # x shape: (batch_size, seq_len, hidden_size)
        x = self.dropout(x)
        x = self.output_layer(x)
        # x shape: (batch_size, seq_len, output_size)
        return x + residual

在这个代码中,GRN 的输入 x 是一个 (batch_size, seq_len, input_size) 的张量,其中 batch_size 表示批次大小,seq_len 表示时间序列的长度,input_size 表示每个时间步的特征数。GRN 的输出是一个 (batch_size, seq_len, output_size) 的张量,其中 output_size 表示每个时间步的输出特征数。

在 GRN 的实现中,首先通过一个线性层 (residual) 将输入 x 转换为与输出相同维度的特征向量,然后经过三个卷积层 (conv1, conv2 和 conv3) 和两个门控线性单元 (gate1 和 gate2) 的处理,最后再通过一个线性层 (output_layer) 得到输出。在每个卷积层和门控线性单元后都添加了 dropout 层,以提高模型的泛化能力。残差连接 (residual) 用于保留输入的信息,避免信息丢失。

TFT 模型中的 Gated Residual Network (GRN) 详解及 Pytorch 代码

原文地址: https://www.cveoy.top/t/topic/lRpC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录