পাঠ ০৭ · ৪৫-এর মধ্যে · মডিউল ১
Home / AI Courses / Machine Learning / Confusion Matrix

Confusion matrix বোঝা

Confusion matrix — beyond binary
৬ মিনিট পড়া মাঝারি · Intermediate scikit-learn কোডসহ

এই পাঠে যা শিখবেন

  • Confusion matrix-এর গঠন — binary ও multi-class
  • প্রতিটি cell-এর অর্থ ও diagnosis
  • Normalization — কখন row, কখন column
  • Visualization — heatmap-এ pattern চেনা
  • Multi-class extension — Per-class metrics

১ · Confusion Matrix কী

একটি table — যা প্রতিটি (actual, predicted) class combination-এর count দেখায়। L06-এ আমরা TP/FP/FN/TN দেখলাম — confusion matrix এই চারটির visual representation।

Binary confusion matrix

Predicted Positive Predicted Negative
Actual Positive TP — সঠিক FN — miss
Actual Negative FP — false alarm TN — সঠিক

২ · কেন এটি গুরুত্বপূর্ণ

Single number (accuracy, F1) — informative, কিন্তু "কী ধরনের ভুল করছে" বলে না। Confusion matrix সম্পূর্ণ picture দেয়:

  • মডেল কি positive miss করছে (FN বেশি) → recall problem।
  • Spurious positive prediction (FP বেশি) → precision problem।
  • Multi-class — কোন pair confused → which classes look similar।

৩ · scikit-learn-এ confusion matrix

Python · scikit-learn
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import numpy as np

X, y = make_classification(n_samples=1000, weights=[0.9, 0.1],
                            random_state=42)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3,
                                            random_state=42, stratify=y)

model = LogisticRegression()
model.fit(X_tr, y_tr)
y_pred = model.predict(X_te)

cm = confusion_matrix(y_te, y_pred)
print("Confusion Matrix:")
print(cm)
print(f"\nTN={cm[0,0]}, FP={cm[0,1]}")
print(f"FN={cm[1,0]}, TP={cm[1,1]}")

# row-normalized — recall per class
cm_norm = cm / cm.sum(axis=1, keepdims=True)
print(f"\nRow-normalized (recall per class):")
print(np.round(cm_norm, 3))

    
Row-normalized matrix — diagonal-এ প্রতি class-এর recall। Class ০-এ ০.৯৭, class ১-এ হয়তো ০.৬০ — minority class miss করছে।

৪ · Normalization — কখন কোনটা

Raw count-এর সমস্যা — imbalanced data-এ majority class dominate। তিন ধরনের normalization:

  • Row-wise (recall): প্রতি row sum = ১। Diagonal = recall per class।
    "Class A-এর কতগুলো সঠিক identify করলাম?"
  • Column-wise (precision): প্রতি column sum = ১। Diagonal = precision per class।
    "Class A predict করলাম — কতগুলো সঠিক?"
  • Total-wise: সব total-এর fraction। Frequency picture।

scikit-learn-এ normalize='true' (row), 'pred' (column), 'all' (total)।

৫ · Multi-class confusion matrix

K class হলে — K×K matrix। Iris (৩ class):

Python · Iris
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report

X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3,
                                            random_state=42, stratify=y)

model = LogisticRegression(max_iter=200)
model.fit(X_tr, y_tr)
y_pred = model.predict(X_te)

target_names = ['setosa', 'versicolor', 'virginica']
cm = confusion_matrix(y_te, y_pred)
print("Confusion Matrix (rows=actual, cols=predicted):")
print(f"          {target_names}")
for i, row in enumerate(cm):
    print(f"{target_names[i]:12s} {row}")

