File size: 10,467 Bytes
3621f16 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | """
Benchmark模型集合
包含: LSTM, GRU, Transformer, MLP
用于与DMMV模型进行对比
"""
import torch
import torch.nn as nn
import math
class LSTMPredictor(nn.Module):
"""
LSTM时序预测模型
标准的Long Short-Term Memory网络
"""
def __init__(self, input_dim=5, hidden_dim=128, num_layers=2, pred_len=20, dropout=0.1):
super().__init__()
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.pred_len = pred_len
self.lstm = nn.LSTM(
input_size=input_dim,
hidden_size=hidden_dim,
num_layers=num_layers,
batch_first=True,
dropout=dropout if num_layers > 1 else 0
)
self.fc = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, pred_len)
)
def forward(self, x):
"""
x: [B, seq_len, input_dim] → [B, pred_len]
"""
# LSTM编码
lstm_out, (h_n, c_n) = self.lstm(x) # [B, seq_len, hidden_dim]
# 取最后一个时间步的隐藏状态
last_hidden = lstm_out[:, -1, :] # [B, hidden_dim]
# 预测
pred = self.fc(last_hidden) # [B, pred_len]
return pred
class GRUPredictor(nn.Module):
"""
GRU时序预测模型
门控循环单元,比LSTM更简单
"""
def __init__(self, input_dim=5, hidden_dim=128, num_layers=2, pred_len=20, dropout=0.1):
super().__init__()
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.pred_len = pred_len
self.gru = nn.GRU(
input_size=input_dim,
hidden_size=hidden_dim,
num_layers=num_layers,
batch_first=True,
dropout=dropout if num_layers > 1 else 0
)
self.fc = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, pred_len)
)
def forward(self, x):
"""
x: [B, seq_len, input_dim] → [B, pred_len]
"""
gru_out, h_n = self.gru(x) # [B, seq_len, hidden_dim]
last_hidden = gru_out[:, -1, :] # [B, hidden_dim]
pred = self.fc(last_hidden) # [B, pred_len]
return pred
class PositionalEncoding(nn.Module):
"""Transformer的位置编码"""
def __init__(self, d_model, max_len=5000, dropout=0.1):
super().__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
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)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0) # [1, max_len, d_model]
self.register_buffer('pe', pe)
def forward(self, x):
x = x + self.pe[:, :x.size(1), :]
return self.dropout(x)
class TransformerPredictor(nn.Module):
"""
Transformer时序预测模型
使用自注意力机制捕捉长距离依赖
"""
def __init__(self, input_dim=5, d_model=128, nhead=8, num_layers=2,
dim_feedforward=256, pred_len=20, dropout=0.1, seq_len=96):
super().__init__()
self.d_model = d_model
self.pred_len = pred_len
# 输入嵌入
self.embed = nn.Linear(input_dim, d_model)
self.pos_encoder = PositionalEncoding(d_model, max_len=seq_len+pred_len, dropout=dropout)
# Transformer编码器
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model,
nhead=nhead,
dim_feedforward=dim_feedforward,
dropout=dropout,
batch_first=True
)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
# 预测头
self.fc = nn.Sequential(
nn.Linear(d_model * seq_len, d_model),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(d_model, pred_len)
)
self.seq_len = seq_len
def forward(self, x):
"""
x: [B, seq_len, input_dim] → [B, pred_len]
"""
B = x.size(0)
# 嵌入 + 位置编码
x = self.embed(x) # [B, seq_len, d_model]
x = self.pos_encoder(x)
# Transformer编码
x = self.transformer(x) # [B, seq_len, d_model]
# 展平并预测
x = x.reshape(B, -1) # [B, seq_len * d_model]
pred = self.fc(x) # [B, pred_len]
return pred
class MLPPredictor(nn.Module):
"""
MLP时序预测模型
简单的多层感知机,将时序展平后预测
"""
def __init__(self, seq_len=96, input_dim=5, hidden_dim=256, pred_len=20, dropout=0.1):
super().__init__()
self.seq_len = seq_len
self.input_dim = input_dim
self.pred_len = pred_len
input_size = seq_len * input_dim
self.fc = nn.Sequential(
nn.Linear(input_size, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, hidden_dim // 2),
nn.ReLU(),
nn.Linear(hidden_dim // 2, pred_len)
)
def forward(self, x):
"""
x: [B, seq_len, input_dim] → [B, pred_len]
"""
B = x.size(0)
x = x.reshape(B, -1) # [B, seq_len * input_dim]
pred = self.fc(x) # [B, pred_len]
return pred
class TCNBlock(nn.Module):
"""TCN基本块:因果膨胀卷积"""
def __init__(self, in_channels, out_channels, kernel_size, dilation, dropout=0.1):
super().__init__()
padding = (kernel_size - 1) * dilation
self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size,
padding=padding, dilation=dilation)
self.chomp1 = Chomp1d(padding)
self.relu1 = nn.ReLU()
self.dropout1 = nn.Dropout(dropout)
self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size,
padding=padding, dilation=dilation)
self.chomp2 = Chomp1d(padding)
self.relu2 = nn.ReLU()
self.dropout2 = nn.Dropout(dropout)
self.net = nn.Sequential(
self.conv1, self.chomp1, self.relu1, self.dropout1,
self.conv2, self.chomp2, self.relu2, self.dropout2
)
self.downsample = nn.Conv1d(in_channels, out_channels, 1) if in_channels != out_channels else None
self.relu = nn.ReLU()
def forward(self, x):
out = self.net(x)
res = x if self.downsample is None else self.downsample(x)
return self.relu(out + res)
class Chomp1d(nn.Module):
"""裁剪因果卷积的填充"""
def __init__(self, chomp_size):
super().__init__()
self.chomp_size = chomp_size
def forward(self, x):
return x[:, :, :-self.chomp_size].contiguous()
class TCNPredictor(nn.Module):
"""
TCN时序预测模型
时序卷积网络,使用因果膨胀卷积
"""
def __init__(self, input_dim=5, num_channels=[64, 128, 128],
kernel_size=3, pred_len=20, dropout=0.1, seq_len=96):
super().__init__()
self.pred_len = pred_len
layers = []
num_levels = len(num_channels)
for i in range(num_levels):
dilation = 2 ** i
in_ch = input_dim if i == 0 else num_channels[i-1]
out_ch = num_channels[i]
layers.append(TCNBlock(in_ch, out_ch, kernel_size, dilation, dropout))
self.tcn = nn.Sequential(*layers)
self.fc = nn.Sequential(
nn.Linear(num_channels[-1] * seq_len, 256),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(256, pred_len)
)
self.seq_len = seq_len
def forward(self, x):
"""
x: [B, seq_len, input_dim] → [B, pred_len]
"""
B = x.size(0)
x = x.transpose(1, 2) # [B, input_dim, seq_len]
x = self.tcn(x) # [B, num_channels[-1], seq_len]
x = x.reshape(B, -1) # [B, num_channels[-1] * seq_len]
pred = self.fc(x) # [B, pred_len]
return pred
def get_benchmark_model(model_name, **kwargs):
"""
获取Benchmark模型
Args:
model_name: 模型名称 (lstm, gru, transformer, mlp, tcn)
**kwargs: 模型参数
Returns:
模型实例
"""
models = {
'lstm': LSTMPredictor,
'gru': GRUPredictor,
'transformer': TransformerPredictor,
'mlp': MLPPredictor,
'tcn': TCNPredictor,
}
if model_name.lower() not in models:
raise ValueError(f"Unknown model: {model_name}. Available: {list(models.keys())}")
model_class = models[model_name.lower()]
# 过滤参数:只传递模型接受的参数
import inspect
sig = inspect.signature(model_class.__init__)
valid_params = set(sig.parameters.keys()) - {'self'}
filtered_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
return model_class(**filtered_kwargs)
# 测试代码
if __name__ == '__main__':
print("=" * 60)
print("Benchmark模型测试")
print("=" * 60)
batch_size = 4
seq_len = 96
input_dim = 5
pred_len = 20
x = torch.randn(batch_size, seq_len, input_dim)
models = ['lstm', 'gru', 'transformer', 'mlp', 'tcn']
for name in models:
print(f"\n测试 {name.upper()}...")
model = get_benchmark_model(name, seq_len=seq_len, pred_len=pred_len)
# 计算参数量
params = sum(p.numel() for p in model.parameters())
# 前向传播
with torch.no_grad():
output = model(x)
print(f" 输入: {x.shape}")
print(f" 输出: {output.shape}")
print(f" 参数量: {params:,}")
print("\n✅ 所有模型测试通过")
|