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
| """ 基于扩散模型的DMS合成数据生成 """
import torch import torch.nn as nn import numpy as np
class DMSDiffusionGenerator(nn.Module): """ DMS合成数据扩散模型生成器 生成内容: - 驾驶员面部图像 - 眼动状态标注 - 疲劳等级标签 """ def __init__(self, config: dict): super().__init__() self.image_size = config.get('image_size', 256) self.channels = config.get('channels', 3) self.unet = UNet( in_channels=self.channels, out_channels=self.channels, time_emb_dim=256, base_channels=128 ) self.condition_encoder = ConditionEncoder( condition_dim=10, embed_dim=256 ) self.num_timesteps = 1000 self.betas = self.cosine_beta_schedule() self.alphas = 1 - self.betas self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) def cosine_beta_schedule(self, timesteps=1000, s=0.008): """余弦退火噪声调度""" steps = timesteps + 1 x = torch.linspace(0, timesteps, steps) alphas_cumprod = torch.cos(((x / timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2 alphas_cumprod = alphas_cumprod / alphas_cumprod[0] betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) return torch.clip(betas, 0, 0.999) def forward(self, x, t, condition): """ 前向传播(预测噪声) Args: x: 带噪声图像 (B, C, H, W) t: 时间步 (B,) condition: 条件向量 (B, condition_dim) Returns: noise_pred: 预测噪声 """ cond_emb = self.condition_encoder(condition) noise_pred = self.unet(x, t, cond_emb) return noise_pred def generate(self, condition, num_samples=1): """ 生成合成图像 Args: condition: 条件向量 num_samples: 生成数量 Returns: samples: 生成的图像 """ device = next(self.parameters()).device x = torch.randn(num_samples, self.channels, self.image_size, self.image_size).to(device) condition = condition.to(device) for t in reversed(range(self.num_timesteps)): t_tensor = torch.full((num_samples,), t, device=device, dtype=torch.long) noise_pred = self(x, t_tensor, condition) alpha = self.alphas[t].to(device) alpha_cumprod = self.alphas_cumprod[t].to(device) beta = self.betas[t].to(device) if t > 0: noise = torch.randn_like(x) else: noise = torch.zeros_like(x) x = (1 / torch.sqrt(alpha)) * (x - (beta / torch.sqrt(1 - alpha_cumprod)) * noise_pred) + torch.sqrt(beta) * noise samples = (x + 1) / 2 samples = torch.clamp(samples, 0, 1) return samples
class UNet(nn.Module): """简化版UNet""" def __init__(self, in_channels, out_channels, time_emb_dim, base_channels): super().__init__() self.down1 = DownBlock(in_channels, base_channels, time_emb_dim) self.down2 = DownBlock(base_channels, base_channels * 2, time_emb_dim) self.down3 = DownBlock(base_channels * 2, base_channels * 4, time_emb_dim) self.mid = MidBlock(base_channels * 4, base_channels * 4, time_emb_dim) self.up1 = UpBlock(base_channels * 4, base_channels * 2, time_emb_dim) self.up2 = UpBlock(base_channels * 2, base_channels, time_emb_dim) self.up3 = UpBlock(base_channels, base_channels, time_emb_dim) self.out = nn.Conv2d(base_channels, out_channels, 1) def forward(self, x, t, cond_emb): t_emb = self.time_embedding(t) emb = t_emb + cond_emb d1 = self.down1(x, emb) d2 = self.down2(d1, emb) d3 = self.down3(d2, emb) mid = self.mid(d3, emb) u1 = self.up1(mid, d3, emb) u2 = self.up2(u1, d2, emb) u3 = self.up3(u2, d1, emb) return self.out(u3) def time_embedding(self, t): """正弦位置编码""" half_dim = 256 // 2 emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, device=t.device) * -emb) emb = t[:, None] * emb[None, :] emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1) return emb
class ConditionEncoder(nn.Module): """条件编码器""" def __init__(self, condition_dim, embed_dim): super().__init__() self.encoder = nn.Sequential( nn.Linear(condition_dim, 128), nn.ReLU(), nn.Linear(128, embed_dim) ) def forward(self, condition): return self.encoder(condition)
class DownBlock(nn.Module): def __init__(self, in_ch, out_ch, time_emb_dim): super().__init__() self.conv = nn.Sequential( nn.Conv2d(in_ch, out_ch, 3, padding=1), nn.ReLU(), nn.Conv2d(out_ch, out_ch, 3, padding=1), nn.ReLU() ) self.time_proj = nn.Linear(time_emb_dim, out_ch) self.pool = nn.MaxPool2d(2) def forward(self, x, t_emb): x = self.conv(x) + self.time_proj(t_emb)[:, :, None, None] return self.pool(x)
class MidBlock(nn.Module): def __init__(self, in_ch, out_ch, time_emb_dim): super().__init__() self.conv = nn.Sequential( nn.Conv2d(in_ch, out_ch, 3, padding=1), nn.ReLU(), nn.Conv2d(out_ch, out_ch, 3, padding=1), nn.ReLU() ) self.time_proj = nn.Linear(time_emb_dim, out_ch) def forward(self, x, t_emb): return self.conv(x) + self.time_proj(t_emb)[:, :, None, None]
class UpBlock(nn.Module): def __init__(self, in_ch, out_ch, time_emb_dim): super().__init__() self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) self.conv = nn.Sequential( nn.Conv2d(in_ch * 2, out_ch, 3, padding=1), nn.ReLU(), nn.Conv2d(out_ch, out_ch, 3, padding=1), nn.ReLU() ) self.time_proj = nn.Linear(time_emb_dim, out_ch) def forward(self, x, skip, t_emb): x = self.up(x) x = torch.cat([x, skip], dim=1) return self.conv(x) + self.time_proj(t_emb)[:, :, None, None]
if __name__ == "__main__": config = {'image_size': 256, 'channels': 3} generator = DMSDiffusionGenerator(config) condition = torch.zeros(1, 10) condition[0, 0] = 0.6 condition[0, 1] = 1.0 condition[0, 2] = 1.0 samples = generator.generate(condition, num_samples=4) print(f"生成图像形状: {samples.shape}")
|