print("\n" + classification_report(y_te, y_pred, target_names=target_names))

    
Iris-এ setosa সাধারণত ১০০% সঠিক। Versicolor ↔ virginica সামান্য confused — কারণ overlap। এই pattern-ই matrix-এ visible।
Multi-class Confusion Matrix Iris classifier — 3 classes Predicted → setosa versicolor virginica setosa versicolor virginica ↑ Actual 15 0 0 0 14 1 0 2 13 diagonal = সঠিক off-diag = ভুল Insight: setosa সম্পূর্ণ আলাদা; versicolor ↔ virginica কখনো-কখনো confused Pattern থেকে — petal measurements দু'টি class-এ overlap।
Iris-এর confusion matrix। Setosa সম্পূর্ণ আলাদা, versicolor ও virginica-এ overlap — যা domain knowledge-এর সাথে মিলে।

৬ · Pattern reading

Multi-class matrix পড়ার technique:

  • Diagonal heavy? মডেল ভাল।
  • Off-diagonal cluster? Specific class pair confused — investigate।
  • Asymmetric error? A → B mistake বেশি, কিন্তু B → A কম — class imbalance বা decision boundary skew।
  • একটি column "magnet"? সব class-কে এই class predict করছে — model collapse।

৭ · Visualization — heatmap

Python · matplotlib
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay

ConfusionMatrixDisplay.from_estimator(
    model, X_te, y_te,
    display_labels=target_names,
    cmap='Blues',
    normalize='true'   # row-normalized
)
plt.title("Confusion Matrix (row-normalized)")
plt.show()

    

৮ · Cost-weighted error analysis

প্রতিটি ভুলের same cost না। Cancer detection-এ FN cost FP-এর ১০০x। Cost matrix:

  • FN: ১০০ (missed cancer = death risk)
  • FP: ১ (extra test, anxiety)
  • TP/TN: ০

$$\text{Total cost} = \text{FN} \times 100 + \text{FP} \times 1$$

Threshold tune — total cost minimize। Confusion matrix এই calculation-এর data দেয়।

৯ · Common diagnostic patterns

  • Strong diagonal except one class: সেই class data কম বা features mismatched।
  • 2×2 sub-block confused: Hierarchical structure missing — যেমন "dog/wolf" ও "cat/lynx" — coarse-fine hierarchy।
  • Random distribution: Model trained হয়নি বা features useless।
  • All predicted same class: Probability calibration বা threshold issue।
Confusion matrix প্রথম diagnostic — accuracy/F1 দেখার আগে এটি দেখুন। Pattern থেকে — model improvement direction জানা। Just numbers হিসেবে না, story হিসেবে পড়ুন।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ একটি ১০-class image classifier-এর confusion matrix দেখলেন। "dog" predict সাধারণত সঠিক, কিন্তু "wolf"-কে সবসময় "dog" predict করছে। কী করবেন?

এটি classic case — confusion matrix-ই solution-এর direction দিচ্ছে। Generic accuracy/F1 এই insight কখনই দিত না।

প্রথমে — diagnose what's happening:

  • Wolf class-এ recall ০ near।
  • Dog class-এ recall high কিন্তু precision drop (because wolves classified as dogs)।
  • "Off-diagonal magnet" — wolf row পুরোপুরি dog column-এ।

সম্ভাব্য কারণ:

(১) Class imbalance:

  • Dog: ১০,০০০ images, Wolf: ১০০।
  • Model "always predict dog" — easy 99% on imbalanced metric।
  • Solution: SMOTE (L43), class weights, oversampling।

(২) Feature similarity:

  • Wolves ও dogs visually similar — same fur patterns, body shape।
  • Generic CNN features দু'টোয় activate।
  • Solution: Fine-grained features — ear shape, snout, eye color। Detail-focused architecture।

(৩) Label noise:

  • Training-এ wolves "dog" label!
  • Inspect — random sample of wolf training images।
  • Crowd-sourced labels prone to confusion।

(৪) Background bias:

  • Famous "wolves on snow" research — model snow detect করছে, wolf না।
  • Test-এ wolf indoor — mistaken।
  • Solution: Background diversity, attribution analysis (Grad-CAM)।

(৫) Distribution shift:

  • Training-এ Arctic wolves, test-এ Eurasian — looks closer to dog।
  • Domain adaptation।

