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
| """ 乘员分类CNN模型 多任务学习:年龄估计 + 性别分类 + 儿童/成人区分 """
import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple, Dict
class OccupantClassifier(nn.Module): """ 乘员分类器 输出: 1. 年龄估计(回归) 2. 性别分类(二分类) 3. 年龄组分类(多分类:儿童/青少年/成人/老年) 4. 儿童座椅检测(二分类) """ def __init__(self, backbone: str = 'resnet50', pretrained: bool = True): """ Args: backbone: 骨干网络 pretrained: 是否使用预训练权重 """ super().__init__() if backbone == 'resnet50': from torchvision.models import resnet50, ResNet50_Weights self.backbone = resnet50( weights=ResNet50_Weights.DEFAULT if pretrained else None ) feature_dim = 2048 elif backbone == 'efficientnet_b0': from torchvision.models import efficientnet_b0, EfficientNet_B0_Weights self.backbone = efficientnet_b0( weights=EfficientNet_B0_Weights.DEFAULT if pretrained else None ) feature_dim = 1280 self.backbone.fc = nn.Identity() self.shared_fc = nn.Sequential( nn.Linear(feature_dim, 512), nn.ReLU(), nn.Dropout(0.5), nn.Linear(512, 256), nn.ReLU(), ) self.age_head = nn.Sequential( nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 1), nn.ReLU() ) self.gender_head = nn.Sequential( nn.Linear(256, 64), nn.ReLU(), nn.Linear(64, 2) ) self.age_group_head = nn.Sequential( nn.Linear(256, 64), nn.ReLU(), nn.Linear(64, 5) ) self.child_seat_head = nn.Sequential( nn.Linear(256, 64), nn.ReLU(), nn.Linear(64, 3) ) def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: """ 前向传播 Args: x: 输入图像 (B, 3, H, W) Returns: outputs: 各任务输出 """ features = self.backbone(x) shared = self.shared_fc(features) age = self.age_head(shared).squeeze(-1) gender = self.gender_head(shared) age_group = self.age_group_head(shared) child_seat = self.child_seat_head(shared) return { 'age': age, 'gender': gender, 'age_group': age_group, 'child_seat': child_seat } def predict(self, x: torch.Tensor) -> Dict: """ 推理预测 Returns: predictions: 预测结果字典 """ self.eval() with torch.no_grad(): outputs = self.forward(x) age = outputs['age'].cpu().numpy() gender_prob = F.softmax(outputs['gender'], dim=1) gender = torch.argmax(gender_prob, dim=1).cpu().numpy() gender_conf = torch.max(gender_prob, dim=1)[0].cpu().numpy() age_group_names = ['infant', 'child', 'teenager', 'adult', 'senior'] age_group_prob = F.softmax(outputs['age_group'], dim=1) age_group_idx = torch.argmax(age_group_prob, dim=1).cpu().numpy() age_group = [age_group_names[i] for i in age_group_idx] seat_names = ['none', 'rear-facing', 'forward-facing'] seat_prob = F.softmax(outputs['child_seat'], dim=1) seat_idx = torch.argmax(seat_prob, dim=1).cpu().numpy() child_seat = [seat_names[i] for i in seat_idx] return { 'age': age.tolist(), 'gender': ['male' if g == 0 else 'female' for g in gender], 'gender_confidence': gender_conf.tolist(), 'age_group': age_group, 'child_seat': child_seat }
class MultiTaskLoss(nn.Module): """多任务损失函数""" def __init__(self, age_weight: float = 1.0, gender_weight: float = 1.0, age_group_weight: float = 1.0, child_seat_weight: float = 1.0): super().__init__() self.age_weight = age_weight self.gender_weight = gender_weight self.age_group_weight = age_group_weight self.child_seat_weight = child_seat_weight def forward(self, outputs: Dict[str, torch.Tensor], targets: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, Dict]: """ 计算总损失 Args: outputs: 模型输出 targets: 标签 {'age':, 'gender':, 'age_group':, 'child_seat':} Returns: total_loss: 总损失 loss_dict: 各任务损失 """ age_loss = F.l1_loss(outputs['age'], targets['age']) gender_loss = F.cross_entropy(outputs['gender'], targets['gender']) age_group_loss = F.cross_entropy(outputs['age_group'], targets['age_group']) child_seat_loss = F.cross_entropy(outputs['child_seat'], targets['child_seat']) total_loss = ( self.age_weight * age_loss + self.gender_weight * gender_loss + self.age_group_weight * age_group_loss + self.child_seat_weight * child_seat_loss ) loss_dict = { 'age_loss': age_loss.item(), 'gender_loss': gender_loss.item(), 'age_group_loss': age_group_loss.item(), 'child_seat_loss': child_seat_loss.item(), 'total_loss': total_loss.item() } return total_loss, loss_dict
def train_epoch(model, dataloader, optimizer, criterion, device): """训练一个epoch""" model.train() total_losses = {'age_loss': 0, 'gender_loss': 0, 'age_group_loss': 0, 'child_seat_loss': 0, 'total_loss': 0} for batch in dataloader: images = batch['image'].to(device) targets = { 'age': batch['age'].to(device), 'gender': batch['gender'].to(device), 'age_group': batch['age_group'].to(device), 'child_seat': batch['child_seat'].to(device) } outputs = model(images) loss, loss_dict = criterion(outputs, targets) optimizer.zero_grad() loss.backward() optimizer.step() for k, v in loss_dict.items(): total_losses[k] += v n = len(dataloader) for k in total_losses: total_losses[k] /= n return total_losses
if __name__ == "__main__": model = OccupantClassifier(backbone='resnet50', pretrained=True) batch_size = 4 x = torch.randn(batch_size, 3, 224, 224) predictions = model.predict(x) print("预测结果:") for i in range(batch_size): print(f" 样本{i}: 年龄={predictions['age'][i]:.1f}, " f"性别={predictions['gender'][i]}, " f"年龄组={predictions['age_group'][i]}, " f"儿童座椅={predictions['child_seat'][i]}") n_params = sum(p.numel() for p in model.parameters()) print(f"\n模型参数量: {n_params/1e6:.2f}M")
|