Three-zone confidence decision: bypass sim gate for high-conf, reject low-conf
Browse filesReplace binary similarity gate with three-zone logic:
- class_prob >= 0.85: bypass similarity check (high confidence, trust model)
Fixes organ specimens / non-standard angles being wrongly blocked
- 0.60 <= class_prob < 0.85: require similarity gate (unchanged behavior)
- class_prob < 0.60: always None (low confidence, regardless of similarity)
Also add ClassProb + Sim to inference log for easier debugging.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- app/main.py +18 -5
app/main.py
CHANGED
|
@@ -94,20 +94,33 @@ async def predict(file: UploadFile = File(...)):
|
|
| 94 |
# 先把 positive 類別的原始機率四捨五入(保留原本行為)
|
| 95 |
probability = round(float(probability), 2)
|
| 96 |
|
| 97 |
-
# 類別
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
if not is_in_criteria:
|
| 99 |
prediction = "None"
|
| 100 |
-
# probability 照舊保留 positive 類別機率(如需改 0.0 可自行調整)
|
| 101 |
else:
|
| 102 |
if probability > 0.5:
|
| 103 |
prediction = "bacteria"
|
| 104 |
-
# probability 保持為 positive 類別機率
|
| 105 |
else:
|
| 106 |
prediction = "virus"
|
| 107 |
-
probability = round(1 - probability, 2)
|
| 108 |
|
| 109 |
logger.info(
|
| 110 |
-
f"Inference result - ID: {image_id}, Class: {prediction},
|
|
|
|
| 111 |
)
|
| 112 |
except Exception as e:
|
| 113 |
logger.error(f"Model inference failed - ID: {image_id}, Error: {str(e)}")
|
|
|
|
| 94 |
# 先把 positive 類別的原始機率四捨五入(保留原本行為)
|
| 95 |
probability = round(float(probability), 2)
|
| 96 |
|
| 97 |
+
# 所屬類別機率(bacteria prob 直接用;virus prob = 1 - bacteria prob)
|
| 98 |
+
class_prob = probability if probability > 0.5 else round(1 - probability, 2)
|
| 99 |
+
|
| 100 |
+
# 三區間決策
|
| 101 |
+
# ≥ HIGH_CONF:高信心 → 直接分類,跳過 similarity gate(解決非典型拍攝角度被誤擋)
|
| 102 |
+
# LOW_CONF ~ HIGH_CONF:中信心 → 需通過 similarity gate(原本邏輯)
|
| 103 |
+
# < LOW_CONF:低信心 → None(不夠確定,不管 similarity 如何)
|
| 104 |
+
HIGH_CONF = 0.85
|
| 105 |
+
LOW_CONF = 0.60
|
| 106 |
+
|
| 107 |
+
if class_prob >= HIGH_CONF:
|
| 108 |
+
is_in_criteria = True # bypass sim gate
|
| 109 |
+
elif class_prob < LOW_CONF:
|
| 110 |
+
is_in_criteria = False # 低信心直接 None
|
| 111 |
+
|
| 112 |
if not is_in_criteria:
|
| 113 |
prediction = "None"
|
|
|
|
| 114 |
else:
|
| 115 |
if probability > 0.5:
|
| 116 |
prediction = "bacteria"
|
|
|
|
| 117 |
else:
|
| 118 |
prediction = "virus"
|
| 119 |
+
probability = round(1 - probability, 2)
|
| 120 |
|
| 121 |
logger.info(
|
| 122 |
+
f"Inference result - ID: {image_id}, Class: {prediction}, "
|
| 123 |
+
f"Probability: {probability:.2f}, ClassProb: {class_prob:.2f}, Sim: {sim:.3f}"
|
| 124 |
)
|
| 125 |
except Exception as e:
|
| 126 |
logger.error(f"Model inference failed - ID: {image_id}, Error: {str(e)}")
|