BT San Technology

19 August 2026

異常偵測與警報規則:什麼時候用哪一種,附可執行的比較程式碼

27 分鐘閱讀 · 企業 AI · AI 技術與模型

示意圖:測試台上的馬達裝有電流勾表,螢幕上的訊號始終沒有越過固定閾值線,但有一段異常以琥珀黃標示出來
AI 生成的插圖

警報規則與異常偵測不是非此即彼的競爭關係,兩者找出的事件類型各不相同。本文用可執行的程式碼來證明:4 天的模擬感測器資料、4 種已標註的異常事件、7 種方法並排比較,看每種方法能找出什麼、有多快,以及每天會誤報多少次。

真實的問題:警報太多沒人看,而閾值又看不到某些事件

這個問題有兩個方向相反的面向。第一,固定閾值設得太寬,誤報頻繁,大家就不再去看。第二,有些事件從不越過閾值,例如感測器卡在同一個值、數值緩慢上升但還沒到線,或是數值對重載來說正常、對閒置的設備來說卻異常。同一個數字在不同的設備狀態下意義不同。所以選擇方法要從想看見的事件類型出發,而不是看演算法有多新潮。

三個假設情境

這三個情境是為了輔助說明而假設的,不是 BT San 的真實案件,其中沒有真實的客戶或數字。

  • 假設一家小工廠把馬達電流超過 12 A 設為警報。每次投入重載批次,電流都接近這條線,警報就會響,員工開始把聲音關掉。問題在於同一個閾值被用在所有設備狀態。
  • 假設冷藏庫的溫度感測器在某些日子會連續好幾個小時卡在同一個值。數值仍在正常範圍內,所以沒有任何限值規則觸發,但這些資料已經不能用了。
  • 假設維護團隊想知道幫浦的振動是否在緩慢升高。固定閾值只有在數值越線之後才會警報,這可能為時已晚。

文件怎麼說

主題文件怎麼說對我們程式碼的影響
Outlier 與 noveltyscikit-learn 把 outlier detection(訓練資料裡混有異常值)和 novelty detection(訓練資料是乾淨的,再判斷新資料)區分開來我們用刻意保持乾淨的第一天做訓練,所以屬於 novelty 思路,同時必須承認實際工作中第一天未必乾淨
Isolation Forest隨機選擇特徵和切分點,把一個點隔離出來所需的切分次數就是路徑長度,多棵樹上的平均值用來衡量正常程度,異常點被隔離得更快我們依照這個思路用 numpy 寫了精簡版
IsolationForest 的預設值n_estimators 為 100,max_samples 為 auto 即 min(256, n_samples),contamination 為 auto,score_samples 越低越異常我們同樣使用 100 棵樹和 256 個樣本,但評分方向相反:越高越異常,與原始論文一致
原始論文的分數Liu、Ting 和 Zhou(ICDM 2008)使用平均路徑長度,並依樣本大小用期望值做調整。接近 1 表示異常,低於 0.5 表示正常iforest.py 中的 c_factor 函式負責這個依樣本大小的調整
Modified z-scoreNIST 建議用 0.6745 乘以(x 減去 median)再除以 MAD,並把超過 3.5 的值標記為需要進一步檢查,而不是判定為錯誤robust_z 使用這個公式,用 median 和 MAD 取代平均值和標準差
管制圖NIST 指出,管制界線之外的點是一種訊號,但非隨機的模式,例如大多數點落在中心線的同一側,即使沒有任何點越線,也是一種訊號這就是只靠限值規則不夠的原因,所以我們還用變化率和卡值來檢查模式
Mediannumpy.median 對偶數個值取的是中間兩個值的平均用來求視窗和訓練日的 median
依據 scikit-learn、NIST、numpy 的文件以及 Wikipedia 的 Isolation forest 頁面整理,查閱日期為 2026-11-21。具體細節請閱讀原始文件。

範例概觀

全部程式碼位於 examples/anomaly-detection-vs-rules/ 資料夾中,只使用 Python 3 和 numpy,不使用 sklearn,也不連網。所有資料都是我們自己產生的。請把它當作學習範例,而不是正式環境的程式碼。

