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 4 of 9
Pair Plots, Non-Linear Scatter Relationships & Feature Interactions
Pairwise scatter plots and bivariate density contours expose complex geometric structures that aggregate correlation numbers obscure. Visualizing multi-dimensional manifolds reveals non-linear curves (quadratic, sigmoid, exponential), heteroscedastic fan shapes (variance growing with feature value), multi-modal clusters, and synergistic feature interactions where the predictive impact of one feature depends entirely on the value of another.
Detecting Non-Linear Interactions & Mutual Information
import pandas as pd
import numpy as np
from sklearn.feature_selection import mutual_info_regression
# Synthetic dataset with non-linear dependencies
np.random.seed(42)
n = 1000
x1 = np.random.uniform(-3, 3, n)
# Non-linear relationship: y depends quadratically on x1
x2 = np.random.uniform(0, 10, n)
# Synergistic interaction: effect of x1 depends on x2
noise = np.random.normal(0, 0.5, n)
y = (x1 ** 2) + (x1 * x2 * 0.5) + noise
df = pd.DataFrame({'x1': x1, 'x2': x2, 'y': y})
# 1. PEARSON CORRELATION (Fails on symmetric quadratic)
pearson_x1 = df['x1'].corr(df['y'])
print(f"Linear Pearson correlation of x1 with y: {pearson_x1:.4f} (Appears deceptively near zero!)")
# 2. MUTUAL INFORMATION (Captures arbitrary non-linear dependencies)
# MI measures the reduction in entropy of y given knowledge of X
mi_scores = mutual_info_regression(df[['x1', 'x2']], df['y'], random_state=42)
for feature, score in zip(['x1', 'x2'], mi_scores):
print(f"Non-linear Mutual Information for '{feature}': {score:.4f} (High dependency successfully captured!)")
# 3. INTERACTION FEATURE FORMULATION
df['x1_squared'] = df['x1'] ** 2
df['interaction_x1_x2'] = df['x1'] * df['x2']
print("\nCorrelations with Explicitly Engineered Interactions:")
print(f" Corr(x1_squared, y) : {df['x1_squared'].corr(df['y']):.4f}")
print(f" Corr(interaction_term, y): {df['interaction_x1_x2'].corr(df['y']):.4f}")Pro Tip: Downsample for Pair Plots on Large Datasets
Never run `sns.pairplot()` on datasets with more than 10,000 rows or 10 columns; it will freeze your browser and consume gigabytes of memory rendering millions of vector SVG points. Downsample to a stratified sample of 1,500 rows and select the top 6 most important features identified via Mutual Information.
MlPairPlotsScatter Visual Representation
Hands-On Challenge: Residual Heteroscedasticity Visualizer
Train a simple linear regression model on synthetic heteroscedastic data (where variance of y increases with x). Plot residuals `(y - y_pred)` against predicted values `y_pred` and demonstrate how a fan-shaped cone pattern reveals non-constant variance.
Quick Quiz & Key Concept Checks
Common Pitfall: Over-Interpreting Small Sample Clusters
In scatter plots with few data points (<50 samples), random noise can visually appear as distinct clusters. Always confirm apparent groupings using statistical clustering validation (e.g., Hopkins statistic for clusterability) before engineering features based on visual clusters.
Finished this lesson?