3 Scipy Functions for Validating Your Data’s Distribution

3 Scipy Functions for Validating Your Data’s Distribution

Validating the distribution of variables in a dataset is a crucial part of EDA (exploratory data analysis) as well as model building. Python’s SciPy library, specifically its scipy.stats module, provides implementations of well-known statistical tests suitable for checking whether the data fits a distribution —such as uniform, normal, etc.

Here are three SciPy functions for validating your data’s distribution, each illustrated with an open-source dataset:

1. Kolmogorov-Smirnov Test for Continuous Distributions

The K-S test —as it is commonly abbreviated— calculates the empirical cumulative distribution function (CDF) of a dataset and compares it against a known theoretical distribution of a continuous nature. Common example distributions to compare against include the normal, uniform, and exponential distributions. The goodness-of-fit test is done by calculating the largest vertical distance between the empirical distribution curve and the selected theoretical one. It is frequently used for large sample sizes.

Its SciPy implementation is based on the kstest() function, whose second argument is used to specify the desired reference distribution. Be aware that, by default, SciPy tests your data against the standardized version of the chosen distribution. Therefore, you may have to prepare your raw data first, transforming it to match the scale of that distribution. This example shows how to do this for a standard normal distribution, using a feature from the Iris dataset:

 
import pandas as pd
from scipy import stats

# Loading open-source Iris dataset from a public URL
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
df = pd.read_csv(url)

# Extracting a continuous feature: sepal length
data_ks = df['sepal_length']

# Standardizing the data (mean=0, std=1) to test against a standard normal distribution
scaled_data = (data_ks - data_ks.mean()) / data_ks.std()

# Running the Kolmogorov-Smirnov test against the standard normal CDF
ks_result = stats.kstest(scaled_data, 'norm')

print("--- Kolmogorov-Smirnov Test ---")
print(f"Statistic: {ks_result.statistic:.4f}")
print(f"P-value: {ks_result.pvalue:.4e}")

With a p-value of 0.178 >> 0.05, this example data fails to reject the null hypothesis: there is not enough statistical evidence that the data deviates from a standard normal distribution; in other words, it is consistent with such a distribution.

2. Anderson-Darling Test for Long-Tail Distributions

Unlike the K-S test, the Anderson-Darling test gives additional emphasis to the distribution’s tails, making it more sensitive to deviations in the tails. Also suitable for continuous distributions, it compares its test statistic against several critical values instead of a single, standard p-value.

Let’s see how to apply this test to the Tips dataset. Some good news here: the stats.anderson() function internally estimates the parameters of your data distribution. Thus, for testing against a normal distribution, it doesn’t require prior standardization:

 
import pandas as pd
from scipy import stats

# Loading open-source Tips dataset
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv"
df = pd.read_csv(url)

# Extracting total_bill values
data_ad = df['total_bill']

# Running the Anderson-Darling test for a normal distribution shape
ad_result = stats.anderson(data_ad, dist='norm')

print("--- Anderson-Darling Test ---")
print(f"Statistic (A^2): {ad_result.statistic:.4f}")
for sig_level, crit_val in zip(ad_result.significance_level, ad_result.critical_values):
    print(f"Significance Level: {sig_level}% | Critical Value: {crit_val:.4f}")

The results show that the overall statistic is far larger than the critical values at every significance level. This means the data departs strongly from normality, typically due to skewness and a long-tailed shape:

 
--- Anderson-Darling Test ---
Statistic (A^2): 5.5207
Significance Level: 15.0% | Critical Value: 0.5670
Significance Level: 10.0% | Critical Value: 0.6460
Significance Level: 5.0% | Critical Value: 0.7750
Significance Level: 2.5% | Critical Value: 0.9040
Significance Level: 1.0% | Critical Value: 1.0750

3. Shapiro-Wilk Test for Normality in Smaller Datasets

The last of the three SciPy functions we will use is perfect for rigorously testing whether a sample of small to moderate size follows a normal distribution. Implemented via scipy.stats.shapiro(), the Shapiro-Wilk test is considered one of the most reliable normality tests for continuous data. Here’s how to apply it:

 
import pandas as pd
from scipy import stats

# Loading open-source Palmer Penguins dataset
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
df = pd.read_csv(url).dropna(subset=['body_mass_g'])

# Extracting body mass measurements
data_shapiro = df['body_mass_g']

# Running the Shapiro-Wilk normality test
shapiro_result = stats.shapiro(data_shapiro)

print("--- Shapiro-Wilk Test ---")
print(f"Statistic: {shapiro_result.statistic:.4f}")
print(f"P-value: {shapiro_result.pvalue:.4e}")

With an extremely small p-value of 3.6790e-08, we reject the null hypothesis, which yields strong evidence that the data tested doesn’t follow a normal distribution.

Leave a Reply

Your email address will not be published. Required fields are marked *