Diagnostic procedure:

  • (১) Per-class metrics: precision, recall, F1। Wolf row check।
  • (২) Sample inspection: Misclassified wolf images visualize। Pattern চিনি।
  • (৩) Embedding visualization: t-SNE — dog ও wolf clusters merge?
  • (৪) Attribution: Grad-CAM — model কী দেখছে।
  • (৫) Confidence: Wolf misclassified-এ probability low না high? Low → model uncertain → calibration। High → strong wrong belief → fundamental problem।

Solution roadmap:

  • Imbalance → reweighted loss, SMOTE।
  • Insufficient data → collect more wolves।
  • Feature similarity → finer architecture, attention।
  • Label noise → re-label।
  • Distribution shift → diverse training।

Hierarchy-based:

  • "Canid" super-class → "dog/wolf/coyote" sub-class।
  • Two-stage classifier।
  • Alternatively — "wolf is rare dog" treatment।

মূল উপলব্ধি: Confusion matrix-এ specific pattern → specific intervention। Generic "improve accuracy" approach inefficient। Targeted fixes superior।

প্র ০২ "Row-normalized" এবং "column-normalized" — দু'টি ভিন্ন তথ্য দেয়। কখন কোনটি লাগবে — তিন distinct scenarios?

Normalization choice trivial মনে হলেও — বিভিন্ন stakeholder-এর প্রশ্নের উত্তর ভিন্ন।

Row-normalized = Recall view:

  • Each row sum to ১।
  • Diagonal = recall per class।
  • "Class A-এর কতগুলো actual cases আমরা ধরেছি"।

Column-normalized = Precision view:

  • Each column sum to ১।
  • Diagonal = precision per class।
  • "আমার Class A predictions-এর কতগুলো সঠিক"।

Scenario ১: Cancer screening — Doctor's view

  • Row-normalized।
  • Doctor চান — "All actual cancer patients-এর কতজন আমরা ধরেছি?" — Recall।
  • Cancer row → ০.৯৫ diagonal → ৯৫% caught।
  • Patients-এর perspective — "আমার cancer থাকলে — detect হবে?"
  • FN অগ্রহণযোগ্য।

Scenario ২: Spam filter — User's view

  • Column-normalized।
  • User চান — "Spam-এ পাঠানো email-এর কতগুলো আসলেই spam?" — Precision।
  • Spam column → ০.৯৯ diagonal → ৯৯% genuine spam।
  • FP (legitimate email-spam-এ) intolerable।

Scenario ৩: Court evidence (forensic ID) — Legal view

  • Both!
  • Defendant যদি match — কতগুলো actual matches সঠিক (precision)।
  • Actual match থাকলে — কতবার match identified (recall)।
  • "Innocent until proven" — high precision priority (Type I error rare)।
  • BUT public safety — high recall priority।
  • Tension — explicit tradeoff documented।

আরো scenarios:

(৪) Multi-class search engine:

  • Column-normalized — "Top-1 result-এর কতগুলো সঠিক category?"
  • User experience — precision dominate।

(৫) Public health — outbreak detection:

  • Row-normalized — "Outbreak-এর কতগুলো ধরা পড়েছে?"
  • Recall priority — missed outbreak = epidemic।

(৬) Recommendation systems:

  • Column-normalized at top-K — "শেষ 10 recommendation-এর কতগুলো good?"
  • Precision@K।

(৭) Translation quality:

  • Both views complementary।
  • Matrix-এর different cell different translation pattern।

Reporting best practice:

  • Both row ও column normalized দু'টোই present।
  • Stakeholder-specific explanation।
  • Cost matrix attached — business impact translation।

Subtle point:

  • Row + column normalized + raw counts — সব context দেয়।
  • Imbalanced data-এ raw count misleading; normalized necessary।

মূল উপলব্ধি: Normalization "stylistic choice" নয় — fundamentally different question উত্তর। Stakeholder identify, তারপর choose।

