3. 基于孤立森林的传感器异常检测
任务说明
本案例针对工业传感器时间序列数据,构建基于孤立森林(Isolation Forest)的异常检测模型。输入为某设备振动传感器连续采集的1000个温度读数(含人为注入的异常点),输出为每个样本的异常标签(1为异常,0为正常),并给出异常分数分布。目标是通过无监督方式识别传感器数据中的离群点,无需人工标注历史异常样本。
实现方案
采用孤立森林算法:通过随机切分特征空间构建多棵隔离树,异常点因容易被孤立而路径更短,据此计算异常分数。代码使用scikit-learn库实现,包含数据生成、模型训练、预测与结果可视化四个环节。数据生成阶段在正常温度波动(正弦趋势+高斯噪声)基础上注入5%的突变异常,以模拟传感器故障或外部干扰。
代码实现
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, classification_report
# ========== 1. 生成带注入异常的传感器数据 ==========
np.random.seed(42)
n_samples = 1000
t = np.linspace(0, 100, n_samples)
# 正常模式:正弦趋势 + 高斯噪声
normal = 50 + 10 * np.sin(t / 10) + np.random.normal(0, 1.5, n_samples)
# 注入异常:随机选择50个位置(5%),替换为突变值
n_anomalies = 50
anomaly_idx = np.random.choice(n_samples, n_anomalies, replace=False)
data = normal.copy()
data[anomaly_idx] += np.random.uniform(20, 40, n_anomalies) # 正向突变
# 真实标签(用于验证,不参与训练)
true_labels = np.ones(n_samples)
true_labels[anomaly_idx] = -1
# ========== 2. 数据预处理 ==========
# 孤立森林对单维数据可直接处理,此处标准化便于分数解释
scaler = StandardScaler()
X = scaler.fit_transform(data.reshape(-1, 1))
# ========== 3. 训练孤立森林模型 ==========
model = IsolationForest(
n_estimators=100,
contamination=0.05, # 与注入比例一致
random_state=42,
n_jobs=-1
)
model.fit(X)
# ========== 4. 预测与异常分数 ==========
pred_labels = model.predict(X) # 1为正常,-1为异常
anomaly_scores = model.score_samples(X) # 分数越低越异常
# ========== 5. 验证与评估 ==========
# 将预测结果与真实注入位置对比
cm = confusion_matrix(true_labels, pred_labels, labels=[1, -1])
tn, fp, fn, tp = cm.ravel()
# 输出关键指标
print(f"注入异常数: {n_anomalies}")
print(f"检出异常数: {tp}")
print(f"漏报数: {fn}")
print(f"误报数: {fp}")
print(f"召回率: {tp / (tp + fn):.3f}")
print(f"精确率: {tp / (tp + fp):.3f}")
# 输出前10个样本的预测结果与分数(便于人工核对)
print("\n前10个样本详情:")
print("索引 真实标签 预测标签 异常分数")
for i in range(10):
print(f"{i:4d} {true_labels[i]:+d} {pred_labels[i]:+d} {anomaly_scores[i]:.4f}")
运行方式与依赖
运行环境需安装numpy和scikit-learn:
pip install numpy scikit-learn
python sensor_anomaly_detection.py
验证方法与判定标准
执行脚本后,观察控制台输出的混淆矩阵指标。判定通过标准:
- 召回率 ≥ 0.90:至少检出45个注入异常(共50个);
- 精确率 ≥ 0.85:误报数不超过8个;
- 前10个样本输出中,若索引位置在注入集合内,其预测标签应为
-1且异常分数明显低于正常样本。
由于代码中固定了随机种子(random_state=42),每次运行结果完全一致,可直接复现上述指标。若修改随机种子,指标会有小幅波动,但应仍满足上述阈值。