檔案用途
data.py產生包含 3 個通道和設備狀態的模擬資料,附帶事件標籤,並讀取含有空白或文字的 CSV
detectors.py限值規則、變化率規則、卡值規則、滑動視窗 z-score,以及依設備狀態區分的 z-score
iforest.py用 numpy 寫的精簡版 Isolation Forest
alarm_mgmt.py把訊號合併為單一事件,並讓多種方法投票
metrics.py依事件層級評分:是否找出、延遲多久、誤報幾次
pipeline.py / demo.py / sweep.py在同一份資料上執行所有方法,列印表格,並嘗試多個 seed
sample_edge.csv邊界情況資料:空白、文字、負值、超出範圍的值、卡住的值
test_anomaly.py / output.txt8 項 unittest 測試和實際執行的結果

工作順序是:產生已知答案的資料,執行每種偵測器並讓它指出該懷疑哪個感測器,對照答案評分,然後再嘗試合併多種方法並減少警報數量。

步驟 1:產生已知答案的資料

資料包括馬達電流、振動、溫度,以及來自 PLC 的設備狀態(0 閒置,1 輕載,2 重載),每分鐘取樣一次,共 4 天。第一天是正常資料,留作訓練。溫度隨負載緩慢變化,就像有熱慣性的真實設備。注入的異常共有 4 種:spike(數值短暫跳變)、drift(數值緩慢上升)、stuck(感測器卡在同一個值)和 context(設備閒置時電流高出 5 A,仍低於限值線,但對這個狀態來說是錯誤的)。

data.py · 行 9–29
def make_data(seed=7):
    rng = np.random.default_rng(seed)
    # machine state from the PLC: 0 idle, 1 light, 2 heavy; blocks of 60-179 minutes
    raw = np.zeros(N)
    i, first = 0, [0, 1, 2]          # the clean training day must see every state
    while i < N:
        n = int(rng.integers(60, 180))
        raw[i:i + n] = first.pop(0) if first else rng.choice([0, 1, 2], p=[0.35, 0.30, 0.35])
        i += n
    load = np.convolve(np.pad(raw, (4, 0), mode="edge"), np.ones(5) / 5, mode="valid")
    state = np.rint(load).astype(int)
    t = np.arange(N)
    cur = np.interp(load, [0, 1, 2], [3.0, 7.0, 11.4]) + rng.normal(0, 0.40, N)
    vib = np.interp(load, [0, 1, 2], [0.8, 1.2, 1.7]) + rng.normal(0, 0.08, N)
    target = np.interp(load, [0, 1, 2], [35.0, 45.0, 55.0]) + 3 * np.sin(2 * np.pi * t / 1440)
    temp = np.empty(N)
    temp[0] = target[0]
    for k in range(1, N):                      # first-order lag: temperature follows load slowly
        temp[k] = temp[k - 1] + 0.02 * (target[k] - temp[k - 1])
    temp += rng.normal(0, 0.15, N)
    d = {"cur": cur, "vib": vib, "temp": temp, "state": state}
data.py 中建立設備狀態和訊號的部分,注入異常的程式碼在同一個檔案的後面

前三個狀態區塊被強制設為 0、1、2,以確保訓練日能看到所有狀態。一開始我們沒有這樣做,結果遇到 Mean of empty slice 警告,因為訓練日裡完全沒有閒置狀態。

步驟 2:三種可以解釋的規則

限值規則把數值與固定的線比較。變化率規則在每分鐘變化量超過閾值時警報。卡值規則在數值連續 10 個樣本完全相同時警報。三種規則都依通道回傳結果,因此警報能說明懷疑的是哪個感測器。遺失的值(NaN)不會觸發限值規則,因為感測器遺失由另一個獨立的 missing 函式負責。

detectors.py · 行 17–27
def fixed_limits(d):
    # NaN never alarms here; a dead sensor is the job of missing()
    return {ch: np.nan_to_num(d[ch], nan=-1e9) > LIMITS[ch] for ch in CH}


def missing(d):
    return np.isnan(d["cur"]) | np.isnan(d["vib"]) | np.isnan(d["temp"])


