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
| """ EF-SCConv-CapsGCN: EEG-fNIRS Spatial-Channel Convolution + Capsule GCN
论文核心模型复现 参考:Expert Systems with Applications, 2026 """
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from typing import Tuple
class SCConv(nn.Module): """ Spatial-Channel Convolution (SCConv) 同时提取空间维(脑区位置)和通道维(特征类型)的特征 - 空间维:脑电极位置的空间关系 - 通道维:不同频段的功率特征 """ def __init__(self, in_channels: int, out_channels: int, n_eeg_channels: int = 32, n_fnirs_channels: int = 16): super().__init__() self.spatial_conv = nn.Conv2d( in_channels, out_channels, kernel_size=(n_eeg_channels + n_fnirs_channels, 1), stride=1, padding=(0, 0) ) self.channel_conv = nn.Conv2d( out_channels, out_channels, kernel_size=(1, 3), stride=1, padding=(0, 1), groups=out_channels ) self.bn = nn.BatchNorm2d(out_channels) self.act = nn.GELU() def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (B, C, T) where C = EEG_ch + fNIRS_ch, T = time_steps Returns: out: (B, out_C, 1, T) """ x = x.unsqueeze(2) x = self.spatial_conv(x) x = self.channel_conv(x) x = self.bn(x) x = self.act(x) return x.squeeze(2)
class CapsuleGCN(nn.Module): """ Capsule Graph Convolutional Network 将脑区视为图节点,用图卷积建模脑区间功能连接 胶囊网络替代传统 FC 层,保留空间层次关系 """ def __init__(self, n_features: int, n_regions: int = 7, n_classes: int = 3, capsule_dim: int = 16): super().__init__() self.n_regions = n_regions self.capsule_dim = capsule_dim self.register_buffer( 'adj_matrix', self._create_brain_region_adjacency(n_regions) ) self.gc1 = nn.Linear(n_features, 64) self.gc2 = nn.Linear(64, capsule_dim) self.routing_iterations = 3 self.W_route = nn.Parameter( torch.randn(n_regions, capsule_dim, capsule_dim) * 0.01 ) self.classifier = nn.Linear(n_regions * capsule_dim, n_classes) def _create_brain_region_adjacency(self, n: int) -> torch.Tensor: """创建脑区邻接矩阵""" adj = torch.zeros(n, n) regions = ['frontal', 'central', 'parietal', 'occipital', 'temporal_l', 'temporal_r', 'motor'] adj[0, [1, 5, 6, 4]] = 1 adj[1, [0, 2, 6]] = 1 adj[2, [1, 3]] = 1 adj[3, [2]] = 1 adj[4, [0]] = 1 adj[5, [0]] = 1 adj[6, [0, 1]] = 1 adj = (adj + adj.T).clamp(max=1) adj.fill_diagonal_(1) degree = adj.sum(dim=1, keepdim=True) adj_norm = adj / (degree + 1e-8) return adj_norm def graph_conv(self, x: torch.Tensor) -> torch.Tensor: """图卷积""" x = torch.matmul(self.adj_matrix, x) return x def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: x: (B, n_regions, n_features) Returns: logits: (B, n_classes) capsules: (B, n_regions, capsule_dim) """ B, N, F_in = x.shape h = self.graph_conv(x) h = F.gelu(self.gc1(h)) h = self.graph_conv(h) h = F.gelu(self.gc2(h)) capsules = self._dynamic_routing(h) flat = capsules.view(B, -1) logits = self.classifier(flat) return logits, capsules def _dynamic_routing(self, h: torch.Tensor) -> torch.Tensor: """动态路由算法(简化版)""" B, N, D = h.shape b = torch.zeros(B, N, N, device=h.device) for i in range(self.routing_iterations): c = F.softmax(b, dim=2) s = torch.einsum('bij,jkl->bikl', c, self.W_route) s = s.sum(dim=1) v = self._squash(s) if i < self.routing_iterations - 1: b = b + torch.einsum('bik,bjk->bij', v, h) return v @staticmethod def _squash(s: torch.Tensor) -> torch.Tensor: """Squash 激活函数""" sq = torch.norm(s, dim=-1, keepdim=True) return s * sq / (1 + sq**2)
class EFSCConvCapsGCN(nn.Module): """ 完整的 EF-SCConv-CapsGCN 模型 输入:EEG (B, 32, T) + fNIRS (B, 16, T) 输出:警觉等级 (B, 3) [清醒, 轻度疲劳, 重度疲劳] """ def __init__(self, n_eeg: int = 32, n_fnirs: int = 16, n_classes: int = 3, n_brain_regions: int = 7): super().__init__() self.eeg_scconv = SCConv(1, 32, n_eeg_channels=n_eeg) self.eeg_pool = nn.AdaptiveAvgPool1d(1) self.fnirs_scconv = SCConv(1, 16, n_eeg_channels=n_fnirs) self.fnirs_pool = nn.AdaptiveAvgPool1d(1) self.fusion = nn.Linear(32 + 16, n_brain_regions * 32) self.caps_gcn = CapsuleGCN( n_features=32, n_regions=n_brain_regions, n_classes=n_classes, capsule_dim=16 ) def forward(self, eeg: torch.Tensor, fnirs: torch.Tensor): """ Args: eeg: (B, 32, T) fnirs: (B, 16, T) """ eeg_feat = self.eeg_scconv(eeg.unsqueeze(1)) eeg_feat = self.eeg_pool(eeg_feat).squeeze(-1) fnirs_feat = self.fnirs_scconv(fnirs.unsqueeze(1)) fnirs_feat = self.fnirs_pool(fnirs_feat).squeeze(-1) fused = torch.cat([eeg_feat, fnirs_feat], dim=1) region_feat = self.fusion(fused) region_feat = region_feat.view(-1, 7, 32) logits, capsules = self.caps_gcn(region_feat) return logits, capsules
if __name__ == "__main__": model = EFSCConvCapsGCN(n_eeg=32, n_fnirs=16, n_classes=3) eeg = torch.randn(4, 32, 100) fnirs = torch.randn(4, 16, 100) logits, capsules = model(eeg, fnirs) print(f"Logits shape: {logits.shape}") print(f"Capsules shape: {capsules.shape}") print(f"Prediction: {torch.argmax(logits, dim=-1)}") print(f"Total params: {sum(p.numel() for p in model.parameters()):,}")
|