堅牢な外れ値検出のための5 つの必須アプローチ
KDnuggets は、データ品質の向上とモデルの信頼性確保のために不可欠な堅牢な外れ値検出のための 5 つの実践的アプローチを体系的に解説している。
キーポイント
統計的手法の活用
IQR(四分位範囲)や Z スコアなどの古典的な統計手法を用いて、データ分布から外れ値を定量的に特定する基礎的なアプローチ。
機械学習ベースのアプローチ
Isolation Forest や Local Outlier Factor (LOF) といった教師なし学習アルゴリズムを活用し、多次元データにおける複雑な外れ値パターンを検出する手法。
深層学習による検出
オートエンコーダーなどのニューラルネットワークを用いて、データの再構成誤差に基づき異常を検出する高度な手法で、非線形な関係性を捉えることに優れる。
ドメイン知識の統合
純粋な数値計算だけでなく、業務領域特有のルールや文脈情報を組み合わせて判断することで、誤検知を減らし実用性を高める重要な要素。
影響分析・編集コメントを表示
影響分析
この記事は、データサイエンスの実務において外れ値処理がモデル性能に与える影響を理解し、適切な手法を選択するための指針となる。特に、単純な統計量から機械学習まで段階的なアプローチを提示することで、現場のエンジニアやアナリストが状況に応じた最適なソリューションを選定する際の判断材料を提供している。
編集コメント
実務でモデルの精度が思わしくない場合、外れ値の扱い方が原因となっているケースが多いため、本記事の手法を再検討する価値があります。特にドメイン知識との融合は、AI システムの実用化において見過ごされがちだが極めて重要なポイントです。
image**
# イントロダクション
データセットを探索している際、何か*奇妙な*データポイントに出会ったことはありませんか?観測値の绝大多数とは不釣り合いに異なるように見える1つまたは数個のポイントが、平均値を大幅に歪め、分散を膨らませてしまうことがあります。私もそのような経験があります。これらのポイントは外れ値(アウトライヤー)です。その影響はデータ統計量を変更するだけに留まりません:外れ値は構築した予測分析モデルのパフォーマンスを容易に損なうため、あらゆるデータプロジェクトにおいてそれらを堅牢に検出し処理することは極めて重要です。この記事では、これらを検出するための5つの本質的なアプローチを列挙・比較し、それぞれについて短いPythonの例を示します。
# 1. Z スコア法
Z スコア計算は、正規分布するデータ変数に対して最もよく機能するシンプルな手法です。これは各ポイントが平均値から標準偏差で何個分離れているかを測定します。本質的に、Z スコアが3以上(または-3以下)であるデータポイントは外れ値としてフラグ付けされます:つまり、そのポイントと平均値の間に3つの標準偏差を超える距離があることを意味します。シンプルさゆえに優れていますが、平均値や標準偏差が極端な値に対して本質的に非常に敏感であるという欠点があります。
import numpy as np
from scipy import stats
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250])
z_scores = np.abs(stats.zscore(data))
outliers = data[z_scores > 3]
print(outliers)出力:
[250]
# 2. 四分位範囲(IQR)法
あなたのデータ変数が正規分布していない場合、Z スコア計算よりも IQR の方がより堅牢で信頼性の高い選択肢となります。この手法はパーセンタイルを使用し、具体的には第 1 四分位数(Q1、25 パーセンタイル)と第 3 四分位数(Q3、75 パーセンタイル)の間の広がりを特定することで機能します。Q1 の 1.5 倍 IQR 未満および Q3 の 1.5 倍 IQR 以上の境界点を以下のように計算し、これらが「フェンス」として機能します。つまり、これらの 2 つのフェンスのどちら側にも外れた点は異常値としてフラグが立てられます。朗報は、IQR の堅牢性は極端な値が平均や標準偏差を歪めるように四分位数を変化させないという事実に基づいている点です。
import numpy as np
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250])
q1, q3 = np.percentile(data, [25, 75])
iqr = q3 - q1
lower_fence = q1 - 1.5 * iqr
upper_fence = q3 + 1.5 * iqr
outliers = data[(data < lower_fence) | (data > upper_fence)]
print(outliers)
出力:
[250]
# 3. イソレーションフォレスト
多次元データを扱う際、Z スコアや IQR(四分位範囲)といった従来の手法はもはや効果的ではありません。そこで登場するのがアイソレーションフォレストです。これは異常値を「正常」なデータから分離することを学習する機械学習の手法です。この考え方は、分類や回帰のための古典的な決定木に似ています。外れ値は稀なデータポイントであるため、ツリー分割を通じてそれらを分離するのは非常に容易です。したがって、ある点がツリーアルゴリズムによって他の点から非常に簡単に分離される場合、それは外れ値である可能性が高いのです。
import numpy as np
from sklearn.ensemble import IsolationForest
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250]).reshape(-1, 1)
model = IsolationForest(contamination=0.1, random_state=42)
predictions = model.fit_predict(data)
outliers = data[predictions == -1]
print(outliers)
Output:
[[250]]
# 4. メディアン絶対偏差 (MAD: Median Absolute Deviation)
これは、いわば Z スコアのより頑健なバージョンです。MAD は極端な値に耐性のある中央値(メディアン)を使用し、そこから計算される絶対偏差を用いて、強化された「Z スコア」を算出します。ただし注意が必要なのは、この手法は非正規分布の変数にも適用可能ですが、通常は 1 次元データに対して用いられるため、単変量解析の技術であるということです。
import numpy as np
from scipy.stats import median_abs_deviation
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250])
mad = median_abs_deviation(data, scale="normal")
median = np.median(data)
modified_z_scores = np.abs(data - median) / mad
outliers = data[modified_z_scores > 3]
print(outliers)
Output:
[250]
# 5.密度ベースクラスタリング:DBSCAN
これは、空間データや複雑なグループ構造を持つデータセットにおける外れ値の特定に優れたアプローチです。DBSCAN** アルゴリズムは、高密度領域において互いに近接した点を中心にグループを構築します。適用過程では、低密度領域に孤立しているデータ点は自動的にノイズ、つまり外れ値として識別されます。方法 3(アイソレーションフォレスト)と同様に、これは多変量手法であり、外れ値検出プロセスにおいて多次元データポイントを評価することを可能にします。
import numpy as np
from sklearn.cluster import DBSCAN
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250]).reshape(-1, 1)
model = DBSCAN(eps=5, min_samples=2)
labels = model.fit_predict(data)
outliers = data[labels == -1]
print(outliers)
Output:
[250]
# まとめ
適切な外れ値検出手法を選ぶことは、データを理解することにかかっています。Z スコアと IQR は単変量データに対する迅速でシンプルな選択肢であり、特に変数が正規分布しない場合には IQR がより安全な選択となります。MAD は、極端な値が結果を歪める可能性がある場合に、より頑健な単変量の代替手段を提供します。データに多次元性或は複雑な構造がある場合、アイソレーションフォレストや DBSCAN は単純な統計的閾値を超えて外れ値検出を拡張し、単純な手法では捉えきれない関係性を捉えます。唯一最善のアプローチというものは存在せず、データの形状と規模に最も適したものを選ぶだけです。
Iván Palomares Carrascosa は、AI、機械学習、ディープラーニング、LLM におけるリーダー、作家、スピーカー、そしてアドバイザーです。彼は現実世界で AI を活用する方法を他者に指導・訓練しています。
原文を表示

