Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 6 of 9
Categorical Cardinality, Frequency Distributions & Association Tests
Categorical features in production data range from low-cardinality nominals (marital status, device type) to high-cardinality entities (merchant category codes, postal zip codes, user agents). Conducting frequency audits, identifying rare long-tail categories, and evaluating statistical independence between categorical features and target labels via Chi-Square (χ²) tests and Cramér's V prevents high-dimensional pipeline bloat.
Categorical Association Testing via Chi-Square & Cramér's V
import pandas as pd
import numpy as np
import scipy.stats as stats
# Generate synthetic marketing subscription conversion dataset
np.random.seed(42)
n = 1500
channels = np.random.choice(['Organic', 'Paid_Search', 'Email_Newsletter', 'Referral', 'Affiliate'], size=n, p=[0.3, 0.25, 0.2, 0.15, 0.1])
device = np.random.choice(['Mobile', 'Desktop', 'Tablet'], size=n, p=[0.6, 0.35, 0.05])
# Conversions with channel dependency
conv_probs = {'Organic': 0.08, 'Paid_Search': 0.15, 'Email_Newsletter': 0.28, 'Referral': 0.22, 'Affiliate': 0.05}
converted = [np.random.uniform(0, 1) < conv_probs[ch] for ch in channels]
df_cat = pd.DataFrame({'channel': channels, 'device': device, 'converted': converted})
# 1. CONTINGENCY TABLE (CROSSTAB)
contingency = pd.crosstab(df_cat['channel'], df_cat['converted'])
print("=== CONTINGENCY MATRIX (Channel vs Conversion) ===")
print(contingency)
# 2. CHI-SQUARE (χ²) TEST OF INDEPENDENCE
# H0: Acquisition channel and conversion outcome are independent
chi2, p_val, dof, expected = stats.chi2_contingency(contingency)
print(f"\nChi-Square Statistic: {chi2:.4f} | p-value: {p_val:.4e} (df = {dof})")
# 3. CRAMÉR'S V STATISTIC (Measures association strength between 0.0 and 1.0)
n_obs = contingency.sum().sum()
min_dim = min(contingency.shape) - 1
cramers_v = np.sqrt(chi2 / (n_obs * min_dim))
print(f"Cramér's V Association Strength: {cramers_v:.4f} -> {'Strong Association' if cramers_v > 0.25 else 'Moderate'}")
# 4. LONG-TAIL RARE CATEGORY COLLAPSER
def collapse_rare_categories(series: pd.Series, threshold_pct=0.05) -> pd.Series:
freq = series.value_counts(normalize=True)
rare_cats = freq[freq < threshold_pct].index
return series.replace({cat: '__OTHER__' for cat in rare_cats})
df_cat['clean_channel'] = collapse_rare_categories(df_cat['channel'], threshold_pct=0.12)
print("\nAfter collapsing rare categories (<12% frequency):")
print(df_cat['clean_channel'].value_counts())Pro Tip: The Long-Tail Category Bucketing Strategy
In production, high-cardinality features like `user_agent` or `merchant_city` often contain thousands of categories that appear only once or twice. Replace all categories accounting for less than 1% of the data with a unified `'__OTHER__'` bucket. This prevents one-hot matrix bloat and avoids overfitting on rare noise.
MlCategoricalFeatureAnalysis Visual Representation
Hands-On Challenge: Information Value & Weight of Evidence
Implement Weight of Evidence (WoE) and Information Value (IV) for a categorical risk feature. Classify the feature as 'Suspicious/Too Good', 'Strong Predictor' (0.3-0.5), 'Medium Predictor' (0.1-0.3), or 'Useless' (<0.02) based on Basel credit scoring standards.
Quick Quiz & Key Concept Checks
Common Pitfall: Label Encoding Nominal Categorical Features
Using `LabelEncoder` or ordinal integer mappings (e.g. mapping `['Red': 0, 'Green': 1, 'Blue': 2]`) for nominal features with no natural ordering forces linear models and neural networks to assume that 'Blue' is greater than 'Green' and twice as large as 'Red'. Use One-Hot or Target Encoding instead.
Finished this lesson?