【深度学习】时序数据用在Transformer的好能手-TIme2Vec-pytorch实现

该博客介绍了如何在时序问题中应用Time2Vec模型,通过修改原始代码使其适用于训练阶段。Time2Vec模型基于激活函数(如sin或cos)对时间序列进行编码,并通过全连接层进行转换。博主提供了修订后的PyTorch实现,包括模型结构和一个示例运行代码,展示如何处理批量数据。
摘要由CSDN通过智能技术生成

面对时序问题,如果我们想直接引入Transformer会很困难,还是那句话我比较着急,直接上代码,这个是我修订后的,原作者那个没有batch_size 不能直接用在训练阶段,源代码地址:https://github.com/ojus1/Time2Vec-PyTorch

class Time2Vec(nn.Module):
    def __init__(self, activation, hidden_dim):
        '''
        
        :param activation: 激活函数(非线性激活函数) sin/cos
        :param hidden_dim: 隐藏(自定义,不影响运行)
        '''
        super(Time2Vec, self).__init__()
        if activation == 'sin':
            self.activation = torch.sin
        else:
            self.activation = torch.cos
        self.out_features = hidden_dim
        self.fc1 = nn.Linear(hidden_dim, 2)
    def forward(self, x):
        # 获取x的尺寸信息
        batch_size = x.shape[0]
        sentence_len = x.shape[1]
        in_features = x.shape[2]
        # 初始化权重和偏置
        self.w0 = nn.parameter.Parameter(torch.randn(batch_size, in_features, 1))
        self.b0 = nn.parameter.Parameter(torch.randn(batch_size,sentence_len, 1))
        self.w = nn.parameter.Parameter(torch.randn(batch_size, in_features, self.out_features - 1))
        self.b = nn.parameter.Parameter(torch.randn(batch_size,sentence_len, in_features - 1))
        # 运算
        v1 = self.activation(torch.matmul(x, self.w) + self.b)
        v2 = torch.matmul(x, self.w0) + self.b0
        v3 = torch.cat([v1, v2], -1)
        x = self.fc1(v3)
        return x

举个例子

if __name__ == '__main__':
   time2vec = Time2Vec("sin", 5)
   # batch_sizex句长x特征数量
   n = torch.randn((3, 32, 5))
   m = time2vec(n)
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值