প্র ০৩ আপনার medical diagnosis মডেল — confusion matrix-এ "rare disease" class-এ ৫০% recall। এটি কেন বড় সমস্যা — এবং accuracy ৯৭% সত্ত্বেও কেন?

Medical AI-এর সবচেয়ে dangerous trap — accuracy figure thrown around without context।

এই matrix-এর সম্ভাব্য realistic numbers:

  • Rare disease prevalence ১% (১০০ in ১০০০০ test)।
  • Healthy: ৯৯০০।
  • Healthy → healthy: ৯৭৭০ (TN, recall ০.৯৮৭)
  • Healthy → diseased: ১৩০ (FP)
  • Diseased → diseased: ৫০ (TP, recall ০.৫০)
  • Diseased → healthy: ৫০ (FN)
  • Total accuracy: (৯৭৭০ + ৫০) / ১০০০০ = ৯৮.২%।

কেন এটি ভয়াবহ:

  • ৫০% diseased patients miss — কেউ severe disease নিয়ে home যাচ্ছে।
  • "৯৮% accuracy" headline — public confidence misplaced।
  • Trivially "all healthy predict" — accuracy ৯৯%। আমাদের model এর সমান।

কেন এই pattern সাধারণ:

(১) Class imbalance:

  • Standard cross-entropy — majority class dominate।
  • Loss function unaware of disease severity।
  • Solution: Weighted loss, focal loss, oversampling।

(২) Limited training examples:

  • ১% prevalence — ১০০০০ patient মাত্র ১০০ disease।
  • Insufficient signal।
  • Solution: Active learning, synthetic data (with caution), data augmentation।

(৩) Feature inadequacy:

  • Common features capture both classes — disease-specific markers missing।
  • Solution: Domain-expert-guided feature engineering।

Real-world consequences:

  • Direct harm: Patient false-reassured, disease progresses।
  • Liability: Hospital liable for missed diagnosis।
  • Trust: Once one missed case publicized — system credibility shattered।
  • Equity: Rare diseases often affect minorities more — bias amplification।

Solution architecture:

(১) Tier-1 high-recall screening:

  • Threshold low enough → recall ০.৯৫+।
  • Many FP — flagged for review।
  • FP cost = additional test, FN cost = death।

(২) Tier-2 specialist confirmation:

  • Tier-1 positive cases — human radiologist/specialist।
  • Higher precision, lower volume।

(৩) Continuous monitoring:

  • Production confusion matrix tracking।
  • Distribution shift detection।
  • Per-subgroup analysis (gender, ethnicity, age)।

Reporting standards:

  • Per-class precision, recall, F1।
  • Sensitivity (recall) ও Specificity (TNR) — medical standard।
  • PPV (precision) ও NPV — clinical interpretation।
  • NEVER report only accuracy in medical AI।

Regulatory:

  • FDA AI/ML guidance — confusion matrix submission required।
  • Subgroup performance — fairness bias check।

মূল উপলব্ধি: Imbalanced + high-stakes domain = accuracy misleading। Confusion matrix essential — disease class focus, sensitivity priority। Single-number summary deadly mistake।

প্র ০৪ Confusion matrix বনাম per-class metrics — কখন matrix overkill, কখন essential? Multi-label (multiple classes per sample) confusion matrix — কীভাবে?

Confusion matrix powerful কিন্তু always optimal না। Higher-dimensional classification এর প্রয়োজন রিথিঙ্ক।

Confusion matrix কখন overkill:

(১) Many classes (>২০):

  • ২০×২০ = ৪০০ cell — visually unintelligible।
  • Solution: Top-confused-pair list।
  • Hierarchical class group।

(২) Production monitoring:

  • Real-time dashboard — single F1 simpler।
  • Confusion matrix periodic deep-dive।

(৩) Quick comparison of models:

  • "Model A vs B" — single-number সহজ।
  • Matrix detailed comparison-এ।

