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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
| """ IDEAL框架 ========== 论文: arXiv 2609.39421 代码: github.com/WY-BCI-Club/IDEAL
输入: EEG(64ch×time) + Eye(gaze×time) 输出: 情感类别(valence/arousal)
架构: 1. 多模态特征提取器 (EEG + Eye) 2. 实例级课程扩展模块 (数据级) 3. 层次对抗对齐网络 (特征级) 4. 角度对比约束 (语义级) 5. 情感分类器 """
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from typing import Tuple, Dict
class IDEAL(nn.Module): """ IDEAL: Instance-based Domain Expansion and Adversarial Learning 多模态EEG+眼动情感识别+跨个体域适应 """ def __init__(self, config: dict = None): super().__init__() config = config or { "eeg_channels": 64, "eeg_time": 300, "gaze_dim": 4, "gaze_time": 300, "embed_dim": 128, "num_classes": 3, "num_adversarial_layers": 3, "temperature": 0.07, } self.config = config self.eeg_encoder = EEGEncoder( channels=config["eeg_channels"], time=config["eeg_time"], embed_dim=config["embed_dim"], ) self.eye_encoder = EyeEncoder( input_dim=config["gaze_dim"], time=config["gaze_time"], embed_dim=config["embed_dim"], ) self.instance_expander = InstanceCurriculumExpansion( embed_dim=config["embed_dim"] * 2, confidence_threshold=0.8, max_expansion=0.3, ) self.hierarchical_aligner = HierarchicalAdversarialAligner( embed_dim=config["embed_dim"] * 2, num_layers=config["num_adversarial_layers"], ) self.angular_contrast = AngularContrastiveLoss( temperature=config["temperature"], ) self.classifier = nn.Sequential( nn.Linear(config["embed_dim"] * 2, config["embed_dim"]), nn.ReLU(), nn.Dropout(0.3), nn.Linear(config["embed_dim"], config["num_classes"]), ) def forward( self, eeg: torch.Tensor, eye: torch.Tensor, domain: str = "source", ) -> Dict: """ Args: eeg: (B, C, T) EEG信号 eye: (B, D, T) 眼动信号 domain: "source" or "target" Returns: output: {logits, features, expanded_features, domain_pred} """ eeg_feat = self.eeg_encoder(eeg) eye_feat = self.eye_encoder(eye) features = torch.cat([eeg_feat, eye_feat], dim=-1) if domain == "target": features, expansion_info = self.instance_expander(features) else: expansion_info = None aligned_features, domain_pred = self.hierarchical_aligner(features) logits = self.classifier(aligned_features) return { "logits": logits, "features": features, "aligned_features": aligned_features, "domain_pred": domain_pred, "expansion_info": expansion_info, }
class EEGEncoder(nn.Module): """EEG特征编码器""" def __init__(self, channels, time, embed_dim): super().__init__() self.temporal_conv = nn.Conv1d(channels, channels * 2, kernel_size=25, padding=12) self.spatial_conv = nn.Conv1d(channels * 2, embed_dim, kernel_size=1) self.bn = nn.BatchNorm1d(embed_dim) self.elu = nn.ELU() self.attention = nn.MultiheadAttention(embed_dim, 4, batch_first=True) self.pool = nn.AdaptiveAvgPool1d(1) self.proj = nn.Linear(embed_dim, embed_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (B, C, T) EEG信号 Returns: features: (B, embed_dim) """ x = self.temporal_conv(x) x = self.spatial_conv(x) x = self.bn(x) x = self.elu(x) x = x.permute(0, 2, 1) attn_out, _ = self.attention(x, x, x) x = x + attn_out x = x.permute(0, 2, 1) x = self.pool(x).squeeze(-1) x = self.proj(x) return x
class EyeEncoder(nn.Module): """眼动特征编码器""" def __init__(self, input_dim, time, embed_dim): super().__init__() self.conv1 = nn.Conv1d(input_dim, 32, kernel_size=5, padding=2) self.conv2 = nn.Conv1d(32, 64, kernel_size=5, padding=2) self.conv3 = nn.Conv1d(64, embed_dim, kernel_size=3, padding=1) self.bn = nn.BatchNorm1d(embed_dim) self.lstm = nn.LSTM(embed_dim, embed_dim, batch_first=True, bidirectional=True) self.proj = nn.Linear(embed_dim * 2, embed_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (B, D, T) 眼动信号 Returns: features: (B, embed_dim) """ x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) x = self.bn(x) x = x.permute(0, 2, 1) out, _ = self.lstm(x) x = self.proj(out) x = x.mean(dim=1) return x
class InstanceCurriculumExpansion(nn.Module): """实例级课程扩展(数据级域适应)""" def __init__(self, embed_dim, confidence_threshold=0.8, max_expansion=0.3): super().__init__() self.confidence_threshold = confidence_threshold self.max_expansion = max_expansion self.confidence_net = nn.Sequential( nn.Linear(embed_dim, embed_dim // 2), nn.ReLU(), nn.Linear(embed_dim // 2, 1), nn.Sigmoid(), ) def forward(self, features: torch.Tensor) -> Tuple[torch.Tensor, Dict]: """ 课程扩展策略: 1. 预测每个target样本的置信度 2. 高置信样本加入扩展集 3. 课程式逐步增加扩展比例 Args: features: (B, embed_dim) target域特征 """ confidence = self.confidence_net(features) high_conf_mask = confidence.squeeze(-1) > self.confidence_threshold n_high = high_conf_mask.sum().item() if n_high > 0: high_conf_feat = features[high_conf_mask] noise = torch.randn_like(high_conf_feat) * 0.01 expanded = high_conf_feat + noise n_expand = int(self.max_expansion * features.shape[0]) if n_expand > 0 and n_expand <= n_high: indices = torch.randperm(n_high)[:n_expand] expanded = expanded[indices] features = torch.cat([features, expanded], dim=0) info = { "confidence_mean": confidence.mean().item(), "n_high_confidence": n_high, "expansion_ratio": min(n_high / features.shape[0], self.max_expansion), } return features, info
class HierarchicalAdversarialAligner(nn.Module): """层次对抗对齐网络""" def __init__(self, embed_dim, num_layers=3): super().__init__() self.num_layers = num_layers self.domain_discriminators = nn.ModuleList([ nn.Sequential( nn.Linear(embed_dim, embed_dim // (2 ** i)), nn.ReLU(), nn.Linear(embed_dim // (2 ** i), 1), ) for i in range(num_layers) ]) self.feature_transforms = nn.ModuleList([ nn.Linear(embed_dim, embed_dim) for _ in range(num_layers) ]) def forward(self, features: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ 渐进式层次对齐: Layer 1: 低层统计对齐 Layer 2: 中层特征对齐 Layer 3: 高层语义对齐 """ x = features domain_preds = [] for i in range(self.num_layers): x = self.feature_transforms[i](x) x = F.layer_norm(x, x.shape[-1:]) x = F.gelu(x) domain_pred = self.domain_discriminators[i](x) domain_preds.append(domain_pred) domain_pred = torch.stack(domain_preds, dim=0).mean(dim=0) return x, domain_pred
class AngularContrastiveLoss(nn.Module): """角度对比约束""" def __init__(self, temperature=0.07): super().__init__() self.temperature = temperature def forward( self, features: torch.Tensor, labels: torch.Tensor, ) -> torch.Tensor: """ 角度对比损失: - 类内紧凑: 同类样本角度小 - 类间分离: 不同类样本角度大 Args: features: (B, embed_dim) labels: (B,) 类别标签 """ feat_norm = F.normalize(features, dim=-1) sim = torch.matmul(feat_norm, feat_norm.T) / self.temperature sim = sim - sim.max(dim=-1, keepdim=True).values.detach() labels = labels.unsqueeze(0) pos_mask = (labels == labels.T).float() eye = torch.eye(features.shape[0], device=features.device) pos_mask = pos_mask - eye pos_mask = (pos_mask > 0).float() exp_sim = torch.exp(sim) * (1 - eye) log_prob = sim - torch.log(exp_sim.sum(dim=-1, keepdim=True) + 1e-8) pos_log_prob = (pos_mask * log_prob).sum(dim=-1) / (pos_mask.sum(dim=-1) + 1e-8) loss = -pos_log_prob.mean() return loss
if __name__ == "__main__": model = IDEAL() B = 16 eeg = torch.randn(B, 64, 300) eye = torch.randn(B, 4, 300) source_output = model(eeg, eye, domain="source") print("=== IDEAL框架测试 ===\n") print(f"输入: EEG {eeg.shape}, Eye {eye.shape}") print(f"\nSource域输出:") print(f" 情感类别: {source_output['logits'].shape}") print(f" 特征维度: {source_output['features'].shape}") print(f" 域预测: {source_output['domain_pred'].shape}") target_output = model(eeg, eye, domain="target") print(f"\nTarget域输出:") print(f" 扩展信息: {target_output['expansion_info']}") labels = torch.randint(0, 3, (B,)) loss = model.angular_contrast(source_output['aligned_features'], labels) print(f"\n角度对比损失: {loss.item():.4f}") total_params = sum(p.numel() for p in model.parameters()) print(f"\n总参数: {total_params:,}") print(f"大小: {total_params * 4 / 1024 / 1024:.2f} MB")
|