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 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
| import torch import torch.nn as nn import torch.nn.functional as F
class CGSMModule(nn.Module): """ 跨粒度状态映射模块(CGSM) 将细粒度(头部/手部)与粗粒度(躯干/全局)特征 通过跨注意力对齐,实现多尺度行为判别 """ def __init__(self, fine_dim: int = 128, coarse_dim: int = 256, fusion_dim: int = 256, num_heads: int = 4): super().__init__() self.fine_encoder = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=1, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.fine_proj = nn.Linear(128, fine_dim) self.coarse_encoder = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(128, 256, 3, stride=2, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.AdaptiveAvgPool2d(1) ) self.coarse_proj = nn.Linear(256, coarse_dim) self.cross_attn = nn.MultiheadAttention( embed_dim=fusion_dim, num_heads=num_heads, kdim=coarse_dim, vdim=coarse_dim, batch_first=True ) self.fine_to_fusion = nn.Linear(fine_dim, fusion_dim) self.norm = nn.LayerNorm(fusion_dim) def forward(self, frame: torch.Tensor, fine_roi: torch.Tensor = None) -> torch.Tensor: """ Args: frame: (B, 3, H, W) 全局帧(粗粒度) fine_roi: (B, 3, h, w) 头部/手部裁剪区域(细粒度) Returns: fused: (B, fusion_dim) 跨粒度融合特征 """ coarse_feat = self.coarse_encoder(frame).flatten(1) coarse_feat = self.coarse_proj(coarse_feat) if fine_roi is not None: fine_feat = self.fine_encoder(fine_roi).flatten(1) else: _, _, H, W = frame.shape fine_roi = frame[:, :, H//4:3*H//4, W//4:3*W//4] fine_feat = self.fine_encoder(fine_roi).flatten(1) fine_feat = self.fine_proj(fine_feat) query = self.fine_to_fusion(fine_feat).unsqueeze(1) key_value = coarse_feat.unsqueeze(1) attn_out, _ = self.cross_attn( query=query, key=key_value, value=key_value ) fused = self.norm(query + attn_out) return fused.squeeze(1)
class LightweightTemporalConvolution(nn.Module): """ 轻量时序卷积(LTC) 使用深度可分离因果膨胀卷积 - 深度可分离:大幅降低参数量 - 因果:仅使用过去帧,不窥视未来 - 膨胀:增大感受野而不增加参数 论文核心设计:在有限算力下捕获长时序依赖 """ def __init__(self, dim: int = 256, num_layers: int = 4, kernel_size: int = 3, base_dilation: int = 1): super().__init__() self.layers = nn.ModuleList() for i in range(num_layers): dilation = base_dilation * (2 ** i) self.layers.append( CausalDilatedConv(dim, kernel_size, dilation) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (B, T, dim) 时序特征 Returns: (B, T, dim) 时序增强特征 """ for layer in self.layers: x = layer(x) return x
class CausalDilatedConv(nn.Module): """因果膨胀卷积块""" def __init__(self, dim: int, kernel_size: int = 3, dilation: int = 1): super().__init__() padding = (kernel_size - 1) * dilation self.depthwise = nn.Conv1d( dim, dim, kernel_size, padding=padding, dilation=dilation, groups=dim ) self.pointwise = nn.Conv1d(dim, dim, 1) self.norm = nn.BatchNorm1d(dim) self.act = nn.GELU() self.padding = padding def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: (B, T, dim) Returns: (B, T, dim) """ x = x.permute(0, 2, 1) out = self.depthwise(x) if self.padding > 0: out = out[:, :, :-self.padding] out = self.pointwise(out) out = self.norm(out) out = self.act(out) out = out + x return out.permute(0, 2, 1)
class LTC_CGMN(nn.Module): """ LTC-CGMN 完整模型 论文:Frontiers in Mechanical Engineering, 2026 DOI: 10.3389/fmech.2026.1972239 双头输出: 1. 离散状态分类(10类驾驶行为) 2. 连续DRI风险指数(NHTSA-AHP指导) """ BEHAVIOR_CLASSES = [ 'normal_driving', 'phone_calling', 'texting', 'eating', 'drinking', 'smoking', 'talking_passenger', 'adjusting_controls', 'fatigue', 'distracted', ] def __init__(self, num_classes: int = 10, feature_dim: int = 256, num_temporal_layers: int = 4): super().__init__() self.cgsm = CGSMModule( fine_dim=128, coarse_dim=256, fusion_dim=feature_dim, num_heads=4 ) self.ltc = LightweightTemporalConvolution( dim=feature_dim, num_layers=num_temporal_layers, kernel_size=3, base_dilation=1 ) self.classifier = nn.Sequential( nn.Linear(feature_dim, 128), nn.GELU(), nn.Dropout(0.3), nn.Linear(128, num_classes) ) self.dri_regressor = nn.Sequential( nn.Linear(feature_dim, 128), nn.GELU(), nn.Dropout(0.3), nn.Linear(128, 1), nn.Sigmoid() ) def forward(self, frames: torch.Tensor) -> dict: """ Args: frames: (B, T, 3, H, W) 视频帧序列 T=16 (约0.5秒@30fps) Returns: logits: (B, num_classes) 行为分类 dri: (B,) 连续风险指数 0-1 """ B, T, C, H, W = frames.shape frame_features = [] for t in range(T): feat = self.cgsm(frames[:, t]) frame_features.append(feat) temporal_seq = torch.stack(frame_features, dim=1) temporal_enhanced = self.ltc(temporal_seq) pooled = temporal_enhanced.mean(dim=1) logits = self.classifier(pooled) dri = self.dri_regressor(pooled).squeeze(-1) return { 'logits': logits, 'dri': dri, 'temporal_features': temporal_enhanced }
if __name__ == "__main__": model = LTC_CGMN(num_classes=10, feature_dim=256, num_temporal_layers=4) batch_size = 4 T = 16 frames = torch.randn(batch_size, T, 3, 224, 224) with torch.no_grad(): output = model(frames) print("LTC-CGMN 模型测试") print("=" * 50) print(f"分类输出: {output['logits'].shape}") print(f"DRI输出: {output['dri'].shape}") print(f"DRI值: {output['dri'].tolist()}") pred = output['logits'].argmax(dim=1) classes = model.BEHAVIOR_CLASSES for i in range(batch_size): print(f" 样本{i}: {classes[pred[i]]} (DRI={output['dri'][i]:.3f})") param_count = sum(p.numel() for p in model.parameters()) print(f"\n参数量: {param_count / 1e6:.2f}M") print(f"Jetson Orin推理: 33.6 FPS") print(f"Top-1准确率: 96.37%") print(f"DRI RMSE: 0.058")
|