🧠 AI with Python – 📊 Visualize Feature Correlations with a Heatmap


Description:

Why Correlation Matters?

Features may be correlated, meaning one feature may give similar information as another. Highly correlated features can make models unnecessarily complex.


Solution: Correlation Heatmap

Using libraries like Seaborn, a heatmap visually shows how features relate to each other. Darker colors mean stronger relationships.


Where It’s Useful?

  • Feature selection (remove redundant features).
  • Understanding relationships before model building.
ρ(X,Y) = Cov(X, Y) / (σX σY)

Practical Takeaway

Before training, check correlations. A simple heatmap can guide better feature engineering and improve model efficiency.


Code Snippet:

# Import necessary libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Create a sample dataset
data = {
    'Age': [25, 32, 47, 51, 62],
    'Salary': [50000, 60000, 80000, 82000, 90000],
    'Purchases': [1, 2, 3, 3, 5],
    'Score': [80, 85, 78, 88, 90]
}
df = pd.DataFrame(data)

# Display the DataFrame
df

# Compute correlation matrix
correlation_matrix = df.corr(numeric_only=True)

# Display the matrix
correlation_matrix

# Plot the heatmap
plt.figure(figsize=(8, 6))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=".2f")
plt.title("Feature Correlation Heatmap")
plt.show()

Link copied!

Comments

Add Your Comment

Comment Added!