4. Outlier Management
Identifying Outliers: IQR and Z-Score Methods
Outliers are data points that deviate significantly from the rest of the distribution, often distorting model training and parameter estimation. Two classic statistical methods are used to identify outliers: the Interquartile Range (IQR) method and the Z-score method. The IQR method is non-parametric, meaning it makes no assumptions about the shape of your data distribution. It calculates the difference between the 75th percentile (Q3) and the 25th percentile (Q1). Points that lie below Q1 - 1.5 * IQR or above Q3 + 1.5 * IQR are flagged as outliers.
Conversely, the Z-score method is a parametric technique that assumes your data follows a normal (Gaussian) distribution. The Z-score measures how many standard deviations an individual data point lies away from the distribution mean. A common threshold is an absolute Z-score of 3; any data point with a score beyond this range is identified as an extreme outlier. Below is a comparison of these two approaches:
| Method | Distribution Assumption | Threshold Rule |
|---|---|---|
| IQR (Interquartile Range) | Non-parametric (any distribution shape) | Below Q1 - 1.5 * IQR or above Q3 + 1.5 * IQR |
| Z-Score | Parametric (Normal Gaussian distribution) | Absolute value of Z-score > 3 |
import numpy as np import pandas as pd np.random.seed(42) data = np.random.normal(loc=10, scale=2, size=100) data = np.append(data, [35, -15]) # Inject extreme outliers df = pd.DataFrame(data, columns=['value']) # IQR Method q1 = df['value'].quantile(0.25) q3 = df['value'].quantile(0.75) iqr = q3 - q1 iqr_outliers = df[(df['value'] < q1 - 1.5 * iqr) | (df['value'] > q3 + 1.5 * iqr)] # Z-Score Method mean = df['value'].mean() std = df['value'].std() df['z_score'] = (df['value'] - mean) / std z_outliers = df[df['z_score'].abs() > 3] print(f"IQR Method identified: {len(iqr_outliers)} outliers") print(f"Z-Score Method identified: {len(z_outliers)} outliers")
Winsorization: Clipping Extreme Features
When managing outliers, dropping rows can cause you to lose valuable data or introduce selection bias. Winsorization solves this by capping extreme values instead of deleting them. Named after statistician Charles Winsor, this method replaces values beyond specified percentiles with the values of those percentiles.
For example, in a 98% Winsorization, all values below the 1st percentile are replaced by the 1st percentile value, and all values above the 99th percentile are capped at the 99th percentile value. This keeps your sample size intact while preventing extreme values from exerting excessive leverage over your models.
import numpy as np import pandas as pd np.random.seed(42) df = pd.DataFrame({'income': np.append(np.random.normal(50000, 10000, 100), [500000, 2000])}) # Define thresholds lower_limit = df['income'].quantile(0.01) upper_limit = df['income'].quantile(0.99) # Apply Winsorization using clipping df['winsorized_income'] = df['income'].clip(lower=lower_limit, upper=upper_limit) print(f"Original Max: {df['income'].max()} | Winsorized Max: {df['winsorized_income'].max()}") print(f"Original Min: {df['income'].min()} | Winsorized Min: {df['winsorized_income'].min()}")
Log and Power Transformations for Skewed Distributions
Many real-world variables, such as transactional values, populations, and user activity, exhibit high right-skewness. These distributions are packed with small values and contain a long right tail of rare, very large values. This asymmetry violates the assumptions of many estimators and impairs standard scaling techniques.
Applying logarithmic transformations stabilizes the variance and compresses the extreme tail. If your feature contains zeros, you must use a log1p transformation (which calculates log(x + 1)) to prevent mathematical undefined infinity. For complex skewed shapes, Power Transformations such as Box-Cox (strictly positive data) or Yeo-Johnson (handles negative and zero values) optimize an exponent parameter lambda to transform features to behave as close to normal distributions as possible.
import numpy as np import pandas as pd from sklearn.preprocessing import PowerTransformer np.random.seed(42) skewed_data = np.random.exponential(scale=2.0, size=100) df = pd.DataFrame({'skewed_feature': skewed_data}) # 1. Log1p Transformation df['log_transformed'] = np.log1p(df['skewed_feature']) # 2. Yeo-Johnson Power Transformation pt = PowerTransformer(method='yeo-johnson') df['yeo_johnson'] = pt.fit_transform(df[['skewed_feature']]) print(f"Original Skewness: {df['skewed_feature'].skew():.3f}") print(f"Log1p Skewness: {df['log_transformed'].skew():.3f}") print(f"Yeo-Johnson Skewness: {df['yeo_johnson'].skew():.3f}")
Using FunctionTransformer for Custom Pipeline Mathematics
To prevent data leakage and guarantee reproducibility during model scoring, outlier transformations must reside directly inside your Scikit-Learn Pipelines. Custom numpy functions can be seamlessly packaged using scikit-learn's FunctionTransformer.
The FunctionTransformer turns any basic, stateless python mathematical function into a fully compatible transformer block. This allows you to chain custom clipping, log transforms, or specialized outlier treatments seamlessly with other scaling and modeling steps.
import numpy as np import pandas as pd from sklearn.preprocessing import FunctionTransformer from sklearn.pipeline import Pipeline # Sample dataset with extreme values df = pd.DataFrame({'signal': [12.0, 15000.0, -9999.0, 45.0, -10.0]}) # Custom math function to clip values between -100 and 100 def robust_clipper(X): return np.clip(X, -100.0, 100.0) # Instantiate the transformer clipper_transformer = FunctionTransformer(robust_clipper) # Build the production pipeline pipeline = Pipeline([ ('custom_clipping', clipper_transformer) ]) processed_df = pipeline.fit_transform(df) print("Original features:\n", df['signal'].tolist()) print("Pipeline output:\n", np.array(processed_df).tolist())
Knowledge Check
Ready to test your understanding of 4. Outlier Management?