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
| import torch import torch.nn as nn import numpy as np
class VisionEncoder(nn.Module): """视觉特征编码器(面部CNN)""" def __init__(self, feature_dim: int = 256): super().__init__() self.backbone = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU6(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU6(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU6(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), ) self.face_attention = nn.Sequential( nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 128), nn.Sigmoid() ) self.proj = nn.Linear(128, feature_dim) def forward(self, face_img: torch.Tensor) -> torch.Tensor: """ Args: face_img: [B, 3, 96, 96] 面部图像 Returns: features: [B, feature_dim] """ feat = self.backbone(face_img) att = self.face_attention(feat) feat = feat * att return self.proj(feat)
class TactileEncoder(nn.Module): """触觉特征编码器(方向盘压力时序)""" def __init__(self, n_sensors: int = 16, feature_dim: int = 256): super().__init__() self.conv1d = nn.Sequential( nn.Conv1d(n_sensors, 32, 5, stride=1), nn.BatchNorm1d(32), nn.ReLU(), nn.Conv1d(32, 64, 3, stride=2), nn.BatchNorm2d(64), nn.ReLU(), ) self.lstm = nn.LSTM( 64, 128, batch_first=True, bidirectional=True ) self.proj = nn.Linear(256, feature_dim) def forward(self, pressure_seq: torch.Tensor) -> torch.Tensor: """ Args: pressure_seq: [B, n_sensors, T] 压力时序 Returns: features: [B, feature_dim] """ x = self.conv1d(pressure_seq) x = x.permute(0, 2, 1) out, _ = self.lstm(x) feat = out[:, -1, :] return self.proj(feat)
class CrossModalFusion(nn.Module): """ 跨模态融合模块 视觉+触觉→注意力加权融合→分类 """ def __init__(self, feature_dim: int = 256, n_classes: int = 3): super().__init__() self.vision_to_tactile = nn.Linear(feature_dim, feature_dim) self.tactile_to_vision = nn.Linear(feature_dim, feature_dim) self.fusion = nn.Sequential( nn.Linear(feature_dim * 2, feature_dim), nn.ReLU(), nn.Dropout(0.3), nn.Linear(feature_dim, n_classes) ) self.modality_weight = nn.Sequential( nn.Linear(feature_dim * 2, 2), nn.Softmax(dim=-1) ) def forward(self, vision_feat: torch.Tensor, tactile_feat: torch.Tensor) -> dict: """ Args: vision_feat: [B, D] tactile_feat: [B, D] Returns: logits, modality_weights """ v_informed = vision_feat * torch.sigmoid( self.tactile_to_vision(tactile_feat) ) t_informed = tactile_feat * torch.sigmoid( self.vision_to_tactile(vision_feat) ) combined = torch.cat([v_informed, t_informed], dim=-1) weights = self.modality_weight(combined) fused = ( weights[:, 0:1] * v_informed + weights[:, 1:2] * t_informed ) logits = self.fusion(combined) return { 'logits': logits, 'modality_weights': weights, }
class VisionTactileFatigueModel(nn.Module): """ 视觉+触觉多模态疲劳检测完整模型 """ def __init__(self, n_classes: int = 3): super().__init__() self.vision_encoder = VisionEncoder() self.tactile_encoder = TactileEncoder(n_sensors=16) self.fusion = CrossModalFusion(n_classes=n_classes) def forward(self, face_img: torch.Tensor, pressure_seq: torch.Tensor) -> dict: v_feat = self.vision_encoder(face_img) t_feat = self.tactile_encoder(pressure_seq) return self.fusion(v_feat, t_feat)
if __name__ == "__main__": model = VisionTactileFatigueModel(n_classes=3) face = torch.randn(4, 3, 96, 96) pressure = torch.randn(4, 16, 100) result = model(face, pressure) print("视觉+触觉多模态疲劳检测:") print(f" 输出: {result['logits'].shape}") print(f" 模态权重: {result['modality_weights']}") print(f" 视觉权重: {result['modality_weights'][:, 0].mean():.2f}") print(f" 触觉权重: {result['modality_weights'][:, 1].mean():.2f}") total_params = sum(p.numel() for p in model.parameters()) print(f"\n总参数: {total_params:,}")
|