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
| import torch import torch.nn as nn import torch.nn.functional as F import numpy as np
class EyeMovementAnnotator: """ 眼动辅助标注器 论文方法实现:用双眼视差自动标注EEG的专注/分心状态 输入:双眼眼动数据(注视点坐标) 输出:专注/分心标签 + 时间戳 """ def __init__(self, disparity_threshold=None): self.disparity_threshold = disparity_threshold def annotate(self, left_gaze, right_gaze, gaze_events): """ Args: left_gaze: (T, 2) 左眼注视点序列 right_gaze: (T, 2) 右眼注视点序列 gaze_events: (T,) 注视事件标签(fixation/saccade/blink) Returns: labels: (T,) 0=分心, 1=专注 """ disparity = np.linalg.norm(left_gaze - right_gaze, axis=1) if self.disparity_threshold is None: threshold = np.mean(disparity) + np.std(disparity) else: threshold = self.disparity_threshold base_labels = (disparity < threshold).astype(int) labels = np.where( (base_labels == 1) & (gaze_events == 'fixation'), 1, 0 ) return labels, disparity
class EEGFocusTransformer(nn.Module): """ EEG专注状态识别Transformer 论文核心模型:62通道EEG → 5频段DE特征 → Transformer分类 输入:62通道EEG信号 输出:专注/分心二分类 性能:被试内90.16%,跨被试87.65% """ def __init__(self, num_channels=62, num_bands=5, feat_dim=256, num_heads=8, num_layers=4): super().__init__() self.band_proj = nn.Linear(num_channels * num_bands, feat_dim) self.pos_enc = PositionalEncoding(d_model=feat_dim, max_len=1000) encoder_layer = nn.TransformerEncoderLayer( d_model=feat_dim, nhead=num_heads, dim_feedforward=feat_dim * 4, dropout=0.1, activation='gelu', batch_first=True ) self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) self.classifier = nn.Sequential( nn.Linear(feat_dim, feat_dim // 2), nn.GELU(), nn.Dropout(0.1), nn.Linear(feat_dim // 2, 2) ) def forward(self, eeg_de_features): """ Args: eeg_de_features: (B, T, 62*5) 各通道各频段微分熵 Returns: logits: (B, T, 2) 专注/分心分类 """ x = self.band_proj(eeg_de_features) x = self.pos_enc(x) x = self.transformer(x) logits = self.classifier(x) return logits
class PositionalEncoding(nn.Module): """正弦位置编码""" def __init__(self, d_model, max_len=1000): super().__init__() pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len).unsqueeze(1).float() div_term = torch.exp( torch.arange(0, d_model, 2).float() * (-np.log(10000.0) / d_model) ) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) self.register_buffer('pe', pe.unsqueeze(0)) def forward(self, x): return x + self.pe[:, :x.size(1)]
class FocusRecognitionPipeline: """ 完整的专注状态识别管道 1. 眼动标注 → 2. EEG特征提取 → 3. Transformer分类 """ def __init__(self): self.annotator = EyeMovementAnnotator() self.transformer = EEGFocusTransformer() def extract_de_features(self, eeg_signal, fs=200, window_sec=2): """ 提取各频段微分熵(DE)特征 频段: delta: 1-4 Hz theta: 4-8 Hz alpha: 8-14 Hz beta: 14-31 Hz gamma: 31-50 Hz """ bands = [(1, 4), (4, 8), (8, 14), (14, 31), (31, 50)] window_samples = int(fs * window_sec) num_channels = eeg_signal.shape[1] fft_vals = np.fft.fft(eeg_signal, axis=0) freqs = np.fft.fftfreq(eeg_signal.shape[0], 1/fs) de_features = [] for low, high in bands: band_mask = (freqs >= low) & (freqs <= high) band_power = np.sum(np.abs(fft_vals[band_mask])**2, axis=0) de = 0.5 * np.log2(2 * np.pi * np.e * band_power + 1e-8) de_features.append(de) return np.concatenate(de_features)
if __name__ == "__main__": annotator = EyeMovementAnnotator() np.random.seed(42) left = np.random.randn(1000, 2) * 5 + 100 right = left + np.random.randn(1000, 2) * 2 events = np.random.choice(['fixation', 'saccade', 'blink'], 1000, p=[0.6, 0.3, 0.1]) labels, disparity = annotator.annotate(left, right, events) print(f"眼动标注: {np.sum(labels)}/1000 帧为专注状态 ({np.mean(labels)*100:.1f}%)") model = EEGFocusTransformer() x = torch.randn(4, 100, 310) logits = model(x) print(f"EEG输入: {x.shape}") print(f"分类输出: {logits.shape}") print(f"参数量: {sum(p.numel() for p in model.parameters()):,}")
|