「堅牢な」データサイエンティスト:汚れたデータとPingouin で勝利する
本記事は、現実世界のノイズや外れ値に強い「ロバスト統計」の重要性を説き、Python の Pingouin ライブラリを用いた具体的な実装アプローチを紹介している。
キーポイント
教科書と現実のギャップ
理想化されたデータセットで教えられる統計手法は、外れ値や歪んだ分布が多い現場では機能しないという課題を提起する。
ロバスト統計の導入
古典的な仮定(正規性など)を満たさないデータに対しても信頼性の高い結果をもたらす数学的手法である「ロバスト統計」の活用を推奨する。
Pingouin を用いた実践
Python の Pingouin ライブラリを活用し、ワイン品質データセットのような messy なデータに対して、外れ値や仮定違反を検出・処理する具体的なコード例を示す。
シナリオ別アプローチ
データの異なる問題点(外れ値、非正規分布など)に応じた「Choose your own adventure」形式の解決策を提示し、現場での適用可能性を高める。
正規性テストの失敗とリスク
ワインのアルコール含有量データは正規分布に従わないため、通常の t テストを使用すると外れ値の影響を受けやすく、信頼性の低い結果を招く可能性があります。
マン・ホイットニー U 検定の有効性
平均値ではなくデータの順位(ランク)を比較するマン・ホイットニー U 検定は、外れ値の極端な大きさの影響を排除し、歪んだデータでも頑健な分析結果をもたらします。
ペアデータに非正規分布がある場合の対応
標準的なペア t テストは差の分布が正規でない場合に信頼区間を歪めるため、Wilcoxon符号付順位検定(pg.wilcoxon)を使用する。
重要な引用
"textbook data science usually becomes a lie in the real world."
"Throwing the data away isn't the solution: turning robust is."
"These are mathematical methods particularly built to yield reliable and valid results even when the data does not meet classical assumptions or is pervaded by outliers and noise."
This rank-based approach is the master trick that strips outliers of their sometimes dangerous magnitude.
Since the p-value is not below 0.05, there is no statistically significant difference in alcohol content between the two wine types — and this conclusion is guaranteed to be outlier-proof and skewness-proof.
"The ideal fix in this scenario is the Wilcoxon Signed-Rank Test: the robust sibling of the paired t-test"
影響分析・編集コメントを表示
影響分析
この記事は、データサイエンティストが現場で直面する「データの質」の問題に対して、理論的な裏付けと実用的なツール(Pingouin)を組み合わせた解決策を提供しています。教科書通りのアプローチに依存せず、ロバスト統計の重要性を再認識させることで、より堅牢な分析プロセスの構築を促す影響があります。
編集コメント
理想化された理論と現実のデータのギャップを埋めるための、非常に実践的なガイドラインです。特に初学者や現場でデータクレンジングに悩むエンジニアにとって即戦力となる知見が含まれています。
画像は編集者によるものです
# イントロダクション
まず厳しい真実を述べましょう:教科書的なデータサイエンスは、現実世界では嘘になることがよくあります。概念や技術は、細かく選別された美しくベルカーブを描くデータ変数に基づいて教えられますが、一旦実際のプロジェクトの荒野へと足を踏み入れると、多くの外れ値、不当に歪んだ分布、そして不屈的な分散に直面させられます。
Pingouin を用いた探索的データ分析(EDA: Exploratory Data Analysis)パイプラインの構築に関する以前の論文では、同分散性や正規性といったさまざまな仮定をデータが違反しているケースを統計検定を通じて検出する方法が示されました。しかし、もしその検定が失敗したらどうなるでしょうか?データを捨ててしまうのは解決策ではありません:ロバスト(頑健)になることです。
本記事では、データサイエンスプロセスにおいてロバスト統計学を活用する職人技を明らかにします。これらは、データが古典的な仮定を満たさない場合や、外れ値やノイズに満ちている場合でも、信頼性が高く有効な結果をもたらすために特別に設計された数学的手法です。「自分自身で冒険を選ぶ」アプローチを採用し、Python の Pingouin を用いて、日常業務で遭遇する可能性のあるデータ内の最も醜い側面を管理するための 3 つのシナリオを作成します。
# 初期セットアップ
**
まずは、必要であれば Pingouin と Pandas をインストールし、インポートします。その後、こちら で入手可能なワインの品質データセットを読み込みます。
!pip install pingouin pandas
import pandas as pd
import pingouin as pg
赤ワインと白ワインのサンプルを含む、現実世界のような messy なデータセットを読み込む
url = "https://raw.githubusercontent.com/gakudo-ai/open-datasets/refs/heads/main/wine-quality-white-and-red.csv"
df = pd.read_csv(url)
これから扱う内容を確認するために少しだけ覗いてみる
df.head()
もし以前の Pingouin 記事をご覧になった方であれば、このデータセットが非常に messy で、いくつかの一般的な仮定を満たしていないことは既にご存知でしょう。今からは 3 つの異なる「冒険」に取り組みます。それぞれが特定のシナリオ、中核的な問題、そしてそれに対処するための提案された堅牢な解決策を強調するものです。
// 冒険 1: 正規性検定が失敗した場合
白ワインサンプルと赤ワインサンプルの 2 つのグループに対して正規性検定を実行すると仮定します。
white_wine_alcohol = df[df['type'] == 'white']['alcohol']
red_wine_alcohol = df[df['type'] == 'red']['alcohol']
print("白ワインアルコール含有量の正規性検定:")
print(pg.normality(white_wine_alcohol))
print("\n赤ワインアルコール含有量の正規性検定:")
print(pg.normality(red_wine_alcohol))
どちらの分布も正規分布ではないことがわかります。p 値は極めて低く、非正規性そのものが直接外れ値や歪みを示すわけではありませんが、正規性からの強い逸脱は、データにそのような特性が存在する可能性を示唆しています。このような状況で t テストを用いて平均を比較するのは危険であり、信頼性の低い結果をもたらす可能性が高いです。
このようなシナリオに対する堅牢な解決策はマン・ホイットニー U 検定(Mann-Whitney U test)です。この検定では平均値を比較するのではなく、データ内の順位を比較します。例えば、あるグループ内のすべてのワインをアルコール含有量の低い順から高い順に並べ替えるようなアプローチです。この順位ベースのアプローチは、外れ値が持つ時として危険な大きさを取り除くための主要なトリックとなります。具体的な手順は以下の通りです。
2 つのグループを分離する
red_wine = df[df['type'] == 'red']['alcohol']
white_wine = df[df['type'] == 'white']['alcohol']
堅牢なマン・ホイットニー U 検定の実行
mwu_results = pg.mwu(x=red_wine, y=white_wine)
print(mwu_results)
出力:
U_val alternative p_val RBC CLES
MWU 3829043.5 two-sided 0.181845 -0.022193 0.488903
p 値が 0.05 より下回らないため、2 つのワインタイプ間でアルコール含有量に統計的に有意な差はありません。この結論は、外れ値や歪みに対して頑健であることが保証されています。
// アドベンチャー 2: ペア付き t テストが失敗する場合
同じ被験者から取得した2つの測定値を比較したい場合を考えてみましょう。例えば、薬物プロトタイプの投与前後の患者の血糖値や、同一のワインボトルで測定された2つの性質などです。ここでは、対になった測定値間の*差*がどのように分布しているかに焦点を当てます。これらの差が正規分布しない場合、標準的な対応のある t 検定では信頼区間が不正確な結果をもたらす可能性があります。
このシナリオにおける理想的な解決策はウィルコクソンの符号付順位和検定 (Wilcoxon Signed-Rank Test)です。これは対応のある t 検定の堅牢な兄弟であり、列間の差を観察し、その絶対値の順位をつけることで機能します。Pingouin では、この検定は pg.wilcoxon() を使用して実行され、同じ被験者内の対になった測定値を含む2つの列(例えば、2種類のワインの酸度)を引数として渡します。
対応データに対する堅牢なウィルコクソンの符号付順位和検定を実行する
wilcoxon_results = pg.wilcoxon(x=df['fixed acidity'], y=df['volatile acidity'])
print(wilcoxon_results)
結果:
W_val alternative p_val RBC CLES
Wilcoxon 0.0 two-sided 0.0 1.0 1.0
上記の結果は、2つの測定値間に統計的に有意な差、あるいは「完全な分離」があることを示しています。2つのワインの性質が異なるだけでなく、データセット全体を通じて全く異なる規模の階層で機能していることもわかります。
// アドベンチャー 3: ANOVA が失敗する場合
この3回目かつ最後の冒険では、ワインの品質評価(3から9までの整数値であり、離散的なカテゴリとして扱える)間で残糖レベルが有意に異なるかどうかを確認したいと考えます。
Pingouin の等分散性検定である Levene 検定が劇的に失敗した場合 — 例えば、中程度のワインでは糖分の変動が非常に大きいのに、最高品質のワインでは変動が極めて小さい場合など — 、この検定はグループ間の等分散を前提としているため、古典的な一元配置分散分析(ANOVA)は誤った結果をもたらす可能性があります。
その解決策はWelch の ANOVAです。これは変異度の高いグループにペナルティを与え、尺度のバランスを整えて複数のカテゴリ間での比較をより公平に行うものです。Pingouin を用いて従来の ANOVA に代わるこの堅牢な手法を実行する方法は以下の通りです:
品質評価間で糖分を比較するために Welch の ANOVA を実行する
welch_results = pg.welch_anova(data=df, dv='residual sugar', between='quality')
print(welch_results)
結果:
Source ddof1 ddof2 F p_unc np2
0 quality 6 54.507934 10.918282 5.937951e-08 0.008353
等分散性の違いにより一元配置 ANOVA が困難を極めた場合でも、Welch の ANOVA は確固たる結論をもたらします。非常に小さな p 値は、残糖レベルがワインの品質評価間で有意に異なることを明確な証拠として示しています。ただし、糖分はワインの品質に影響を与えるパズルの一部に過ぎず、その低めのエータ二乗値(0.008)がこの点を強調していることに留意してください。
まとめ
3 つの例シナリオを通じて、それぞれが厄介なデータの問題と堅牢な統計戦略を対にすることで、熟練したデータサイエンティストであることは、データを完璧に持つことや完全に調整することではないことがわかりました。それは、データがさまざまな理由で扱いにくくなったときに何をすべきかを知っていることです。Pingouin の関数は、失敗した仮定という罠から脱出し、わずかな追加努力で数学的に妥当な洞察を引き出すための多様な堅牢な検定を実装しています。
Iván Palomares Carrascosa は、AI、機械学習、ディープラーニング、LLM におけるリーダー、作家、スピーカー、そしてアドバイザーです。彼は、現実世界で AI を活用する方法を他者に指導・訓練しています。
原文を表示

