Sub topic 13
Choosing confidence and IoU thresholds
This chapter assumes you can run a pretrained YOLO model, that you know what intersection over union (IoU) and non-maximum suppression (NMS) do, and that you have met precision, recall and AP. Here you will learn which numbers to set at inference time and how to pick them from data instead of guessing.
Two thresholds, two different jobs
A detector produces many candidate boxes per image. Two thresholds decide which of them reach your application.
- The confidence threshold (
confin Ultralytics) drops any candidate whose score is below the value. It controls how sure the model must be before you believe a box. - The NMS IoU threshold (
iouin Ultralytics) controls duplicate removal. If two boxes of the same class overlap by more than this value, the lower-scoring one is discarded.
They are easy to confuse because both are numbers between 0 and 1 and both appear in the same predict call. They act on different things. Confidence filters by score. The NMS IoU threshold filters by overlap between boxes.
A third IoU value exists, and it is the source of much confusion. During evaluation, a prediction counts as a true positive only if its IoU with a ground-truth box reaches a matching threshold, such as 0.5. That threshold belongs to the metric. It is not the iou argument you pass to predict.
| Threshold | Where it is applied | Effect when raised |
|---|---|---|
| `conf` | Inference, after scoring | Fewer boxes, higher precision, lower recall |
| NMS `iou` | Inference, inside NMS | More overlapping boxes survive, so more duplicates |
| Matching IoU | Evaluation only | Boxes must be placed more tightly to count as correct |
Confidence: the precision and recall trade-off
Lowering conf lets more boxes through. Some of them are real objects the model was unsure about, so recall rises. Others are background mistakes, so precision falls. Raising conf does the reverse.
There is no universally correct value. The right choice depends on what a mistake costs in your application.
- A safety alarm or medical screen usually favors recall. Missing an object is worse than a false alert, so you accept a low
conf, such as 0.1 to 0.25, and let a human or a second stage reject false positives. - An automated action, such as counting items for billing or triggering a robot, usually favors precision. A false positive causes a wrong action, so you use a higher
conf, such as 0.5 to 0.7. - A balanced task often targets the score that maximizes F1, the harmonic mean of precision and recall.
The Ultralytics default of 0.25 for prediction is a convenient starting point. It is not tuned for your data.
Why validation uses a very low confidence
When you call model.val(), Ultralytics uses a very low confidence threshold (0.001 by default). This is deliberate. AP and mAP are computed by sweeping the threshold across the whole range, so the evaluation needs the full ranked list of predictions, including weak ones. If you evaluate at conf=0.25, you cut the precision-recall curve short and mAP drops, which makes the model look worse than it is.
The consequence is that mAP tells you about the model's ranking quality across all thresholds. It does not tell you how your deployed setting behaves. For that you need a specific operating point, which you pick from curves.
Choosing `conf` from the training curves
Ultralytics saves curve plots in the run directory after training or validation. The useful ones are the F1-confidence curve, the precision-confidence curve and the recall-confidence curve. Each plots a metric against the confidence threshold, with one line per class and a bold line for all classes.
A practical procedure:
- Decide what matters. Name the metric you must protect, for example "precision at least 0.9" or "recall at least 0.95".
- Read the matching curve on the validation set, not the training set, to find the
confthat meets the requirement. - If no value satisfies both goals, the model is the limit and no threshold will fix it. Improve the data or the model instead.
- Set that value in your application and check it on a held-out set the tuning never touched.
You can also compute the curve yourself. The sketch below takes per-prediction scores and a flag saying whether each prediction matched a ground-truth box, and then finds the threshold that maximizes F1.
def best_f1_threshold(scores, is_tp, num_gt):
# scores: confidence of each prediction
# is_tp: True if that prediction matched a ground-truth box
# num_gt: total number of ground-truth boxes
pairs = sorted(zip(scores, is_tp), reverse=True)
tp = fp = 0
best = (0.0, 1.0) # (f1, threshold)
for score, hit in pairs:
if hit:
tp += 1
else:
fp += 1
precision = tp / (tp + fp)
recall = tp / num_gt
f1 = 2 * precision * recall / (precision + recall) if tp else 0.0
if f1 > best[0]:
best = (f1, score)
return best
scores = [0.95, 0.90, 0.80, 0.60, 0.55, 0.30, 0.20]
is_tp = [True, True, True, False, True, False, False]
f1, thr = best_f1_threshold(scores, is_tp, num_gt=5)
print(round(f1, 3), thr) # 0.8 0.55The loop treats each score as a candidate threshold: keeping every prediction at or above that score gives the running precision and recall. Here the best F1 of 0.8 comes at a threshold of 0.55, where four of five true objects are found with one false positive.
The NMS IoU threshold
NMS keeps the highest-scoring box and removes others of the same class that overlap it by more than the threshold. The value decides how much overlap counts as "the same object".
- A low threshold, such as 0.3, is aggressive. It removes boxes with modest overlap. Duplicates disappear, but two real objects that sit close together, such as people in a crowd, may be merged into one detection.
- A high threshold, such as 0.8, is lenient. Crowded objects survive, but a single object may keep two or three slightly shifted boxes.
The default of 0.7 in Ultralytics predict (and 0.7 in val) works for many scenes. Adjust it by looking at failures:
- Seeing doubled boxes on single objects: lower
iou. - Seeing missing objects in crowds or stacks: raise
iou.
Because NMS here runs per class by default, overlapping boxes of different classes do not suppress each other. A cat and a dog that overlap heavily both survive. If your classes are mutually exclusive and you see one object labelled twice with different classes, pass agnostic_nms=True so that suppression ignores the class.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
for conf in (0.1, 0.25, 0.5):
for iou_thr in (0.4, 0.7):
r = model.predict("bus.jpg", conf=conf, iou=iou_thr, verbose=False)[0]
print(f"conf={conf} iou={iou_thr} -> {len(r.boxes)} boxes")Running this grid on a few representative images shows how the box count responds to each setting. Count alone is not a quality measure, so look at the images too.
A subtle point: tune on validation, report on test
Any threshold you pick from a curve is a trained parameter in disguise. If you choose conf to maximize F1 on the validation set and then report that same F1, the number is optimistic. Keep a separate test split. Choose thresholds on validation, then measure once on test and report that result.
Also expect the value to shift when the data does. A threshold tuned on daytime images may be too high for night images, because scores are usually lower on harder inputs. If conditions vary, check the threshold per condition.
Per-class thresholds
Classes often differ in difficulty. A large, distinctive class may be reliable at 0.5 while a small or rare class never scores above 0.4. A single global conf then either floods you with false positives for the easy class or erases the hard one.
Ultralytics predict takes one conf value, so a common pattern is to run with a low global conf and filter afterwards.
from ultralytics import YOLO
class_conf = {"cat": 0.5, "dog": 0.3} # per-class minimum scores
model = YOLO("yolov8n.pt")
result = model.predict("bus.jpg", conf=0.1, verbose=False)[0]
kept = []
for box in result.boxes:
name = model.names[int(box.cls[0])]
score = float(box.conf[0])
if score >= class_conf.get(name, 0.25):
kept.append((name, round(score, 2)))
print(kept)Classes missing from the dictionary fall back to 0.25. Setting the global conf below every per-class value is required, otherwise the model discards boxes before your filter sees them.
Common mistakes
- Tuning
confto raise mAP. mAP is computed over all thresholds, so changing theconfyou validate with only truncates the curve. Tuneconffor the operating point and leave validation at its low default. - Confusing the two IoU values. The NMS
iousetting and the metric's matching IoU are separate. Changing one does not change the other. - Choosing thresholds on training data. Scores on training images are inflated, so the picked value will be too high for new data.
- Expecting thresholds to repair a weak model. If the best F1 across all
confvalues is low, the precision-recall curve itself is poor, and the fix is more or better labeled data. - Ignoring calibration. A score of 0.8 does not mean an 80 percent chance of being correct. Scores rank detections well, but they are not probabilities, and they change after retraining. Re-tune after every new model.
Exercise
A model has a validation precision of 0.95 and recall of 0.60 at conf=0.5. Your application must not miss objects, and false alarms are cheap to review. Which direction should you move conf, and what do you expect to happen to precision and recall? Also, you notice some single objects have two nearly identical boxes. Which other threshold do you adjust, and in which direction?
Show answer
Lower conf, for example toward 0.2. More low-scoring boxes pass, so recall rises and precision falls. Confirm the new operating point on the validation curves and then on a held-out test set. For the doubled boxes, lower the NMS iou threshold (for example from 0.7 to 0.5) so that overlapping boxes of the same class are suppressed more aggressively. Check crowded scenes afterward, because a lower value can merge nearby real objects.
Exercise
You run model.val(conf=0.25) and your mAP50-95 is lower than the figure reported with the default validation settings. Is the model worse? Explain why.
Show answer
No. The model is the same. Validating at conf=0.25 discards low-scoring predictions, so the precision-recall curve is cut short and recall at the tail is lost. AP is the area under that curve, so it shrinks. Use the very low default confidence for mAP, and use a separate chosen conf only for deployment.