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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
| import torch import torch.nn as nn import torch.nn.functional as F import numpy as np
class DriverDensityMatrix(nn.Module): """ 驾驶员行为密度矩阵 将驾驶行为编码为量子密度矩阵,统一表征: - 行为不确定性(对角元素 = 概率) - 行为相干性(非对角元素 = 状态间干涉) - 时序演化(密度矩阵的幺正/近似幺正变换) 论文Section 3: Quantum-Inspired Representation Args: n_basis: 行为基矢维度(默认3: 自由流/过渡/拥堵) n_features: 输入特征维度(速度/加速度/间距等) """ def __init__(self, n_basis: int = 3, n_features: int = 6): super().__init__() self.n_basis = n_basis self.encoder = nn.Sequential( nn.Linear(n_features, 64), nn.ReLU(), nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, n_basis * n_basis) ) self.evolution = nn.Sequential( nn.Linear(n_basis * n_basis, 128), nn.ReLU(), nn.Linear(128, n_basis * n_basis) ) def to_density_matrix(self, features: torch.Tensor) -> torch.Tensor: """ 将驾驶特征转换为密度矩阵 Args: features: (B, n_features) 包含速度/加速度/间距/相对速度等 Returns: rho: (B, n_basis, n_basis) 密度矩阵,满足Tr(ρ)=1, ρ≥0 """ raw = self.encoder(features) mat = raw.view(-1, self.n_basis, self.n_basis) mat = (mat + mat.transpose(-1, -2)) / 2 rho = F.softmax(mat.flatten(1), dim=1).view_as(mat) trace = torch.diagonal(rho, dim1=-1, dim2=-2).sum(-1, keepdim=True) rho = rho / (trace.unsqueeze(-1) + 1e-8) return rho def evolve(self, rho: torch.Tensor) -> torch.Tensor: """ 密度矩阵演化(近似幺正变换) Args: rho: (B, n_basis, n_basis) 当前密度矩阵 Returns: rho_next: (B, n_basis, n_basis) 演化后密度矩阵 """ flat = rho.flatten(1) evolved = self.evolution(flat) U = evolved.view(-1, self.n_basis, self.n_basis) rho_next = U @ rho @ U.transpose(-1, -2) rho_next = (rho_next + rho_next.transpose(-1, -2)) / 2 trace = torch.diagonal(rho_next, dim1=-1, dim2=-2).sum(-1, keepdim=True) rho_next = rho_next / (trace.unsqueeze(-1) + 1e-8) return rho_next def measure(self, rho: torch.Tensor, observable: torch.Tensor) -> torch.Tensor: """ 测量:计算可观测量的期望值 ⟨O⟩ = Tr(Oρ) Args: rho: (B, n_basis, n_basis) 密度矩阵 observable: (n_basis, n_basis) 可观测算子(如速度、加速度) Returns: expectation: (B,) 期望值 """ product = torch.matmul(observable.unsqueeze(0), rho) expectation = torch.diagonal(product, dim1=-1, dim2=-2).sum(-1) return expectation def forward(self, features: torch.Tensor) -> dict: """ 完整前向传播 Args: features: (B, n_features) 驾驶特征序列 Returns: dict: { 'rho': 当前密度矩阵, 'rho_next': 演化后密度矩阵, 'profile': 行为剖面概率 } """ rho = self.to_density_matrix(features) rho_next = self.evolve(rho) profile = torch.diagonal(rho, dim1=-1, dim2=-2) return { 'rho': rho, 'rho_next': rho_next, 'profile': profile }
class QuantumDriverModel(nn.Module): """ 量子启发的驾驶行为完整模型 架构: [驾驶特征] → [密度矩阵编码] → [时序演化] → [行为预测] 论文Section 4: Framework Architecture Args: n_basis: 行为基矢数 n_features: 输入特征维度 n_steps: 历史步数 predict_horizon: 预测步数 """ def __init__(self, n_basis: int = 3, n_features: int = 6, n_steps: int = 10, predict_horizon: int = 5): super().__init__() self.n_basis = n_basis self.n_steps = n_steps self.predict_horizon = predict_horizon self.encoder = DriverDensityMatrix(n_basis, n_features) self.evolution_layers = nn.ModuleList([ DriverDensityMatrix(n_basis, n_features) for _ in range(predict_horizon) ]) self.observables = nn.Parameter( torch.randn(predict_horizon, n_basis, n_basis) * 0.1 ) self.classifier = nn.Sequential( nn.Linear(n_basis, 32), nn.ReLU(), nn.Linear(32, n_basis) ) def forward(self, x: torch.Tensor) -> dict: """ Args: x: (B, n_steps, n_features) 驾驶特征历史序列 Returns: dict: { 'predictions': (B, predict_horizon) 预测值, 'profiles': (B, n_basis) 行为剖面 } """ B = x.size(0) current_features = x[:, -1, :] result = self.encoder(current_features) rho = result['rho'] predictions = [] profiles = [] for t, layer in enumerate(self.evolution_layers): rho = layer.evolve(rho) obs = self.observables[t] pred = self.encoder.measure(rho, obs) predictions.append(pred) profile = torch.diagonal(rho, dim1=-1, dim2=-2) profiles.append(profile) predictions = torch.stack(predictions, dim=1) profiles = torch.stack(profiles, dim=1).mean(dim=1) logits = self.classifier(profiles) return { 'predictions': predictions, 'profiles': profiles, 'logits': logits }
if __name__ == "__main__": import time from sklearn.metrics import accuracy_score N_BASIS = 3 N_FEATURES = 6 N_STEPS = 10 PREDICT_HORIZON = 5 PROFILES = ['Free Flow', 'Transition', 'Congestion'] model = QuantumDriverModel( n_basis=N_BASIS, n_features=N_FEATURES, n_steps=N_STEPS, predict_horizon=PREDICT_HORIZON ) total_params = sum(p.numel() for p in model.parameters()) print(f"QuantumDriverModel参数量: {total_params:,}") np.random.seed(42) BATCH_SIZE = 32 def generate_driving_sequence(profile: str, batch=1): """生成模拟驾驶序列""" t = np.linspace(0, 5, N_STEPS) if profile == 'Free Flow': speed = 28 + np.random.randn(batch, N_STEPS) * 1.5 accel = np.random.randn(batch, N_STEPS) * 0.3 gap = 40 + np.random.randn(batch, N_STEPS) * 5 rel_speed = np.random.randn(batch, N_STEPS) * 0.5 lane_offset = np.random.randn(batch, N_STEPS) * 0.1 steering = np.random.randn(batch, N_STEPS) * 0.02 elif profile == 'Transition': speed = 18 + np.sin(t * 2) * 3 + np.random.randn(batch, N_STEPS) * 1.5 accel = np.cos(t * 2) * 0.8 + np.random.randn(batch, N_STEPS) * 0.3 gap = 25 + np.sin(t * 2) * 5 + np.random.randn(batch, N_STEPS) * 3 rel_speed = np.sin(t * 2) * 1 + np.random.randn(batch, N_STEPS) * 0.5 lane_offset = np.random.randn(batch, N_STEPS) * 0.2 steering = np.sin(t * 2) * 0.05 + np.random.randn(batch, N_STEPS) * 0.02 else: speed = 5 + np.random.randn(batch, N_STEPS) * 2 accel = np.random.randn(batch, N_STEPS) * 1.5 gap = 8 + np.random.randn(batch, N_STEPS) * 2 rel_speed = np.random.randn(batch, N_STEPS) * 1.5 lane_offset = np.random.randn(batch, N_STEPS) * 0.3 steering = np.random.randn(batch, N_STEPS) * 0.05 features = np.stack([speed, accel, gap, rel_speed, lane_offset, steering], axis=-1) return torch.tensor(features, dtype=torch.float32) print("\n--- 生成模拟数据 ---") x_data = [] y_data = [] for i, profile in enumerate(PROFILES): seq = generate_driving_sequence(profile, batch=20) x_data.append(seq) y_data.append(torch.full((20,), i, dtype=torch.long)) x_all = torch.cat(x_data) y_all = torch.cat(y_data) print("\n--- 前向传播 ---") model.eval() with torch.no_grad(): out = model(x_all) print(f"输入: {x_all.shape}") print(f"预测值: {out['predictions'].shape}") print(f"行为剖面: {out['profiles'].shape}") for i, profile in enumerate(PROFILES): idx = (y_all == i) mean_profile = out['profiles'][idx].mean(0) print(f" {profile:12s}: Free={mean_profile[0]:.3f}, " f"Trans={mean_profile[1]:.3f}, " f"Cong={mean_profile[2]:.3f}") print("\n--- 训练流程 ---") criterion = nn.CrossEntropyLoss() optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4) model.train() for epoch in range(5): optimizer.zero_grad() out = model(x_all) cls_loss = criterion(out['logits'], y_all) pred_loss = F.mse_loss( out['predictions'][:, 0], x_all[:, -1, 0] ) loss = cls_loss + 0.1 * pred_loss loss.backward() optimizer.step() acc = accuracy_score(y_all.numpy(), torch.argmax(out['logits'], dim=1).detach().numpy()) print(f"Epoch {epoch+1}: Total={loss.item():.4f}, " f"Cls={cls_loss.item():.4f}, Pred={pred_loss.item():.4f}, " f"Acc={acc:.2%}") model.eval() with torch.no_grad(): start = time.time() for _ in range(100): _ = model(x_all[:1]) elapsed = (time.time() - start) / 100 print(f"\n单样本推理延迟: {elapsed*1000:.1f}ms") print(f"理论帧率: {1/elapsed:.0f} FPS") print("\n--- 密度矩阵分析 ---") with torch.no_grad(): for i, profile in enumerate(PROFILES): rho = model.encoder.to_density_matrix( x_all[y_all == i, -1, :].mean(0, keepdim=True) ) print(f"\n{profile} 密度矩阵:") print(f" 对角线(概率): {torch.diagonal(rho[0]).numpy().round(3)}") print(f" 非对角线(相干): {rho[0, 0, 1].item():.3f}, " f"{rho[0, 0, 2].item():.3f}") print(f" 迹: {torch.trace(rho[0]).item():.3f}")
|