Pingouin を用いた現代的な EDA パイプラインの構築
この記事は、Pingouin ライブラリを活用して SciPy と pandas の統合を図り、機械学習モデルの前提条件を検証する堅牢な探索的データ分析(EDA)パイプラインを構築する方法を解説している。
キーポイント
GIGO 原則と EDA の重要性
「ガベージイン・ガベージアウト」の原則に基づき、線形回帰や ANOVA などの統計的仮定を満たさないデータを入力するとモデルが機能しないことを強調し、単なる可視化を超えた厳密な検証の必要性を説く。
Pingouin の役割と統合
Pingouin が SciPy と pandas を橋渡しするライブラリとして機能し、統計的仮定(正規性など)を自動的に検証することで、自動化された堅牢な EDA パイプラインの構築を可能にする。
単変量正規性の検定
機械学習アルゴリズムや統計テストの多くが連続変数の正規分布を前提としているため、Pingouin を用いてデータセット内の各変数が正規分布に従っているかを厳密にチェックする手順を示す。
実践的な実装例
ワインの品質データセットを用いた具体的な Python コード例を提供し、ライブラリのインストールからデータの読み込み、可視化までの実際のワークフローを提示している。
単変量正規性の確認と対応
Shapiro-Wilk検定により特徴量の正規性が確認され、本データセットではすべて非正規であることが示された。この場合、後続のモデル学習前にlog変換やBox-Cox変換などの前処理を検討する必要がある。
多変量正規性の評価とモデル選択
Henze-Zirkler検定を用いて特徴量間の相互作用を含めた多変量正規性を確認した結果、これも成立していないことが判明した。この場合、線形回帰やSVMなどのパラメトリックモデルよりも、勾配ブースティングやランダムフォレストなどのノンパラメトリック・ツリーベースモデルがより堅牢な選択肢となる。
等分散性の確認と異分散性問題
PingouinのLevene検定を用いて変数の分散が一定か(等分散性)を確認し、結果がFalseの場合は異分散性(heteroscedasticity)の問題があることを示唆します。
重要な引用
the golden rule of downstream machine learning modeling, known as garbage in, garbage out (GIGO)
Pingouin helps do this by bridging the gap between two well-known libraries in data science and statistics: SciPy and pandas
Many traditional algorithms for training machine learning models — and statistical tests like ANOVAs and t-tests, for that matter — need the assumption that continuous variables
If you are going to train a machine learning model on this dataset, this means non-parametric, tree-based models like gradient boosting and random forests might be a more robust alternative than parametric, weight-based models like SVM, linear regression, and so on.
detecting them and knowing what to do about them before downstream, machine learning analysis is far better than building a potentially flawed model.
PCA will be rendered rather useless in case there are not any: [correlations between variables].
影響分析・編集コメントを表示
影響分析
この記事は、機械学習プロジェクトの初期段階における「データの質」への意識を高める重要な役割を果たします。特に、統計的仮定を満たさないデータをそのままモデルに投入するリスクを軽減し、再現性の高い分析基盤を構築するための具体的な手法(Pingouin の活用)を提供している点で実務家にとって有益です。ただし、特定のライブラリの紹介に留まるため、業界全体を揺るがすような技術的ブレイクスルーというよりは、標準的なデータサイエンスプラクティスの強化と捉えるべきです。
編集コメント
データサイエンスの現場では、モデル構築前にデータの統計的性質を厳密に検証する工程がしばしば軽視されがちですが、この記事はその重要性を再認識させる良い教材です。Pingouin のような専用ライブラリを活用することで、手動でのチェックから解放され、より効率的で信頼性の高いパイプラインを構築できるでしょう。