def rate_rule(d):
    return {ch: np.nan_to_num(np.abs(np.diff(d[ch], prepend=d[ch][0]))) > RATE[ch] for ch in CH}
detectors.py:限值規則、遺失值檢查和變化率規則
detectors.py · 行 30–40
def flatline(d, n=10):
    """Same value n samples in a row. Real ADCs are noisy, so exact repeats mean a frozen reading.
    simplified: exact equality; production would use a tolerance sized to the sensor resolution."""
    out = {}
    for ch in CH:
        x = d[ch]
        out[ch] = np.zeros(len(x), bool)
        for k in range(n - 1, len(x)):
            if np.ptp(x[k - n + 1:k + 1]) == 0:
                out[ch][k] = True
    return out
detectors.py:卡值規則,使用完全相等的值,這是程式碼中註明的限制

步驟 3:抗離群值的 z-score

第一種方法把最新的值與過去 180 分鐘的 median 和 MAD 比較,只使用歷史資料,超過 3.5 就視為可疑。優點是不需要知道設備狀態。缺點是當設備從閒置變為重載時,數值會跳變並引發警報。

detectors.py · 行 43–58
def robust_z(x, med, mad):
    return 0.6745 * (x - med) / max(mad, 1e-6)          # Iglewicz-Hoaglin modified z-score


def rolling_robust_z(d, win=180, thr=3.5):
    out = {}
    for ch in CH:
        x = d[ch]
        out[ch] = np.zeros(len(x), bool)
        for k in range(win, len(x)):
            w = x[k - win:k]                              # past samples only
            med = np.nanmedian(w)
            mad = np.nanmedian(np.abs(w - med))
            if abs(robust_z(x[k], med, mad)) > thr:
                out[ch][k] = True
    return out
detectors.py:robust_z 和 rolling_robust_z

第二種方法知道設備狀態。它使用訓練日中每個狀態各自的 median 和 MAD,並依目前狀態進行比較。閾值為 4,並且在狀態切換後跳過 6 個樣本,因為這段時間數值還在爬升。它能找出 context 異常,但需要可靠的狀態訊號。

detectors.py · 行 61–91
def state_baseline(d, n_train):
    """median and MAD of each channel per machine state, from the clean training day."""
    base = {}
    for s in (0, 1, 2):
        m = d["state"][:n_train] == s
        for ch in ("cur", "vib", "temp"):
            v = d[ch][:n_train][m]
            med = np.median(v)
            base[(s, ch)] = (med, np.median(np.abs(v - med)))
    return base


def blanking(state):
    """True for samples right after a state change (ramps look odd, state-aware methods skip them)."""
    ch = np.r_[False, state[1:] != state[:-1]]
    out = np.zeros(len(state), bool)
    for k in np.flatnonzero(ch):
        out[k:k + BLANK] = True
    return out


def state_robust_z(d, base, thr=4.0):
    out = {ch: np.zeros(len(d[ch]), bool) for ch in CH}
    for s in (0, 1, 2):
        m = d["state"] == s
        for ch in CH:
            med, mad = base[(s, ch)]
            z = 0.6745 * (np.nan_to_num(d[ch], nan=med) - med) / max(mad, 1e-6)
            out[ch] |= m & (np.abs(z) > thr)
    blank = blanking(d["state"])
    return {ch: v & ~blank for ch, v in out.items()}
detectors.py:依狀態建立 baseline、跳過狀態切換期間,以及依狀態的 z-score

步驟 4:精簡版 Isolation Forest

每棵樹隨機選擇特徵和切分點,直到深度達到樣本大小的 log2。平均路徑長度短,代表容易被隔離,也就代表異常。截斷閾值取訓練日分數的第 99.5 百分位數。我們試了兩種做法:把設備狀態當作特徵,以及不當作特徵。

iforest.py · 行 6–48
def c_factor(n):
    return 0.0 if n <= 1 else 2 * (np.log(n - 1) + 0.5772156649) - 2 * (n - 1) / n


