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
| import torch import torch.nn as nn import torch.nn.functional as F
class SpatialTransformer(nn.Module): """空间变换网络(STN): 对齐驾驶员姿态""" def __init__(self): super().__init__() self.loc_net = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 6) ) self.loc_net[-1].weight.data.zero_() self.loc_net[-1].bias.data.copy_(torch.tensor([1,0,0,0,1,0], dtype=torch.float)) def forward(self, x): theta = self.loc_net(x).view(-1, 2, 3) grid = F.affine_grid(theta, x.size()) return F.grid_sample(x, grid)
class SEnet(nn.Module): """SE通道注意力模块""" def __init__(self, channels, reduction=16): super().__init__() self.squeeze = nn.AdaptiveAvgPool2d(1) self.excite = nn.Sequential( nn.Linear(channels, channels//reduction), nn.ReLU(), nn.Linear(channels//reduction, channels), nn.Sigmoid() ) def forward(self, x): b, c = x.size(0), x.size(1) w = self.excite(self.squeeze(x).view(b, c)) return x * w.view(b, c, 1, 1)
class CBAM(nn.Module): """CBAM: 通道+空间双重注意力""" def __init__(self, channels, reduction=16): super().__init__() self.channel_avg = nn.AdaptiveAvgPool2d(1) self.channel_max = nn.AdaptiveMaxPool2d(1) self.mlp = nn.Sequential( nn.Linear(channels, channels//reduction), nn.ReLU(), nn.Linear(channels//reduction, channels) ) self.spatial = nn.Conv2d(2, 1, 7, padding=3) def forward(self, x): b, c = x.size(0), x.size(1) avg_w = self.mlp(self.channel_avg(x).view(b, c)) max_w = self.mlp(self.channel_max(x).view(b, c)) chan_w = torch.sigmoid(avg_w + max_w).view(b, c, 1, 1) x = x * chan_w avg_s = x.mean(dim=1, keepdim=True) max_s = x.max(dim=1, keepdim=True)[0] spat_w = torch.sigmoid(self.spatial(torch.cat([avg_s, max_s], dim=1))) return x * spat_w
class PSNBlock(nn.Module): """PSN块: STN → SE → CBAM → 残差""" def __init__(self, in_ch, out_ch): super().__init__() self.stn = SpatialTransformer() self.conv = nn.Sequential( nn.Conv2d(in_ch, out_ch, 3, padding=1), nn.BatchNorm2d(out_ch), nn.ReLU(), nn.Conv2d(out_ch, out_ch, 3, padding=1), nn.BatchNorm2d(out_ch) ) self.se = SEnet(out_ch) self.cbam = CBAM(out_ch) self.downsample = nn.Conv2d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity() def forward(self, x): identity = self.downsample(x) out = self.stn(x) out = self.conv(out) out = self.se(out) out = self.cbam(out) return F.relu(out + identity)
class PSN(nn.Module): """ 级联姿态分析网络(Pose Analysis Network) 论文核心架构: 多级PSN块级联 """ def __init__(self, num_poses=5): super().__init__() self.blocks = nn.Sequential( PSNBlock(3, 32), PSNBlock(32, 64), PSNBlock(64, 128), PSNBlock(128, 256) ) self.gap = nn.AdaptiveAvgPool2d(1) self.classifier = nn.Sequential( nn.Flatten(), nn.Linear(256, 64), nn.ReLU(), nn.Linear(64, num_poses) ) def forward(self, x): return self.classifier(self.gap(self.blocks(x)))
class AdaptiveSeatController(nn.Module): """ 自适应座椅控制器 基于识别的姿态输出座椅调节参数 """ def __init__(self, num_poses=5): super().__init__() self.controller = nn.Sequential( nn.Linear(num_poses, 32), nn.ReLU(), nn.Linear(32, 6) ) def forward(self, pose_logits): pose_prob = F.softmax(pose_logits, dim=-1) params = torch.sigmoid(self.controller(pose_prob)) return params
class IntelligentSeatSystem(nn.Module): """完整的智能座椅系统""" def __init__(self): super().__init__() self.psn = PSN(num_poses=5) self.controller = AdaptiveSeatController(num_poses=5) def forward(self, image): pose_logits = self.psn(image) seat_params = self.controller(pose_logits) return { 'pose': pose_logits, 'seat_params': seat_params, 'pose_name': ['upright', 'relaxed', 'reclined', 'leaning', 'slouching'] }
if __name__ == "__main__": import numpy as np, time model = IntelligentSeatSystem() params = sum(p.numel() for p in model.parameters()) print(f"智能座椅系统参数量: {params:,}") np.random.seed(42) x = torch.rand(8, 3, 128, 128) model.eval() with torch.no_grad(): out = model(x) print(f"\n姿态分类: {out['pose'].shape}") print(f"座椅参数: {out['seat_params'].shape}") print(f"参数: height={out['seat_params'][0,0]:.2f}, " f"backrest={out['seat_params'][0,1]:.2f}, " f"lumbar={out['seat_params'][0,2]:.2f}") criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) labels = torch.randint(0, 5, (8,)) model.train() for ep in range(3): optimizer.zero_grad() out = model(x) loss = criterion(out['pose'], labels) loss.backward() optimizer.step() print(f"Epoch {ep+1}: Loss={loss.item():.4f}") model.eval() with torch.no_grad(): start = time.time() for _ in range(50): _ = model(x[:1]) print(f"\n推理延迟: {(time.time()-start)/50*1000:.1f}ms")
|