The Story: Dr. Meera's TB Screening Crisis
Rohan builds a model, tests it, and comes back beaming: "Doctor, the model is 89.5% accurate!"
Dr. Meera is unconvinced. She asks Rohan to tell her specifically how many real TB patients the model missed. Rohan checks — the model missed 5 out of 50 TB patients. Five people with active, infectious TB walked out undetected.
At the same time, it sent 100 healthy people for needlessly expensive follow-up tests.
"That is not 89.5% good," Dr. Meera says. "That is a public health failure. You need better metrics." Rohan reaches for Precision, Recall, and F1 Score.
Look for the interactive boxes: the Accuracy Trap (Section 02), the Patient Sorter (03), Two Pools (05), the Threshold Trade-off (06), Harmonic vs Arithmetic (07), the F-Beta Dial (08), the Metric Explorer (09), the Robust Metrics Lab (10) and the Averaging Lab (11). Move sliders, click cells and type numbers. Every value is computed live.
Why Accuracy Fails on Imbalanced Data
| Metric | Value | What It Hides |
|---|---|---|
| Accuracy | 89.5% | Looks great — is misleading |
| Missed TB cases (FN) | 5 patients | Walking out undetected |
| Wasted tests (FP) | 100 patients | Unnecessary cost & stress |
A model that predicts everyone is healthy gets (950/1000) = 95% accuracy — yet catches zero TB cases. Accuracy is useless here.
| Metric | Value | What It Reveals |
|---|---|---|
| Precision | 31% | Most positive flags are wrong |
| Recall | 90% | Most real TB cases are caught |
| F1 Score | 46% | Overall weak performance |
These metrics tell the true story: the model floods the lab with false alarms but does catch 90% of actual TB. Whether that trade-off is acceptable is a medical decision, not a model decision.
Try It — The Accuracy Trap
Each square is one of Dr. Meera's 1 000 patients. Pick a model and watch the colours: green = TB caught, red = TB missed, amber = false alarm, light blue = healthy and cleared. Then move the TB prevalence and see what happens to accuracy.
कहानी: डॉ. मीरा की TB Screening मुश्किल
रोहन model बनाता है, उसे test करता है, और खुशी से लौटता है: "डॉक्टर, model 89.5% accurate है!"
डॉ. मीरा को भरोसा नहीं होता। वो रोहन से साफ़-साफ़ पूछती हैं कि model ने कितने असली TB मरीज़ों को miss किया। रोहन चेक करता है — model ने 50 में से 5 TB मरीज़ों को miss किया। active और फैलने वाली TB वाले पाँच लोग बिना पकड़े बाहर चले गए।
साथ ही, model ने 100 स्वस्थ लोगों को बेवजह महँगे follow-up test के लिए भेज दिया।
"यह 89.5% अच्छा नहीं है," डॉ. मीरा कहती हैं। "यह public health की नाकामी है। तुम्हें बेहतर metrics चाहिए।" तब रोहन Precision, Recall, और F1 Score की ओर बढ़ता है।
इन interactive boxes को देखिए: Accuracy Trap (सेक्शन 02), Patient Sorter (03), Two Pools (05), Threshold Trade-off (06), Harmonic vs Arithmetic (07), F-Beta Dial (08), Metric Explorer (09), Robust Metrics Lab (10) और Averaging Lab (11)। sliders खिसकाइए, cells पर click कीजिए और numbers टाइप कीजिए। हर value तुरंत live निकलती है।
Imbalanced Data पर Accuracy क्यों फेल होती है
| Metric | Value | यह क्या छुपाता है |
|---|---|---|
| Accuracy | 89.5% | बढ़िया दिखती है — पर गुमराह करती है |
| Miss हुए TB केस (FN) | 5 मरीज़ | बिना पकड़े बाहर चले गए |
| बेकार के test (FP) | 100 मरीज़ | बेवजह खर्च और तनाव |
जो model कहे कि सब स्वस्थ हैं, उसे (950/1000) = 95% accuracy मिलती है — फिर भी वो एक भी TB केस नहीं पकड़ता। यहाँ accuracy किसी काम की नहीं।
| Metric | Value | यह क्या बताता है |
|---|---|---|
| Precision | 31% | ज़्यादातर positive flags गलत हैं |
| Recall | 90% | ज़्यादातर असली TB केस पकड़े गए |
| F1 Score | 46% | कुल मिलाकर कमज़ोर performance |
ये metrics सच्ची कहानी बताते हैं: model lab को false alarms से भर देता है, पर असली TB के 90% केस पकड़ लेता है। यह trade-off ठीक है या नहीं, यह एक medical फ़ैसला है, model का नहीं।
खुद करके देखिए — The Accuracy Trap
हर square डॉ. मीरा के 1 000 मरीज़ों में से एक है। एक model चुनिए और रंग देखिए: हरा = TB पकड़ी गई, लाल = TB miss हुई, पीला = false alarm, हल्का नीला = स्वस्थ और clear। फिर TB prevalence बदलिए और देखिए कि accuracy का क्या होता है।
故事:Dr. Meera 的 TB 筛查危机
Rohan 做好 model,测试后笑着回来说: “医生,这个 model 的 accuracy 有 89.5%!”
Dr. Meera 并不相信。她让 Rohan 具体告诉她,model 漏掉了 多少真正的 TB 病人。Rohan 查了一下:model 漏掉了 50 名 TB 病人中的 5 名。五个患有活动性、有传染性 TB 的人没有被发现,就这样离开了。
同时,它还让 100 名健康的人去做了 没有必要的昂贵复查。
“这不是 89.5% 的好,”Dr. Meera 说,“这是一次公共卫生的失败。 你需要更好的 metric。”于是 Rohan 拿出了 Precision、Recall 和 F1 Score。
请留意这些互动框:Accuracy Trap(第 02 节)、Patient Sorter(03)、 Two Pools(05)、Threshold Trade-off(06)、Harmonic vs Arithmetic(07)、 F-Beta Dial(08)、Metric Explorer(09)、Robust Metrics Lab(10) 和 Averaging Lab(11)。你可以拖动滑块、点击格子、输入数字。每个数值都会实时计算。
为什么 Accuracy 在不平衡数据上会失效
| Metric | 数值 | 它掩盖了什么 |
|---|---|---|
| Accuracy | 89.5% | 看起来很好,但会误导人 |
| 漏掉的 TB 病例(FN) | 5 名病人 | 没被发现就离开了 |
| 浪费的检查(FP) | 100 名病人 | 不必要的花费和压力 |
一个预测所有人都健康的 model 能得到 (950/1000) = 95% 的 accuracy,但一个 TB 病例都抓不到。 在这里 accuracy 没有用。
| Metric | 数值 | 它揭示了什么 |
|---|---|---|
| Precision | 31% | 大多数 positive 标记是错的 |
| Recall | 90% | 大多数真实 TB 病例被抓到了 |
| F1 Score | 46% | 整体表现较弱 |
这些 metric 说出了真实情况:model 给实验室带来大量误报, 但确实抓到了 90% 的真实 TB。这个 trade-off 能不能接受, 是一个医学决定,不是 model 的决定。
动手试试:Accuracy Trap
每个小方块代表 Dr. Meera 的 1 000 名病人中的一位。选一个 model,看看颜色: 绿色 = 抓到了 TB,红色 = 漏掉了 TB, 琥珀色 = 误报,浅蓝色 = 健康且被正确排除。 然后调整 TB 患病率,看看 accuracy 会怎么变化。
The Confusion Matrix — The Foundation of All Metrics
Every classification metric is derived from a single 2×2 table called the Confusion Matrix. Understanding it is the first step.
| Cell | Full Name | Count | Plain-English Meaning |
|---|---|---|---|
| TN | True Negative | 850 | Healthy patients correctly cleared — no action needed |
| FP | False Positive | 100 | Healthy patients wrongly flagged — wasted tests, anxiety |
| FN | False Negative | 5 | TB patients missed — most dangerous; walk away untreated |
| TP | True Positive | 45 | TB patients correctly detected — the goal |
In disease detection, fraud, and safety systems, a False Negative (missed threat) is usually far more costly than a False Positive (false alarm). A missed TB patient spreads infection. A missed fraud claim costs thousands. A missed safety defect causes accidents. Always ask: "Which error is worse in my domain?" — then choose and tune your metrics accordingly.
Try It — Patient Sorter
Sort 16 patients into the confusion matrix yourself. Each card shows the truth and what the model said. Click TP, FP, FN or TN. The patient then drops into the right cell.
Confusion Matrix — सभी Metrics की नींव
हर classification metric एक ही 2×2 table से निकलता है, जिसे Confusion Matrix कहते हैं। इसे समझना पहला कदम है।
| Cell | पूरा नाम | गिनती | आसान भाषा में मतलब |
|---|---|---|---|
| TN | True Negative | 850 | स्वस्थ मरीज़ सही से clear हुए — कुछ करने की ज़रूरत नहीं |
| FP | False Positive | 100 | स्वस्थ मरीज़ गलती से flag हुए — बेकार के test, चिंता |
| FN | False Negative | 5 | TB मरीज़ छूट गए — सबसे खतरनाक; बिना इलाज चले जाते हैं |
| TP | True Positive | 45 | TB मरीज़ सही पकड़े गए — यही लक्ष्य है |
बीमारी पकड़ने, fraud और safety systems में, False Negative (छूटा हुआ खतरा) आमतौर पर False Positive (false alarm) से कहीं ज़्यादा महँगा होता है। छूटा हुआ TB मरीज़ infection फैलाता है। छूटा हुआ fraud claim हज़ारों का नुकसान करता है। छूटी हुई safety खराबी हादसे करवाती है। हमेशा पूछिए: "मेरे field में कौन सी गलती ज़्यादा बुरी है?" — फिर उसी हिसाब से अपने metrics चुनिए और tune कीजिए।
खुद करके देखिए — Patient Sorter
16 मरीज़ों को खुद confusion matrix में बाँटिए। हर card पर सच और model का जवाब दिखता है। TP, FP, FN या TN पर click कीजिए। फिर मरीज़ सही cell में चला जाता है।
Confusion Matrix:所有 metric 的基础
每一个 classification metric 都来自一张 2×2 的表,叫做 Confusion Matrix。理解它是第一步。
| 格子 | 全称 | 数量 | 通俗解释 |
|---|---|---|---|
| TN | True Negative | 850 | 健康的病人被正确排除,不需要处理 |
| FP | False Positive | 100 | 健康的病人被错误标记,浪费检查,带来焦虑 |
| FN | False Negative | 5 | TB 病人被漏掉,最危险;他们没有得到治疗就离开了 |
| TP | True Positive | 45 | TB 病人被正确发现,这正是目标 |
在疾病检测、欺诈检测和安全系统中,False Negative (漏掉的威胁)通常比 False Positive(误报)的代价大得多。 漏掉一个 TB 病人,会传播感染。漏掉一笔欺诈理赔,会损失好几千。 漏掉一个安全缺陷,会造成事故。一定要问:“在我的领域里, 哪种错误更糟?”然后据此选择和调整你的 metric。
动手试试:Patient Sorter
自己把 16 名病人分到 confusion matrix 里。每张卡片显示真实情况和 model 的判断。 点击 TP、FP、FN 或 TN。病人就会落到对应的格子里。
Precision — When You Raise the Alarm, How Often Are You Right?
High precision is critical when false alarms are costly. Examples: a spam filter that moves legitimate emails to spam (FP = lost business email); a legal document retrieval system that returns irrelevant results (FP = wasted lawyer hours); a credit card block that stops a legitimate transaction (FP = angry customer). In all these cases, you want every positive prediction to be correct.
Recall — Of All Real Positives, How Many Did You Find?
High recall is critical when missing a real positive is catastrophic. Examples: cancer screening (missing cancer = delayed treatment, death); fraud detection (missing fraud = financial loss); airport security (missing a threat = public safety risk); earthquake early warning (missing an alert = disaster). In these domains, you would rather have many false alarms than miss one real event.
Try It — Two Pools
Precision and recall divide by different groups of patients. Left: everyone the model flagged. Right: everyone who really has TB. Change the number of false alarms (FP) and missed cases (FN) and watch each pool.
Precision — जब आप alarm बजाते हैं, तो कितनी बार सही होते हैं?
High precision तब बहुत ज़रूरी है जब false alarms महँगे हों। उदाहरण: एक spam filter जो असली emails को spam में डाल दे (FP = ज़रूरी business email खो गया); एक legal document खोजने वाला system जो बेकार results दे (FP = वकील के घंटे बर्बाद); एक credit card block जो सही transaction रोक दे (FP = नाराज़ customer)। इन सभी cases में, आप चाहते हैं कि हर positive prediction सही हो।
Recall — सभी असली Positives में से आपने कितने ढूँढे?
High recall तब बहुत ज़रूरी है जब एक असली positive छूटना भारी तबाही हो। उदाहरण: cancer screening (cancer छूटा = इलाज में देर, मौत); fraud detection (fraud छूटा = पैसों का नुकसान); airport security (कोई खतरा छूटा = लोगों की सुरक्षा को खतरा); भूकंप की early warning (alert छूटा = आपदा)। इन fields में, एक असली घटना छूटने से बेहतर है कि बहुत सारे false alarms हों।
खुद करके देखिए — Two Pools
Precision और recall मरीज़ों के अलग-अलग groups से भाग देते हैं। बाएँ: वो सब जिन्हें model ने flag किया। दाएँ: वो सब जिन्हें सच में TB है। false alarms (FP) और छूटे cases (FN) की गिनती बदलिए और हर pool को देखिए।
Precision:当你发出警报时,有多少次是对的?
当误报的代价很高时,高 precision 非常关键。例如: 垃圾邮件过滤器把正常邮件放进垃圾箱(FP = 丢失业务邮件); 法律文件检索系统返回无关结果(FP = 浪费律师的工作时间); 信用卡冻结拦下了一笔正常交易(FP = 生气的客户)。 在这些情况下,你希望每一个 positive prediction 都是正确的。
Recall:在所有真正的 Positive 中,你找到了多少?
当漏掉一个真正的 positive 会造成灾难时,高 recall 非常关键。 例如:癌症筛查(漏掉癌症 = 延误治疗,甚至死亡); 欺诈检测(漏掉欺诈 = 经济损失);机场安检(漏掉一个 威胁 = 公共安全风险);地震预警(漏掉一次警报 = 灾难)。 在这些领域,你宁愿有很多误报,也不想漏掉一个真实事件。
动手试试:Two Pools
Precision 和 recall 除以的是不同的病人群体。左边:所有被 model 标记的人。 右边:所有真正患有 TB 的人。改变误报(FP)和漏诊(FN)的数量,看看每一组的变化。
The Precision-Recall Trade-off
Precision and Recall pull in opposite directions. As you lower the classification threshold (flag more things as positive), you catch more real positives (recall rises) but also flag more false alarms (precision falls). As you raise the threshold, you become more selective (precision rises) but miss more real positives (recall falls).
The vertical dashed line marks where F1 Score peaks — the balanced operating point. Moving left (lower threshold) boosts Recall at the cost of Precision. Moving right (higher threshold) boosts Precision at the cost of Recall.
Try It — Threshold Trade-off
Now the model gives each of the 1 000 patients a TB score. Anyone at or above the threshold is flagged. Slide the threshold (or click the chart) and watch precision, recall and F1 move against each other.
Precision-Recall Trade-off
Precision और Recall उल्टी दिशाओं में खींचते हैं। जब आप classification threshold घटाते हैं (ज़्यादा चीज़ों को positive flag करते हैं), तो आप ज़्यादा असली positives पकड़ते हैं (recall बढ़ता है), पर ज़्यादा false alarms भी आते हैं (precision गिरता है)। जब आप threshold बढ़ाते हैं, तो आप ज़्यादा चुनिंदा हो जाते हैं (precision बढ़ता है), पर ज़्यादा असली positives छूट जाते हैं (recall गिरता है)।
खड़ी dashed line वहाँ है जहाँ F1 Score सबसे ऊपर है — यही संतुलित operating point है। बाएँ जाने पर (कम threshold) Recall बढ़ता है, पर Precision घटता है। दाएँ जाने पर (ज़्यादा threshold) Precision बढ़ता है, पर Recall घटता है।
खुद करके देखिए — Threshold Trade-off
अब model 1 000 मरीज़ों में से हर एक को एक TB score देता है। जिसका score threshold के बराबर या ऊपर है, वो flag होता है। threshold को खिसकाइए (या chart पर click कीजिए) और देखिए कि precision, recall और F1 एक-दूसरे के उलट कैसे चलते हैं।
Precision-Recall 的 Trade-off
Precision 和 Recall 朝着相反的方向拉扯。当你降低 classification threshold(把更多对象标记为 positive)时,你会抓到更多真正的 positive(recall 上升),但也会产生更多误报(precision 下降)。 当你提高 threshold 时,你会变得更挑剔(precision 上升),但 会漏掉更多真正的 positive(recall 下降)。
竖直的虚线标出 F1 Score 的峰值,也就是平衡的工作点。 往左移(threshold 更低)会提高 Recall,但会牺牲 Precision。 往右移(threshold 更高)会提高 Precision,但会牺牲 Recall。
动手试试:Threshold Trade-off
现在 model 给 1 000 名病人每人一个 TB score。score 等于或高于 threshold 的人都会被标记。 拖动 threshold(或点击图表),看看 precision、recall 和 F1 如何此消彼长。
F1 Score — The Harmonic Mean of Precision and Recall
Neither Precision nor Recall alone is sufficient. We need a single metric that balances both. The F1 Score does this by taking their harmonic mean — not the arithmetic mean.
F1 = 2·TP / (2·TP + FP + FN)Ranges from 0 (worst) to 1 (perfect). Penalises extreme imbalances between P and R.
This gives an optimistic picture — it lets a very high Recall paper over a terrible Precision.
Arithmetic mean = (1.0 + 0.05) / 2 = 0.525 = 52.5% — looks decent!
Harmonic mean (F1) = 2·(1.0·0.05) / (1.0+0.05) = 0.095 = 9.5% — correctly terrible.
Try It — Harmonic vs Arithmetic
Set a precision and a recall (or click the map). Compare the plain average with F1. In the map, darker green means a higher F1, and each curve joins points with the same F1.
F1 Score — Precision और Recall का Harmonic Mean
अकेला Precision या अकेला Recall काफ़ी नहीं है। हमें एक ऐसा metric चाहिए जो दोनों को संतुलित करे। F1 Score यही करता है। यह दोनों का harmonic mean लेता है — arithmetic mean नहीं।
F1 = 2·TP / (2·TP + FP + FN)इसकी value 0 (सबसे खराब) से 1 (perfect) तक होती है। यह P और R के बीच बहुत ज़्यादा अंतर को सज़ा देता है।
यह एक ज़रूरत से ज़्यादा अच्छी तस्वीर दिखाता है — बहुत ऊँचा Recall बहुत खराब Precision को ढक देता है।
Arithmetic mean = (1.0 + 0.05) / 2 = 0.525 = 52.5% — ठीक-ठाक लगता है!
Harmonic mean (F1) = 2·(1.0·0.05) / (1.0+0.05) = 0.095 = 9.5% — सही में बहुत खराब।
खुद करके देखिए — Harmonic vs Arithmetic
एक precision और एक recall सेट कीजिए (या map पर click कीजिए)। सीधे average की तुलना F1 से कीजिए। Map में, गहरा हरा मतलब ज़्यादा F1, और हर curve एक जैसे F1 वाले points को जोड़ता है।
F1 Score:Precision 和 Recall 的 Harmonic Mean
单看 Precision 或 Recall 都不够。我们需要一个能同时 平衡两者的 metric。F1 Score 的做法是取它们的 harmonic mean,而不是 arithmetic mean。
F1 = 2·TP / (2·TP + FP + FN)取值从 0(最差)到 1(完美)。P 和 R 相差很大时,它会给出惩罚。
这给出的是一个过于乐观的结果:它让很高的 Recall 掩盖了很差的 Precision。
Arithmetic mean = (1.0 + 0.05) / 2 = 0.525 = 52.5%,看起来还不错!
Harmonic mean(F1)= 2·(1.0·0.05) / (1.0+0.05) = 0.095 = 9.5%,正确地显示出它很糟糕。
动手试试:Harmonic vs Arithmetic
设定一个 precision 和一个 recall(或点击地图)。比较普通平均值和 F1。 在地图中,绿色越深表示 F1 越高,每条曲线连接的是 F1 相同的点。
F-Beta Score — Tuning the Precision-Recall Balance
The F1 score weights Precision and Recall equally. But in the real world, one is often more important than the other. The F-Beta score lets you control that balance with a single parameter β.
β = 1: equal weight → standard F1 score.
β > 1: weights Recall more heavily (e.g. β=2 → Recall twice as important).
| β Value | Name | Recall weight vs Precision | Use Case | Dr. Meera's Score |
|---|---|---|---|---|
β = 0.5 |
F0.5 | Precision 2× more important | Spam filter, legal search, product recommendation — false alarms are costly | F0.5 = (1+0.25)×(0.310×0.900)/(0.25×0.310+0.900) = 0.354 |
β = 1 |
F1 | Equal weight | General-purpose; balanced domains | 0.461 |
β = 2 |
F2 | Recall 2× more important | TB / cancer screening, fraud, safety — missed positives are catastrophic | F2 = (1+4)×(0.310×0.900)/(4×0.310+0.900) = 0.612 |
Dr. Meera consults with her epidemiologist and decides that for TB screening, a missed TB case is four times more costly than a false alarm. She adopts F2 as her primary metric. Under F2, the model scores 61.2% — still modest, but it now rewards the model's high recall while still accounting for the flood of false alarms. She lowers the threshold from 0.5 to 0.3 to push Recall above 95%, accepting lower Precision — and the F2 score guides whether the trade-off was worth it.
Try It — F-Beta Dial
Turn the β dial. The box shows Dr. Meera's Fβ worked out step by step. The chart shows Fβ for every threshold on the 1 000 patients and marks the best one. Watch the best threshold move as β changes.
F-Beta Score — Precision-Recall संतुलन को Tune करना
F1 score Precision और Recall को बराबर weight देता है। पर असली दुनिया में, अक्सर एक दूसरे से ज़्यादा ज़रूरी होता है। F-Beta score आपको एक ही parameter β से यह संतुलन control करने देता है।
β = 1: बराबर weight → सामान्य F1 score।
β > 1: Recall को ज़्यादा weight देता है (जैसे β=2 → Recall दोगुना ज़रूरी)।
| β Value | नाम | Precision के मुकाबले Recall का weight | कहाँ इस्तेमाल करें | डॉ. मीरा का Score |
|---|---|---|---|---|
β = 0.5 |
F0.5 | Precision 2× ज़्यादा ज़रूरी | Spam filter, legal search, product recommendation — false alarms महँगे हैं | F0.5 = (1+0.25)×(0.310×0.900)/(0.25×0.310+0.900) = 0.354 |
β = 1 |
F1 | बराबर weight | आम इस्तेमाल; संतुलित fields | 0.461 |
β = 2 |
F2 | Recall 2× ज़्यादा ज़रूरी | TB / cancer screening, fraud, safety — छूटे positives भारी तबाही हैं | F2 = (1+4)×(0.310×0.900)/(4×0.310+0.900) = 0.612 |
डॉ. मीरा अपने epidemiologist से सलाह लेती हैं। वो तय करती हैं कि TB screening में, एक छूटा TB केस एक false alarm से चार गुना ज़्यादा महँगा है। वो F2 को अपना मुख्य metric बनाती हैं। F2 में model का score 61.2% है — अब भी मामूली, पर अब यह model के high recall को इनाम देता है, और false alarms की बाढ़ को भी गिनता है। वो threshold को 0.5 से घटाकर 0.3 करती हैं ताकि Recall 95% से ऊपर जाए, और कम Precision मान लेती हैं — और F2 score बताता है कि यह trade-off फ़ायदेमंद था या नहीं।
खुद करके देखिए — F-Beta Dial
β dial घुमाइए। Box में डॉ. मीरा का Fβ step by step निकाला गया दिखता है। Chart 1 000 मरीज़ों पर हर threshold के लिए Fβ दिखाता है और सबसे अच्छे वाले को mark करता है। देखिए कि β बदलने पर best threshold कैसे खिसकता है।
F-Beta Score:调节 Precision 和 Recall 的平衡
F1 score 给 Precision 和 Recall 相同的权重。但在现实世界中, 往往其中一个比另一个更重要。F-Beta score 让你用一个参数 β 来控制这种平衡。
β = 1:权重相同 → 标准的 F1 score。
β > 1:更看重 Recall(例如 β=2 → Recall 的重要性是两倍)。
| β 值 | 名称 | Recall 相对 Precision 的权重 | 使用场景 | Dr. Meera 的分数 |
|---|---|---|---|---|
β = 0.5 |
F0.5 | Precision 重要 2 倍 | 垃圾邮件过滤、法律检索、商品推荐:误报的代价很高 | F0.5 = (1+0.25)×(0.310×0.900)/(0.25×0.310+0.900) = 0.354 |
β = 1 |
F1 | 权重相同 | 通用场景;两者同样重要的领域 | 0.461 |
β = 2 |
F2 | Recall 重要 2 倍 | TB / 癌症筛查、欺诈、安全:漏掉 positive 会造成灾难 | F2 = (1+4)×(0.310×0.900)/(4×0.310+0.900) = 0.612 |
Dr. Meera 咨询了她的流行病学专家,决定在 TB 筛查中, 漏掉一个 TB 病例的代价是误报的四倍。 她选用 F2 作为主要 metric。在 F2 下,这个 model 得分 61.2%。虽然仍然一般,但它现在会奖励 model 的高 recall,同时 也考虑到了大量误报。她把 threshold 从 0.5 降到 0.3,让 Recall 超过 95%,并接受更低的 Precision。 F2 score 帮助她判断这个 trade-off 是否值得。
动手试试:F-Beta Dial
转动 β 旋钮。方框里会一步一步算出 Dr. Meera 的 Fβ。图表显示 1 000 名病人在每个 threshold 下的 Fβ,并标出最好的那个。看看最佳 threshold 如何随 β 移动。
Other Essential Metrics
Specificity — Recall for the Negative Class
All Metrics at a Glance — Using Dr. Meera's Numbers
| Metric | Formula | Value | Meaning in TB Context |
|---|---|---|---|
| Accuracy | (TP+TN) / N | 89.5% | Misleading — ignores class imbalance |
| Precision (PPV) | TP / (TP+FP) | 31.0% | Only 3 in 10 positive flags are real TB |
| Recall (Sensitivity) | TP / (TP+FN) | 90.0% | Catches 9 of 10 real TB cases |
| Specificity (TNR) | TN / (TN+FP) | 89.5% | Clears 89.5% of healthy patients correctly |
| NPV | TN / (TN+FN) | 99.4% | If cleared, 99.4% chance actually healthy |
| F1 Score | 2·P·R / (P+R) | 46.1% | Balanced score — reveals the precision gap |
| F2 Score | (1+4)·P·R / (4P+R) | 61.2% | Recall-weighted — more appropriate here |
| False Discovery Rate | FP / (FP+TP) | 69.0% | 69% of positive alerts are false alarms |
| Miss Rate | FN / (FN+TP) | 10.0% | 10% of real TB cases are missed |
| Fall-out (FPR) | FP / (FP+TN) | 10.5% | 10.5% of healthy patients wrongly flagged |
Try It — Metric Explorer
Every metric in the table above comes from the same four numbers. Click a metric: the cells on top of its fraction glow green, cells only in the bottom get a purple ring, and ignored cells fade. Type new numbers or use the buttons.
दूसरे ज़रूरी Metrics
Specificity — Negative Class के लिए Recall
सभी Metrics एक नज़र में — डॉ. मीरा के Numbers से
| Metric | Formula | Value | TB के संदर्भ में मतलब |
|---|---|---|---|
| Accuracy | (TP+TN) / N | 89.5% | गुमराह करती है — class imbalance को अनदेखा करती है |
| Precision (PPV) | TP / (TP+FP) | 31.0% | 10 positive flags में से सिर्फ़ 3 असली TB हैं |
| Recall (Sensitivity) | TP / (TP+FN) | 90.0% | 10 असली TB केस में से 9 पकड़ता है |
| Specificity (TNR) | TN / (TN+FP) | 89.5% | 89.5% स्वस्थ मरीज़ों को सही clear करता है |
| NPV | TN / (TN+FN) | 99.4% | अगर clear हुए, तो 99.4% chance कि सच में स्वस्थ हैं |
| F1 Score | 2·P·R / (P+R) | 46.1% | संतुलित score — precision की कमी दिखाता है |
| F2 Score | (1+4)·P·R / (4P+R) | 61.2% | Recall को ज़्यादा weight — यहाँ ज़्यादा सही |
| False Discovery Rate | FP / (FP+TP) | 69.0% | 69% positive alerts false alarms हैं |
| Miss Rate | FN / (FN+TP) | 10.0% | 10% असली TB केस छूट जाते हैं |
| Fall-out (FPR) | FP / (FP+TN) | 10.5% | 10.5% स्वस्थ मरीज़ गलती से flag होते हैं |
खुद करके देखिए — Metric Explorer
ऊपर की table का हर metric इन्हीं चार numbers से बनता है। किसी metric पर click कीजिए: उसकी fraction के ऊपर वाले cells हरे चमकते हैं, सिर्फ़ नीचे वाले cells पर बैंगनी घेरा आता है, और बाकी cells फीके पड़ जाते हैं। नए numbers टाइप कीजिए या buttons इस्तेमाल कीजिए।
其他重要的 Metric
Specificity:Negative Class 的 Recall
所有 Metric 一览:用 Dr. Meera 的数字
| Metric | 公式 | 数值 | 在 TB 场景中的含义 |
|---|---|---|---|
| Accuracy | (TP+TN) / N | 89.5% | 有误导性:忽略了 class imbalance |
| Precision (PPV) | TP / (TP+FP) | 31.0% | 10 个 positive 标记中只有 3 个是真的 TB |
| Recall (Sensitivity) | TP / (TP+FN) | 90.0% | 抓到 10 个真实 TB 病例中的 9 个 |
| Specificity (TNR) | TN / (TN+FP) | 89.5% | 正确排除了 89.5% 的健康病人 |
| NPV | TN / (TN+FN) | 99.4% | 如果被排除,有 99.4% 的可能真的健康 |
| F1 Score | 2·P·R / (P+R) | 46.1% | 平衡的分数:暴露了 precision 的短板 |
| F2 Score | (1+4)·P·R / (4P+R) | 61.2% | 更看重 recall:在这里更合适 |
| False Discovery Rate | FP / (FP+TP) | 69.0% | 69% 的 positive 警报是误报 |
| Miss Rate | FN / (FN+TP) | 10.0% | 10% 的真实 TB 病例被漏掉 |
| Fall-out (FPR) | FP / (FP+TN) | 10.5% | 10.5% 的健康病人被错误标记 |
动手试试:Metric Explorer
上表中的每个 metric 都来自同样的四个数字。点击一个 metric:位于分子的格子会发出 绿色光,只在分母中的格子会有一个紫色圆环,没用到的格子会变淡。 输入新的数字,或者使用按钮。
healthy
TB
Advanced Metrics: MCC and Cohen's Kappa
When class imbalance is severe and you need a single metric that's genuinely robust, two metrics stand out above accuracy and F1.
Formula:
MCC = (TP·TN − FP·FN) / √[(TP+FP)(TP+FN)(TN+FP)(TN+FN)]Dr. Meera's model:
MCC = (45·850 − 100·5) / √[(145)(50)(950)(855)]
= (38 250 − 500) / √[5 893 781 250]
= 37 750 / 76 773 ≈ 0.491
Formula:
κ = (p_observed − p_expected) / (1 − p_expected)Where p_expected is what you'd get by chance given class distributions.
κ < 0: worse than chance | κ = 0: chance level | κ = 1: perfect agreement
General guide: κ < 0.20 = poor, 0.20–0.40 = fair, 0.40–0.60 = moderate, 0.60–0.80 = substantial, 0.80–1.0 = almost perfect.
Formula:
Balanced Accuracy = (Recall + Specificity) / 2Dr. Meera's model: (0.900 + 0.895) / 2 = 0.8975 = 89.75%
Much more honest than the raw 89.5% accuracy, and it reflects the model's genuine ability on both classes equally.
| Metric | Range | Handles Imbalance? | Uses all 4 CM cells? | Best for |
|---|---|---|---|---|
| Accuracy | 0–1 | No | Yes | Balanced datasets only |
| Precision | 0–1 | Partial | No (TN ignored) | FP cost is high |
| Recall | 0–1 | Partial | No (TN ignored) | FN cost is high |
| F1 | 0–1 | Partial | No (TN ignored) | General-purpose imbalance |
| MCC | −1 to 1 | Yes | Yes | Imbalanced binary — most robust |
| Cohen's Kappa | −1 to 1 | Yes | Yes | Agreement quality; multi-class |
| Balanced Accuracy | 0–1 | Yes | Yes | Interpretable imbalance metric |
Try It — Robust Metrics Lab
Five models, five metrics, one chart. Pick a model (or type your own four numbers) and compare the bars. Watch accuracy stay high for the useless models while MCC and κ drop to zero or below.
Advanced Metrics: MCC और Cohen's Kappa
जब class imbalance बहुत ज़्यादा हो और आपको एक ऐसा metric चाहिए जो सच में मज़बूत हो, तो दो metrics accuracy और F1 से आगे निकलते हैं।
Formula:
MCC = (TP·TN − FP·FN) / √[(TP+FP)(TP+FN)(TN+FP)(TN+FN)]डॉ. मीरा का model:
MCC = (45·850 − 100·5) / √[(145)(50)(950)(855)]
= (38 250 − 500) / √[5 893 781 250]
= 37 750 / 76 773 ≈ 0.491
Formula:
κ = (p_observed − p_expected) / (1 − p_expected)यहाँ p_expected वो है जो class distributions के हिसाब से सिर्फ़ chance से मिलता।
κ < 0: chance से भी बुरा | κ = 0: chance level | κ = 1: perfect सहमति
आम गाइड: κ < 0.20 = कमज़ोर, 0.20–0.40 = ठीक-ठाक, 0.40–0.60 = मध्यम, 0.60–0.80 = अच्छा, 0.80–1.0 = लगभग perfect।
Formula:
Balanced Accuracy = (Recall + Specificity) / 2डॉ. मीरा का model: (0.900 + 0.895) / 2 = 0.8975 = 89.75%
यह सीधी 89.5% accuracy से कहीं ज़्यादा ईमानदार है, और यह model की असली क्षमता को दोनों classes पर बराबर दिखाता है।
| Metric | Range | Imbalance संभालता है? | चारों CM cells इस्तेमाल करता है? | किसके लिए सबसे अच्छा |
|---|---|---|---|---|
| Accuracy | 0–1 | नहीं | हाँ | सिर्फ़ balanced datasets |
| Precision | 0–1 | आंशिक | नहीं (TN अनदेखा) | जब FP की कीमत ज़्यादा हो |
| Recall | 0–1 | आंशिक | नहीं (TN अनदेखा) | जब FN की कीमत ज़्यादा हो |
| F1 | 0–1 | आंशिक | नहीं (TN अनदेखा) | आम imbalance के लिए |
| MCC | −1 से 1 | हाँ | हाँ | Imbalanced binary — सबसे मज़बूत |
| Cohen's Kappa | −1 से 1 | हाँ | हाँ | सहमति की quality; multi-class |
| Balanced Accuracy | 0–1 | हाँ | हाँ | आसानी से समझ आने वाला imbalance metric |
खुद करके देखिए — Robust Metrics Lab
पाँच models, पाँच metrics, एक chart। एक model चुनिए (या अपने चार numbers टाइप कीजिए) और bars की तुलना कीजिए। देखिए कि बेकार models के लिए accuracy ऊँची रहती है, जबकि MCC और κ zero या उससे नीचे गिर जाते हैं।
进阶 Metric:MCC 和 Cohen's Kappa
当 class imbalance 很严重,而你需要一个真正 稳健的 metric 时,有两个 metric 比 accuracy 和 F1 更出色。
公式:
MCC = (TP·TN − FP·FN) / √[(TP+FP)(TP+FN)(TN+FP)(TN+FN)]Dr. Meera 的 model:
MCC = (45·850 − 100·5) / √[(145)(50)(950)(855)]
= (38 250 − 500) / √[5 893 781 250]
= 37 750 / 76 773 ≈ 0.491
公式:
κ = (p_observed − p_expected) / (1 − p_expected)其中 p_expected 是在给定 class 分布下,靠运气能得到的一致率。
κ < 0:比随机还差 | κ = 0:随机水平 | κ = 1:完全一致
一般参考:κ < 0.20 = 差,0.20–0.40 = 一般, 0.40–0.60 = 中等,0.60–0.80 = 较好,0.80–1.0 = 几乎完美。
公式:
Balanced Accuracy = (Recall + Specificity) / 2Dr. Meera 的 model:(0.900 + 0.895) / 2 = 0.8975 = 89.75%
它比原始的 89.5% accuracy 诚实得多,并且同等地反映了 model 在两个 class 上的真实能力。
| Metric | 范围 | 能处理不平衡吗? | 用到全部 4 个 CM 格子吗? | 最适合 |
|---|---|---|---|---|
| Accuracy | 0–1 | 否 | 是 | 只适合平衡的 dataset |
| Precision | 0–1 | 部分 | 否(忽略 TN) | FP 代价高时 |
| Recall | 0–1 | 部分 | 否(忽略 TN) | FN 代价高时 |
| F1 | 0–1 | 部分 | 否(忽略 TN) | 通用的不平衡场景 |
| MCC | −1 到 1 | 是 | 是 | 不平衡的 binary 问题:最稳健 |
| Cohen's Kappa | −1 到 1 | 是 | 是 | 一致性质量;multiclass |
| Balanced Accuracy | 0–1 | 是 | 是 | 容易解释的不平衡 metric |
动手试试:Robust Metrics Lab
五个 model,五个 metric,一张图。选一个 model(或输入你自己的四个数字),然后比较这些柱子。 你会看到:对没用的 model,accuracy 仍然很高,而 MCC 和 κ 会降到 0 或更低。
Multi-Class Metrics — Macro, Micro & Weighted Averaging
For problems with more than 2 classes, Precision, Recall, and F1 are computed per class and then averaged. Three averaging strategies exist, each with a different philosophy.
| Class | Support | Precision | Recall | F1 |
|---|---|---|---|---|
| Benign | 600 | 0.94 | 0.96 | 0.95 |
| Type-A | 300 | 0.82 | 0.78 | 0.80 |
| Type-B | 100 | 0.61 | 0.55 | 0.58 |
Try It — Averaging Lab
A 3-class confusion matrix close to the worked example (600 / 300 / 100 patients). Rows are the truth, columns are the prediction, and green-bordered cells are correct. Edit any cell and compare macro, weighted and micro averages. Then try model ignores Type-B.
Multi-Class Metrics — Macro, Micro & Weighted Averaging
2 से ज़्यादा classes वाली problems में, Precision, Recall और F1 हर class के लिए अलग निकाले जाते हैं और फिर उनका average लिया जाता है। Averaging के तीन तरीके हैं, और हर एक की सोच अलग है।
| Class | Support | Precision | Recall | F1 |
|---|---|---|---|---|
| Benign | 600 | 0.94 | 0.96 | 0.95 |
| Type-A | 300 | 0.82 | 0.78 | 0.80 |
| Type-B | 100 | 0.61 | 0.55 | 0.58 |
खुद करके देखिए — Averaging Lab
एक 3-class confusion matrix, जो ऊपर के उदाहरण जैसा है (600 / 300 / 100 मरीज़)। Rows सच हैं, columns prediction हैं, और हरे border वाले cells सही हैं। कोई भी cell बदलिए और macro, weighted और micro averages की तुलना कीजिए। फिर model Type-B को नज़रअंदाज़ करता है आज़माइए।
Multiclass Metric:Macro、Micro 和 Weighted 平均
对于超过 2 个 class 的问题,Precision、Recall 和 F1 会 按每个 class 分别计算,然后再取平均。有三种平均 策略,每种的思路都不同。
| Class | Support | Precision | Recall | F1 |
|---|---|---|---|---|
| Benign | 600 | 0.94 | 0.96 | 0.95 |
| Type-A | 300 | 0.82 | 0.78 | 0.80 |
| Type-B | 100 | 0.61 | 0.55 | 0.58 |
动手试试:Averaging Lab
这是一个 3 个 class 的 confusion matrix,和上面的计算示例很接近(600 / 300 / 100 名病人)。行是真实情况,列是 prediction,绿色边框的格子是正确的。修改任意一个格子,比较 macro、weighted 和 micro 平均值。 然后试试 model 忽略 Type-B。
Metric Selection Guide — When to Use What
When in doubt: report Precision, Recall, F1, and MCC together — they cover different angles and provide a complete picture for stakeholders and engineering teams alike.
Python — All Metrics from Scratch
Metric चुनने की गाइड — कब क्या इस्तेमाल करें
शक हो तो: Precision, Recall, F1 और MCC साथ में बताइए — ये अलग-अलग पहलू देखते हैं और stakeholders व engineering teams दोनों को पूरी तस्वीर देते हैं।
Python — सभी Metrics शुरू से
Metric 选择指南:什么时候用什么
拿不准的时候:把 Precision、Recall、F1 和 MCC 一起报告。它们覆盖不同的 角度,能给相关人员和工程团队一个完整的画面。
Python:从零实现所有 Metric
import math
# ── Confusion matrix values ───────────────────────────────────
TP, FP, FN, TN = 45, 100, 5, 850
N_total = TP + FP + FN + TN # 1000
P = TP + FN # all actual positives = 50
# ── Core metrics ─────────────────────────────────────────────
accuracy = (TP + TN) / N_total
precision = TP / (TP + FP)
recall = TP / (TP + FN)
specificity = TN / (TN + FP)
npv = TN / (TN + FN) # Negative Predictive Value
fpr = FP / (FP + TN) # False Positive Rate
miss_rate = FN / (FN + TP) # False Negative Rate
fdr = FP / (FP + TP) # False Discovery Rate
# ── F-scores ─────────────────────────────────────────────────
def f_beta(precision, recall, beta=1):
b2 = beta ** 2
if precision + recall == 0:
return 0.0
return (1 + b2) * precision * recall / (b2 * precision + recall)
f1 = f_beta(precision, recall, beta=1)
f2 = f_beta(precision, recall, beta=2)
f_half = f_beta(precision, recall, beta=0.5)
# ── Matthews Correlation Coefficient ─────────────────────────
mcc_num = (TP * TN) - (FP * FN)
mcc_den = math.sqrt((TP+FP) * (TP+FN) * (TN+FP) * (TN+FN))
mcc = mcc_num / mcc_den if mcc_den > 0 else 0.0
# ── Balanced Accuracy ─────────────────────────────────────────
balanced_acc = (recall + specificity) / 2
# ── Cohen's Kappa ─────────────────────────────────────────────
p_obs = (TP + TN) / N_total
p_pos = ((TP + FP) / N_total) * ((TP + FN) / N_total)
p_neg = ((TN + FN) / N_total) * ((TN + FP) / N_total)
p_exp = p_pos + p_neg
kappa = (p_obs - p_exp) / (1 - p_exp)
# ── Print results ─────────────────────────────────────────────
print(f"{'Metric':<25} {'Value':>8}")
print("-" * 35)
for name, val in [
("Accuracy", accuracy),
("Precision (PPV)", precision),
("Recall (Sensitivity)", recall),
("Specificity (TNR)", specificity),
("NPV", npv),
("False Positive Rate", fpr),
("Miss Rate (FNR)", miss_rate),
("F0.5 Score", f_half),
("F1 Score", f1),
("F2 Score", f2),
("MCC", mcc),
("Balanced Accuracy", balanced_acc),
("Cohen's Kappa", kappa),
]:
print(f"{name:<25} {val:>8.4f}")
Python — Full Pipeline with scikit-learn
Python — scikit-learn के साथ पूरी Pipeline
Python:用 scikit-learn 搭建完整流程
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
confusion_matrix,
classification_report,
precision_score, recall_score,
f1_score, fbeta_score,
matthews_corrcoef, cohen_kappa_score,
balanced_accuracy_score,
precision_recall_fscore_support
)
# ── 1. Load & split ───────────────────────────────────────────
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# ── 2. Train ──────────────────────────────────────────────────
model = LogisticRegression(C=1.0, max_iter=1000, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# ── 3. Full classification report ────────────────────────────
print("=== Classification Report ===")
print(classification_report(y_test, y_pred,
target_names=['Malignant', 'Benign']))
# ── 4. Individual metrics ─────────────────────────────────────
print("=== Individual Metrics (positive class = Benign) ===")
print(f"Precision : {precision_score(y_test, y_pred):.4f}")
print(f"Recall : {recall_score(y_test, y_pred):.4f}")
print(f"F1 Score : {f1_score(y_test, y_pred):.4f}")
print(f"F2 Score : {fbeta_score(y_test, y_pred, beta=2):.4f}")
print(f"F0.5 Score : {fbeta_score(y_test, y_pred, beta=0.5):.4f}")
print(f"MCC : {matthews_corrcoef(y_test, y_pred):.4f}")
print(f"Cohen's Kappa : {cohen_kappa_score(y_test, y_pred):.4f}")
print(f"Balanced Accuracy: {balanced_accuracy_score(y_test, y_pred):.4f}")
# ── 5. Threshold tuning for high Recall ──────────────────────
y_proba = model.predict_proba(X_test)[:, 1]
threshold = 0.3
y_pred_low = (y_proba >= threshold).astype(int)
print(f"\n=== Metrics at threshold = {threshold} ===")
print(f"Precision : {precision_score(y_test, y_pred_low):.4f}")
print(f"Recall : {recall_score(y_test, y_pred_low):.4f}")
print(f"F1 : {f1_score(y_test, y_pred_low):.4f}")
print(f"F2 : {fbeta_score(y_test, y_pred_low, beta=2):.4f}")
# ── 6. Multi-class macro / weighted / micro ───────────────────
from sklearn.datasets import load_iris
Xi, yi = load_iris(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(Xi, yi, test_size=0.25, random_state=0)
mc_model = LogisticRegression(max_iter=500).fit(Xtr, ytr)
yp = mc_model.predict(Xte)
print("\n=== Multi-class Averaging (Iris, 3 classes) ===")
for avg in ['macro', 'weighted', 'micro']:
p, r, f, _ = precision_recall_fscore_support(yte, yp, average=avg)
print(f"{avg:>10} → P={p:.3f} R={r:.3f} F1={f:.3f}")
print("\n=== Per-Class Breakdown ===")
print(classification_report(yte, yp,
target_names=['setosa', 'versicolor', 'virginica']))
Golden Rules
classification_report() and inspect each class's
Precision, Recall, and F1 individually — especially for minority classes.
सुनहरे नियम
classification_report() print कीजिए और हर class का
Precision, Recall और F1 अलग-अलग जाँचिए — खासकर minority classes का।
黄金法则
classification_report(),逐个检查每个 class 的
Precision、Recall 和 F1,尤其是少数 class。