Confusion matrix কখন essential:

  • Per-class diagnosis জরুরি।
  • Pattern of errors বুঝা — model improvement direction।
  • Stakeholder communication — visual storytelling।
  • Cost-weighted analysis।
  • Bias/fairness audit।

Multi-label classification challenge:

সংজ্ঞা:

  • Each sample-এ multiple labels possible।
  • উদাহরণ — image: "cat" + "indoor" + "sleeping"।
  • Movie genre — "comedy" + "drama" + "romance"।
  • Multi-class ভিন্ন (single label) — multi-label more general।

Confusion matrix সরাসরি apply করা যায় না:

  • K class হলে $2^K$ possible label combinations।
  • Matrix size exponential।

Multi-label evaluation alternatives:

(১) Per-label binary confusion:

  • প্রতি label-কে independent binary problem treat।
  • K matrices — each ২×২।
  • Per-label precision, recall।

(২) Hamming loss:

  • Average wrong predictions per sample।
  • $H = \frac{1}{nK}\sum |y_{pred} \oplus y_{true}|$ — XOR।

(৩) Subset accuracy (exact match):

  • সব labels exact match — strict।
  • Most demanding metric।

(৪) Jaccard similarity:

  • $J = |y_{pred} \cap y_{true}| / |y_{pred} \cup y_{true}|$।
  • Set-based evaluation।

(৫) Co-occurrence confusion matrix:

  • K×K matrix — কোন pair correctly co-predicted।
  • Pattern reveal — which labels co-occur in errors।

(৬) Label-aware confusion:

  • প্রতি sample — predicted labels compared to actual।
  • Common errors aggregated।

Hierarchical classification:

  • Class taxonomy থাকে।
  • Confusion matrix flat — hierarchical structure miss।
  • Hierarchical metric: closer wrong < farther wrong।
  • "Predicted dog instead of wolf" < "Predicted dog instead of car"।

Imbalance + multi-label:

  • Some labels rare (১% samples)।
  • Macro-averaged F1 — equal weight per label।
  • Micro-averaged — sample-wise।

Production tools:

  • scikit-learn — multi-label confusion matrix।
  • Sklearn classification_report — multi-label aware।
  • Custom dashboards — per-label drill-down।

Modern deep learning:

  • Embedding visualization > confusion matrix often।
  • t-SNE/UMAP — class separation view।
  • Confusion remains useful for specific class issues।

মূল উপলব্ধি: Confusion matrix specific scenarios-এ optimal — multi-class moderate-size supervised classification। Multi-label, hierarchical, very-many-class — alternatives explore।

অনুশীলন

  1. হিসাব: ৩-class confusion matrix — diag=[৫০, ৪০, ৩০], off-diag total ১০ + ১৫ + ৫ + ০ + ০ + ০ = (৬০ predicted A, ৪০ predicted B etc.)। Per-class precision ও recall?

    সঠিক figures dependant; concept — diagonal element / row sum = recall, diagonal / column sum = precision। প্রতিটি class-এর জন্য আলাদা।

  2. scikit-learn: উপরের Iris code চালান। n_estimators=১ Decision Tree চেষ্টা করুন। Confusion matrix কেমন?

    Single deep tree — কিছু overfitting হলে test-এ versicolor↔virginica confusion বেশি। Logistic Regression-এর সাথে compare।

  3. চিন্তা: Bkash fraud detection-এ আপনার confusion matrix — TP=৫০, FP=৫০০, FN=১০, TN=৯৪৪০। কী insight? Threshold কোন direction-এ tune?

    Recall = ৫০/৬০ = ০.৮৩ (ভাল)। Precision = ৫০/৫৫০ = ০.০৯ (খারাপ)। অর্থাৎ ৯১% alerts false। Threshold বাড়ান — fewer alerts, higher precision। অবশ্যই recall drop watch — ০.৭০-এর নিচে গেলে problem।

আরও পড়ুন

কোড রানার কাজ না করলে? Google Colab ব্যবহার করুন।
পূর্ববর্তী পাঠ
পাঠ ০৬ · মূল্যায়ন মেট্রিক