# イントロダクション
データサイエンスにそれなりの時間を費やした人なら、遅かれ早かれ何かを学ぶはずです:下流の機械学習モデリングにおける黄金律として知られる「ガベージイン・ガベージアウト」(GIGO) です。
例えば、高度な共線性を持つデータを線形回帰モデルに供給したり、不均一分散に対して分散分析 (ANOVA: Analysis of Variance) テストを実行したりすることは、適切に学習しない非効果的なモデルを作るための完璧なレシピです。
探索的データ分析 (EDA) は、散布図やヒストグラムなどの可視化において多くのことを示唆しますが、下流の分析やモデルに必要な数学的仮説に対してデータを厳密に検証する必要がある場合、それだけでは不十分です。Pingouin は、データサイエンスと統計学の2 つのよく知られたライブラリである SciPy と pandas の間のギャップを埋めることでこれを可能にします。さらに、堅牢で自動化された EDA パイプラインを構築するための素晴らしい味方にもなります。この記事では、重要なデータ特性のいくつかを検証する厳密な統計的 EDA 用の包括的なパイプラインを構築する方法を学びます。
# 初期セットアップ
まず、Python 環境に Pingouin (まだ pandas がインストールされていない場合はそちらも) をインストールすることを確認しましょう:
!pip install pingouin pandas
その後、これらの主要ライブラリをインポートし、データをロードする時間です。例として、ワインの特性とその品質を含むサンプルデータを持つオープンなデータセットを使用します。
import pandas as pd
import pingouin as pg
オープンデータセット GitHub リポジトリからワインデータセットを読み込む
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()
# 単変量正規性の確認
私たちが実施する特定の探索的解析の第一歩は、単変量正規性(univariate normality)の確認に関するものです。機械学習モデルをトレーニングするための多くの従来のアルゴリズムや、統計検定である分散分析(ANOVA)や t 検定も、連続変数が正規分布、すなわちガウス分布に従うという仮定を必要とします。Pingouin の pg.normality() 関数は、データフレーム全体にわたるシャピロ・ウィルク検定(Shapiro-Wilk test)を通じてこの確認を行うのを助けます:
正規性チェックのための連続変数のサブセットを選択する
features = ['fixed acidity', 'volatile acidity', 'citric acid', 'pH', 'alcohol']
正規性検定を実行する
normality_results = pg.normality(df[features])
print(normality_results)
出力:
W pval normal
固定酸度 0.879789 2.437973e-57 False
揮発性酸度 0.875867 6.255995e-58 False
クエン酸 0.964977 5.262332e-37 False
pH 0.991448 2.204049e-19 False
アルコール 0.953532 2.918847e-41 False
手元にある数値特徴量のいずれも正規性を満たしていないようです。これはデータに何らかの欠陥があるわけではなく、単にそのデータが持つ特性の一部です。私たちが受け取っているメッセージは、探索的データ分析(EDA)を超えた後のデータ前処理ステップにおいて、生データをより「正規分布に近い」形に変換し、正規性を前提とするモデルに適した形にするために、対数変換やボックス・コックス変換などのデータ変換を適用することを検討する必要があるということです。
# 多変量正規性の確認
同様に、特徴量を一つずつ評価するのではなく、特徴量間の相互作用を考慮して正規性を評価することも、 inspect すべき興味深い側面です。例えば、多変量分散分析(MANOVA)のような手法における重要な要件である多変量正規性をどのようにチェックするかを見てみましょう。
Henze-Zirkler 多変量正規性検定
multivariate_normality_results = pg.multivariate_normality(df[features])
print(multivariate_normality_results)
出力:
HZResults(hz=np.float64(23.72107048442373), pval=np.float64(0.0), normal=False)
そして、予想外かもしれませんが、HZResults(hz=np.float64(23.72107048442373), pval=np.float64(0.0), normal=False) のような結果が得られる可能性があります。これは、多変量正規性も成り立たないことを意味します。このデータセットで機械学習モデルを訓練する予定であれば、SVM や線形回帰などのパラメトリックな重みベースのモデルよりも、勾配ブースティングやランダムフォレストのようなノンパラメトリックなツリーベースのモデルの方が、より堅牢な代替手段となり得ます。
# 等分散性の確認
次に、非常に単純な概念に対してややこしい用語が登場します:等分散性(homoscedasticity)**です。これは予測における誤差全体にわたる分散が等しい、あるいは一定であることを指し、信頼性の尺度として解釈されます。この性質をテストするために(申し訳ありませんが、名前を書くのがまた難しいので!)、Pingouin の実装であるレヴェンの検定(Levene's test)を用います。以下のように実行します:
グループ間での等分散性に対するレヴェンの検定
'dv' は目的変数(従属変数)、'group' はカテゴリカル変数です
homoscedasticity_results = pg.homoscedasticity(data=df, dv='alcohol', group='quality')
print(homoscedasticity_results)
結果:
W pval equal_var
levene 66.338684 2.317649e-80 False
再び False が得られたため、いわゆる不均分散性(heteroscedasticity)の問題を抱えていることになります。これは下流の分析において考慮する必要があります。一つの可能な対処法は、回帰モデルを訓練する際に頑健な標準誤差(robust standard errors)を採用することです。
# 球面性の確認
**
分析すべきもう一つの統計的性質は球面性(sphericity)であり、これは可能な条件のすべての対組合せ間の差の分散が等しいかどうかを識別するものです。次元削減のための主成分分析(PCA: Principal Component Analysis)を実行する前にこの性質を検証することが通常望ましく、それは変数間に相関があるかどうかを理解するのに役立ちます。もし相関がない場合、PCA はむしろ役に立たないものになります:
Mauchly の球面性検定
sphericity_results = pg.sphericity(df[features])
print(sphericity_results)
結果:
SpherResults(spher=False, W=np.float64(0.004437706589942777), chi2=np.float64(35184.26583883276), dof=9, pval=np.float64(0.0))
どうやら私たちは非常に不屈で乾燥したデータセットを選んでしまったようです!しかし恐れることはありません。この記事は意図的に EDA(探索的データ分析)プロセスに焦点を当て、このような多くのデータ上の問題を特定するお手伝いをするように設計されています。結局のところ、下流の機械学習分析を行う前にそれらを検出し、どう対処すべきかを知っておくことは、潜在的な欠陥を抱えたモデルを構築するよりもはるかに優れています。この場合、注意すべき点があります:p 値が 0.0 であるため、相関行列が同一(identity)であるという帰無仮説は棄却され、つまり変数間に意味のある相関が存在します。したがって、もし多くの特徴量があり次元削減を行いたいのであれば、PCA を適用することは良い考えかもしれません。
# 多重共線性の確認
最後に、多重共線性を確認します。これは、予測変数間に高い相関があるかどうかを示す性質であり、線形回帰などの解釈可能なモデルでは、ある時点で望ましくない特性となる可能性があります。確認してみましょう。
p 値付きの頑健な相関行列の計算
correlation_matrix = pg.rcorr(df[features], method='pearson')
print(correlation_matrix)
出力された行列:
fixed acidity volatile acidity citric acid pH alcohol
fixed acidity - * * * *
volatile acidity 0.219 - * * **
citric acid 0.324 -0.378 - ***
pH -0.253 0.261 -0.33 - ***
alcohol -0.095 -0.038 -0.01 0.121 -
pandas の corr() メソッドでも同様の計算が可能ですが、Pingouin の対応する関数は、各相関の統計的有意水準をアスタリスクで示します(* は p < 0.05、 は p < 0.01、* は p < 0.001)。相関が統計的に有意であっても、その大きさ自体は小さい場合があります。多重共線性が問題となるのは、相関係数の絶対値が高い場合(通常は 0.8 を超える)です。今回のケースでは、ペアごとの相関のうち危険なほど大きなものはなく、評価された 5 つの特徴量はすべて、さらに分析を進める上で互いに重複せず、それぞれが独自に有用な情報を提供しています。
まとめ
一連の例を一つずつ適用し、説明することで、オープンソースの Python ライブラリである Pingouin の可能性を解き放ち、高度な統計検定や機械学習モデルに基づいてデータ前処理および下流分析においてより良い意思決定を行うための堅牢で現代的な EDA パイプラインを実行する方法を見てきました。これにより、実行すべき適切なアクションと使用するべき適切なモデルを選択できるようになります。
Iván Palomares Carrascosa は、AI、機械学習、ディープラーニング、LLM におけるリーダー、作家、スピーカー、そしてアドバイザーです。彼は、現実世界で AI を活用する方法を他者に指導・訓練しています。
原文を表示

# Introduction
**
Anyone who has spent a fair amount of time doing data science may sooner or later learn something: the golden rule of downstream machine learning modeling, known as garbage in, garbage out** (GIGO).
For example, feeding a linear regression model with highly collinear data, or running ANOVA tests on heteroscedastic variances, is the perfect recipe... for ineffective models that won't learn properly.
Exploratory data analysis (EDA) has a lot to say in terms of visualizations like scatter plots and histograms, yet they aren't sufficient when we need rigorous validation of data against the mathematical assumptions needed in downstream analyses or models. Pingouin helps do this by bridging the gap between two well-known libraries in data science and statistics: SciPy and pandas. Further, it can be a great ally to build solid, automated EDA pipelines. This article teaches you how to build a holistic pipeline for rigorous, statistical EDA, validating several important data properties.
# Initial Setup
**
Let's start by making sure we install Pingouin in our Python environment (and pandas, in case you don't have it yet):
!pip install pingouin pandasAfter that, it's time to import these key libraries and load our data. As an example open dataset, we will use one containing samples of wine properties and their quality.
import pandas as pd
import pingouin as pg
# Loading the wine dataset from an open dataset GitHub repository
url = "https://raw.githubusercontent.com/gakudo-ai/open-datasets/refs/heads/main/wine-quality-white-and-red.csv"
df = pd.read_csv(url)
# Displaying the first few rows to understand our features
df.head()# Checking Univariate Normality
The first of the specific exploratory analyses we will conduct pertains to a check on univariate normality. Many traditional algorithms for training machine learning models — and statistical tests like ANOVAs and t-tests, for that matter — need the assumption that continuous variables follow a normal, a.k.a. Gaussian distribution. Pingouin's pg.normality() function helps do this check through a Shapiro-Wilk test across the entire dataframe:
# Selecting a subset of continuous features for normality checks
features = ['fixed acidity', 'volatile acidity', 'citric acid', 'pH', 'alcohol']
# Running the normality test
normality_results = pg.normality(df[features])
print(normality_results)Output:
W pval normal
fixed acidity 0.879789 2.437973e-57 False
volatile acidity 0.875867 6.255995e-58 False
citric acid 0.964977 5.262332e-37 False
pH 0.991448 2.204049e-19 False
alcohol 0.953532 2.918847e-41 FalseIt seems like none of the numeric features at hand satisfy normality. This is by no means something wrong with the data; it's simply part of its traits. We are just getting the message that, in later data preprocessing steps beyond our EDA, we might want to consider applying data transformations like log-transform or Box-Cox that make the raw data look "more normal-like" and thus more suitable for models that assume normality.
# Checking Multivariate Normality
Similarly, evaluating normality not feature by feature, but accounting for the interaction between features, is another interesting aspect to inspect. Let's see how to check for multivariate normality: a key requirement in techniques like multivariate ANOVA (MANOVA), for instance.
# Henze-Zirkler multivariate normality test
multivariate_normality_results = pg.multivariate_normality(df[features])
print(multivariate_normality_results)Output:
HZResults(hz=np.float64(23.72107048442373), pval=np.float64(0.0), normal=False)And guess what: you may get something like HZResults(hz=np.float64(23.72107048442373), pval=np.float64(0.0), normal=False), which means multivariate normality doesn't hold either. If you are going to train a machine learning model on this dataset, this means non-parametric, tree-based models like gradient boosting and random forests might be a more robust alternative than parametric, weight-based models like SVM, linear regression, and so on.
# Checking Homoscedasticity
Next comes a tricky word for a rather simple concept: homoscedasticity**. This refers to equal or constant variance across errors in predictions, and it is interpreted as a measure of reliability. We will test this property (sorry, too hard to write its name again!) with Pingouin's implementation of Levene's test, as follows:
# Levene's test for equal variances across groups
# 'dv' is the target, dependent variable, 'group' is the categorical variable
homoscedasticity_results = pg.homoscedasticity(data=df, dv='alcohol', group='quality')
print(homoscedasticity_results)Result:
W pval equal_var
levene 66.338684 2.317649e-80 FalseSince we got False once again, we have a so-called heteroscedasticity problem, which should be accounted for in downstream analyses. One possible way could be by employing robust standard errors when training regression models.
# Checking Sphericity
**
Another statistical property to analyze is sphericity, which identifies whether the variances of differences between possible pairwise combinations of conditions are equal. Testing this property is usually desirable before running principal component analysis (PCA) for dimensionality reduction, as it helps us understand whether there are correlations between variables. PCA will be rendered rather useless in case there are not any:
# Mauchly's sphericity test
sphericity_results = pg.sphericity(df[features])
print(sphericity_results)Result:
SpherResults(spher=False, W=np.float64(0.004437706589942777), chi2=np.float64(35184.26583883276), dof=9, pval=np.float64(0.0))Looks like we have chosen a pretty indomitable, arid dataset! But fear not — this article is intentionally designed to focus on the EDA process and help you identify plenty of data issues like these. At the end of the day, detecting them and knowing what to do about them before downstream, machine learning analysis is far better than building a potentially flawed model. In this case, there is a catch: we have a p-value of 0.0, which means the null hypothesis of an identity correlation matrix is rejected, i.e. meaningful correlations exist between the variables. So if we had plenty of features and wanted to reduce dimensionality, applying PCA might be a good idea.
# Checking Multicollinearity
Last, we will check multicollinearity: a property that indicates whether there are highly correlated predictors. This might become, at some point, an undesirable property in interpretable models like linear regressors. Let's check it:
# Calculating a robust correlation matrix with p-values
correlation_matrix = pg.rcorr(df[features], method='pearson')
print(correlation_matrix)Output matrix:
fixed acidity volatile acidity citric acid pH alcohol
fixed acidity - *** *** *** ***
volatile acidity 0.219 - *** *** **
citric acid 0.324 -0.378 - ***
pH -0.253 0.261 -0.33 - ***
alcohol -0.095 -0.038 -0.01 0.121 -While pandas' corr() can also be used, Pingouin's counterpart uses asterisks to indicate the statistical significance level of each correlation (* for p < 0.05, ** for p < 0.01, and *** for p < 0.001). A correlation can be statistically significant yet still small in magnitude — multicollinearity becomes a concern when the absolute value of the correlation is high (typically above 0.8). In our case, none of the pairwise correlations are dangerously large, with all five evaluated features providing largely non-overlapping, unique information of their own for further analyses.
# Wrapping Up
Through a series of examples applied and explained one by one, we have seen how to unleash the potential of Pingouin, an open-source Python library, to perform robust, modern EDA pipelines that help you make better decisions in data preprocessing and downstream analyses based on advanced statistical tests or machine learning models, helping you choose the right actions to perform and the right models to use.
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日報で今日の重要ニュースをまとめ読み