Visualizing Classification Performance Through Confusion Matrix Heatmaps in Python

Environment Setup

Install the required dependencies via pip before execution:

pip install numpy pandas matplotlib scikit-learn seaborn

Data Partitioning and Classifier Fitting

Load a standard benchmark dataset, split the feature set into training and testing subsets, and train an ensemble classifier. The resulting predictions serve as the basis for downstream evaluation.

import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

# Extract features and targets
dataset = load_wine()
X_data = dataset.data
y_labels = dataset.target

# Stratified split to preserve class distribution
X_train, X_val, y_true, y_pred = train_test_split(
    X_data, y_labels, test_size=0.25, stratify=y_labels, random_state=7
)

# Initialize and fit the model
clf = LogisticRegression(max_iter=1000, multi_class="multinomial")
clf.fit(X_train, y_true)

# Generate target predictions
y_pred = clf.predict(X_val)

Matrix Computation

Calculate the raw contingency table comparing ground truth against predicted outputs. Scikit-learn handles dimension alignment automatically without manual iteration.

from sklearn.metrics import confusion_matrix

raw_counts = confusion_matrix(y_true, y_pred)
print("Raw Contingency Table:\n", raw_counts)

Heatmap Rendering and Annotation

Transform the numerical array into a labeled DataFrame. Apply a diverging color palette, enable inline integer annotations, and adjust axis parameters for publication-ready output. Normalization is often applied to highlight relative error rates rather than absolute counts.

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

class_names = dataset.target_names

df_matrix = pd.DataFrame(
    raw_counts,
    index=pd.Index(class_names, name="Actual Class"),
    columns=pd.Index(class_names, name="Predicted Class")
)

fig, ax = plt.subplots(figsize=(8, 6))
sns.heatmap(
    df_matrix,
    annot=True,
    fmt=".0f",
    cmap="viridis",
    cbar_kws={"label": "Sample Frequency"},
    linewidths=0.5
)
plt.title("Classification Error Distribution")
plt.tight_layout()
plt.show()

Interpreting the Visualization

The rendered plot maps quantitative relationships through chromatic intensity. Key analytical patterns include:

  • Primary Diagonal Elements: Each cell along the top-left to bottom-right axis represents accurate classifications. Higher values here indicate superior model calibration for that specific class.
  • Secondary Off-Diagonal Elements: Values outside the main diagonal quantify false positives and false negatives. Clusters of darker cells reveal systematic misclassification tendencies, such as confusing similar morphological features between adjacent categories.
  • Color Scale Gradient: Intensity shifts correspond directly to sample volume. Diverging palettes can be substituted for normalized ratios (e.g., df_matrix.div(df_matrix.sum(axis=1), axis=0)) to emphasize proportional error rates when dealing with imbalanced datasets.

Adjusting hyperparameters based on these localized failure points typically yields targeted improvements in recall precision without degrading overall accuracy metrics. Feature engineering pipelines can also be refined by isolating ambiguous class boundaries identified in the off-diagonal regions.

Tags: python Machine Learning Data Visualization Confusion Matrix scikit-learn

Posted on Mon, 03 Aug 2026 16:55:23 +0000 by kruahsohr