class IForest:
    def __init__(self, n_trees=100, sample=256, seed=0):
        self.n_trees, self.sample, self.rng = n_trees, sample, np.random.default_rng(seed)

    def _build(self, X, depth, limit):
        if depth >= limit or len(X) <= 1:
            return ("leaf", len(X))
        f = int(self.rng.integers(X.shape[1]))
        lo, hi = X[:, f].min(), X[:, f].max()
        if lo == hi:
            return ("leaf", len(X))
        cut = self.rng.uniform(lo, hi)
        m = X[:, f] < cut
        return (f, cut, self._build(X[m], depth + 1, limit), self._build(X[~m], depth + 1, limit))

    def fit(self, X):
        psi = min(self.sample, len(X))
        limit = int(np.ceil(np.log2(psi)))
        self.psi = psi
        self.trees = [self._build(X[self.rng.choice(len(X), psi, replace=False)], 0, limit)
                      for _ in range(self.n_trees)]
        return self

    def _path(self, X, node, depth, out, idx):
        if node[0] == "leaf":
            out[idx] = depth + c_factor(node[1])
            return
        f, cut, left, right = node
        m = X[idx, f] < cut
        self._path(X, left, depth + 1, out, idx[m])
        self._path(X, right, depth + 1, out, idx[~m])

    def score(self, X):
        total = np.zeros(len(X))
        for tree in self.trees:
            out = np.zeros(len(X))
            self._path(X, tree, 0, out, np.arange(len(X)))
            total += out
        return 2 ** (-(total / self.n_trees) / c_factor(self.psi))
iforest.py:精簡版 Isolation Forest。如同程式碼自己註明的,它是簡化版,實際工作中請使用有人維護的函式庫。

Isolation Forest 只能告訴你這個點很奇怪,不能告訴你是哪個感測器。所以我們把責任歸到依狀態 z-score 最高的那個通道,這是程式碼中註明的一種捷徑。

detectors.py · 行 94–104
def blame(flag, d, base):
    """simplified: Isolation Forest says 'odd', not which sensor. Blame the channel with the
    largest per-state z. Production: SHAP-style attribution or per-channel models."""
    out = {ch: np.zeros(len(flag), bool) for ch in CH}
    for k in np.flatnonzero(flag):
        zs = []
        for ch in CH:
            med, mad = base[(int(d["state"][k]), ch)]
            zs.append(abs(0.6745 * (d[ch][k] - med) / max(mad, 1e-6)))
        out[CH[int(np.argmax(zs))]][k] = True
    return out
detectors.py:blame 選出偏離最大的通道

步驟 5:把訊號合併成人看得懂的警報

多種方法同時觸發,不應該變成幾十條警報。episodes 把間隔不超過 10 分鐘的被標記樣本合併為單一事件。

alarm_mgmt.py · 行 7–19
def episodes(flags, gap=10):
    """Group flagged samples into (start, end) episodes; a quiet stretch longer than gap closes one."""
    idx = np.flatnonzero(flags)
    if len(idx) == 0:
        return []
    out, s, prev = [], idx[0], idx[0]
    for i in idx[1:]:
        if i - prev > gap:
            out.append((int(s), int(prev)))
            s = i
        prev = i
    out.append((int(s), int(prev)))
    return out
alarm_mgmt.py:episodes

manage 中的策略是:卡值和變化率這類專用規則可以單獨發出警報,其他方法則要求至少有兩種方法對同一事件意見一致。這是警報管理的精簡版,沒有優先順序,也沒有確認機制。

alarm_mgmt.py · 行 26–40
def manage(sources, alone=(), gap=10, votes=2):
    """sources: method name -> {channel: bool array}. One notification per episode.
    Methods in 'alone' (specific rules such as flatline) may notify by themselves; the rest
    must agree with at least votes-1 other methods inside the same episode.
    simplified: no priorities, no acknowledge or shelve state; see the alarm management article."""
    union = np.zeros(len(next(iter(sources.values()))["cur"]), bool)
    for by_ch in sources.values():
        union |= anyflag(by_ch)
    notes = []
    for s, e in episodes(union, gap):
        who = sorted(n for n, f in sources.items() if anyflag(f)[s:e + 1].any())
        if set(who) & set(alone) or len(who) >= votes:
            chans = sorted({c for n in who for c in CH if sources[n][c][s:e + 1].any()})
            notes.append({"start": s, "end": e, "sources": who, "channels": chans})
    return notes
