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
| import numpy as np from dataclasses import dataclass from typing import Tuple, List from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score, LeaveOneOut from sklearn.metrics import classification_report import warnings warnings.filterwarnings('ignore')
""" 飞行员认知负荷三模态融合分类器 参考 Xu et al., IEEE TIM 2026
模态: fNIRS (前额叶血流) + ECG (心率变异性) + 眼动 (瞳孔直径) 分类: 低负荷 / 中等负荷 / 过载 """
@dataclass class MultimodalSample: """三模态样本""" fnirs_features: np.ndarray ecg_features: np.ndarray eye_features: np.ndarray label: int subject_id: int
class MentalWorkloadClassifier: """ 认知负荷三模态融合分类器 基于 SHAP 分析结果,使用最有效的特征子集 """ FNIRS_KEY_CHANNELS = [17, 19] ECG_KEY_INDICES = [0, 4] EYE_KEY_INDICES = [0] def __init__(self, n_estimators: int = 100, use_shap_features: bool = True): self.classifier = RandomForestClassifier( n_estimators=n_estimators, max_depth=10, random_state=42, class_weight='balanced' ) self.use_shap_features = use_shap_features self.feature_names = [] def _select_key_features(self, fnirs: np.ndarray, ecg: np.ndarray, eye: np.ndarray) -> np.ndarray: """选择 SHAP 分析确定的关键特征""" fnirs_key = fnirs[:, self.FNIRS_KEY_CHANNELS] ecg_key = ecg[:, self.ECG_KEY_INDICES] eye_key = eye[:, self.EYE_KEY_INDICES] return np.concatenate([fnirs_key, ecg_key, eye_key], axis=1) def _extract_all_features(self, fnirs_raw: np.ndarray, ecg_raw: np.ndarray, eye_raw: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """从原始信号提取特征""" fnirs_beta = np.mean(fnirs_raw, axis=1, keepdims=True) fnirs_features = np.hstack([fnirs_beta, np.std(fnirs_raw, axis=1, keepdims=True)]) rr_intervals = np.diff(ecg_raw) * 1000 mean_nn = np.mean(rr_intervals) if len(rr_intervals) > 0 else 800 sdnn = np.std(rr_intervals) if len(rr_intervals) > 0 else 50 rmssd = np.sqrt(np.mean(np.diff(rr_intervals)**2)) if len(rriffs)>0 else 30 pnn50 = np.mean(np.abs(np.diff(rr_intervals)) > 50) * 100 if len(rr_intervals)>1 else 5 w_power = np.var(rr_intervals) if len(rr_intervals) > 0 else 2500 ecg_features = np.array([[mean_nn, sdnn, rmssd, pnn50, w_power]]) avg_pupil = np.mean(eye_raw) std_pupil = np.std(eye_raw) gaze_stability = 1.0 / (1.0 + np.std(np.diff(eye_raw))) eye_features = np.array([[avg_pupil, std_pupil, gaze_stability]]) return fnirs_features, ecg_features, eye_features def fit(self, samples: List[MultimodalSample]): """训练分类器""" X = [] y = [] for s in samples: if self.use_shap_features: features = np.concatenate([ s.fnirs_features, s.ecg_features, s.eye_features ]).reshape(1, -1) else: features = np.concatenate([ s.fnirs_features, s.ecg_features, s.eye_features ]).reshape(1, -1) X.append(features.flatten()) y.append(s.label) X = np.array(X) y = np.array(y) self.classifier.fit(X, y) self.feature_names = [ 'fNIRS_CH18_beta', 'fNIRS_CH20_beta', 'ECG_MeanNN', 'ECG_W_power', 'Eye_avg_pupil' ] return self def predict(self, fnirs: np.ndarray, ecg: np.ndarray, eye: np.ndarray) -> int: """预测认知负荷""" features = np.concatenate([fnirs, ecg, eye]).reshape(1, -1) return self.classifier.predict(features)[0] def evaluate_loso(self, samples: List[MultimodalSample]) -> dict: """留一被试交叉验证""" subject_ids = [s.subject_id for s in samples] unique_subjects = list(set(subject_ids)) results = {'per_subject': {}, 'mean_acc': 0.0} X_all = np.array([ np.concatenate([s.fnirs_features, s.ecg_features, s.eye_features]) for s in samples ]) y_all = np.array([s.label for s in samples]) accs = [] for test_subj in unique_subjects: train_mask = np.array([s != test_subj for s in subject_ids]) test_mask = ~train_mask if np.sum(test_mask) < 2: continue clf = RandomForestClassifier( n_estimators=100, max_depth=10, random_state=42, class_weight='balanced' ) clf.fit(X_all[train_mask], y_all[train_mask]) pred = clf.predict(X_all[test_mask]) acc = np.mean(pred == y_all[test_mask]) results['per_subject'][f'subject_{test_subj}'] = acc accs.append(acc) results['mean_acc'] = np.mean(accs) if accs else 0 return results
if __name__ == "__main__": np.random.seed(42) print("=" * 70) print("飞行员认知负荷三模态融合分类器测试") print("参考: Xu et al., IEEE TIM 2026") print("=" * 70) num_subjects = 27 samples_per_subject = 30 all_samples = [] for subj_id in range(num_subjects): for i in range(samples_per_subject): label = i // 10 if label == 0: fnirs = np.array([ np.random.normal(0.45, 0.08), np.random.normal(0.35, 0.07), ]) elif label == 1: fnirs = np.array([ np.random.normal(0.55, 0.08), np.random.normal(0.30, 0.07), ]) else: fnirs = np.array([ np.random.normal(0.35, 0.08), np.random.normal(0.50, 0.07), ]) if label == 0: ecg = np.array([850, 3000]) elif label == 1: ecg = np.array([750, 2500]) else: ecg = np.array([650, 1800]) ecg += np.random.normal(0, 50, 2) if label == 0: eye = np.array([3.5]) elif label == 1: eye = np.array([4.2]) else: eye = np.array([5.1]) eye += np.random.normal(0, 0.3, 1) all_samples.append(MultimodalSample( fnirs_features=fnirs, ecg_features=ecg, eye_features=eye, label=label, subject_id=subj_id )) print(f"\n数据集: {len(all_samples)} 样本, {num_subjects} 被试") print(f"特征: fNIRS(2) + ECG(2) + Eye(1) = 5 维") classifier = MentalWorkloadClassifier(use_shap_features=True) classifier.fit(all_samples) X_all = np.array([ np.concatenate([s.fnirs_features, s.ecg_features, s.eye_features]) for s in all_samples ]) y_all = np.array([s.label for s in all_samples]) cv_scores = cross_val_score( classifier.classifier, X_all, y_all, cv=10, scoring='accuracy' ) print(f"\n10 折交叉验证准确率: {np.mean(cv_scores):.4f} ± {np.std(cv_scores):.4f}") loso_results = classifier.evaluate_loso(all_samples) print(f"LOSO 准确率: {loso_results['mean_acc']:.4f}") print(f"\n{'='*70}") print("对比论文结果:") print(f" 论文 10 折: 85.76% | 模拟: {np.mean(cv_scores)*100:.2f}%") print(f" 论文 LOSO: 78.57% | 模拟: {loso_results['mean_acc']*100:.2f}%") print(f"\n{'='*70}") print("单模态对比 (LOSO):") for modality, idx in [("fNIRS only", [0,1]), ("ECG only", [2,3]), ("Eye only", [4]), ("All (SHAP)", [0,1,2,3,4])]: X_mod = X_all[:, idx] loo = LeaveOneOut() scores = cross_val_score( RandomForestClassifier(100, max_depth=10, random_state=42, class_weight='balanced'), X_mod, y_all, cv=loo, scoring='accuracy' ) print(f" {modality:<15}: {np.mean(scores)*100:.2f}%") print(f"\n{'='*70}") print("SHAP 特征重要性 (基于 Gini impurity):") importances = classifier.classifier.feature_importances_ for name, imp in sorted(zip(classifier.feature_names, importances), key=lambda x: -x[1]): bar = "█" * int(imp * 50) print(f" {name:<18} {imp:.4f} {bar}")
|