**
Image by Editor
# Introduction
A harsh truth to begin with: textbook data science** usually becomes a lie in the real world. Concepts and techniques are taught on finely curated, beautifully bell-curved data variables, but as soon as we venture into the wild of real projects, we are hit with lots of outliers, unduly skewed distributions, and indomitable variances.
A previous article on building an exploratory data analysis (EDA) pipeline with Pingouin showed how to detect, through tests, cases when the data violates a variety of assumptions like homoscedasticity and normality. But what if the tests fail? Throwing the data away isn't the solution: turning robust is.
This article uncovers the craftsmanship of using robust statistics in data science processes. These are mathematical methods particularly built to yield reliable and valid results even when the data does not meet classical assumptions or is pervaded by outliers and noise. By adopting a "choose your own adventure" approach, we will create a trio of scenarios using Python's Pingouin to manage the ugliest aspects within the data you may encounter in your daily work.
# Initial Setup
**
Let's start by installing (if needed) and importing Pingouin and Pandas**, after which we will load the wine quality dataset available here.
!pip install pingouin pandas
import pandas as pd
import pingouin as pg
# Loading our messy, real-world-like dataset, containing red and white wine samples
url = "https://raw.githubusercontent.com/gakudo-ai/open-datasets/refs/heads/main/wine-quality-white-and-red.csv"
df = pd.read_csv(url)
# Take a small peek at what we are about to deal with
df.head()If you looked at the previous Pingouin article, you already know this is a notoriously messy dataset that failed to meet several common assumptions. Now we will embark on three different "adventures", each highlighting a scenario, a core problem, and a proposed robust fix to address it.
// Adventure 1: When the Normality Test Fails
Suppose we run normality tests on two groups: white wine samples and red wine samples.
white_wine_alcohol = df[df['type'] == 'white']['alcohol']
red_wine_alcohol = df[df['type'] == 'red']['alcohol']
print("Normality test for White Wine Alcohol content:")
print(pg.normality(white_wine_alcohol))
print("\nNormality test for Red Wine Alcohol content:")
print(pg.normality(red_wine_alcohol))You will find that neither distribution is normal, with extremely low p-values. Although non-normality itself doesn't directly signal outliers or skewness, a strong deviation from normality often suggests such characteristics may be present in the data. Comparing means through a t-test in this situation would be dangerous and likely to yield unreliable results.
The robust fix for a scenario like this is the Mann-Whitney U test. Instead of comparing averages, this test compares the ranks in the data — sorting all wines in a group from lowest to highest alcohol content, for instance. This rank-based approach is the master trick that strips outliers of their sometimes dangerous magnitude. Here's how:
# Separating our two groups
red_wine = df[df['type'] == 'red']['alcohol']
white_wine = df[df['type'] == 'white']['alcohol']
# Running the robust Mann-Whitney U test
mwu_results = pg.mwu(x=red_wine, y=white_wine)
print(mwu_results)Output:
U_val alternative p_val RBC CLES
MWU 3829043.5 two-sided 0.181845 -0.022193 0.488903Since the p-value is not below 0.05, there is no statistically significant difference in alcohol content between the two wine types — and this conclusion is guaranteed to be outlier-proof and skewness-proof.
// Adventure 2: When the Paired T-Test Fails
Say you now want to compare two measurements taken from the same subject — e.g. a patient's sugar level before and after a drug prototype, or two properties measured in the same bottle of wine. The focus here is on how the *differences* between paired measurements are distributed. When such differences are not normally distributed, a standard paired t-test will yield unreliable confidence intervals.
The ideal fix in this scenario is the Wilcoxon Signed-Rank Test: the robust sibling of the paired t-test, which works by observing the differences between columns and ranking their absolute values. In Pingouin, this test is called using pg.wilcoxon(), passing in the two columns containing the paired measures within the same subject — e.g. two types of wine acidity.
# Run the robust Wilcoxon signed-rank test for paired data
wilcoxon_results = pg.wilcoxon(x=df['fixed acidity'], y=df['volatile acidity'])
print(wilcoxon_results)Result:
W_val alternative p_val RBC CLES
Wilcoxon 0.0 two-sided 0.0 1.0 1.0The result above shows a statistically significant difference, or "perfect separation," between the two measurements. Not only are the two wine properties different, but they also operate at entirely different magnitude tiers across the dataset.
// Adventure 3: When ANOVA Fails
In this third and final adventure, we want to check whether residual sugar levels in wine differ significantly across distinct quality ratings — note that the latter range between 3 and 9, taking integer values, and can therefore be treated as discrete categories.
If Pingouin's Levene test of homoscedasticity fails dramatically — for instance, because sugar variance in mediocre wines is huge but very small in top-quality wines — a classical one-way ANOVA may produce misleading results, as this test assumes equal variances among groups.
The fix is Welch's ANOVA, which penalizes groups with high variance, thereby balancing out scales and making comparisons fairer across several categories. Here is how to run this robust alternative to traditional ANOVA using Pingouin:
# Run Welch's ANOVA to compare sugar across quality ratings
welch_results = pg.welch_anova(data=df, dv='residual sugar', between='quality')
print(welch_results)Result:
Source ddof1 ddof2 F p_unc np2
0 quality 6 54.507934 10.918282 5.937951e-08 0.008353Even where a one-way ANOVA might have struggled due to unequal variances, Welch's ANOVA delivers a solid conclusion. The very small p-value is clear evidence that residual sugar levels differ significantly across wine quality ratings. Bear in mind, however, that sugar is only a small piece of the puzzle influencing wine quality — a point underscored by the low eta-squared value of 0.008.
# Wrapping Up
Through three example scenarios, each pairing a messy-data problem with a robust statistical strategy, we have learned that being a skilled data scientist doesn't mean having perfect data or tuning it perfectly — it means knowing what to do when the data gets difficult for different reasons. Pingouin's functions implement a variety of robust tests that help escape the failed-assumptions trap and extract mathematically sound insights with little extra effort.
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.
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み