alarm_mgmt.py:manage 讓各方法投票,並允許部分方法單獨警報

步驟 6:依事件層級評分,而不是依點評分

人們不在乎哪些點被標記,而在乎真實事件有沒有被找出,以及沒有事件時警報了多少次。如果從事件開始到事件結束後 10 分鐘內有警報,並且警報歸責的通道與事件相同,這個事件就算被找出。延遲是從事件開始到第一次警報的分鐘數。Precision 依方法分別計算,只統計第 2 天到第 4 天。

metrics.py · 行 8–30
def score(by_ch, events, n_train, n):
    f = {ch: v.copy() for ch, v in by_ch.items()}
    for v in f.values():
        v[:n_train] = False                              # only judge the test days
    per_type, delays = {}, {}
    for ev in events:
        win = f[ev["ch"]][ev["start"]:ev["end"] + 1 + GRACE]   # the alarm must blame the right sensor
        hit = np.flatnonzero(win)
        t = ev["type"]
        per_type.setdefault(t, [0, 0])
        per_type[t][1] += 1
        if len(hit):
            per_type[t][0] += 1
            delays.setdefault(t, []).append(int(hit[0]))
    eps = episodes(anyflag(f), gap=GRACE)
    good = 0
    for s, e in eps:
        good += any(f[ev["ch"]][max(s, ev["start"]):min(e, ev["end"] + GRACE) + 1].any()
                    for ev in events if s <= ev["end"] + GRACE and e >= ev["start"])
    return {"types": per_type, "delay": {t: float(np.median(v)) for t, v in delays.items()},
            "episodes": len(eps), "true_episodes": good,
            "precision": good / len(eps) if eps else float("nan"),
            "false_per_day": (len(eps) - good) / ((n - n_train) / 1440)}
metrics.py:score
pipeline.py · 行 12–30
def run_all(seed=7):
    d, events = make_data(seed)
    base = state_baseline(d, N_TRAIN)
    blank = blanking(d["state"])
    ifs = {}
    for name, with_state in (("iforest_no_state", False), ("iforest_state", True)):
        X = features(d, with_state)
        model = IForest(n_trees=100, sample=256, seed=1).fit(X[:N_TRAIN])
        thr = np.quantile(model.score(X[:N_TRAIN]), 0.995)
        flag = model.score(X) > thr
        if with_state:
            flag &= ~blank              # state-aware methods skip the ramp after a state change
        ifs[name] = blame(flag, d, base)
    methods = {"fixed_limits": fixed_limits(d), "rate_rule": rate_rule(d), "flatline": flatline(d),
               "rolling_z": rolling_robust_z(d), "state_z": state_robust_z(d, base), **ifs}
    combo = {k: methods[k] for k in COMBO}
    notes = manage(combo, alone=("flatline", "rate_rule"), gap=10, votes=2)
    methods["combined+mgmt"] = to_flags(notes, N)
    return d, events, methods, combo, notes
pipeline.py:run_all 執行所有方法並接上警報管理層

實際執行結果

2026-11-21 在本機上用 seed 7 執行了 python3 demo.py。以下是整個檔案的實際輸出。

output.txt
data: 5760 samples, 1/min, day 1 clean (training), days 2-4 test
labelled events:
  spike    vib  start=d2 09:20 length=2 min
  spike    cur  start=d3 07:50 length=1 min
  spike    cur  start=d3 17:00 length=2 min
  spike    vib  start=d4 11:20 length=3 min
  drift    vib  start=d2 19:20 length=600 min
  drift    temp start=d3 23:40 length=500 min
  stuck    temp start=d2 14:20 length=240 min
  stuck    cur  start=d3 10:20 length=120 min
  context  cur  start=d2 13:05 length=40 min
  context  cur  start=d3 05:49 length=40 min
  context  cur  start=d3 09:10 length=40 min

