下面给出两套思路,并分别提供可直接运行的 Python 代码。
• 监督式:手里有 “哪几个点是真异常” 的标注时 —— 用一次排序就能在所有可能阈值上线性扫一遍,O(N log N)。
• 非监督式:完全没有标签 —— 用极值理论 (Peak-Over-Threshold, POT) + 稳健统计(MAD);当尾部足够长时用 POT,当尾部过短时退化成 MAD,整体仍是 O(N log N) 以内。
────────────────────────
一、监督式最佳阈值(有标签)
────────────────────────
核心想法
- 先把分数按降序排好,只会有 ≤N 个“候选阈值”(即每一个唯一分数)。
- 依次把阈值往下放,相当于把新样本从负类变成正类,只需滚动更新 TP / FP 等计数即可。
- 同时计算想优化的指标(F1、J-index、precision-recall …),记录最优值与阈值。
代码(F1 为例,可替换成其它指标)
import numpy as np
from collections import namedtuple
Result = namedtuple('Result', ['best_threshold', 'best_score', 'curve'])
def best_threshold_supervised(scores, labels, metric='f1'):
"""
scores : 1-D ndarray,分数越大“越异常”
labels : 1-D ndarray,1=异常,0=正常
metric : 'f1' / 'youden' / 自定义 callable(tp, fp, fn, tn)->float
"""
scores = np.asarray(scores)
labels = np.asarray(labels).astype(np.int8)
assert scores.shape == labels.shape
# 按分数降序排列
idx = np.argsort(-scores)
scores_sorted = scores[idx]
labels_sorted = labels[idx]
# 统计全局正负
P = labels.sum()
N = len(labels) - P
tp = fp = 0
fn = P # 一开始阈值=+∞,所有样本预测为负,因此 fn = P
tn = N
best_val = -1
best_thr = np.inf
curve = [] # 可选:保存所有点画 ROC/PR
# 遍历所有唯一分数 → 下一段的阈值设为这个分数
i = 0
while i < len(scores_sorted):
thr = scores_sorted[i]
# 把分数 == thr 的一段一次性加进去(向上移动阈值边界)
j = i
while j < len(scores_sorted) and scores_sorted[j] == thr:
if labels_sorted[j]:
tp += 1; fn -= 1
else:
fp += 1; tn -= 1
j += 1
# 计算指标
if callable(metric):
cur_val = metric(tp, fp, fn, tn)
elif metric == 'f1':
prec = tp / (tp + fp) if (tp + fp) else 0
rec = tp / (tp + fn) if (tp + fn) else 0
cur_val = 2*prec*rec / (prec+rec) if (prec+rec) else 0
elif metric == 'youden':
tpr = tp / P if P else 0
fpr = fp / N if N else 0
cur_val = tpr - fpr
else:
raise ValueError('metric not supported')
curve.append((thr, tp, fp, fn, tn, cur_val))
if cur_val > best_val:
best_val = cur_val
best_thr = thr
i = j
return Result(best_thr, best_val, curve)
使用示例
>>> rng = np.random.default_rng(0)
>>> scores = rng.normal(size=20000)
>>> labels = (scores > 3).astype(int) # 假装 3σ 以外是真异常
>>> res = best_threshold_supervised(scores, labels, metric='f1')
>>> res.best_threshold, res.best_score
(2.980..., 0.823...)
优点:
• 只对排序后的唯一分数做遍历,最坏 O(N log N);
• 对极大/极小离群值天然鲁棒——它们只影响单个候选阈值,不会像 max-percent 法那样“拉高上限”。
────────────────────────
二、非监督式阈值(无标签)
────────────────────────
没有标签时,最常见的方法是先定位“尾部”再在尾部上做统计。下面的混合方案在两种极端数据上都能工作:
步骤
- Robust Z-Score:先用中位数 & MAD 做一次稳健中心化 / 尺度化,过滤掉“很正常”的主体部分。
z_i = (s_i − median) / MAD
建议 k_mad = 3~5,把 z_i > k_mad 的点看作候选“尾部”。
- 如果尾部候选点 ≥ min_tail(比如 50)——说明尾巴够长,可以用 POT:
a. 把候选数据减去阈值 u(可取 = k_mad·MAD + median);
b. 拟合 Generalized Pareto Distribution (GPD),估计形状 ξ、尺度 β;
c. 给定期望的 tail-probability α(如 1e-3),阈值
T = u + β/ξ * ((α * n_tail)^(−ξ) − 1) (ξ≠0)
d. 若 ξ≈0,用指数分布简化:T = u − β * log(α)。
- 如果尾部太短(< min_tail),退化成 MAD 法:
T = median + k_mad * MAD。
整合代码
import numpy as np
from scipy.stats import genpareto
def mad(arr):
med = np.median(arr)
return np.median(np.abs(arr - med))
def pot_threshold(scores, k_mad=3.5, min_tail=50, alpha=1e-3):
"""
无监督阈值,返回 best_thr
scores : ndarray
alpha : 设定的“期望超出阈值概率”,越小阈值越高
"""
scores = np.asarray(scores, dtype=float)
med = np.median(scores)
mad_ = mad(scores) or 1e-9 # 防止除 0
# step1: 找尾部
z = (scores - med) / mad_
tail_mask = z > k_mad
tail = scores[tail_mask]
u = med + k_mad * mad_
if len(tail) >= min_tail:
# step2: POT
excess = tail - u
# 只要正的
excess = excess[excess > 0]
if len(excess) == 0:
return u # 没尾巴
# MLE 拟合 GPD
c, loc, scale = genpareto.fit(excess, floc=0) # c=ξ, scale=β
xi, beta = c, scale
# step2c
if abs(xi) < 1e-4: # 近似指数
T = u - beta * np.log(alpha)
else:
T = u + beta/xi * ((alpha * len(excess))**(-xi) - 1)
return T
else:
# step3: 退化到 MAD
return med + k_mad * mad_
测试几组极端场景
rng = np.random.default_rng(42)
# 场景 A:主体 0~1, 少量巨大的离群点
scores1 = np.concatenate([rng.uniform(0, 1, 19990), [1e6]*10])
print(pot_threshold(scores1)) # 输出远小于 1e6,但能把巨离群点识别出来
# 场景 B:所有异常都很小
scores2 = rng.exponential(scale=0.1, size=20000)
print(pot_threshold(scores2)) # 返回 ~0.3 左右的一个小阈值
# 场景 C:几乎正态,无明显异常
scores3 = rng.normal(0, 1, 20000)
print(pot_threshold(scores3)) # ≈ 3~4σ
复杂度
• 排序(genpareto.fit 内部) O(N log N);若只用 MAD 法则 O(N)。
• 空间 O(N)。
────────────────────────
三、总结选型建议
────────────────────────
- 如果有少量已知异常标签,首选监督式:
best_threshold_supervised → 一次排序 + 线性扫描。
- 若无标签但尾部够长,POT 是极值理论里最靠谱的无监督阈值法;
尾部过短时转用 Median + k·MAD,仍然鲁棒。
- 两种方法都只跟排序或少量统计量打交道,对 2 万级别甚至百万级别数据都能在毫秒~秒级内完成。