মূল্যায়ন মেট্রিক — accuracy, F1, ROC
এই পাঠে যা শিখবেন
- Accuracy কেন প্রায়ই misleading
- Precision, Recall, F1 — সংজ্ঞা ও কখন কোনটি
- ROC curve ও AUC — threshold-independent metric
- Regression metrics — MSE, MAE, R², MAPE
- Business-aligned metric design
১ · Accuracy — শুরুর metric
সবচেয়ে সরল:
$$\text{Accuracy} = \frac{\text{Correct predictions}}{\text{Total predictions}}$$
Balanced classification (প্রতি class ~৫০%)-এ যথেষ্ট। Iris (৩ class, প্রতিটি ৩৩%) — accuracy fine।
২ · Accuracy কেন misleading — Imbalanced
Cancer detection — ১% রোগী আসলে cancer। একটি "dummy" model — সবাইকে "no cancer" বলে — accuracy ৯৯%! কিন্তু একজন cancer patient-ও ধরে না — useless।
Imbalanced data-এ — accuracy "সঠিক উত্তর-এ ভুল প্রশ্ন।" আমরা minority class-এর performance চাই। Accuracy majority class-এ dominated।
৩ · Confusion Matrix — চারটি সংখ্যা
Binary classification-এ — ৪টি outcome। L07-এ বিস্তারিত:
- TP (True Positive): Cancer পেলাম, সত্যিই cancer।
- FP (False Positive): Cancer বললাম, আসলে না — false alarm।
- FN (False Negative): "No cancer" বললাম, আসলে cancer — missed detection।
- TN (True Negative): "No cancer", আসলেই না।
৪ · Precision — quality of positive predictions
$$\text{Precision} = \frac{TP}{TP + FP}$$
প্রশ্ন: "আমার positive prediction-এর কতগুলো সঠিক?" Spam filter — high precision চাই (legitimate email spam-এ ফেলা ভয়াবহ)।
৫ · Recall (Sensitivity) — coverage of actual positives
$$\text{Recall} = \frac{TP}{TP + FN}$$
প্রশ্ন: "আসল positive-এর কতগুলো ধরলাম?" Cancer detection — high recall চাই (একজন cancer patient miss করা মৃত্যুসমান)।
৬ · F1 Score — harmonic balance
Precision আর Recall-এর tradeoff। F1 — harmonic mean (geometric চেয়ে কঠোর):
$$F_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}$$
একটি ০ হলে F1 = ০। দু'টোই উচ্চ লাগে।
F-beta: $F_\beta = (1+\beta^2) \cdot \frac{P \cdot R}{\beta^2 P + R}$. β > ১ → recall বেশি weight; β < ১ → precision বেশি weight।
৭ · ROC ও AUC
Classifier সাধারণত probability output দেয় (যেমন ০.৭৩)। Threshold ০.৫ মানে — ০.৫-এর বেশি = positive। কিন্তু threshold change করলে — precision/recall পাল্টায়।
ROC curve: থ্রেশহোল্ডে ০ থেকে ১ পর্যন্ত plot —
- X-axis: False Positive Rate = FP/(FP+TN)
- Y-axis: True Positive Rate (Recall) = TP/(TP+FN)
AUC (Area Under Curve): ০ থেকে ১। ০.৫ = random। ১.০ = perfect। ০.৭+ = useful, ০.৮+ = good, ০.৯+ = excellent।
AUC interpretation — randomly chosen positive ও negative-এ — মডেল কত % সময় positive-কে higher score দেয়।
৮ · scikit-learn-এ সব metric
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import (accuracy_score, precision_score,
recall_score, f1_score, roc_auc_score,
classification_report)
# Imbalanced binary — 95% negative
X, y = make_classification(n_samples=1000, weights=[0.95, 0.05],
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)
y_prob = model.predict_proba(X_te)[:, 1]
print(f"Accuracy: {accuracy_score(y_te, y_pred):.4f}")
print(f"Precision: {precision_score(y_te, y_pred):.4f}")
print(f"Recall: {recall_score(y_te, y_pred):.4f}")
print(f"F1 score: {f1_score(y_te, y_pred):.4f}")
print(f"ROC-AUC: {roc_auc_score(y_te, y_prob):.4f}\n")
print(classification_report(y_te, y_pred))
৯ · Regression metrics
- MSE: $\frac{1}{n}\sum(y - \hat{y})^2$ — outliers-এ sensitive।
- RMSE: $\sqrt{\text{MSE}}$ — same units as $y$।
- MAE: $\frac{1}{n}\sum|y - \hat{y}|$ — robust to outliers।
- R² (coefficient of determination): ১ - SS_res/SS_tot। ০ = mean-এর সমান, ১ = perfect।
- MAPE: $\frac{1}{n}\sum|y - \hat{y}|/|y| \times 100$ — % error, scale-independent।
১০ · Multi-class metrics
Macro vs Micro vs Weighted average:
- Macro: প্রতি class-এর F1 গণনা, তারপর mean। সব class-কে সমান weight — minority class উপেক্ষা না।
- Weighted: Class size-অনুসারে weighted mean।
- Micro: সব samples globally — accuracy-র সমান (multi-class-এ)।
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১
আপনি এই ৪টি ব্যবসায় ML deploy করছেন। কোনটায় কোন metric optimize? কেন?
(ক) Email spam filter (খ) Bkash fraud detection (গ) Cancer screening (ঘ) Music recommendation
Metric choice — domain expertise + cost analysis-এর সমন্বয়। Same algorithm, ভিন্ন domain → ভিন্ন metric।
(ক) Email spam filter:
- Optimize: Precision (high)।
- Reasoning: Legitimate email spam-এ ফেলা = user frustration। User-এর important email lost।
- Cost matrix: FP = ১০০ (legitimate lost); FN = ১ (spam in inbox — easy to delete)।
- Threshold: Conservative (high prob threshold)। ১০ spam inbox-এ থাকলেও — ১ legitimate filter-এ ফেলা ভয়াবহ।
(খ) Bkash fraud detection:
- Optimize: Recall (high) — কিন্তু অবশ্যই precision balance।
- Reasoning: Fraud miss করা = টাকা harm; FP — block legitimate transaction = customer annoyed।
- Imbalanced (০.১% fraud) — accuracy useless।
- Practical: F1 + business cost matrix। Fraud cost > FP cost — recall higher weight।
- Layered approach: High recall first stage → manual review high precision। PR-AUC + threshold tuning।
(গ) Cancer screening:
- Optimize: Recall (very high — ৯৯%+)।
- Reasoning: Cancer miss = মৃত্যু। FP = additional test (cost, anxiety, but not death)।
- Cost ratio: FN ১০০০x more costly than FP।
- Practical: Recall ০.৯৯, precision ০.১০ acceptable। ১০০ false alarms per missed cancer — fine।
- Sensitivity-Specificity medical literature-এ। ROC curve standard।
(ঘ) Music recommendation:
- Optimize: Ranking metrics — NDCG, MAP, Precision@K।
- Reasoning: User শুধু top ১০-২০ recommendation দেখে — তাদের relevance important। Bottom ১০০০ irrelevant।
- Not binary: "Like" gradient (tap, listen-time, replay)।
- Online metric: Click-through-rate (CTR), session length, return visits — A/B test।
- Diversity metric: "Filter bubble" এড়াতে।
একটি cross-cutting principle:
- Offline metric (F1, AUC) — proxy।
- Real metric — business outcome (revenue, retention, deaths prevented)।
- Always validate offline-online correlation।
মূল উপলব্ধি: "Best metric" doesn't exist — শুধু "right metric for THIS problem"। Cost matrix carefully analyze করুন।
প্র ০২ "AUC ০.৯৫ মডেল ভাল" — এটা কেন সবসময় সত্য না? PR-AUC vs ROC-AUC — imbalanced data-এ কোনটা?
AUC misinterpretation ML-এর সবচেয়ে সাধারণ mistakes-এর একটি। Practitioners ০.৯+ AUC দেখে assume "great model" — অনেক সময় ভুল।
ROC-AUC কী মাপে:
- Random positive ও negative — কত % সময় positive higher score পায়।
- "Ranking quality" — threshold-independent।
- Class balance-এর প্রতি প্রায়-invariant।
সমস্যা ১: Imbalanced data-এ misleading
- ১% positive class।
- Negative class বিশাল — অনেক true negative।
- FPR = FP/N। N বিশাল হলে — হাজার FP-ও FPR ছোট।
- ROC curve সহজে এক কোণার কাছে — AUC ০.৯৫।
- কিন্তু precision ০.১০ — ১০০ alert-এর ১০ সঠিক।
উদাহরণ:
- ১০K test samples; ১০০ positive।
- Model ৫০০ alert; ৭০ সঠিক, ৪৩০ FP।
- Recall = ৭০/১০০ = ০.৭০।
- FPR = ৪৩০/৯৯০০ = ০.০৪৩ (small!)।
- ROC curve almost ideal → AUC ~০.৯৫।
- Precision = ৭০/৫০০ = ০.১৪ — ৮৬% alerts wrong।
সমাধান — PR-AUC:
- Y-axis: Precision; X-axis: Recall।
- Imbalanced data-এ — অনেক বেশি sensitive।
- Baseline = positive class fraction (০.০১, ০.০৫ etc.)।
- PR-AUC ০.৩ — ০.০১ baseline-এর ৩০ গুণ ভাল — significant।
- ROC-AUC ০.৯ এর সাথে PR-AUC ০.২ — class minority confusion।
সমস্যা ২: Threshold কী হবে — AUC বলে না
- Production-এ specific threshold লাগে।
- Different threshold-এ ভিন্ন precision-recall।
- AUC overall ranking; specific operating point আলাদা।
সমস্যা ৩: Calibration আলাদা
- AUC ranking metric — actual probability calibrated কি না বলে না।
- "৭০% probability" আসলে ৭০% নাকি ৩০%?
- Brier score বা reliability diagram দরকার।
সমস্যা ৪: Class imbalance change
- Test set-এর class ratio শিফট হলে — ROC-AUC stable, কিন্তু precision/recall শিফট।
Best practices:
- Imbalanced — PR-AUC report।
- Both report — ROC ও PR।
- Specific threshold-এ confusion matrix।
- Confidence intervals (bootstrap)।
- Calibration plot।
একটি famous paper: "The Relationship Between Precision-Recall and ROC Curves" (Davis & Goadrich, ICML 2006)। Imbalanced data-এ PR superior।
মূল উপলব্ধি: "AUC ০.৯+" pretty number — কিন্তু production behavior describe করে না। Multiple metrics + threshold analysis।
প্র ০৩ Regression-এ একটি model R²=০.৯, MAPE=১৫%, MAE=১২। অন্যটি R²=০.৭, MAPE=৫%, MAE=৩। কোনটা ভাল? — কেন এটি একটি tricky প্রশ্ন?
Regression metrics-এর "ভাল-মন্দ" context-dependent। Different metrics সাধারণত correlated কিন্তু সবসময় না — তখন insight শুরু।
প্রথমে — কী হচ্ছে বুঝি:
- R² ০.৯ vs ০.৭: মডেল ১ variance বেশি explain।
- MAPE ১৫% vs ৫%: মডেল ২ relative error অনেক ছোট।
- MAE ১২ vs ৩: মডেল ২ absolute error ৪x ছোট।
- Contradiction: R² বলে ১ ভাল; MAE/MAPE বলে ২ ভাল।
R² কেন উচ্চ — অথচ error বেশি:
- R² = ১ - SS_res/SS_tot।
- $y$-এর variance বেশি হলে — moderate error-ও high R²।
- $y$-এর variance কম হলে — small error-ও low R²।
- R² scale-dependent on the variability of $y$ in your test set।
সম্ভাব্য scenario:
- মডেল ১: ব্যাপক range-এর $y$ predict — bad units, captures big trends।
- মডেল ২: Narrower range, but precise within।
- Same data — different problems formulated।
কোনটি ভাল — depends:
- House price prediction (range ১০L-১০CR):
- মডেল ১ — high R², ১৫% MAPE। Accept।
- "১.৫ Crore" বলবে যেখানে actual ১.৩ Crore — acceptable।
- Temperature prediction (২৫-৩৫°C):
- মডেল ২ — ৩°C MAE preferable।
- ৫% MAPE = ১.৫°C — perfect for forecasting।
Considerations:
(১) Outliers কীভাবে handle:
- MSE (R²-এর basis) — outliers heavily penalize।
- MAE — robust।
- Outlier-rich data-এ R² misleading।
(২) Scale dependency:
- MAPE % — scale-free, business-friendly।
- MAE — same units as target — interpretable।
- R² — fraction of variance — scale-free কিন্তু benchmark-dependent।
(৩) Distribution of $y$:
- $y = 0$-এর কাছাকাছি — MAPE explode (division by zero)।
- Skewed $y$ — log-transform consider।
(৪) Business meaning:
- "১৫% off" — pricing acceptable, dosage critical।
- Dollar amounts — MAE direct interpretable।
আমার approach:
- Always report multiple — RMSE, MAE, R²।
- Visualize residuals — distribution বুঝা।
- Domain expert-এর সাথে — "৫°C error in temperature" meaning।
- Best-case ও worst-case examples দেখানো।
মূল উপলব্ধি: Single metric দিয়ে regression model judge করা incomplete। Multiple complementary metrics + domain context।
প্র ০৪ "Threshold ০.৫ default" — কেন এটি সাধারণত ভুল choice? Threshold tuning কীভাবে ও কখন?
০.৫ threshold — historical artifact, optimal rarely। Threshold tuning practitioner expertise-এর marker।
০.৫-এর ইতিহাস:
- Logistic regression default — sigmoid ০.৫ midpoint।
- Balanced data-এ — accuracy maximize।
- Imbalanced data-এ — meaningless।
কেন প্রায়ই ভুল:
- Imbalanced training — model probability skew towards majority।
- Cost asymmetry — FP vs FN-এর cost ভিন্ন।
- Calibration imperfect — output "probability" actual probability নাও হতে পারে।
- Domain requirement — "block ১০% top risky" — independent of ০.৫।
Threshold tuning techniques:
(১) F1-maximizing threshold:
- Precision-recall curve plot।
- Threshold range ০.০১ থেকে ০.৯৯।
- F1 calculate প্রতি threshold।
- argmax F1 select।
(২) Cost-based:
- Cost matrix define: FP cost, FN cost।
- Total cost = FP_cost × FP_count + FN_cost × FN_count।
- Minimize cost → optimal threshold।
(৩) Operating point:
- "Recall ০.৯-এ সর্বোচ্চ precision চাই"।
- PR curve থেকে ০.৯ recall-এ threshold।
(৪) Capacity constraint:
- "মাত্র ১০০ alerts/day handle করতে পারি"।
- Top ১০০ predicted — implicit threshold।
(৫) Youden's J statistic:
- J = TPR - FPR (recall - FPR)।
- argmax J — ROC curve-এর "knee"।
- Equal weight to TP and TN।
scikit-learn-এ সরাসরি code:
from sklearn.metrics import precision_recall_curve
y_prob = model.predict_proba(X_te)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_te, y_prob)
# F1 maximize
f1 = 2 * precision * recall / (precision + recall + 1e-10)
best_idx = f1.argmax()
best_threshold = thresholds[best_idx]
print(f"Best threshold: {best_threshold:.3f}, F1: {f1[best_idx]:.4f}")
সাধারণ pitfall:
- Test set-এ threshold tune — leakage। Validation-এ tune, test-এ apply।
- Production drift — threshold periodically update।
- Multiple class — multi-threshold complex।
Calibration-এর সাথে সম্পর্ক:
- Calibrated model — ০.৭ output → ৭০% positive probability।
- Well-calibrated — threshold meaningful।
- Uncalibrated (Naive Bayes, SVM) — threshold tune essential।
- Platt scaling, isotonic regression — calibration techniques।
Asymmetric thresholds বিশেষ ক্ষেত্রে:
- "Definitely positive" — ০.৯+ → auto-action।
- "Definitely negative" — ০.১-এর নিচে → auto-reject।
- Middle (০.১-০.৯) — human review।
- "Reject option" classification।
মূল উপলব্ধি: Threshold model-এর integral part — careful selection essential। ০.৫ default rarely appropriate। Validation set-এ optimize, business-aligned।
অনুশীলন
-
হিসাব: Confusion matrix — TP=৭০, FP=২০, FN=১০, TN=৯০০। Precision, Recall, F1, Accuracy?
- Precision = ৭০/৯০ = ০.৭৭৮
- Recall = ৭০/৮০ = ০.৮৭৫
- F1 = ২(০.৭৭৮)(০.৮৭৫)/(০.৭৭৮+০.৮৭৫) = ০.৮২৪
- Accuracy = ৯৭০/১০০০ = ০.৯৭০
-
scikit-learn: উপরের code চালান। imbalanced ratio change করুন (০.৯৯ vs ০.০১) — কোন metric বেশি drop?
Imbalance বাড়লে — accuracy stable বা বাড়ে; precision/recall/F1 drop। AUC সাধারণত stable। PR-AUC drop। Imbalance-এর প্রকৃত effect F1 ও PR-AUC-এ।
-
চিন্তা: "Hospital readmission risk score" — ১ থেকে ১০। Doctor চান top 20% high-risk patient flag করতে। কী metric optimize, কী threshold?
Capacity-constrained — top ২০% prob threshold। Metric: precision@20%। AUC overall ranking quality। Recall: actual readmission-এর কতটা top ২০%-এ পড়ল।
আরও পড়ুন
- পাঠ ০৭ · Confusion matrix বোঝা পরবর্তী পাঠ এই metrics-এর source — confusion matrix-এর গভীর analysis।
- পাঠ ০৫ · Cross-validation আগের পাঠ Robust score estimate-এর পদ্ধতি।
- পাঠ ৪৩ · Imbalanced classes পরবর্তী মডিউল Imbalance handle করার techniques।
- AI Foundations · L28 · Metrics প্রাসঙ্গিক Foundational metric concepts।