anomaly-detector について
データエンジニアやアナリスト向けの異常検知スキルです。表形式データと時系列の外れ値を、統計・密度ベース・アンサンブルの手法で検出します。
主な機能
- 01Z-score と IQR による検出
- 02Modified Z-score による検出
- 03Isolation Forest と LOF
- 04Rolling と STL による時系列検出
- 05複数手法によるアンサンブル投票
活用シーン
- 01単一列の外れ値の特定
- 02複数の数値列にまたがる異常の検出
- 03トレンドや季節性のある系列の異常検出
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ majesticlabs-dev/ majestic-marketplace --skill anomaly-detectorインストール後、Claude Code で/anomaly-detectorを入力して読み込まれたか確認します。
同梱ファイルscripts/anomaly_detection.py
詳細
異常検知
対象読者: データセットの外れ値を検出するデータエンジニアやアナリスト。
目的: さまざまなデータ型に対応した、本番環境ですぐに使える異常検知関数を提供します。
スクリプト
scripts/anomaly_detection.py の検知関数を実行します。
from scripts.anomaly_detection import (
detect_anomalies_zscore,
detect_anomalies_iqr,
detect_anomalies_modified_zscore,
detect_anomalies_isolation_forest,
detect_anomalies_lof,
detect_anomalies_rolling,
detect_anomalies_stl,
detect_anomalies_ensemble
)
手法の選択
| 手法 | 最適な対象 | 制限事項 |
|---|---|---|
| Z-Score | 正規分布 | 外れ値の影響を受けやすい |
| IQR | 歪んだ分布 | 全体的に感度が低い |
| Modified Z-Score | ロバストな検知 | 計算が遅い |
| Isolation Forest | 高次元データ | パラメーター調整が必要 |
| LOF | 局所密度の異常 | 計算コストが高い |
| Rolling | トレンドのある時系列 | ウィンドウサイズに敏感 |
| STL | 季節性のある時系列 | 周期が既知である必要がある |
使用例
単一列の検知
import pandas as pd
from scripts.anomaly_detection import detect_anomalies_zscore, detect_anomalies_iqr
df = pd.read_csv('data.csv')
# Z-score method (good for normal distributions)
anomalies_z = detect_anomalies_zscore(df['value'], threshold=3.0)
# IQR method (robust to skewed data)
anomalies_iqr = detect_anomalies_iqr(df['value'], multiplier=1.5)
print(f"Z-score found {anomalies_z.sum()} anomalies")
print(f"IQR found {anomalies_iqr.sum()} anomalies")
Isolation Forest を使用した複数列の検知
from scripts.anomaly_detection import detect_anomalies_isolation_forest
numeric_cols = ['revenue', 'quantity', 'price']
anomalies = detect_anomalies_isolation_forest(df, numeric_cols, contamination=0.01)
df_anomalies = df[anomalies]
アンサンブル手法(推奨)
from scripts.anomaly_detection import detect_anomalies_ensemble
results = detect_anomalies_ensemble(
df,
columns=['revenue', 'quantity'],
methods=['zscore', 'iqr', 'isolation_forest'],
min_agreement=2 # Flag if 2+ methods agree
)
confirmed_anomalies = df[results['is_anomaly']]
時系列の異常
from scripts.anomaly_detection import detect_anomalies_rolling, detect_anomalies_stl
# Rolling window (for trending data)
anomalies = detect_anomalies_rolling(df['daily_sales'], window=7, n_std=2.0)
# STL decomposition (for seasonal data)
anomalies = detect_anomalies_stl(df['monthly_revenue'], period=12, threshold=3.0)
依存関係
pandas
numpy
scikit-learn # For Isolation Forest, LOF
statsmodels # For STL decomposition
コメント
Markdown 対応