recall (found/total) and median delay in minutes, per anomaly type
method           spike             drift             stuck             context           
fixed_limits     4/4    0.0        1/2  478.0        0/2    -          0/3    -          
rate_rule        4/4    0.0        1/2  500.0        2/2  180.0        3/3   40.0        
flatline         0/4    -          0/2    -          2/2    9.0        0/3    -          
rolling_z        4/4    0.0        2/2  157.5        2/2   60.0        3/3    0.0        
state_z          3/4    0.0        2/2  209.5        1/2   58.0        3/3    3.0        
iforest_no_state 3/4    0.0        2/2  345.0        1/2   57.0        0/3    -          
iforest_state    0/4    -          2/2  347.5        1/2   63.0        0/3    -          
combined+mgmt    4/4    0.0        2/2  264.5        2/2    9.0        3/3    3.0        

precision = alarm episodes that overlap a real event / all alarm episodes
method             episodes      real  precision  false per day
fixed_limits             49         5       0.10           14.7
rate_rule                11        10       0.91            0.3
flatline                  2         2       1.00            0.0
rolling_z                24        14       0.58            3.3
state_z                  23        13       0.57            3.3
iforest_no_state         20        13       0.65            2.3
iforest_state             8         7       0.88            0.3
combined+mgmt            15        12       0.80            1.0

alarm management on the five combined methods (days 2-4)
  flagged samples summed over the 5 methods     : 1156
  flagged samples after OR                      : 1043
  notifications if every episode is sent (OR)   : 62
  notifications with the policy (see alarm_mgmt): 15
  notes by who raised them: fixed_limits+iforest_state=1, fixed_limits+iforest_state+rate_rule+state_z=1, fixed_limits+iforest_state+state_z=1, fixed_limits+rate_rule+state_z=5, fixed_limits+state_z=2, flatline+iforest_state+rate_rule+state_z=1, flatline+rate_rule=1, rate_rule+state_z=3

edge cases from sample_edge.csv (empty cell, text, negative, out-of-range, frozen value)
  row  0 cur=3.1    vib=0.81   temp=35.2   state= 0 -> -
  row  1 cur=3.0    vib=0.79   temp=35.1   state= 0 -> -
  row  2 cur=nan    vib=0.8    temp=35.3   state= 0 -> missing
  row  3 cur=3.2    vib=nan    temp=35.2   state= 0 -> missing
  row  4 cur=-1.5   vib=0.82   temp=35.0   state= 0 -> -
  row  5 cur=7.0    vib=1.2    temp=45.0   state= 1 -> -
  row  6 cur=7.1    vib=1.19   temp=45.1   state= 1 -> -
  row  7 cur=13.4   vib=1.25   temp=45.2   state= 1 -> fixed
  row  8 cur=11.5   vib=1.75   temp=55.0   state= 2 -> -
  row  9 cur=11.5   vib=1.75   temp=55.0   state= 2 -> -
  row 10 cur=11.5   vib=1.75   temp=55.0   state= 2 -> flat(n=3)
  row 11 cur=11.6   vib=2.9    temp=72.5   state= 2 -> fixed
python3 demo.py 的實際執行輸出(numpy 2.3.5,seed 7)
  1. 限值規則找出了 4 個 spike 中的全部 4 個,但每天誤報 14.7 次,precision 為 0.10,因為重載時的電流靠近 12 A 這條線。它漏掉了所有 stuck 和 context 事件,2 個 drift 中只找出 1 個,而且晚了 478 分鐘。
  2. 卡值規則找出了 2 個 stuck 事件,都在 9 分鐘內,誤報為零。但它完全看不到其他類型的事件,所以應該與其他規則並用,而不是取代它們。
  3. 變化率規則找出了 3 個 context 事件中的 3 個,但是在 40 分鐘時,也就是數值回落時,而不是異常開始時,所以不應算作發現得快。
  4. 依狀態的 z-score 在 3 分鐘內找出了 context 事件。滑動視窗版本在這些事件上能立即找出,但每天誤報 3.3 次。兩種方法的 precision 都在 0.57 到 0.58 左右。
  5. Isolation Forest 找出了全部 2 個 drift,但漏掉了一部分 spike。把設備狀態加入特徵後,4 個 spike 全部漏掉,因為超出以往見過範圍的值只會得到略高一點的分數。這是已知的限制。Precision 提高到了 0.88。
  6. 組合方案找出了 4 個 spike 中的 4 個、2 個 drift 中的 2 個、2 個 stuck 中的 2 個、3 個 context 中的 3 個,每天誤報約 1.0 次,依投票策略,警報數量從 62 條減少到 15 條。

