学术
模块更新于 2026-11-20· 浏览 0· 下载 0

tAPE 时间绝对位置编码

把长度写进频率:将序列长度 L 与嵌入维度 d_model 一并编入频率项(按 d_model/L 缩放),低维下位置内积随距离平滑单调变化,找回距离感知、缓解各向异性

时间序列时间序列tAPE位置编码Transformer

结构图

tAPE 时间绝对位置编码结构图
tAPE 时间绝对位置编码结构图

把长度写进频率:将序列长度 L 与嵌入维度 d_model 一并编入频率项(按 d_model/L 缩放),低维下位置内积随距离平滑单调变化,找回距离感知、缓解各向异性

论文信息

  • 论文:Improving position encoding of transformers for multivariate time series classification
  • 出处:Data Mining and Knowledge Discovery (DMKD) 2024

核心痛点

自注意力对输入顺序完全不变,时序数据又不像图像、文本那样自带语义,必须显式注入位置信息;而原始绝对位置编码为语言建模设计,时序嵌入维度普遍很低(论文 32 个数据集里 28 个输入维度不足 64)。低维正弦编码因此失去"距离感知",还出现各向异性,位置信息形同虚设。

模块亮点

  • 把长度写进频率:将序列长度 L 与嵌入维度 d_model 一并编入频率项(按 d_model/L 缩放),低维下位置内积随距离平滑单调变化,找回距离感知、缓解各向异性
  • 零参数即插即用:固定正弦/余弦编码、以 buffer 注册,不新增可训练参数、不改注意力结构,加上就能用
  • 涨点有据:实验显示 tAPE 在时序分类上优于 Vanilla APE 等现有绝对位置编码;搭载它的 ConvTran(tAPE + eRPE + 卷积嵌入)在 32 个多变量时序基准上显著超过 SOTA 卷积与 Transformer 模型

适用场景

领域为多变量时间序列分类;这套编码可轻松集成进 Transformer 块,用于预测、外部回归、异常检测等下游任务,人体动作识别、ECG/EEG 信号诊断等时序场景同样适用。

插入位置建议

  • 直接替换 Transformer 输入端的标准正弦/余弦绝对位置编码,低维、变长序列收益最明显
  • 与相对位置编码(如 eRPE)叠加:tAPE 管绝对位置、eRPE 管相对距离
  • 放在时序嵌入层(线性或卷积)之后、自注意力之前

适用任务

  • 多变量时间序列分类

完整代码

tape.py
import math
import torch
import torch.nn as nn

"""
Transformer 在深度学习的许多应用中表现出了出色的性能。当应用于时间序列数据时,变压器需要有效的位置编码来捕获时间序列数据的顺序。
位置编码在时间序列分析中的功效尚未得到充分研究,并且仍然存在争议,例如,注入绝对位置编码或相对位置编码或它们的组合是否更好。为了澄清这一点,我们首先回顾一下应用于时间序列分类时现有的绝对和相对位置编码方法。
然后,我们提出了一种专用于时间序列数据的新绝对位置编码方法,称为时间绝对位置编码(tAPE)。我们的新方法将序列长度和输入嵌入维度合并到绝对位置编码中。
"""


class tAPE(nn.Module):
    r"""Inject some information about the relative or absolute position of the tokens
        in the sequence. The positional encodings have the same dimension as
        the embeddings, so that the two can be summed. Here, we use sine and cosine
        functions of different frequencies.
    .. math::
        \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model))
        \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model))
        \text{where pos is the word position and i is the embed idx)
    Args:
        d_model: the embed dim (required).
        dropout: the dropout value (default=0.1).
        max_len: the max. length of the incoming sequence (default=1024).
    """

    def __init__(self, d_model, dropout=0.1, max_len=32, scale_factor=1.0):
        super(tAPE, self).__init__()
        self.dropout = nn.Dropout(p=dropout)
        pe = torch.zeros(max_len, d_model)  # positional encoding
        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)*(d_model/max_len))
        pe[:, 1::2] = torch.cos((position * div_term)*(d_model/max_len))
        pe = scale_factor * pe.unsqueeze(0)
        self.register_buffer('pe', pe)  # this stores the variable in the state_dict (used for non-trainable variables)

    def forward(self, x):
        r"""Inputs of forward function
        Args:
            x: the sequence fed to the positional encoder model (required).
        Shape:
            x: [sequence length, batch size, embed dim]
            output: [sequence length, batch size, embed dim]
        """
        x = x + self.pe
        return self.dropout(x)

if __name__ == '__main__':
    block = tAPE(d_model=512)
    input = torch.rand(20, 32, 512) # [sequence length, batch size, embed dim]
    output = block(input)
    print(input.size())
    print(output.size())

环境与依赖

Python 3.9+

继续浏览

下一篇TFF 时序特征融合模块跨时间门控机制:双时相特征先相减得到粗变化表征,再分别与两时刻特征拼接,经深度可分离卷积、1×1 卷积 + Sigmoid 打分后加权融合,增强感兴趣变化、抑制非感兴趣变化

相关资源