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
| import torch import torch.nn as nn import torch.nn.functional as F
class MultimodalFatigueDetector(nn.Module): """ 多模态被动疲劳检测器 论文: Applied Sciences 2026, 16, 9049 输入: 眼动特征 + ECG心电特征 输出: 疲劳等级(清醒/轻度疲劳/严重疲劳) 核心创新: 1. 眼动特征: 注视模式+眨眼+瞳孔直径 2. ECG特征: HRV心率变异性+频域分析 3. 跨模态注意力: 自动调整两种模态权重 """ def __init__(self, eye_feat_dim=128, ecg_feat_dim=128, hidden_dim=256, num_classes=3): super().__init__() self.eye_encoder = EyeMovementEncoder(feat_dim=eye_feat_dim) self.ecg_encoder = ECGEncoder(feat_dim=ecg_feat_dim) self.cross_attn = CrossModalAttention( eye_dim=eye_feat_dim, ecg_dim=ecg_feat_dim, hidden_dim=hidden_dim ) self.classifier = nn.Sequential( nn.Linear(hidden_dim, hidden_dim // 2), nn.GELU(), nn.Dropout(0.3), nn.Linear(hidden_dim // 2, num_classes) ) def forward(self, eye_data, ecg_data): """ Args: eye_data: dict with 'gaze', 'blink', 'pupil' tensors ecg_data: (B, T) ECG信号序列 Returns: logits: (B, num_classes) 疲劳等级 attn_weights: 跨模态注意力权重 """ eye_feat = self.eye_encoder(eye_data) ecg_feat = self.ecg_encoder(ecg_data) fused, attn_weights = self.cross_attn(eye_feat, ecg_feat) logits = self.classifier(fused) return logits, attn_weights
class EyeMovementEncoder(nn.Module): """眼动特征编码器""" def __init__(self, feat_dim=128): super().__init__() self.gaze_encoder = nn.LSTM( input_size=2, hidden_size=64, num_layers=2, batch_first=True, bidirectional=True ) self.blink_encoder = nn.Sequential( nn.Linear(5, 32), nn.GELU(), nn.Linear(32, 32) ) self.pupil_encoder = nn.Sequential( nn.Linear(3, 32), nn.GELU(), nn.Linear(32, 32) ) self.fusion = nn.Sequential( nn.Linear(128 + 32 + 32, feat_dim), nn.GELU(), nn.Linear(feat_dim, feat_dim) ) def forward(self, eye_data): gaze = eye_data['gaze'] blink = eye_data['blink'] pupil = eye_data['pupil'] gaze_out, _ = self.gaze_encoder(gaze) gaze_feat = gaze_out[:, -1, :] blink_feat = self.blink_encoder(blink) pupil_feat = self.pupil_encoder(pupil) combined = torch.cat([gaze_feat, blink_feat, pupil_feat], dim=-1) return self.fusion(combined)
class ECGEncoder(nn.Module): """ECG心电特征编码器""" def __init__(self, feat_dim=128, signal_len=500): super().__init__() self.conv = nn.Sequential( nn.Conv1d(1, 32, kernel_size=7, stride=2, padding=3), nn.BatchNorm1d(32), nn.ReLU(), nn.MaxPool1d(2), nn.Conv1d(32, 64, kernel_size=5, stride=2, padding=2), nn.BatchNorm1d(64), nn.ReLU(), nn.MaxPool1d(2), nn.Conv1d(64, 128, kernel_size=3, stride=1, padding=1), nn.BatchNorm1d(128), nn.ReLU(), nn.AdaptiveAvgPool1d(1) ) self.hrv_encoder = nn.Sequential( nn.Linear(6, 32), nn.GELU(), nn.Linear(32, 32) ) self.fusion = nn.Sequential( nn.Linear(128 + 32, feat_dim), nn.GELU(), nn.Linear(feat_dim, feat_dim) ) def forward(self, ecg_signal): """ Args: ecg_signal: (B, T) ECG信号 """ x = ecg_signal.unsqueeze(1) wave_feat = self.conv(x).squeeze(-1) hrv_feat = torch.randn(ecg_signal.shape[0], 6) hrv_encoded = self.hrv_encoder(hrv_feat) combined = torch.cat([wave_feat, hrv_encoded], dim=-1) return self.fusion(combined)
class CrossModalAttention(nn.Module): """跨模态注意力融合""" def __init__(self, eye_dim, ecg_dim, hidden_dim): super().__init__() self.eye_proj = nn.Linear(eye_dim, hidden_dim) self.ecg_proj = nn.Linear(ecg_dim, hidden_dim) self.eye_to_ecg_attn = nn.MultiheadAttention(hidden_dim, num_heads=4, batch_first=True) self.ecg_to_eye_attn = nn.MultiheadAttention(hidden_dim, num_heads=4, batch_first=True) self.gate = nn.Sequential( nn.Linear(hidden_dim * 2, hidden_dim), nn.Sigmoid() ) self.output_proj = nn.Linear(hidden_dim * 2, hidden_dim) def forward(self, eye_feat, ecg_feat): eye = self.eye_proj(eye_feat).unsqueeze(1) ecg = self.ecg_proj(ecg_feat).unsqueeze(1) eye_attended, _ = self.eye_to_ecg_attn(eye, ecg, ecg) ecg_attended, _ = self.ecg_to_eye_attn(ecg, eye, eye) combined = torch.cat([eye_attended.squeeze(1), ecg_attended.squeeze(1)], dim=-1) gate_weight = self.gate(combined) fused = self.output_proj(combined * gate_weight) attn_weights = torch.stack([ gate_weight.mean(dim=-1), (1 - gate_weight).mean(dim=-1) ], dim=-1) return fused, attn_weights
if __name__ == "__main__": model = MultimodalFatigueDetector() batch = 4 eye_data = { 'gaze': torch.randn(batch, 300, 2), 'blink': torch.randn(batch, 5), 'pupil': torch.randn(batch, 3) } ecg_signal = torch.randn(batch, 500) logits, attn = model(eye_data, ecg_signal) print(f"Eye gaze: {eye_data['gaze'].shape}") print(f"ECG signal: {ecg_signal.shape}") print(f"Fatigue logits: {logits.shape}") print(f"Attention [eye, ecg]: {attn.shape}") print(f"Parameters: {sum(p.numel() for p in model.parameters()):,}")
|