不要把這張表當作哪種方法最好的定論。真實事件只有 11 個,每個通道只有寥寥幾個事件。單一 seed 可能偏袒某一種方法。所以才有 sweep.py,它執行 seed 1 到 8,總共 32 個 spike、16 個 drift、16 個 stuck 和 23 個 context 事件。

sweep_output.txt
recall over seeds 1-8 (found/total), and mean false alarm episodes per day
method           spike     drift     stuck     context   false/day
fixed_limits     29/32     4/16      1/16      0/23      14.3
rate_rule        32/32     9/16      15/16     23/23     0.1
flatline         0/32      0/16      16/16     0/23      0.0
rolling_z        32/32     15/16     16/16     20/23     3.9
state_z          31/32     16/16     10/16     23/23     3.4
iforest_no_state 11/32     13/16     5/16      5/23      2.2
iforest_state    5/32      11/16     4/16      8/23      1.2
combined+mgmt    32/32     13/16     16/16     23/23     1.1
python3 sweep.py 的實際執行輸出,共 8 個 seed

8 個 seed 的整體情況與 seed 7 的趨勢一致。限值規則平均每天誤報 14.3 次,完全找不出 context 事件(23 個中 0 個)。卡值規則找出了 16 個 stuck 中的 16 個。變化率規則找出了 16 個 stuck 中的 15 個。Isolation Forest 找出的 spike 很少(32 個中分別為 11 個和 5 個)。組合方案找出了 32 個 spike 中的 32 個和 23 個 context 中的 23 個,但 drift 只找出 16 個中的 13 個,低於某些 z-score,平均每天誤報 1.1 次。所有數字只適用於這份模擬資料。

測試集如何運作

使用 Python 內建的 unittest,執行指令是 python3 -m unittest test_anomaly.py,共 8 項測試,涵蓋容易悄悄出錯的情況,例如:資料重複產生後得到相同的值,並且訓練日沒有事件;卡值必須滿 10 個樣本才會觸發;MAD 為零時不能除以零;異常點的 Isolation Forest 分數必須高於正常點;CSV 中的空白和文字必須變成 NaN,並且不能觸發限值規則;投票機制不能讓單獨一種吵鬧的方法矇混過關。

test_anomaly.py · 行 31–36
    def test_flatline_needs_n_identical_values(self):
        x = np.r_[np.arange(5.0), [9.0] * 10, [3.0] * 4, np.arange(5.0)]
        d = {"cur": x, "vib": np.arange(len(x)) * 1.0, "temp": np.arange(len(x)) * 2.0}
        f = flatline(d, 10)["cur"]
        self.assertEqual(int(f.sum()), 1)                 # only the run of 10 fires, at its last sample
        self.assertTrue(f[14])
test_anomaly.py:卡值必須有連續 10 個相同的值
test_anomaly.py · 行 55–64
    def test_manage_votes(self):
        n = 100
        srcs = {"fixed_limits": one(n, cur=[10]), "state_z": one(n, vib=[50]),
                "flatline": one(n, temp=[80]), "iforest_state": one(n, vib=[51])}
        notes = manage(srcs, alone=("flatline",), gap=5, votes=2)
        starts = [x["start"] for x in notes]
        self.assertNotIn(10, starts)          # one noisy method alone stays silent
        self.assertIn(50, starts)             # two methods agree
        self.assertIn(80, starts)             # specific rule may notify alone
        self.assertEqual(next(x for x in notes if x["start"] == 50)["channels"], ["vib"])
test_anomaly.py:投票。一種方法觸發時保持沉默,兩種方法一致時觸發,專用規則可以單獨警報
test_output.txt
........
----------------------------------------------------------------------
Ran 8 tests in 0.028s

OK
測試的實際執行結果(8 項測試全部通過)

