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
| import numpy as np import torch import torch.nn as nn from typing import Dict, Tuple
class EEGIntentionDetector(nn.Module): """ EEG 驾驶意图检测器 基于 arXiv 2026 论文方法: - 原始 EEG 信号输入(无需预处理) - 深度学习自动提取特征 - 三分类:左转/右转/直行 硬件配置: | 组件 | 型号 | 参数 | 佩戴方式 | |------|------|------|----------| | EEG 头带 | Bitbrain Diadem | 16ch, 500Hz | 头带 | | 干电极 | g.Sahara | Ag/AgCl 干电极 | 头皮接触 | | 处理器 | 车载 GPU | 20W | 中控 | | 延迟 | 端到端 | <50ms | - | 电极位置(10-20 系统): - 运动区:C3, Cz, C4(转向想象主要来源) - 前额:F3, Fz, F4(执行控制) - 顶叶:P3, Pz, P4(空间注意) """ def __init__(self, num_channels: int = 16, num_classes: int = 3, sample_rate: int = 500, window_sec: float = 1.0): super().__init__() self.num_channels = num_channels self.sample_rate = sample_rate self.window_samples = int(window_sec * sample_rate) self.spatial_conv = nn.Sequential( nn.Conv2d(1, 32, kernel_size=(num_channels, 1)), nn.BatchNorm2d(32), nn.ReLU(), ) self.temporal_conv = nn.Sequential( nn.Conv2d(32, 64, kernel_size=(1, 25), padding=(0, 12)), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d((1, 5)), nn.Conv2d(64, 128, kernel_size=(1, 10), padding=(0, 5)), nn.BatchNorm2d(128), nn.ReLU(), nn.MaxPool2d((1, 3)), ) feat_size = 128 * (self.window_samples // 15) self.classifier = nn.Sequential( nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(128, 64), nn.ReLU(), nn.Dropout(0.5), nn.Linear(64, num_classes) ) def forward(self, eeg: torch.Tensor) -> Dict[str, torch.Tensor]: """ Args: eeg: (B, num_channels, window_samples) 原始 EEG Returns: output: { logits: (B, 3) 分类 logits, confidence: (B,) 最大概率, prediction: (B,) 预测类别 } """ x = eeg.unsqueeze(1) x = self.spatial_conv(x) x = self.temporal_conv(x) logits = self.classifier(x) probs = torch.softmax(logits, dim=-1) confidence, prediction = probs.max(dim=-1) return { "logits": logits, "confidence": confidence, "prediction": prediction, "probabilities": probs, }
if __name__ == "__main__": detector = EEGIntentionDetector( num_channels=16, num_classes=3, sample_rate=500, window_sec=1.0 ) eeg = torch.randn(4, 16, 500) with torch.no_grad(): result = detector(eeg) print("=== EEG 意图检测 ===") classes = ["left_turn", "right_turn", "straight"] for i, cls in enumerate(classes): print(f" {cls}: {result['probabilities'][0, i]:.4f}") print(f"预测: {classes[result['prediction'][0]]}") print(f"置信度: {result['confidence'][0]:.4f}") print(f"\n参数量: {sum(p.numel() for p in detector.parameters()):,}")
|