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
| import numpy as np from scipy.stats import entropy
class GazeEntropyCalculator: """ 眼动熵计算器 计算视线分布的熵值 """ def __init__(self, grid_size: int = 8): self.grid_size = grid_size def calculate_entropy(self, gaze_sequence: np.ndarray) -> float: """ 计算眼动熵 Args: gaze_sequence: 视线序列 (N, 2) - (pitch, yaw) Returns: entropy_value: 熵值 """ grid_counts = self.map_to_grid(gaze_sequence) prob_dist = grid_counts.flatten() / grid_counts.sum() entropy_value = entropy(prob_dist) return float(entropy_value) def map_to_grid(self, gaze_sequence: np.ndarray) -> np.ndarray: """将视线映射到网格""" pitch_range = (-30, 30) yaw_range = (-45, 45) pitch_normalized = (gaze_sequence[:, 0] - pitch_range[0]) / (pitch_range[1] - pitch_range[0]) yaw_normalized = (gaze_sequence[:, 1] - yaw_range[0]) / (yaw_range[1] - yaw_range[0]) pitch_idx = np.clip(pitch_normalized * self.grid_size, 0, self.grid_size - 1).astype(int) yaw_idx = np.clip(yaw_normalized * self.grid_size, 0, self.grid_size - 1).astype(int) grid_counts = np.zeros((self.grid_size, self.grid_size)) for p, y in zip(pitch_idx, yaw_idx): grid_counts[p, y] += 1 return grid_counts def calculate_spatial_entropy(self, gaze_sequence: np.ndarray) -> float: """计算空间熵""" return self.calculate_entropy(gaze_sequence) def calculate_temporal_entropy(self, gaze_sequence: np.ndarray, window_size: int = 30) -> float: """ 计算时间熵 评估视线变化的随机性 """ gaze_diff = np.diff(gaze_sequence, axis=0) entropies = [] for i in range(0, len(gaze_diff) - window_size, window_size // 2): window = gaze_diff[i:i+window_size] entropies.append(self.calculate_entropy(window)) return float(np.mean(entropies))
if __name__ == "__main__": normal_gaze = np.random.normal(0, 5, (300, 2)) distracted_gaze = np.random.uniform(-30, 30, (300, 2)) calculator = GazeEntropyCalculator() print(f"正常驾驶熵值: {calculator.calculate_entropy(normal_gaze):.3f}") print(f"认知分心熵值: {calculator.calculate_entropy(distracted_gaze):.3f}")
|