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
| import torch import torch.nn as nn import numpy as np
class CausalDiscoveryModule(nn.Module): """ 因果发现模块 从多模态数据中学习模态间因果关系 使用注意力掩码学习因果图 """ def __init__(self, n_modalities: int = 3, embed_dim: int = 64): super().__init__() self.n_modalities = n_modalities self.causal_mask = nn.Parameter( torch.randn(n_modalities, n_modalities) * 0.1 ) self.modality_embed = nn.ModuleList([ nn.Linear(1, embed_dim) for _ in range(n_modalities) ]) def forward(self, modalities: list) -> tuple: """ Args: modalities: [eeg, eog, ecg] 每个[B, T, 1] Returns: fused: [B, embed_dim] 融合特征 causal_graph: [M, M] 因果图 """ embeddings = [] for i, m in enumerate(modalities): m_embed = self.modality_embed[i](m) m_embed = m_embed.mean(dim=1) embeddings.append(m_embed) stacked = torch.stack(embeddings, dim=1) causal_graph = torch.softmax(self.causal_mask, dim=-1) updated = torch.einsum( 'mm,bme->bme', causal_graph, stacked ) fused = updated.mean(dim=1) return fused, causal_graph
class KANFusionLayer(nn.Module): """ KAN融合层 使用Kolmogorov-Arnold Network进行跨模态融合 替代传统MLP,更少参数更高表达力 """ def __init__(self, in_dim: int, out_dim: int, grid_size: int = 5): super().__init__() self.base_linear = nn.Linear(in_dim, out_dim) self.spline_weight = nn.Parameter( torch.randn(out_dim, in_dim, grid_size + 3) * 0.1 ) h = 1.0 / grid_size grid = torch.linspace(-3*h, 1+3*h, grid_size + 7) self.register_buffer('grid', grid) def forward(self, x: torch.Tensor) -> torch.Tensor: """ KAN前向传播 output = base_linear(x) + spline(x) """ base = self.base_linear(x) x_expanded = x.unsqueeze(-1) grid = self.grid.view(1, 1, -1) b = torch.sigmoid((x_expanded - grid) * grid_size) b = b[..., :self.spline_weight.shape[-1]] spline = torch.einsum( 'big,oig->bog', b.expand(x.shape[0], -1, -1), self.spline_weight ) return base + spline
class CausalKANFatigueModel(nn.Module): """ 因果感知KAN多模态疲劳检测模型 架构: 1. 各模态特征提取(EEG/EOG/ECG) 2. 因果发现模块(学习模态间因果关系) 3. KAN融合层(因果传播后融合) 4. KAN分类器(疲劳/清醒) """ def __init__(self, n_classes: int = 3): super().__init__() self.eeg_encoder = nn.Sequential( nn.Conv1d(1, 32, 7, stride=2), nn.BatchNorm1d(32), nn.ReLU(), nn.Conv1d(32, 64, 5, stride=2), nn.BatchNorm1d(64), nn.ReLU(), nn.AdaptiveAvgPool1d(1), nn.Flatten(), ) self.eog_encoder = nn.Sequential( nn.Conv1d(1, 32, 5, stride=2), nn.BatchNorm1d(32), nn.ReLU(), nn.Conv1d(32, 64, 3, stride=2), nn.BatchNorm1d(64), nn.ReLU(), nn.AdaptiveAvgPool1d(1), nn.Flatten(), ) self.ecg_encoder = nn.Sequential( nn.Conv1d(1, 32, 15, stride=4), nn.BatchNorm1d(32), nn.ReLU(), nn.Conv1d(32, 64, 7, stride=2), nn.BatchNorm1d(64), nn.ReLU(), nn.AdaptiveAvgPool1d(1), nn.Flatten(), ) self.causal = CausalDiscoveryModule(n_modalities=3) self.kan_fusion = KANFusionLayer(64, 128, grid_size=5) self.classifier = KANFusionLayer(128, n_classes, grid_size=5) def forward(self, eeg, eog, ecg): """ Args: eeg: [B, 1, T_eeg] eog: [B, 1, T_eog] ecg: [B, 1, T_ecg] Returns: logits: [B, n_classes] causal_graph: [3, 3] """ eeg_feat = self.eeg_encoder(eeg).unsqueeze(1) eog_feat = self.eog_encoder(eog).unsqueeze(1) ecg_feat = self.ecg_encoder(ecg).unsqueeze(1) fused, causal_graph = self.causal( [eeg_feat, eog_feat, ecg_feat] ) fused = self.kan_fusion(fused) fused = torch.relu(fused) logits = self.classifier(fused) return logits, causal_graph
if __name__ == "__main__": model = CausalKANFatigueModel(n_classes=3) batch = 4 eeg = torch.randn(batch, 1, 200) eog = torch.randn(batch, 1, 200) ecg = torch.randn(batch, 1, 500) logits, causal = model(eeg, eog, ecg) print(f"输出: {logits.shape}") print(f"因果图:\n{causal.detach()}") modality_names = ['EEG', 'EOG', 'ECG'] print(f"\n因果路径强度:") for i in range(3): for j in range(3): if i != j: print(f" {modality_names[i]}→{modality_names[j]}: " f"{causal[i,j].item():.3f}") total_params = sum(p.numel() for p in model.parameters()) print(f"\n总参数: {total_params:,}")
|