评价时间序列异常检测的效果(或精度)的标准

TP 为真正例(True Positive)

表示模型预测为正类且实际也为正类的样本数,即正样本被正确识别的数量。

FP 为假正例(False Positive)

表示模型预测为正类但实际为负类的样本数,即误报的负样本数量。

TN 为真负例(True Negative)

表示模型预测为负类且实际也为负类的样本数,即负样本被正确识别的数量。

FN 为假负例(False Negative)

表示模型预测为负类但实际为正类的样本数,即漏报的正样本数量。

准确率(Accuracy)

正确识别的异常点数量与总样本数的比率。 准确率 Accuracy = (TP + TN) / (TP + FP + TN + FN)

精确率(Precision)

被正确标记为异常的数据点数量与所有标记为异常的数据点数量的比率。 精确率 Precision = TP / (TP + FP)

召回率(敏感度)(Recall)

被正确标记为异常的数据点数量与所有真实异常数据点数量的比率。 召回率 Recall = TP / (TP + FN)

F1 分数

综合考虑精确率和召回率的指标。 F1 分数 F1 = 2 Precision Recall / (Precision + Recall)

计算代码

介绍

使用 sklearn.metrics 的方法计算 混淆矩阵 从而得出 TN、FP、FN、TP 在 混淆矩阵 中,通常约定: 0 表示负例(Negative) ; 1 表示正例(Positive) 通常 负例是“正常”或“非异常” ; 正例是“异常”或“错误”

代码

outliers 为异常值列表 true_labels 为标记的真实标签列表

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
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import pairwise_distances_argmin_min, confusion_matrix

# 与'anomaly'列进行比较
# true_labels列表中 0为正常 1为粗差
# .values 转换成 numpy.ndarray 列表
true_labels = dataframe_total['anomaly'].values

# 在混淆矩阵中,通常约定: 0 表示负例(Negative) ; 1 表示正例(Positive)
# 通常 负例是“正常”或“非异常” ; 正例是“异常”或“错误”

# 如果要处理 true_labels 把他换成混淆矩阵中约定的格式 -> 将true_labels列表中的 0变为1 1变为0
# 使用 np.array() 把 普通列表 转换为 numpy.ndarray 列表:
# true_labels_inverted = np.array([0 if label==1 else 1 for label in true_labels])
# 或者使用:
# true_labels_inverted = 1 - true_labels

# 计算混淆矩阵
conf_matrix = confusion_matrix(true_labels, [1 if idx in outliers else 0 for idx in dataframe_total.index])

# 计算指标
accuracy = accuracy_score(true_labels, [1 if idx in outliers else 0 for idx in dataframe_total.index])
precision = precision_score(true_labels, [1 if idx in outliers else 0 for idx in dataframe_total.index])
recall = recall_score(true_labels, [1 if idx in outliers else 0 for idx in dataframe_total.index])
f1 = f1_score(true_labels, [1 if idx in outliers else 0 for idx in dataframe_total.index])

# 输出结果
print("Confusion Matrix:\n", conf_matrix)
print("True Negative (TN):", conf_matrix[0, 0])
print("False Positive (FP):", conf_matrix[0, 1])
print("False Negative (FN):", conf_matrix[1, 0])
print("True Positive (TP):", conf_matrix[1, 1])
print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)