outlier-detective について
outlier-detectiveは、数値データの外れ値を見つけるPythonツールです。分析担当者やデータクリーニングのワークフロー向けに、統計手法と機械学習手法、グラフ、レポートを提供します。
主な機能
- 01IQR、Z-score、Modified Z-scoreによる検出
- 02Isolation Forest、LOF、DBSCANの手法
- 03単一列と多変量の分析
- 04箱ひげ図、散布図、分布図
- 05閾値の設定とレポート生成
活用シーン
- 01CSVデータの異常値のクリーニング
- 02取引データの不審な金額の抽出
- 03複数のセンサー変数の異常分析
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ dkyazzentwatwa/ chatgpt-skills --skill outlier-detectiveインストール後、Claude Code で/outlier-detectiveを入力して読み込まれたか確認します。
同梱ファイルscripts/outlier_detective.pyscripts/requirements.txt
詳細
外れ値検出
複数の手法を使用して、数値データの異常値や外れ値を検出します。
特長
- 統計的手法:Z スコア、IQR、修正 Z スコア
- 機械学習手法:Isolation Forest、LOF、DBSCAN
- 可視化:箱ひげ図、散布図
- 複数列:複数の変数を分析
- レポート:詳細な外れ値レポート
- 柔軟なしきい値:感度を設定可能
クイックスタート
from outlier_detective import OutlierDetective
detective = OutlierDetective()
detective.load_csv("sales_data.csv")
# Detect outliers in a column
outliers = detective.detect("revenue", method="iqr")
print(f"Found {len(outliers)} outliers")
# Get full report
report = detective.analyze("revenue")
print(report)
CLI の使用方法
# Detect outliers using IQR method
python outlier_detective.py --input data.csv --column sales --method iqr
# Use Z-score with custom threshold
python outlier_detective.py --input data.csv --column price --method zscore --threshold 3
# Analyze all numeric columns
python outlier_detective.py --input data.csv --all
# Generate visualization
python outlier_detective.py --input data.csv --column revenue --plot boxplot.png
# Export outliers to CSV
python outlier_detective.py --input data.csv --column value --output outliers.csv
# Use Isolation Forest (ML)
python outlier_detective.py --input data.csv --method isolation_forest
API リファレンス
OutlierDetective クラス
class OutlierDetective:
def __init__(self)
# Data loading
def load_csv(self, filepath: str, **kwargs) -> 'OutlierDetective'
def load_dataframe(self, df: pd.DataFrame) -> 'OutlierDetective'
# Detection (single column)
def detect(self, column: str, method: str = "iqr", **kwargs) -> pd.DataFrame
def analyze(self, column: str) -> dict
# Detection (multi-column)
def detect_multivariate(self, columns: list = None, method: str = "isolation_forest") -> pd.DataFrame
def analyze_all(self) -> dict
# Visualization
def plot_boxplot(self, column: str, output: str) -> str
def plot_scatter(self, col1: str, col2: str, output: str) -> str
def plot_distribution(self, column: str, output: str) -> str
# Export
def get_outliers(self, column: str, method: str = "iqr") -> pd.DataFrame
def get_clean_data(self, column: str, method: str = "iqr") -> pd.DataFrame
検出方法
統計的手法
IQR(四分位範囲)
- デフォルトで、最も堅牢な手法です
- 外れ値:Q1 - 1.5×IQR 未満、または Q3 + 1.5×IQR を超える値
- 乗数は設定可能です(デフォルト:1.5)
outliers = detective.detect("price", method="iqr", multiplier=1.5)
Z スコア
- 平均からの標準偏差に基づきます
- 正規分布を前提とします
- しきい値は設定可能です(デフォルト:3)
outliers = detective.detect("price", method="zscore", threshold=3)
修正 Z スコア
- 平均の代わりに中央値を使用します
- 既存の外れ値の影響を受けにくい手法です
- MAD(中央絶対偏差)に基づきます
outliers = detective.detect("price", method="modified_zscore", threshold=3.5)
機械学習手法
Isolation Forest
- アンサンブル手法で、高次元データに適しています
- 汚染度パラメーターで、想定される外れ値の割合を設定します
outliers = detective.detect_multivariate(
method="isolation_forest",
contamination=0.1
)
Local Outlier Factor(LOF)
- 密度ベースの手法です
- 局所的な密度を近傍の点と比較します
outliers = detective.detect_multivariate(
method="lof",
n_neighbors=20
)
出力形式
detect() の結果
# Returns DataFrame of outlier rows with additional columns:
# - outlier_score: How extreme the value is
# - outlier_reason: Description of why it's an outlier
index value outlier_score outlier_reason
0 15 5000 4.2 Above Q3 + 1.5×IQR
1 42 -1000 -3.8 Below Q1 - 1.5×IQR
analyze() の結果
{
"column": "revenue",
"total_rows": 1000,
"outlier_count": 23,
"outlier_percent": 2.3,
"methods": {
"iqr": {"count": 23, "indices": [...]},
"zscore": {"count": 18, "indices": [...]},
"modified_zscore": {"count": 20, "indices": [...]}
},
"stats": {
"mean": 5432.10,
"median": 4890.00,
"std": 1234.56,
"min": -1000.00,
"max": 15000.00,
"q1": 3500.00,
"q3": 6200.00,
"iqr": 2700.00
},
"bounds": {
"lower": -550.00,
"upper": 10250.00
}
}
ワークフローの例
データクリーニングパイプライン
detective = OutlierDetective()
detective.load_csv("raw_data.csv")
# Analyze and visualize
report = detective.analyze("price")
print(f"Found {report['outlier_count']} outliers ({report['outlier_percent']:.1f}%)")
# Get clean data
clean_data = detective.get_clean_data("price", method="iqr")
clean_data.to_csv("clean_data.csv")
不正検出
detective = OutlierDetective()
detective.load_csv("transactions.csv")
# Use multiple methods for consensus
iqr_outliers = set(detective.detect("amount", method="iqr").index)
zscore_outliers = set(detective.detect("amount", method="zscore").index)
# Transactions flagged by both methods
high_confidence = iqr_outliers & zscore_outliers
print(f"High-confidence anomalies: {len(high_confidence)}")
複数変数の分析
detective = OutlierDetective()
detective.load_csv("sensors.csv")
# Detect multivariate outliers
outliers = detective.detect_multivariate(
columns=["temp", "pressure", "humidity"],
method="isolation_forest",
contamination=0.05
)
print(f"Anomalous readings: {len(outliers)}")
可視化の例
# Box plot with outliers highlighted
detective.plot_boxplot("revenue", "revenue_boxplot.png")
# Distribution with bounds
detective.plot_distribution("price", "price_dist.png")
# Scatter plot (2D outliers)
detective.plot_scatter("feature1", "feature2", "scatter.png")
依存関係
- pandas>=2.0.0
- numpy>=1.24.0
- scipy>=1.10.0
- scikit-learn>=1.3.0
- matplotlib>=3.7.0
コメント
Markdown 対応