**
# Introduction
Ever come across some *weird* data points in your dataset while exploring it? One or a few that seem unduly different from the vast majority of observations, thus drastically skewing your means and inflating variances? I've been there, too. These points are outliers**. Their impact isn't limited to altering data statistics: outliers can easily ruin the performance of any predictive analysis models you build, so robustly detecting and handling them is crucial in any data project. This article lists and compares five essential approaches for detecting them, along with a short Python example for each.
# 1. The Z-Score Method
**
The Z-score calculation is a simple method that works best for data variables that are normally distributed. It measures how many standard deviations each point lies from the mean. In essence, a data point whose Z-score is 3 or higher (or -3 or lower) is flagged as an outlier: that means there's a distance of more than three standard deviations between that point and the mean. Despite its simplicity, it has the drawback that means and standard deviations are inherently highly sensitive to extreme values.
import numpy as np
from scipy import stats
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250])
z_scores = np.abs(stats.zscore(data))
outliers = data[z_scores > 3]
print(outliers)Output:
[250]# 2. The Interquartile Range (IQR) Method
Are your data variables not normally distributed? Then the IQR is a better and more robust bet than Z-score calculations. This method uses percentiles, specifically by determining the spread between the first quartile (Q1, 25th percentile) and the third quartile (Q3, 75th percentile). Boundary points lying 1.5 times the IQR below Q1 and above Q3 are calculated, as shown below, and they act as a "fence." In other words, any point falling outside these two fences on either side is flagged as an outlier. The good news: the IQR's robustness stems from the fact that extreme values don't alter quartiles the way they alter means and standard deviations.
import numpy as np
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250])
q1, q3 = np.percentile(data, [25, 75])
iqr = q3 - q1
lower_fence = q1 - 1.5 * iqr
upper_fence = q3 + 1.5 * iqr
outliers = data[(data < lower_fence) | (data > upper_fence)]
print(outliers)Output:
[250]# 3. Isolation Forests
When handling complex datasets with high dimensionality, traditional methods like Z-scores and the IQR are no longer effective. Enter isolation forests, a machine learning technique that learns to isolate anomalies from "normal" data. The idea resembles that of classical decision trees for classification and regression: outliers are rare data points, so isolating them through tree partitions is much easier. Thus, when a point is very easily separated from others by the tree algorithm, chances are it's an outlier.
import numpy as np
from sklearn.ensemble import IsolationForest
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250]).reshape(-1, 1)
model = IsolationForest(contamination=0.1, random_state=42)
predictions = model.fit_predict(data)
outliers = data[predictions == -1]
print(outliers)Output:
[[250]]# 4. Median Absolute Deviation (MAD)
This is a considerably more robust version of the Z-score, so to speak: MAD uses the median — immune to extreme values — and absolute deviations from it to calculate an enhanced "Z-score." Be aware, though, that even though it can be applied to non-normal variables, it is normally used on one-dimensional data, i.e. it is a univariate technique.
import numpy as np
from scipy.stats import median_abs_deviation
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250])
mad = median_abs_deviation(data, scale="normal")
median = np.median(data)
modified_z_scores = np.abs(data - median) / mad
outliers = data[modified_z_scores > 3]
print(outliers)Output:
[250]# 5. Density-Based Clustering: DBSCAN
This is a great approach for identifying outliers in spatial data or datasets with complex groupings. The DBSCAN** algorithm builds groups around points that are close to each other in areas of high density. During its application, data points isolated in lower-density areas are automatically identified as noise, i.e. outliers. Just like method number 3 (isolation forests), this is a multivariate technique that allows for evaluating multi-dimensional data points in the outlier detection process.
import numpy as np
from sklearn.cluster import DBSCAN
data = np.array([10, 12, 11, 13, 12, 11, 10, 12, 11, 13, 250]).reshape(-1, 1)
model = DBSCAN(eps=5, min_samples=2)
labels = model.fit_predict(data)
outliers = data[labels == -1]
print(outliers)Output:
[250]# Wrapping Up
Choosing the right outlier detection method comes down to understanding your data. The Z-score and the IQR are quick, simple options for univariate data, with the IQR being the safer choice when your variables are not normally distributed. MAD offers a more robust univariate alternative for cases where extreme values could otherwise skew the result. When your data has multiple dimensions or complex structure, isolation forests and DBSCAN extend outlier detection beyond simple statistical thresholds, capturing relationships that the simpler methods miss entirely. There is no single best approach, only the one best suited to the shape and scale of your data.
Iván Palomares Carrascosa is a leader, writer, speaker, and adviser in AI, machine learning, deep learning & LLMs. He trains and guides others in harnessing AI in the real world.
関連記事
データサイエンティストが知っておくべき実用的な SQL の技
KDnuggets は、データサイエンティストが効率的にデータを処理するために役立つ実践的な SQL のテクニックを紹介している。
AI が読みやすい文書へ再フォーマットする提案:5 分で読める記事
著者は、AI が文書をより理解しやすく処理できるよう、すべてのドキュメントを再フォーマットするよう提案している。このアプローチにより、AI との相互作用が改善される可能性がある。
データクリーニングと前処理のための Pandas の 3 つの技
KDnuggets が紹介する記事で、Pandas ライブラリを用いたデータクリーニングと前処理を効率化する 3 つの実用的なテクニックが解説されています。
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み