import torch
import torch.nn as nn
import torch.nn.functional as F
#用于特定通道数
class my_Layernorm(nn.Module):
"""
Special designed layernorm for the seasonal part
"""
#构造函数,创建了一个layerNorm层,用于数据输入
def __init__(self, channels):
super(my_Layernorm, self).__init__()
self.layernorm = nn.LayerNorm(channels)
#先对输入x进行标准化
def forward(self, x):
x_hat = self.layernorm(x)
#计算标准化后的数据均值,作为偏差项,并从标准化数据中减去这个偏差,以达到某种特殊的规范化效果
bias = torch.mean(x_hat, dim=1).unsqueeze(1).repeat(1, x.shape[1], 1)
return x_hat - bias
#滑动平均模块,用于平滑时间序列数据并突出其趋势
class moving_avg(nn.Module):
"""
Moving average block to highlight the trend of time series
"""
#构造函数,初始化并创建一个一维平均池化层(AvgPool1d),其核大小和步幅由参数定义
def __init__(self, kernel_size, stride):
super(moving_avg, self).__init__()
self.kernel_size = kernel_size
self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=stride, padding=0)
def forward(self, x):
# padding on the both ends of time series
#对序列的两端进行填充,
front = x[:, 0:1, :].repeat(1, (self.kernel_size - 1) // 2, 1)
end = x[:, -1:, :].repeat(1, (self.kernel_size - 1) // 2, 1)
#使用应用平均池化,并将数据维度调整回其原始排列,这样就完成了滑动平均
x = torch.cat([front, x, end], dim=1)
x = self.avg(x.permute(0, 2, 1))
x = x.permute(0, 2, 1)#一维和二维数据互换
return x
#时间序列分解
class series_decomp(nn.Module):
"""
Series decomposition block
"""
#构造函数,初始化创建一个滑动平均模块
def __init__(self, kernel_size):
super(series_decomp, self).__init__()
self.moving_avg = moving_avg(kernel_size, stride=1)
#利用滑动平均模块计算时间序列的移动均值(即趋势成分),从原始数据中减去这个趋势成分,返回剩余部分(可能包含季节性的随机成分)和趋势成分
def forward(self, x):
moving_mean = self.moving_avg(x)
res = x - moving_mean
return res, moving_mean
#多重时间序列分解
class series_decomp_multi(nn.Module):
"""
Multiple Series decomposition block from FEDformer
"""
def __init__(self, kernel_size):
super(series_decomp_multi, self).__init__()
self.kernel_size = kernel_size
#用于多个不同大小的核
self.series_decomp = [series_decomp(kernel) for kernel in kernel_size]
#
def forward(self, x):
moving_mean = []
res = []
#遍历每个分解函数
for func in self.series_decomp:
sea, moving_avg = func(x)
moving_mean.append(moving_avg)
res.append(sea)
#对于每个分解函数得到的季节性成分和趋势成分进行平均,已获得一个综合的结果
sea = sum(res) / len(res)
moving_mean = sum(moving_mean) / len(moving_mean)
return sea, moving_mean
#定义一个包含注意力机制、卷积和时间序列的编码器层
class EncoderLayer(nn.Module):
"""
Autoformer encoder layer with the progressive decomposition architecture
"""
#attention: 注意力机制模块,负责计算输入序列中元素之间的关系。
#d_model: 表示输入序列的特征维度。
#d_ff: 前馈网络中间层的维度,默认为 d_model 的四倍。
#moving_avg: 在序列分解中使用的移动平均窗口大小。
#dropout: 用于正则化的dropout比率。
#activation: 使用的激活函数类型,可以是ReLU或GELU。
def __init__(self, attention, d_model, d_ff=None, moving_avg=25, dropout=0.1, activation="relu"):
super(EncoderLayer, self).__init__()
d_ff = d_ff or 4 * d_model #d_model:输入序列的特征维度 d_ff:前馈网络中间层的维度,默认为d_model的四倍
self.attention = attention #注意力机制模块,负责计算输入序列中元素之间的关系
self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=1, bias=False) #一维卷积层,用于处理序列数据
self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_model, kernel_size=1, bias=False) #一维卷积层,用于处理序列数据
self.decomp1 = series_decomp(moving_avg) #创建序列分解模块,用于将序列中的趋势和季节性成分分开
self.decomp2 = series_decomp(moving_avg) #创建序列分解模块,用于将序列中的趋势和季节性成分分开
self.dropout = nn.Dropout(dropout) #定义一个dropout层,用于训练期间丢弃一些特征,以减少过拟合
self.activation = F.relu if activation == "relu" else F.gelu #设置激活函数,根据提供的参数选择F.relu或者F.gelu
def forward(self, x, attn_mask=None):
new_x, attn = self.attention(
x, x, x,
attn_mask=attn_mask
)
x = x + self.dropout(new_x)
x, _ = self.decomp1(x)
y = x
y = self.dropout(self.activation(self.conv1(y.transpose(-1, 1))))
y = self.dropout(self.conv2(y).transpose(-1, 1))
res, _ = self.decomp2(x + y)
return res, attn
#编码器层的集合,按顺序应用这些层来处理输入数据
class Encoder(nn.Module):
"""
Autoformer encoder
"""
#构造函数,创建一个模块列表,包含所有的注意力层和可选的卷积层、可选的归一化层
def __init__(self, attn_layers, conv_layers=None, norm_layer=None):
super(Encoder, self).__init__()
self.attn_layers = nn.ModuleList(attn_layers)
self.conv_layers = nn.ModuleList(conv_layers) if conv_layers is not None else None
self.norm = norm_layer
def forward(self, x, attn_mask=None):
attns = []
if self.conv_layers is not None:
#对每对注意力层和卷积层进行迭代处理
for attn_layer, conv_layer in zip(self.attn_layers, self.conv_layers):
x, attn = attn_layer(x, attn_mask=attn_mask)
x = conv_layer(x)
attns.append(attn)
x, attn = self.attn_layers[-1](x)
attns.append(attn)
else:
for attn_layer in self.attn_layers:
x, attn = attn_layer(x, attn_mask=attn_mask)
attns.append(attn)
#如果定义了归一化层,增在输出之前对最终的的特征进行归一化
if self.norm is not None:
x = self.norm(x)
return x, attns
#定义一个包含注意力、交叉注意力、卷积和时间序列分解的解码器层
class DecoderLayer(nn.Module):
"""
Autoformer decoder layer with the progressive decomposition architecture
"""
#attention: 注意力机制模块,负责计算输入序列中元素之间的关系。
#d_model: 表示输入序列的特征维度。
#c_out:输出
#d_ff: 前馈网络中间层的维度,默认为 d_model 的四倍。
#moving_avg: 在序列分解中使用的移动平均窗口大小。
#dropout: 用于正则化的dropout比率。
#activation: 使用的激活函数类型,可以是ReLU或GELU。
def __init__(self, self_attention, cross_attention, d_model, c_out, d_ff=None,
moving_avg=25, dropout=0.1, activation="relu"):
super(DecoderLayer, self).__init__()
d_ff = d_ff or 4 * d_model #d_model:输入序列的特征维度 d_ff:前馈网络中间层的维度,默认为d_model的四倍
self.self_attention = self_attention #注意力机制模块,负责计算输入序列中元素之间的关系
self.cross_attention = cross_attention
self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=1, bias=False) #一维卷积层,用于处理序列数据
self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_model, kernel_size=1, bias=False) #一维卷积层,用于处理序列数据
self.decomp1 = series_decomp(moving_avg) #创建序列分解模块,用于将序列中的趋势和季节性成分分开
self.decomp2 = series_decomp(moving_avg) #创建序列分解模块,用于将序列中的趋势和季节性成分分开
self.decomp3 = series_decomp(moving_avg) #创建序列分解模块,用于将序列中的趋势和季节性成分分开
self.dropout = nn.Dropout(dropout) #定义一个dropout层,用于训练期间丢弃一些特征,以减少过拟合
self.projection = nn.Conv1d(in_channels=d_model, out_channels=c_out, kernel_size=3, stride=1, padding=1,
padding_mode='circular', bias=False) #一维卷积层,用于从解码器层输出的特征中生成最终的预测结果
self.activation = F.relu if activation == "relu" else F.gelu #设置激活函数,根据提供的参数选择F.relu或者F.gelu
def forward(self, x, cross, x_mask=None, cross_mask=None):
x = x + self.dropout(self.self_attention(
x, x, x,
attn_mask=x_mask
)[0])
x, trend1 = self.decomp1(x)
x = x + self.dropout(self.cross_attention(
x, cross, cross,
attn_mask=cross_mask
)[0])
x, trend2 = self.decomp2(x)
y = x
y = self.dropout(self.activation(self.conv1(y.transpose(-1, 1))))
y = self.dropout(self.conv2(y).transpose(-1, 1))
x, trend3 = self.decomp3(x + y)
residual_trend = trend1 + trend2 + trend3 #计算得到的三个趋势分量的和,以便输出中保留这些信息
residual_trend = self.projection(residual_trend.permute(0, 2, 1)).transpose(1, 2)
return x, residual_trend
#解码器层的集合,与编码器类似,按顺序应用这些层来处理输入并生成输出
class Decoder(nn.Module):
"""
Autoformer encoder
"""
def __init__(self, layers, norm_layer=None, projection=None):
super(Decoder, self).__init__()
self.layers = nn.ModuleList(layers)
self.norm = norm_layer
self.projection = projection
#实现数据的前向传播流程
def forward(self, x, cross, x_mask=None, cross_mask=None, trend=None):
for layer in self.layers:
x, residual_trend = layer(x, cross, x_mask=x_mask, cross_mask=cross_mask)
trend = trend + residual_trend
if self.norm is not None:
x = self.norm(x)
if self.projection is not None:
x = self.projection(x)
return x, trend