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
| import torch import torch.nn as nn import torch.nn.functional as F from transformers import ViTModel
class CNNBiLSTMDistractionDetector(nn.Module): """ CNN-BiLSTM 混合分心检测框架 架构: 1. CNN (MobileNetV3) 提取空间特征 2. BiLSTM 建模时序动态 3. 注意力机制聚焦关键帧 4. 知识迁移从乘用车预训练模型 适用场景:电动公交车驾驶员 """ def __init__(self, n_classes=10, hidden_dim=256, n_layers=2, pretrained=True): super().__init__() self.n_classes = n_classes self.hidden_dim = hidden_dim self.cnn = MobileNetV3Encoder(pretrained=pretrained) feat_dim = self.cnn.output_dim self.proj = nn.Sequential( nn.Linear(feat_dim, hidden_dim), nn.LayerNorm(hidden_dim), nn.GELU(), nn.Dropout(0.1) ) self.bilstm = nn.LSTM( input_size=hidden_dim, hidden_size=hidden_dim, num_layers=n_layers, batch_first=True, bidirectional=True, dropout=0.2 ) self.temporal_attention = nn.Sequential( nn.Linear(hidden_dim * 2, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, 1) ) self.classifier = nn.Sequential( nn.Linear(hidden_dim * 2, hidden_dim), nn.ReLU(), nn.Dropout(0.3), nn.Linear(hidden_dim, n_classes) ) self.kd_alpha = nn.Parameter(torch.tensor(0.5)) def forward(self, x): """ Args: x: (B, T, 3, H, W) 视频帧序列 Returns: logits: (B, n_classes) attention_weights: (B, T) 注意力权重 """ B, T, C, H, W = x.shape x = x.view(B * T, C, H, W) cnn_feat = self.cnn(x) cnn_feat = self.proj(cnn_feat) cnn_feat = cnn_feat.view(B, T, -1) lstm_out, _ = self.bilstm(cnn_feat) attn_scores = self.temporal_attention(lstm_out) attn_weights = F.softmax(attn_scores, dim=1) weighted = (lstm_out * attn_weights).sum(dim=1) logits = self.classifier(weighted) return logits, attn_weights.squeeze(-1) def knowledge_distillation_loss(self, student_logits, teacher_logits, labels, temperature=4.0): """知识蒸馏损失""" alpha = torch.sigmoid(self.kd_alpha) hard_loss = F.cross_entropy(student_logits, labels) soft_student = F.log_softmax(student_logits / temperature, dim=1) soft_teacher = F.softmax(teacher_logits / temperature, dim=1) soft_loss = F.kl_div(soft_student, soft_teacher, reduction='batchmean') * (temperature ** 2) total_loss = alpha * hard_loss + (1 - alpha) * soft_loss return total_loss, {'hard': hard_loss.item(), 'soft': soft_loss.item(), 'alpha': alpha.item()}
class MobileNetV3Encoder(nn.Module): """轻量化CNN编码器""" def __init__(self, pretrained=True): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 16, 3, stride=2, padding=1), nn.BatchNorm2d(16), nn.Hardswish(), self._make_block(16, 16, 3, 1), self._make_block(16, 24, 3, 2), self._make_block(24, 24, 3, 1), self._make_block(24, 40, 5, 2), self._make_block(40, 40, 5, 1), self._make_block(40, 80, 3, 2), self._make_block(80, 80, 3, 1), self._make_block(80, 112, 3, 1), self._make_block(112, 160, 5, 2), self._make_block(160, 160, 5, 1), nn.Conv2d(160, 576, 1), nn.BatchNorm2d(576), nn.Hardswish(), nn.AdaptiveAvgPool2d(1), ) self.output_dim = 576 def _make_block(self, in_ch, out_ch, kernel_size, stride): return nn.Sequential( nn.Conv2d(in_ch, out_ch, kernel_size, stride=stride, padding=kernel_size//2, groups=in_ch), nn.BatchNorm2d(out_ch), nn.Hardswish(), nn.Conv2d(out_ch, out_ch, 1), nn.BatchNorm2d(out_ch), nn.Hardswish(), ) def forward(self, x): return self.features(x).flatten(1)
BUS_DISTRACTION_CLASSES = { 0: 'safe_driving', 1: 'phone_call_right', 2: 'phone_call_left', 3: 'texting_right', 4: 'texting_left', 5: 'adjusting_radio', 6: 'drinking', 7: 'talking_passenger', 8: 'operating_tickets', 9: 'reaching_back', }
if __name__ == "__main__": B, T = 4, 16 model = CNNBiLSTMDistractionDetector(n_classes=10) video = torch.randn(B, T, 3, 224, 224) logits, attn = model(video) print(f"输入视频: {video.shape}") print(f"输出logits: {logits.shape}") print(f"注意力权重: {attn.shape}") print(f"参数量: {sum(p.numel() for p in model.parameters())/1e6:.2f}M") teacher_logits = torch.randn(B, 10) labels = torch.randint(0, 10, (B,)) loss, info = model.knowledge_distillation_loss(logits, teacher_logits, labels) print(f"\n知识蒸馏损失: {loss.item():.4f}") print(f" 硬标签: {info['hard']:.4f}") print(f" 软标签: {info['soft']:.4f}") print(f" alpha: {info['alpha']:.4f}")
|