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
| """ 跨源视觉负荷指数(VLI)预测框架 论文:Sensors 2026, 26(17), 5521 核心思路:训练用眼动数据,推理用车辆运动学 """
import numpy as np from sklearn.ensemble import GradientBoostingRegressor from sklearn.model_selection import GroupKFold from sklearn.metrics import mean_squared_error, r2_score from scipy.signal import savgol_filter
class VisualLoadIndexPredictor: """ 跨源VLI预测器 训练阶段:使用眼动特征计算VLI代理标签 推理阶段:仅使用车辆运动学特征预测VLI """ def __init__(self, config: dict): super().__init__() self.kinematic_features = config.get('kinematic_features', [ 'steering_angle', 'steering_velocity', 'vehicle_speed', 'lateral_accel', 'longitudinal_accel', 'yaw_rate', 'lane_distance', 'time_since_departure' ]) self.gaze_threshold = config.get('gaze_threshold', 0.3) self.window_sec = config.get('window_sec', 10) self.fps = config.get('fps', 30) self.model = None self.architectures = ['GBDT', 'RandomForest', 'XGBoost', 'Linear', 'MLP'] def compute_vli_proxy(self, gaze_data: np.ndarray) -> np.ndarray: """ 从眼动数据计算VLI代理标签 Args: gaze_data: 眼动数据, shape=(N, 4) columns: [gaze_x, gaze_y, pupil_diameter, blink_rate] Returns: vli: 视觉负荷指数, shape=(N-window,) 0.0 = 低负荷(视线在路上) 1.0 = 高负荷(视线偏离道路) 公式(论文Section 2.2): VLI(t) = mean(|gaze_offset(t)| > threshold) over window + α * (1 - gaze_stability(t)) + β * blink_rate_anomaly(t) """ window = int(self.window_sec * self.fps) vli_values = [] for i in range(len(gaze_data) - window): w = gaze_data[i:i+window] gaze_offset = np.sqrt(w[:, 0]**2 + w[:, 1]**2) off_road_ratio = np.mean(gaze_offset > self.gaze_threshold) gaze_stability = 1.0 - np.std(gaze_offset) / (np.mean(gaze_offset) + 1e-6) blink_anomaly = np.abs(w[:, 3] - np.median(w[:, 3])) / (np.median(w[:, 3]) + 1e-6) blink_score = np.mean(blink_anomaly) alpha = 0.3 beta = 0.2 vli = off_road_ratio + alpha * (1 - gaze_stability) + beta * blink_score vli = np.clip(vli, 0.0, 1.0) vli_values.append(vli) return np.array(vli_values) def extract_kinematic_features(self, can_data: np.ndarray) -> np.ndarray: """ 从CAN总线数据提取运动学特征 Args: can_data: CAN总线数据, shape=(N, 8) columns: [steering_angle, speed, accel_x, accel_y, yaw_rate, lane_dist, brake, throttle] Returns: features: 运动学特征矩阵, shape=(N, M) """ features = np.zeros((len(can_data), 12)) features[:, 0] = can_data[:, 0] features[:, 1] = can_data[:, 1] features[:, 2] = can_data[:, 2] features[:, 3] = can_data[:, 3] features[:, 4] = can_data[:, 4] features[:, 5] = can_data[:, 5] features[:, 6] = np.gradient(can_data[:, 0]) features[:, 7] = np.gradient(can_data[:, 1]) features[:, 8] = savgol_filter(can_data[:, 2], 11, 2) features[:, 9] = can_data[:, 0] * can_data[:, 1] features[:, 10] = np.abs(can_data[:, 4]) * can_data[:, 1] features[:, 11] = np.gradient(can_data[:, 5]) return features def train_cross_source(self, can_data: np.ndarray, gaze_data: np.ndarray, driver_ids: np.ndarray, architecture: str = 'GBDT'): """ 跨源训练:用眼动数据生成标签,用车载数据训练模型 关键:GroupKFold按驾驶员分组,确保驾驶员独立性 Args: can_data: CAN总线数据 gaze_data: 同步眼动数据 driver_ids: 驾驶员ID(用于GroupKFold) architecture: 模型架构 """ vli_labels = self.compute_vli_proxy(gaze_data) window = int(self.window_sec * self.fps) kinematic_features = self.extract_kinematic_features(can_data[:-window]) gkf = GroupKFold(n_splits=5) results = [] for train_idx, test_idx in gkf.split(kinematic_features, vli_labels, groups=driver_ids[:-window]): X_train, X_test = kinematic_features[train_idx], kinematic_features[test_idx] y_train, y_test = vli_labels[train_idx], vli_labels[test_idx] if architecture == 'GBDT': model = GradientBoostingRegressor( n_estimators=200, max_depth=5, learning_rate=0.05, subsample=0.8, random_state=42 ) elif architecture == 'XGBoost': import xgboost as xgb model = xgb.XGBRegressor( n_estimators=200, max_depth=5, learning_rate=0.05, subsample=0.8, random_state=42 ) elif architecture == 'RandomForest': from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor( n_estimators=200, max_depth=8, random_state=42 ) elif architecture == 'Linear': from sklearn.linear_model import Ridge model = Ridge(alpha=1.0) elif architecture == 'MLP': from sklearn.neural_network import MLPRegressor model = MLPRegressor( hidden_layer_sizes=(64, 32), max_iter=500, random_state=42 ) model.fit(X_train, y_train) y_pred = model.predict(X_test) rmse = np.sqrt(mean_squared_error(y_test, y_pred)) r2 = r2_score(y_test, y_pred) results.append({ 'architecture': architecture, 'rmse': rmse, 'r2': r2, 'n_train': len(train_idx), 'n_test': len(test_idx) }) self.model = model return results def predict_realtime(self, can_data: np.ndarray) -> float: """ 实时推理:仅需CAN总线数据,无需眼动仪 Args: can_data: 最近10秒CAN数据, shape=(300, 8) (30fps) Returns: vli_pred: 预测视觉负荷指数 [0, 1] """ features = self.extract_kinematic_features(can_data) latest_feature = features[-1:].reshape(1, -1) vli_pred = self.model.predict(latest_feature)[0] return float(np.clip(vli_pred, 0.0, 1.0))
if __name__ == "__main__": import time np.random.seed(42) n_samples = 10 * 60 * 30 can_data = np.zeros((n_samples, 8)) can_data[:, 0] = np.cumsum(np.random.normal(0, 0.5, n_samples)) can_data[:, 1] = 60 + 20 * np.sin(np.linspace(0, 10, n_samples)) can_data[:, 2] = np.random.normal(0, 0.1, n_samples) can_data[:, 3] = np.random.normal(0, 0.05, n_samples) can_data[:, 4] = np.random.normal(0, 0.02, n_samples) can_data[:, 5] = np.random.normal(0, 0.3, n_samples) gaze_data = np.zeros((n_samples, 4)) gaze_data[:, 0] = np.random.normal(0, 0.2, n_samples) gaze_data[:, 1] = np.random.normal(0, 0.15, n_samples) gaze_data[:, 2] = 4.0 + np.random.normal(0, 0.3, n_samples) gaze_data[:, 3] = 15 + np.random.poisson(1, n_samples) driver_ids = np.repeat(np.arange(10), n_samples // 10) predictor = VisualLoadIndexPredictor({'fps': 30, 'window_sec': 10}) print("=" * 60) print("跨源VLI预测实验") print("=" * 60) for arch in ['GBDT', 'RandomForest', 'Linear']: results = predictor.train_cross_source(can_data, gaze_data, driver_ids, architecture=arch) avg_rmse = np.mean([r['rmse'] for r in results]) avg_r2 = np.mean([r['r2'] for r in results]) print(f"\n{arch}:") print(f" RMSE: {avg_rmse:.4f} (±{np.std([r['rmse'] for r in results]):.4f})") print(f" R²: {avg_r2:.4f} (±{np.std([r['r2'] for r in results]):.4f})") test_can = can_data[:300] vli = predictor.predict_realtime(test_can) print(f"\n实时VLI预测: {vli:.3f}") print(f" VLI > 0.5: {'⚠️ 高视觉负荷' if vli > 0.5 else '✅ 正常'}")
|