机器学习/pytorch笔记:time2vec

发布于:2024-06-29 ⋅ 阅读:(19) ⋅ 点赞:(0)

1 概念部分

对于给定的标量时间概念 t,Time2Vec 的表示 t2v(t)是一个大小为 k+1的向量,定义如下:

  • 其中,t2v(t)[i]是 t2v(t)的第 i 个元素,F是一个周期性激活函数,ω和 ϕ是可学习的参数。

  • 以下是个人理解:
    • t是时间序列中的一个时间点,而不是时间序列的数值。
    • 具体来说,t 代表时间序列中的一个特定时刻,例如某一天、某一小时或某一秒等。Time2Vec 的目标是将每一个时间点 t 转换为一个具有特定特征的向量表示,以便更好地捕捉时间相关的特性和模式。

2 pytorch实现

2.1 函数t2v


def t2v(tau, f, out_features, w, b, w0, b0, arg=None):
    if arg:
        v1 = f(torch.matmul(tau, w) + b, arg)
    else:
        v1 = f(torch.matmul(tau, w) + b)
    v2 = torch.matmul(tau, w0) + b0
    return torch.cat([v1, v2], 1)
  • t2v 负责将输入的时间 tau 通过两个不同的线性变换和激活函数转换成特征向量,并将这两个特征向量连接起来
    • tau 是输入的时间张量。
    • f 是激活函数(例如 torch.sin 或 torch.cos)。
    • out_features 是输出特征的维度。
    • w 和 b 是用于第一个变换的权重和偏置。
    • w0 和 b0 是用于第二个变换的权重和偏置。

2.2 SineActivation

class SineActivation(nn.Module):
    def __init__(self, in_features, out_features):
        super(SineActivation, self).__init__()
        self.out_features = out_features
        self.w0 = nn.parameter.Parameter(torch.randn(in_features, 1))
        self.b0 = nn.parameter.Parameter(torch.randn(in_features, 1))
        self.w = nn.parameter.Parameter(torch.randn(in_features, out_features - 1))
        self.b = nn.parameter.Parameter(torch.randn(in_features, out_features - 1))
        self.f = torch.sin

    def forward(self, tau):
        return t2v(tau, self.f, self.out_features, self.w, self.b, self.w0, self.b0)
  • 实现了使用正弦函数作为激活函数的时间嵌入
  • cos同理,把torch.sin换成torch.cos即可
  • 输入特征的维度(in_features)取决于提供的时间特征的数量
    • 如果你只有一个时间特征(例如,仅一天中的时间),那么输入特征的维度是 1。
    • 如果你有两个时间特征(例如,一天中的时间和一周中的某一天),那么输入特征的维度是 2。
    • 依此类推,输入特征的维度是你提供的时间特征的数量。


网站公告

今日签到

点亮在社区的每一天
去签到