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
| import torch import torch.nn as nn import torch.nn.functional as F
class BidirectionalDelta(nn.Module): """ 双向Delta模块 将一阶时序差分分解为正向(激活)和负向(抑制)两个分量, 显式建模驾驶疲劳过程中神经活动的非对称动态。 论文Section 3.1: Bidirectional Delta Module Args: channels: EEG通道数 temp_size: 时间步数 """ def __init__(self, channels: int, temp_size: int): super().__init__() self.channels = channels self.temp_size = temp_size self.pos_conv = nn.Conv2d(channels, channels, kernel_size=(1, 3), padding=(0, 1), groups=channels) self.neg_conv = nn.Conv2d(channels, channels, kernel_size=(1, 3), padding=(0, 1), groups=channels) self.gate = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(channels * 2, channels), nn.Sigmoid() ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: EEG信号, shape=(B, C, 1, T) Returns: 双向Delta特征, shape=(B, C, 1, T) """ batch_size = x.size(0) delta = x[:, :, :, 1:] - x[:, :, :, :-1] delta = F.pad(delta, (1, 0), mode='constant', value=0) pos_delta = F.relu(delta) neg_delta = F.relu(-delta) pos_feat = self.pos_conv(pos_delta) neg_feat = self.neg_conv(neg_delta) gate_input = torch.cat([ pos_feat.mean(dim=(2, 3)), neg_feat.mean(dim=(2, 3)) ], dim=1) gate_weight = self.gate(gate_input).view(batch_size, self.channels, 1, 1) output = gate_weight * pos_feat + (1 - gate_weight) * neg_feat return output + delta
class GatedTemporalConv(nn.Module): """ 门控时序卷积模块 使用深度可分离卷积捕获每个EEG通道的长期时序依赖, 通过门控机制选择性传递信息。 论文Section 3.2: Gated Temporal Convolution Module Args: channels: 通道数 kernel_size: 卷积核大小 dropout: dropout率 """ def __init__(self, channels: int, kernel_size: int = 3, dropout: float = 0.2): super().__init__() padding = (kernel_size - 1) // 2 self.depthwise_conv = nn.Conv2d( channels, channels, kernel_size=(1, kernel_size), padding=(0, padding), groups=channels ) self.pointwise_conv = nn.Conv2d(channels, channels, kernel_size=1) self.gate_conv = nn.Conv2d( channels, channels, kernel_size=(1, kernel_size), padding=(0, padding), groups=channels ) self.bn1 = nn.BatchNorm2d(channels) self.bn2 = nn.BatchNorm2d(channels) self.dropout = nn.Dropout(dropout) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: shape=(B, C, 1, T) Returns: shape=(B, C, 1, T) """ out = self.depthwise_conv(x) out = self.bn1(out) out = F.elu(out) out = self.pointwise_conv(out) out = self.bn2(out) gate = torch.sigmoid(self.gate_conv(x)) out = out * gate out = self.dropout(out) return out + x
class DeltaGateNet(nn.Module): """ DeltaGateNet: 双向时序动态建模框架 论文: Bidirectional Temporal Dynamics Modeling for EEG-based Driving Fatigue Recognition arXiv: 2602.14071 架构: [Input] → [BiDelta] → [GatedTCN] × N → [GAP] → [FC] → [Output] Args: channels: EEG通道数 (SEED-VIG: 17, SADT: 30) temp_size: 时间步数 num_blocks: GatedTCN块数 num_classes: 分类数 (2: 疲劳/清醒) """ def __init__(self, channels: int = 17, temp_size: int = 1200, num_blocks: int = 3, num_classes: int = 2): super().__init__() self.bi_delta = BidirectionalDelta(channels, temp_size) self.tcn_blocks = nn.ModuleList([ GatedTemporalConv(channels, kernel_size=3, dropout=0.2) for _ in range(num_blocks) ]) self.gap = nn.AdaptiveAvgPool2d(1) self.classifier = nn.Sequential( nn.Flatten(), nn.Linear(channels, 64), nn.ReLU(), nn.Dropout(0.3), nn.Linear(64, num_classes) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: EEG信号, shape=(B, C, 1, T) Returns: logits: shape=(B, num_classes) """ x = self.bi_delta(x) for block in self.tcn_blocks: x = block(x) x = self.gap(x) x = self.classifier(x) return x
if __name__ == "__main__": import numpy as np from sklearn.metrics import accuracy_score, f1_score BATCH_SIZE = 32 CHANNELS = 17 TEMP_SIZE = 1200 NUM_CLASSES = 2 model = DeltaGateNet( channels=CHANNELS, temp_size=TEMP_SIZE, num_blocks=3, num_classes=NUM_CLASSES ) total_params = sum(p.numel() for p in model.parameters()) print(f"DeltaGateNet参数量: {total_params:,}") np.random.seed(42) eeg_normal = torch.randn(BATCH_SIZE, CHANNELS, 1, TEMP_SIZE) * 0.5 t = np.linspace(0, 10, TEMP_SIZE) fatigue_pattern = np.sin(2 * np.pi * 2 * t) * 0.8 eeg_fatigue = torch.tensor( fatigue_pattern + np.random.randn(BATCH_SIZE, CHANNELS, 1, TEMP_SIZE) * 0.3, dtype=torch.float32 ) print("\n--- 正常状态EEG ---") out_normal = model(eeg_normal) pred_normal = torch.argmax(out_normal, dim=1) print(f"输入shape: {eeg_normal.shape}") print(f"输出shape: {out_normal.shape}") print(f"预测: 清醒={torch.sum(pred_normal==0)}, 疲劳={torch.sum(pred_normal==1)}") print("\n--- 疲劳状态EEG ---") out_fatigue = model(eeg_fatigue) pred_fatigue = torch.argmax(out_fatigue, dim=1) print(f"输入shape: {eeg_fatigue.shape}") print(f"输出shape: {out_fatigue.shape}") print(f"预测: 清醒={torch.sum(pred_fatigue==0)}, 疲劳={torch.sum(pred_fatigue==1)}") print("\n--- 训练流程 ---") criterion = nn.CrossEntropyLoss() optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=100) x_mix = torch.cat([eeg_normal, eeg_fatigue], dim=0) y_mix = torch.cat([ torch.zeros(BATCH_SIZE, dtype=torch.long), torch.ones(BATCH_SIZE, dtype=torch.long) ]) model.train() for epoch in range(5): optimizer.zero_grad() logits = model(x_mix) loss = criterion(logits, y_mix) loss.backward() optimizer.step() scheduler.step() acc = accuracy_score(y_mix.numpy(), torch.argmax(logits, dim=1).detach().numpy()) print(f"Epoch {epoch+1}: Loss={loss.item():.4f}, Acc={acc:.2%}") model.eval() import time with torch.no_grad(): start = time.time() for _ in range(100): _ = model(eeg_normal[:1]) elapsed = (time.time() - start) / 100 print(f"\n单样本推理延迟: {elapsed*1000:.1f}ms") print(f"理论帧率: {1/elapsed:.0f} FPS")
|