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
| """ MobileNetV2 + SE注意力分类器
用于7类驾驶员状态识别: 1. 正常 (Normal) 2. 轻度疲劳 (Light Fatigue) 3. 重度疲劳 (Heavy Fatigue) 4. 轻度酒驾 (Light Drunk) 5. 重度酒驾 (Heavy Drunk) 6. 分心 (Distraction) 7. 使用手机 (Phone Use) """
import torch import torch.nn as nn import torch.nn.functional as F from typing import List
class SEModule(nn.Module): """ Squeeze-and-Excitation注意力模块 论文核心:自适应强调关键通道特征 实现: 1. Squeeze: 全局平均池化 2. Excitation: FC -> ReLU -> FC -> Sigmoid 3. Scale: 通道加权 """ def __init__(self, channels: int, reduction: int = 4): super().__init__() reduced_channels = channels // reduction self.squeeze = nn.AdaptiveAvgPool2d(1) self.excitation = nn.Sequential( nn.Linear(channels, reduced_channels, bias=False), nn.ReLU(inplace=True), nn.Linear(reduced_channels, channels, bias=False), nn.Sigmoid() ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: 输入特征 [B, C, H, W] Returns: 加权特征 [B, C, H, W] """ batch, channels, _, _ = x.size() squeezed = self.squeeze(x).view(batch, channels) excited = self.excitation(squeezed) scaled = x * excited.view(batch, channels, 1, 1) return scaled
class InvertedResidual(nn.Module): """ MobileNetV2倒残差块 结构: 1. 1x1扩张卷积 (升维) 2. 3x3深度可分离卷积 3. 1x1压缩卷积 (降维) 4. SE注意力(论文新增) """ def __init__( self, in_channels: int, out_channels: int, stride: int = 1, expand_ratio: int = 6, use_se: bool = True ): super().__init__() hidden_channels = in_channels * expand_ratio self.use_residual = stride == 1 and in_channels == out_channels layers = [] if expand_ratio != 1: layers.extend([ nn.Conv2d(in_channels, hidden_channels, 1, bias=False), nn.BatchNorm2d(hidden_channels), nn.ReLU6(inplace=True), ]) layers.extend([ nn.Conv2d(hidden_channels, hidden_channels, 3, stride, 1, groups=hidden_channels, bias=False), nn.BatchNorm2d(hidden_channels), nn.ReLU6(inplace=True), ]) if use_se: layers.append(SEModule(hidden_channels)) layers.extend([ nn.Conv2d(hidden_channels, out_channels, 1, bias=False), nn.BatchNorm2d(out_channels), ]) self.conv = nn.Sequential(*layers) def forward(self, x: torch.Tensor) -> torch.Tensor: if self.use_residual: return x + self.conv(x) else: return self.conv(x)
class DriverStateClassifier(nn.Module): """ 驾驶员状态分类器 基于MobileNetV2 + SE注意力 论文结果:97.67%准确率 """ def __init__(self, num_classes: int = 7, pretrained: bool = True): super().__init__() self.features = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(32), nn.ReLU6(inplace=True), ) inverted_residual_config = [ [1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2], [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2], [6, 320, 1, 1], ] input_channels = 32 for t, c, n, s in inverted_residual_config: output_channels = c for i in range(n): stride = s if i == 0 else 1 self.features.append( InvertedResidual(input_channels, output_channels, stride, t) ) input_channels = output_channels self.features.append(nn.Conv2d(320, 1280, 1, bias=False)) self.features.append(nn.BatchNorm2d(1280)) self.features.append(nn.ReLU6(inplace=True)) self.avgpool = nn.AdaptiveAvgPool2d(1) self.classifier = nn.Sequential( nn.Dropout(0.2), nn.Linear(1280, num_classes) ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: 输入图像 [B, 3, 224, 224] Returns: 类别概率 [B, num_classes] """ features = self.features(x) pooled = self.avgpool(features) flattened = pooled.view(pooled.size(0), -1) logits = self.classifier(flattened) return logits def get_attention_maps(self, x: torch.Tensor) -> List[torch.Tensor]: """ 获取SE注意力图(可解释性) Returns: 各层注意力权重列表 """ attention_maps = [] for module in self.features: if isinstance(module, InvertedResidual): for layer in module.conv: if isinstance(layer, SEModule): with torch.no_grad(): squeezed = layer.squeeze(x) excited = layer.excitation(squeezed.view(squeezed.size(0), -1)) attention_maps.append(excited) x = module(x) if not isinstance(module, SEModule) else x return attention_maps
if __name__ == "__main__": model = DriverStateClassifier(num_classes=7) x = torch.randn(4, 3, 224, 224) output = model(x) print("=" * 60) print("MobileNetV2 + SE 分类器配置") print("=" * 60) print(f"输入形状: {x.shape}") print(f"输出形状: {output.shape}") print(f"参数量: {sum(p.numel() for p in model.parameters())/1e6:.2f}M") print(f"FLOPs: {sum(p.numel() for p in model.parameters()) * 224 * 224 / 1e9:.2f}G") probs = torch.softmax(output, dim=1) preds = torch.argmax(probs, dim=1) classes = ['正常', '轻度疲劳', '重度疲劳', '轻度酒驾', '重度酒驾', '分心', '使用手机'] print(f"\n预测结果: {[classes[p] for p in preds]}")
|