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
| """ EyeCue论文复现 - 完整训练脚本
论文:Driver Cognitive Distraction Detection via Gaze-Empowered Egocentric Video Understanding 作者:Yoon et al. (2026) """
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import Dataset, DataLoader import numpy as np from pathlib import Path
class CogDriveDataset(Dataset): """CogDrive认知分心数据集""" def __init__(self, data_root, split='train'): self.data_root = Path(data_root) self.split = split self.annotations = self._load_annotations() print(f"加载{split}集:{len(self.annotations)}样本") def _load_annotations(self): """加载标注文件""" annotations = [] for i in range(100 if self.split == 'train' else 20): annotations.append({ 'video_path': f'video_{i:04d}.mp4', 'gaze_path': f'gaze_{i:04d}.npy', 'label': np.random.randint(2), 'scene': np.random.choice(['urban', 'highway', 'rural']) }) return annotations def __len__(self): return len(self.annotations) def __getitem__(self, idx): ann = self.annotations[idx] video = torch.randn(30, 3, 224, 224) gaze = torch.randn(30, 6) label = ann['label'] return { 'video': video, 'gaze': gaze, 'label': torch.tensor(label, dtype=torch.long), 'scene': ann['scene'] }
def train_epoch(model, dataloader, optimizer, criterion, device): """训练一个epoch""" model.train() total_loss = 0 correct = 0 total = 0 for batch in dataloader: video = batch['video'].to(device) gaze = batch['gaze'].to(device) labels = batch['label'].to(device) optimizer.zero_grad() logits = model(video, gaze) loss = criterion(logits, labels) loss.backward() optimizer.step() total_loss += loss.item() _, predicted = logits.max(1) total += labels.size(0) correct += predicted.eq(labels).sum().item() return total_loss / len(dataloader), correct / total
def validate(model, dataloader, criterion, device): """验证""" model.eval() total_loss = 0 correct = 0 total = 0 scene_correct = {} scene_total = {} with torch.no_grad(): for batch in dataloader: video = batch['video'].to(device) gaze = batch['gaze'].to(device) labels = batch['label'].to(device) scenes = batch['scene'] logits = model(video, gaze) loss = criterion(logits, labels) total_loss += loss.item() _, predicted = logits.max(1) total += labels.size(0) correct += predicted.eq(labels).sum().item() for i, scene in enumerate(scenes): if scene not in scene_correct: scene_correct[scene] = 0 scene_total[scene] = 0 scene_total[scene] += 1 if predicted[i] == labels[i]: scene_correct[scene] += 1 scene_acc = {k: scene_correct[k]/scene_total[k] for k in scene_total} return total_loss / len(dataloader), correct / total, scene_acc
if __name__ == "__main__": device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"使用设备: {device}") train_dataset = CogDriveDataset('./data/cogdrive', split='train') val_dataset = CogDriveDataset('./data/cogdrive', split='val') train_loader = DataLoader(train_dataset, batch_size=4, shuffle=True) val_loader = DataLoader(val_dataset, batch_size=4, shuffle=False) model = EyeCue().to(device) criterion = nn.CrossEntropyLoss() optimizer = optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.01) num_epochs = 50 best_acc = 0 for epoch in range(num_epochs): train_loss, train_acc = train_epoch(model, train_loader, optimizer, criterion, device) val_loss, val_acc, scene_acc = validate(model, val_loader, criterion, device) print(f"\nEpoch {epoch+1}/{num_epochs}") print(f"Train Loss: {train_loss:.4f}, Acc: {train_acc:.4f}") print(f"Val Loss: {val_loss:.4f}, Acc: {val_acc:.4f}") print(f"Scene Acc: {scene_acc}") if val_acc > best_acc: best_acc = val_acc torch.save(model.state_dict(), 'eyecue_best.pth') print(f"保存最佳模型,准确率: {best_acc:.4f}") print(f"\n训练完成!最佳准确率: {best_acc:.4f}")
|