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
| import torch import torch.nn as nn import numpy as np from dataclasses import dataclass
@dataclass class GazeContext: """视线-上下文交互特征""" gaze_point: np.ndarray gaze_entropy: float fixation_duration: float saccade_rate: float context_relevance: float
class GazeEncoder(nn.Module): """视线编码器""" def __init__(self, embed_dim: int = 128): super().__init__() self.gaze_embed = nn.Sequential( nn.Linear(4, 32), nn.ReLU(), nn.Linear(32, embed_dim) ) self.temporal = nn.LSTM( embed_dim, 64, num_layers=2, batch_first=True ) def forward(self, gaze_sequence): """ Args: gaze_sequence: (B, T, 4) [x, y, duration, entropy] Returns: gaze_feat: (B, 64) """ embedded = self.gaze_embed(gaze_sequence) out, _ = self.temporal(embedded) return out[:, -1]
class EgocentricVideoEncoder(nn.Module): """自我视角视频编码器""" def __init__(self, embed_dim: int = 128): super().__init__() self.cnn = nn.Sequential( nn.Conv2d(3, 16, 3, stride=2, padding=1), nn.ReLU6(), nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.ReLU6(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU6(), nn.AdaptiveAvgPool2d((4, 4)), ) self.fc = nn.Sequential( nn.Linear(64 * 4 * 4, embed_dim), nn.ReLU() ) def forward(self, frame): feat = self.cnn(frame) return self.fc(feat.flatten(1))
class CrossAttentionFusion(nn.Module): """视线-视觉上下文交叉注意力""" def __init__(self, dim: int = 64): super().__init__() self.gaze_proj = nn.Linear(dim, dim) self.video_proj = nn.Linear(128, dim) self.cross_attn = nn.MultiheadAttention( embed_dim=dim, num_heads=4, batch_first=True ) def forward(self, gaze_feat, video_feat): g = self.gaze_proj(gaze_feat).unsqueeze(1) v = self.video_proj(video_feat).unsqueeze(1) attn_out, _ = self.cross_attn(g, v, v) return attn_out.squeeze(1)
class EyeCueModel(nn.Module): """ EyeCue完整模型 架构: 1. 视线编码(时序) 2. 自我视角视频编码 3. 交叉注意力融合 4. 认知分心分类 """ def __init__(self, n_classes: int = 3): super().__init__() self.gaze_encoder = GazeEncoder() self.video_encoder = EgocentricVideoEncoder() self.fusion = CrossAttentionFusion(dim=64) self.classifier = nn.Sequential( nn.Linear(64, 32), nn.ReLU(), nn.Dropout(0.1), nn.Linear(32, n_classes) ) def forward(self, gaze_sequence, video_frame): gaze_feat = self.gaze_encoder(gaze_sequence) video_feat = self.video_encoder(video_frame) fused = self.fusion(gaze_feat, video_feat) return self.classifier(fused)
class CognitiveMetrics: """认知分心检测指标""" @staticmethod def gaze_entropy(gaze_points: np.ndarray) -> float: """ 计算视线熵 高熵=广扫描=专注 低熵=凝视固定=认知分心 """ hist, _ = np.histogram2d( gaze_points[:, 0], gaze_points[:, 1], bins=10, range=[[0, 1], [0, 1]] ) hist = hist / hist.sum() + 1e-10 return -np.sum(hist * np.log(hist)) @staticmethod def saccade_rate(gaze_points: np.ndarray, fps: float = 30) -> float: """扫视频率(次/秒)""" if len(gaze_points) < 2: return 0 diffs = np.diff(gaze_points, axis=0) distances = np.sqrt((diffs ** 2).sum(axis=1)) saccades = (distances > 0.05).sum() return saccades / (len(gaze_points) / fps) @staticmethod def fixation_ratio(gaze_points: np.ndarray, threshold: float = 0.02) -> float: """凝视比例""" if len(gaze_points) < 2: return 1.0 diffs = np.diff(gaze_points, axis=0) distances = np.sqrt((diffs ** 2).sum(axis=1)) fixations = (distances < threshold).sum() return fixations / len(distances)
if __name__ == "__main__": model = EyeCueModel(n_classes=3) gaze_seq = torch.randn(1, 30, 4) video_frame = torch.randn(1, 3, 224, 224) output = model(gaze_seq, video_frame) print("=== EyeCue认知分心检测 ===") print(f"输出: {output}") print(f"预测: {['专注', '轻度分心', '深度分心'][output.argmax(1).item()]}") metrics = CognitiveMetrics() attentive_gaze = np.random.rand(100, 2) distracted_gaze = np.random.randn(100, 2) * 0.05 + 0.5 print(f"\n=== 认知指标 ===") print(f"专注: 熵={metrics.gaze_entropy(attentive_gaze):.3f} " f"扫视={metrics.saccade_rate(attentive_gaze):.1f}/s " f"凝视={metrics.fixation_ratio(attentive_gaze):.2f}") print(f"分心: 熵={metrics.gaze_entropy(distracted_gaze):.3f} " f"扫视={metrics.saccade_rate(distracted_gaze):.1f}/s " f"凝视={metrics.fixation_ratio(distracted_gaze):.2f}") params = sum(p.numel() for p in model.parameters()) print(f"\n参数: {params:,}")
|