異常検知にzスコアを使う

Anomaly Detection in Python

Bekhruz (Bex) Tuychiev

Kaggle Master, Data Science Content Creator

zスコアとは?

  • zスコアは示す:
    • 平均から何標準偏差離れているか

例:

  • 分布で $\mu=10$, $\sigma=3$ のとき:
    • $Z_{16.3}=(16.3-10) / 3=2.1$

zスコアの計算式。

Anomaly Detection in Python

経験則と外れ値

経験則(Empirical Rule):

  • 68% は1標準偏差以内
  • 95% は2標準偏差以内
  • 99.7% は3標準偏差以内

外れ値:

  • 3標準偏差の範囲外
  • 裾(両端のピンク領域)に位置

WikipediaのEmpirical Ruleの画像。正規分布と68%、95%、99.7%の領域が示されている。

1 WikipediaのEmpirical Ruleページの画像
Anomaly Detection in Python

コードでのzスコア

from scipy.stats import zscore


scores = zscore(sales) scores[:5]
0    0.910601
1   -1.018440
2   -0.049238
3    0.849103
4   -0.695373
Anomaly Detection in Python

コードでのzスコア

is_over_3 = np.abs(scores) > 3

is_over_3[:5]
0    False
1    False
2    False
3    True
4    False
Anomaly Detection in Python

コードでのzスコア

outliers = sales[is_over_3]

print(len(outliers))
90
Anomaly Detection in Python

zスコアの欠点

  • 正規分布で最も有効
  • 平均と標準偏差は外れ値の影響が大きい
  • 外れ値が多いと性能低下
Anomaly Detection in Python

中央値絶対偏差(MAD)

  • 散らばり(ばらつき)を測る
  • 外れ値に強い
  • 中央値に基づく

中央値絶対偏差(MAD)の計算式。

Anomaly Detection in Python

MADスコア

from scipy.stats import median_abs_deviation

mad_score = median_abs_deviation(sales)

mad_score
1081.925
Anomaly Detection in Python

PyOD入門

  • MADを用いた修正zスコアはPyODで実装済み
  • PyOD(Python Outlier Detection):
    • 40以上のアルゴリズムを提供
    • すべてsklearn風の構文
Anomaly Detection in Python

修正zスコアのコード

from pyod.models.mad import MAD

# threshold defaults to 3.5
mad = MAD(threshold=3.5)


# Reshape sales sales_reshaped = sales.values.reshape(-1, 1)
Anomaly Detection in Python

修正zスコアのコード

labels = mad.fit_predict(sales_reshaped)

print(labels.sum())
83
Anomaly Detection in Python

Let's practice!

Anomaly Detection in Python

Preparing Video For Download...