如果要用於實際工作

  • 真實資料存放在時間序列資料庫中:用查詢每次取一個時間區段,並在 SQL 中依狀態計算 median 和 MAD,或者預先算好。不要把整張資料表載入記憶體。
  • 大檔案:用串流式 CSV 讀取器分塊讀取,或者先轉換成欄式格式。這個範例檔案很小,所以可以整個讀入。
  • 資料持續流入:滑動視窗 z-score 只保留最近的視窗就可以做成串流處理。Isolation Forest 則依排程定期訓練,然後逐點對新資料評分。
  • 編碼和數字格式:來自設備或 Excel 的檔案可能是帶 BOM 的 UTF-8,小數點用逗號,或者使用佛曆年份,讀取前必須檢查。這個範例只檢查空白和非數字文字。
  • 設備狀態訊號:如果 PLC 送出的狀態有誤或有延遲,依狀態的 z-score 也會跟著出錯。應該為狀態訊號本身加一條檢查規則。
  • 閾值與時間:範例中所有閾值都是針對模擬資料調整的,必須依真實的感測器和設備來調整,並在警報發出時指定負責人。

應用到業務場景

  • 冷藏庫或冷藏櫃:依商品的安全閾值使用限值規則,加上卡值規則來找出感測器故障,再依門開或門關的狀態建立 baseline。
  • 建築物內的幫浦或馬達:結合運轉狀態的 z-score 與振動趨勢,在越過限值線之前就看出劣化。
  • 非設備類的業務資料,例如每小時訂單量:原則相同,即與同一時段的正常水準比較,而不是與固定數字比較,並把警報合併為每個時段一個事件。

常見錯誤

  • 所有設備狀態都用同一個閾值,導致誤報很多,大家就不再去看。
  • 依點而不是依事件來評估,事件較長時數字看起來比實際好得多。
  • 把 Isolation Forest 的分數方向讀反:sklearn 的 score_samples 越低越異常,而原始論文是越高越異常。本範例使用原始論文的方向。
  • 相信 Isolation Forest 每次都能找出 spike,而實際上超出以往見過範圍的值只會得到略高一點的分數。
  • 訓練資料中不知不覺混入了事件,系統就會把這些事件當成正常。
  • 只憑幾個事件或單一 seed 下結論,沒有試多組資料。
  • 讓每種方法都直接向人發警報,沒有合併和投票層。
  • 忘記遺失值、負值和超出範圍的值,而真實資料中一定會有這些。

使用前的檢查清單

  1. 明確想找出的事件類型,以及漏報或誤報的代價。
  2. 從可以解釋的規則開始,並衡量它們漏掉了什麼。
  3. 把過去的真實事件收集起來作為答案,至少幾十個,而不是寥寥幾個。
  4. 檢查訓練資料是否夠乾淨,是否包含所有設備狀態。
  5. 依事件層級衡量:是否找出、延遲多久、每天誤報多少次。
  6. 在相信結果之前,先在多段資料或多個 seed 上測試。
  7. 加入合併警報的層,並指定負責人。
  8. 在設備或製程發生變化時,定期重新檢查 baseline。

本範例的注意事項:資料是模擬的,並非來自真實設備。異常事件很少。數字會隨 seed 變化。Isolation Forest 是精簡版。歸責到某個通道用了捷徑。卡值規則使用完全相等的值。警報管理層沒有優先順序和確認機制。沒有用真實資料或真實感測器測試過。請把它當作學習範例,而不是可直接使用的程式碼。

參考資料

  1. scikit-learn — Novelty and Outlier Detection (Isolation Forest, outlier vs novelty) (accessed 2026-11-21)
  2. scikit-learn — IsolationForest (defaults, score_samples) (accessed 2026-11-21)
  3. NIST/SEMATECH e-Handbook — Control charts (accessed 2026-11-21)
  4. NIST/SEMATECH e-Handbook — Detection of outliers (modified z-score, MAD, 3.5) (accessed 2026-11-21)
  5. NumPy — numpy.median (accessed 2026-11-21)
  6. Wikipedia — Isolation forest (Liu, Ting, Zhou, ICDM 2008; score interpretation) (accessed 2026-11-21)

用 LINE 加我們好友

請用手機上的 LINE App 掃描

加入 LINE @Bankoos 的 QR code

LINE ID: @Bankoos

在這台電腦上開啟 LINE