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
| """ 二进制接触感知坐姿识别系统 论文复现:arXiv:2608.01512
用 10 个接触开关实现 4 种坐姿分类 适用于: OOP 初级检测、座椅姿态监控
硬件成本: <$5 (10个微动开关 + Arduino/ESP32) """
import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score, LeaveOneOut from sklearn.metrics import classification_report, confusion_matrix import json from typing import Tuple, List
class BinaryContactPostureSystem: """ 二进制接触感知坐姿识别系统 硬件: 10个机械接触开关, 5×2阵列 接口: GPIO → 10-bit 二值向量 输出: 姿态分类 (normal/leaning_back/leaning_left/leaning_right) """ NUM_SWITCHES = 10 ROWS = 2 COLS = 5 POSTURES = { 0: 'normal_sitting', 1: 'leaning_back', 2: 'leaning_left', 3: 'leaning_right' } IDEAL_PATTERNS = { 0: np.array([1,1,1,1,1, 1,1,1,1,1], dtype=int), 1: np.array([1,1,1,1,1, 0,0,0,0,0], dtype=int), 2: np.array([1,1,0,0,0, 1,1,0,0,0], dtype=int), 3: np.array([0,0,0,1,1, 0,0,0,1,1], dtype=int), } def __init__(self, noise_rate: float = 0.04): """ Args: noise_rate: 模拟噪声率(开关抖动、接触不良) """ self.noise_rate = noise_rate self.classifier = DecisionTreeClassifier( max_depth=5, criterion='gini', random_state=42 ) self.lr_classifier = LogisticRegression( max_iter=1000, multi_class='multinomial', solver='lbfgs' ) self.is_trained = False def generate_training_data(self, samples_per_posture: int = 50) -> Tuple[np.ndarray, np.ndarray]: """ 生成模拟训练数据(带噪声) 实际使用时替换为真实 GPIO 读取数据 Args: samples_per_posture: 每种姿态的样本数 Returns: X: shape=(N, 10), 二值特征 y: shape=(N,), 姿态标签 """ X_list = [] y_list = [] for label, pattern in self.IDEAL_PATTERNS.items(): for _ in range(samples_per_posture): noisy = pattern.copy() for i in range(len(noisy)): if np.random.random() < self.noise_rate: noisy[i] = 1 - noisy[i] X_list.append(noisy) y_list.append(label) return np.array(X_list), np.array(y_list) def generate_test_data(self, samples_per_posture: int = 20) -> Tuple[np.ndarray, np.ndarray]: """生成测试数据(噪声更高)""" return self.generate_training_data(samples_per_posture) def train(self, X: np.ndarray, y: np.ndarray): """训练分类器""" self.classifier.fit(X, y) self.lr_classifier.fit(X, y) self.is_trained = True print(f"训练完成: {len(X)} 个样本, {len(np.unique(y))} 类姿态") def predict(self, switch_state: np.ndarray) -> Tuple[str, float]: """ 预测坐姿 Args: switch_state: shape=(10,), 0/1 二值向量 Returns: posture_name: 姿态名称 confidence: 置信度 """ if not self.is_trained: raise ValueError("模型未训练") x = switch_state.reshape(1, -1) pred = self.classifier.predict(x)[0] proba = self.classifier.predict_proba(x)[0] confidence = proba[pred] return self.POSTURES[pred], float(confidence) def read_gpio(self, gpio_pins: List[int]) -> np.ndarray: """ 从 GPIO 读取开关状态(实际部署用) 需要在树莓派/ESP32 上运行 Args: gpio_pins: 10个GPIO引脚编号 Returns: switch_state: shape=(10,), 0/1 二值向量 """ try: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) states = [] for pin in gpio_pins: GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) states.append(GPIO.input(pin)) return np.array(states, dtype=int) except ImportError: print("警告: 无 GPIO 硬件, 返回模拟数据") return self.IDEAL_PATTERNS[0].copy() def shap_analysis(self, X: np.ndarray, y: np.ndarray) -> dict: """ 简化版 SHAP 分析:计算每个开关的信息增益 Returns: importance: 每个开关的重要性得分 """ importance = self.classifier.feature_importances_ positions = ['S1','S2','S3','S4','S5','S6','S7','S8','S9','S10'] result = {} for i, (pos, imp) in enumerate(zip(positions, importance)): row = 'Upper' if i < 5 else 'Lower' col = i % 5 if col == 0: side = 'Left' elif col == 4: side = 'Right' else: side = 'Center' result[pos] = { 'importance': float(imp), 'position': f'{row}-{side}', 'row': row, 'col': col } return result def evaluate(self, X_test: np.ndarray, y_test: np.ndarray) -> dict: """全面评估模型""" y_pred = self.classifier.predict(X_test) cv_scores = cross_val_score( self.classifier, X_test, y_test, cv=LeaveOneOut(), scoring='accuracy' ) cm = confusion_matrix(y_test, y_pred) report = classification_report( y_test, y_pred, target_names=[self.POSTURES[i] for i in range(4)], output_dict=True ) return { 'accuracy': float(np.mean(y_pred == y_test)), 'cv_mean': float(cv_scores.mean()), 'cv_std': float(cv_scores.std()), 'confusion_matrix': cm.tolist(), 'report': report }
class OOPDetectionExtension: """ 将接触感知坐姿识别扩展为 OOP 检测系统 OOP 场景映射: normal_sitting → 安全位置(ISOFIX 正常坐姿) leaning_back → 后仰 OOP(安全带 submarining 风险) leaning_left/right → 侧倾 OOP(气囊部署不当风险) 无接触 → 空座或站立(儿童站立/跪姿风险) """ OOP_RISK_LEVEL = { 'normal_sitting': ('safe', 0), 'leaning_back': ('high_risk', 2), 'leaning_left': ('medium_risk', 1), 'leaning_right': ('medium_risk', 1), 'no_contact': ('critical', 3), } def __init__(self, posture_system: BinaryContactPostureSystem): self.ps = posture_system def assess_oop_risk(self, switch_state: np.ndarray) -> dict: """ 评估 OOP 风险等级 Args: switch_state: 10-bit 开关状态 Returns: risk assessment """ if np.sum(switch_state) == 0: posture = 'no_contact' else: posture_name, confidence = self.ps.predict(switch_state) posture = posture_name risk_level, risk_score = self.OOP_RISK_LEVEL.get( posture, ('unknown', -1) ) airbag_advice = self._get_airbag_advice(risk_level) belt_advice = self._get_belt_advice(risk_level, posture) return { 'posture': posture, 'risk_level': risk_level, 'risk_score': risk_score, 'airbag_action': airbag_advice, 'belt_action': belt_advice, 'switch_pattern': switch_state.tolist(), 'timestamp': None } def _get_airbag_advice(self, risk_level: str) -> str: """根据风险等级给出气囊建议""" advice_map = { 'safe': '正常部署', 'medium_risk': '降低部署力度(Stage 1)', 'high_risk': '禁用气囊(后仰姿势下气囊可能造成伤害)', 'critical': '禁用气囊(无乘员或站立)', 'unknown': '保守策略:禁用' } return advice_map.get(risk_level, '保守策略:禁用') def _get_belt_advice(self, risk_level: str, posture: str) -> str: """根据风险等级和姿态给出安全带建议""" if risk_level == 'safe': return '正常张紧' elif posture == 'leaning_back': return '增加张紧力(防止 submarining)+ 腰部气囊' elif 'leaning' in posture: return '调整张紧角度 + 锁止卷收器' elif risk_level == 'critical': return '未系安全带告警' return '保守张紧'
if __name__ == "__main__": print("=" * 60) print("二进制接触感知坐姿识别系统测试") print("论文: arXiv:2608.01512") print("=" * 60) system = BinaryContactPostureSystem(noise_rate=0.04) X_train, y_train = system.generate_training_data(samples_per_posture=50) X_test, y_test = system.generate_test_data(samples_per_posture=20) print(f"\n训练集: {X_train.shape}, 测试集: {X_test.shape}") print(f"姿态类别: {list(system.POSTURES.values())}") system.train(X_train, y_train) results = system.evaluate(X_test, y_test) print(f"\n=== 模型评估 ===") print(f"测试准确率: {results['accuracy']:.1%}") print(f"留一交叉验证: {results['cv_mean']:.1%} ± {results['cv_std']:.1%}") shap = system.shap_analysis(X_train, y_train) print(f"\n=== 传感器重要性 (SHAP) ===") sorted_shap = sorted(shap.items(), key=lambda x: -x[1]['importance']) for name, info in sorted_shap: bar = '█' * int(info['importance'] * 50) print(f" {name} ({info['position']:12s}): {bar} {info['importance']:.3f}") print(f"\n=== 姿态预测演示 ===") test_cases = [ ('正常坐姿', np.array([1,1,1,1,1, 1,1,1,1,1])), ('后仰', np.array([1,1,1,1,1, 0,0,0,0,0])), ('左倾', np.array([1,1,0,0,0, 1,1,0,0,0])), ('右倾', np.array([0,0,0,1,1, 0,0,0,1,1])), ('空座', np.array([0,0,0,0,0, 0,0,0,0,0])), ] oop_system = OOPDetectionExtension(system) for name, state in test_cases: if np.sum(state) == 0: risk = oop_system.assess_oop_risk(state) print(f" {name:8s} → 风险: {risk['risk_level']:12s} | " f"气囊: {risk['airbag_action']} | 安全带: {risk['belt_action']}") else: posture, conf = system.predict(state) risk = oop_system.assess_oop_risk(state) print(f" {name:8s} → 姿态: {posture:16s} (置信度 {conf:.0%}) | " f"风险: {risk['risk_level']:12s} | 气囊: {risk['airbag_action']}") print(f"\n=== 混淆矩阵 ===") cm = np.array(results['confusion_matrix']) posture_names = ['normal', 'lean_back', 'lean_left', 'lean_right'] print(f"{'':15s}", end='') for n in posture_names: print(f"{n:>12s}", end='') print() for i, name in enumerate(posture_names): print(f"{name:15s}", end='') for j in range(4): print(f"{cm[i][j]:12d}", end='') print()
|