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
| from typing import Dict, Any import torch import torch.nn as nn
class MultiModalImpairmentModel(nn.Module): """ 多模态损伤检测模型 融合视觉、车辆、语音特征 """ def __init__( self, visual_dim: int = 128, vehicle_dim: int = 32, audio_dim: int = 64, hidden_dim: int = 256, num_classes: int = 4 ): super().__init__() self.visual_encoder = nn.Sequential( nn.Linear(visual_dim, hidden_dim), nn.ReLU(), nn.Dropout(0.3), nn.Linear(hidden_dim, hidden_dim // 2) ) self.vehicle_encoder = nn.Sequential( nn.Linear(vehicle_dim, hidden_dim // 4), nn.ReLU(), nn.Dropout(0.3) ) self.audio_encoder = nn.Sequential( nn.Linear(audio_dim, hidden_dim // 4), nn.ReLU(), nn.Dropout(0.3) ) self.attention = nn.MultiheadAttention( embed_dim=hidden_dim // 2, num_heads=4, batch_first=True ) self.classifier = nn.Sequential( nn.Linear(hidden_dim // 2, hidden_dim // 4), nn.ReLU(), nn.Dropout(0.3), nn.Linear(hidden_dim // 4, num_classes) ) def forward( self, visual_features: torch.Tensor, vehicle_features: torch.Tensor, audio_features: torch.Tensor ) -> Dict[str, torch.Tensor]: """ 前向传播 Args: visual_features: 视觉特征, shape=(B, T, visual_dim) vehicle_features: 车辆特征, shape=(B, T, vehicle_dim) audio_features: 语音特征, shape=(B, T, audio_dim) Returns: logits: 分类结果 attention_weights: 注意力权重 """ visual_encoded = self.visual_encoder(visual_features) vehicle_encoded = self.vehicle_encoder(vehicle_features) audio_encoded = self.audio_encoder(audio_features) combined = visual_encoded + vehicle_encoded.unsqueeze(1) + audio_encoded.unsqueeze(1) attended, attention_weights = self.attention( combined, combined, combined ) pooled = attended.mean(dim=1) logits = self.classifier(pooled) return { 'logits': logits, 'attention_weights': attention_weights }
class ImpairmentInferenceEngine: """损伤检测推理引擎""" def __init__(self, model_path: str, device: str = 'cpu'): self.model = MultiModalImpairmentModel() self.model.load_state_dict(torch.load(model_path, map_location=device)) self.model.eval() self.device = device self.confidence_threshold = 0.7 def detect( self, face_image: np.ndarray, vehicle_signals: dict, audio_clip: np.ndarray ) -> dict: """ 检测驾驶员损伤状态 Args: face_image: 面部图像 vehicle_signals: 车辆信号 {steering, speed, acceleration} audio_clip: 语音片段 Returns: result: 检测结果 """ visual_features = self._extract_visual_features(face_image) vehicle_features = self._extract_vehicle_features(vehicle_signals) audio_features = self._extract_audio_features(audio_clip) visual_tensor = torch.tensor(visual_features).float().unsqueeze(0).unsqueeze(0) vehicle_tensor = torch.tensor(vehicle_features).float().unsqueeze(0) audio_tensor = torch.tensor(audio_features).float().unsqueeze(0).unsqueeze(0) with torch.no_grad(): outputs = self.model(visual_tensor, vehicle_tensor, audio_tensor) probs = torch.softmax(outputs['logits'], dim=1) pred_class = torch.argmax(probs, dim=1).item() confidence = probs[0, pred_class].item() label_map = { 0: 'normal', 1: 'fatigue', 2: 'alcohol_impairment', 3: 'drug_impairment' } result = { 'state': label_map[pred_class], 'confidence': confidence, 'alert_required': confidence > self.confidence_threshold and pred_class > 0 } return result def _extract_visual_features(self, image: np.ndarray) -> np.ndarray: """提取视觉特征""" return np.random.randn(128) def _extract_vehicle_features(self, signals: dict) -> np.ndarray: """提取车辆特征""" features = [ signals.get('steering_angle', 0) / 360, signals.get('speed', 0) / 200, signals.get('lateral_acceleration', 0) / 10, signals.get('steering_correction_rate', 0) ] return np.array(features) def _extract_audio_features(self, audio: np.ndarray) -> np.ndarray: """提取语音特征""" return np.random.randn(64)
|