Reference for ultralytics/utils/metrics.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/utils/metrics.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.utils.metrics.ConfusionMatrix
ConfusionMatrix(nc, conf=0.25, iou_thres=0.45, task='detect')
A class for calculating and updating a confusion matrix for object detection and classification tasks.
Attributes:
Name | Type | Description |
---|---|---|
task |
str
|
The type of task, either 'detect' or 'classify'. |
matrix |
ndarray
|
The confusion matrix, with dimensions depending on the task. |
nc |
int
|
The number of classes. |
conf |
float
|
The confidence threshold for detections. |
iou_thres |
float
|
The Intersection over Union threshold. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
nc
|
int
|
Number of classes. |
required |
conf
|
float
|
Confidence threshold for detections. |
0.25
|
iou_thres
|
float
|
IoU threshold for matching detections to ground truth. |
0.45
|
task
|
str
|
Type of task, either 'detect' or 'classify'. |
'detect'
|
Source code in ultralytics/utils/metrics.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
|
matrix
matrix()
Return the confusion matrix.
Source code in ultralytics/utils/metrics.py
393 394 395 |
|
plot
plot(normalize=True, save_dir='', names=(), on_plot=None)
Plot the confusion matrix using seaborn and save it to a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
Whether to normalize the confusion matrix. |
True
|
save_dir
|
str
|
Directory where the plot will be saved. |
''
|
names
|
tuple
|
Names of classes, used as labels on the plot. |
()
|
on_plot
|
func
|
An optional callback to pass plots path and data when they are rendered. |
None
|
Source code in ultralytics/utils/metrics.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 |
|
print
print()
Print the confusion matrix to the console.
Source code in ultralytics/utils/metrics.py
455 456 457 458 |
|
process_batch
process_batch(detections, gt_bboxes, gt_cls)
Update confusion matrix for object detection task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detections
|
Array[N, 6] | Array[N, 7]
|
Detected bounding boxes and their associated information.
Each row should contain (x1, y1, x2, y2, conf, class)
or with an additional element |
required |
gt_bboxes
|
Array[M, 4] | Array[N, 5]
|
Ground truth bounding boxes with xyxy/xyxyr format. |
required |
gt_cls
|
Array[M]
|
The class labels. |
required |
Source code in ultralytics/utils/metrics.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
|
process_cls_preds
process_cls_preds(preds, targets)
Update confusion matrix for classification task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds
|
Array[N, min(nc, 5)]
|
Predicted class labels. |
required |
targets
|
Array[N, 1]
|
Ground truth class labels. |
required |
Source code in ultralytics/utils/metrics.py
323 324 325 326 327 328 329 330 331 332 333 |
|
tp_fp
tp_fp()
Return true positives and false positives.
Returns:
Type | Description |
---|---|
tuple
|
True positives and false positives. |
Source code in ultralytics/utils/metrics.py
397 398 399 400 401 402 403 404 405 406 407 |
|
ultralytics.utils.metrics.Metric
Metric()
Bases: SimpleClass
Class for computing evaluation metrics for YOLOv8 model.
Attributes:
Name | Type | Description |
---|---|---|
p |
list
|
Precision for each class. Shape: (nc,). |
r |
list
|
Recall for each class. Shape: (nc,). |
f1 |
list
|
F1 score for each class. Shape: (nc,). |
all_ap |
list
|
AP scores for all classes and all IoU thresholds. Shape: (nc, 10). |
ap_class_index |
list
|
Index of class for each AP score. Shape: (nc,). |
nc |
int
|
Number of classes. |
Methods:
Name | Description |
---|---|
ap50 |
AP at IoU threshold of 0.5 for all classes. Returns: List of AP scores. Shape: (nc,) or []. |
ap |
AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: List of AP scores. Shape: (nc,) or []. |
mp |
Mean precision of all classes. Returns: Float. |
mr |
Mean recall of all classes. Returns: Float. |
map50 |
Mean AP at IoU threshold of 0.5 for all classes. Returns: Float. |
map75 |
Mean AP at IoU threshold of 0.75 for all classes. Returns: Float. |
map |
Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: Float. |
mean_results |
Mean of results, returns mp, mr, map50, map. |
class_result |
Class-aware result, returns p[i], r[i], ap50[i], ap[i]. |
maps |
mAP of each class. Returns: Array of mAP scores, shape: (nc,). |
fitness |
Model fitness as a weighted combination of metrics. Returns: Float. |
update |
Update metric attributes with new evaluation results. |
Source code in ultralytics/utils/metrics.py
689 690 691 692 693 694 695 696 |
|
ap
property
ap
Return the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.
Returns:
Type | Description |
---|---|
(ndarray, list)
|
Array of shape (nc,) with AP50-95 values per class, or an empty list if not available. |
ap50
property
ap50
Return the Average Precision (AP) at an IoU threshold of 0.5 for all classes.
Returns:
Type | Description |
---|---|
(ndarray, list)
|
Array of shape (nc,) with AP50 values per class, or an empty list if not available. |
curves
property
curves
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results
Return a list of curves for accessing specific metrics curves.
map
property
map
Return the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
Returns:
Type | Description |
---|---|
float
|
The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05. |
map50
property
map50
Return the mean Average Precision (mAP) at an IoU threshold of 0.5.
Returns:
Type | Description |
---|---|
float
|
The mAP at an IoU threshold of 0.5. |
map75
property
map75
Return the mean Average Precision (mAP) at an IoU threshold of 0.75.
Returns:
Type | Description |
---|---|
float
|
The mAP at an IoU threshold of 0.75. |
maps
property
maps
Return mAP of each class.
mp
property
mp
Return the Mean Precision of all classes.
Returns:
Type | Description |
---|---|
float
|
The mean precision of all classes. |
mr
property
mr
Return the Mean Recall of all classes.
Returns:
Type | Description |
---|---|
float
|
The mean recall of all classes. |
class_result
class_result(i)
Return class-aware result, p[i], r[i], ap50[i], ap[i].
Source code in ultralytics/utils/metrics.py
772 773 774 |
|
fitness
fitness()
Return model fitness as a weighted combination of metrics.
Source code in ultralytics/utils/metrics.py
784 785 786 787 |
|
mean_results
mean_results()
Return mean of results, mp, mr, map50, map.
Source code in ultralytics/utils/metrics.py
768 769 770 |
|
update
update(results)
Update the evaluation metrics with a new set of results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
results
|
tuple
|
A tuple containing evaluation metrics: - p (list): Precision for each class. - r (list): Recall for each class. - f1 (list): F1 score for each class. - all_ap (list): AP scores for all classes and all IoU thresholds. - ap_class_index (list): Index of class for each AP score. - p_curve (list): Precision curve for each class. - r_curve (list): Recall curve for each class. - f1_curve (list): F1 curve for each class. - px (list): X values for the curves. - prec_values (list): Precision values for each class. |
required |
Source code in ultralytics/utils/metrics.py
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 |
|
ultralytics.utils.metrics.DetMetrics
DetMetrics(save_dir=Path('.'), plot=False, names={})
Bases: SimpleClass
Utility class for computing detection metrics such as precision, recall, and mean average precision (mAP).
Attributes:
Name | Type | Description |
---|---|---|
save_dir |
Path
|
A path to the directory where the output plots will be saved. |
plot |
bool
|
A flag that indicates whether to plot precision-recall curves for each class. |
names |
dict
|
A dictionary of class names. |
box |
Metric
|
An instance of the Metric class for storing detection results. |
speed |
dict
|
A dictionary for storing execution times of different parts of the detection process. |
task |
str
|
The task type, set to 'detect'. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir
|
Path
|
Directory to save plots. |
Path('.')
|
plot
|
bool
|
Whether to plot precision-recall curves. |
False
|
names
|
dict
|
Dictionary mapping class indices to names. |
{}
|
Source code in ultralytics/utils/metrics.py
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 |
|
ap_class_index
property
ap_class_index
Return the average precision index per class.
curves
property
curves
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results
Return dictionary of computed performance metrics and statistics.
fitness
property
fitness
Return the fitness of box object.
keys
property
keys
Return a list of keys for accessing specific metrics.
maps
property
maps
Return mean Average Precision (mAP) scores per class.
results_dict
property
results_dict
Return dictionary of computed performance metrics and statistics.
class_result
class_result(i)
Return the result of evaluating the performance of an object detection model on a specific class.
Source code in ultralytics/utils/metrics.py
897 898 899 |
|
mean_results
mean_results()
Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.
Source code in ultralytics/utils/metrics.py
893 894 895 |
|
process
process(tp, conf, pred_cls, target_cls, on_plot=None)
Process predicted results for object detection and update metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp
|
ndarray
|
True positive array. |
required |
conf
|
ndarray
|
Confidence array. |
required |
pred_cls
|
ndarray
|
Predicted class indices array. |
required |
target_cls
|
ndarray
|
Target class indices array. |
required |
on_plot
|
callable
|
Function to call after plots are generated. |
None
|
Source code in ultralytics/utils/metrics.py
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 |
|
ultralytics.utils.metrics.SegmentMetrics
SegmentMetrics(save_dir=Path('.'), plot=False, names=())
Bases: SimpleClass
Calculates and aggregates detection and segmentation metrics over a given set of classes.
Attributes:
Name | Type | Description |
---|---|---|
save_dir |
Path
|
Path to the directory where the output plots should be saved. |
plot |
bool
|
Whether to save the detection and segmentation plots. |
names |
dict
|
Dictionary of class names. |
box |
Metric
|
An instance of the Metric class to calculate box detection metrics. |
seg |
Metric
|
An instance of the Metric class to calculate mask segmentation metrics. |
speed |
dict
|
Dictionary to store the time taken in different phases of inference. |
task |
str
|
The task type, set to 'segment'. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir
|
Path
|
Directory to save plots. |
Path('.')
|
plot
|
bool
|
Whether to plot precision-recall curves. |
False
|
names
|
dict
|
Dictionary mapping class indices to names. |
()
|
Source code in ultralytics/utils/metrics.py
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 |
|
ap_class_index
property
ap_class_index
Return the class indices.
Boxes and masks have the same ap_class_index.
curves
property
curves
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results
Return dictionary of computed performance metrics and statistics.
fitness
property
fitness
Return the fitness score for both segmentation and bounding box models.
keys
property
keys
Return a list of keys for accessing metrics.
maps
property
maps
Return mAP scores for object detection and semantic segmentation models.
results_dict
property
results_dict
Return results of object detection model for evaluation.
class_result
class_result(i)
Return classification results for a specified class index.
Source code in ultralytics/utils/metrics.py
1020 1021 1022 |
|
mean_results
mean_results()
Return the mean metrics for bounding box and segmentation results.
Source code in ultralytics/utils/metrics.py
1016 1017 1018 |
|
process
process(tp, tp_m, conf, pred_cls, target_cls, on_plot=None)
Process the detection and segmentation metrics over the given set of predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp
|
ndarray
|
True positive array for boxes. |
required |
tp_m
|
ndarray
|
True positive array for masks. |
required |
conf
|
ndarray
|
Confidence array. |
required |
pred_cls
|
ndarray
|
Predicted class indices array. |
required |
target_cls
|
ndarray
|
Target class indices array. |
required |
on_plot
|
callable
|
Function to call after plots are generated. |
None
|
Source code in ultralytics/utils/metrics.py
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 |
|
ultralytics.utils.metrics.PoseMetrics
PoseMetrics(save_dir=Path('.'), plot=False, names=())
Bases: SegmentMetrics
Calculates and aggregates detection and pose metrics over a given set of classes.
Attributes:
Name | Type | Description |
---|---|---|
save_dir |
Path
|
Path to the directory where the output plots should be saved. |
plot |
bool
|
Whether to save the detection and pose plots. |
names |
dict
|
Dictionary of class names. |
box |
Metric
|
An instance of the Metric class to calculate box detection metrics. |
pose |
Metric
|
An instance of the Metric class to calculate pose metrics. |
speed |
dict
|
Dictionary to store the time taken in different phases of inference. |
task |
str
|
The task type, set to 'pose'. |
Methods:
Name | Description |
---|---|
process |
Processes metrics over the given set of predictions. |
mean_results |
Returns the mean of the detection and segmentation metrics over all the classes. |
class_result |
Returns the detection and segmentation metrics of class |
maps |
Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95. |
fitness |
Returns the fitness scores, which are a single weighted combination of metrics. |
ap_class_index |
Returns the list of indices of classes used to compute Average Precision (AP). |
results_dict |
Returns the dictionary containing all the detection and segmentation metrics and fitness score. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir
|
Path
|
Directory to save plots. |
Path('.')
|
plot
|
bool
|
Whether to plot precision-recall curves. |
False
|
names
|
dict
|
Dictionary mapping class indices to names. |
()
|
Source code in ultralytics/utils/metrics.py
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 |
|
curves
property
curves
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results
Return dictionary of computed performance metrics and statistics.
fitness
property
fitness
Return combined fitness score for pose and box detection.
keys
property
keys
Return list of evaluation metric keys.
maps
property
maps
Return the mean average precision (mAP) per class for both box and pose detections.
class_result
class_result(i)
Return the class-wise detection results for a specific class i.
Source code in ultralytics/utils/metrics.py
1166 1167 1168 |
|
mean_results
mean_results()
Return the mean results of box and pose.
Source code in ultralytics/utils/metrics.py
1162 1163 1164 |
|
process
process(tp, tp_p, conf, pred_cls, target_cls, on_plot=None)
Process the detection and pose metrics over the given set of predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp
|
ndarray
|
True positive array for boxes. |
required |
tp_p
|
ndarray
|
True positive array for keypoints. |
required |
conf
|
ndarray
|
Confidence array. |
required |
pred_cls
|
ndarray
|
Predicted class indices array. |
required |
target_cls
|
ndarray
|
Target class indices array. |
required |
on_plot
|
callable
|
Function to call after plots are generated. |
None
|
Source code in ultralytics/utils/metrics.py
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 |
|
ultralytics.utils.metrics.ClassifyMetrics
ClassifyMetrics()
Bases: SimpleClass
Class for computing classification metrics including top-1 and top-5 accuracy.
Attributes:
Name | Type | Description |
---|---|---|
top1 |
float
|
The top-1 accuracy. |
top5 |
float
|
The top-5 accuracy. |
speed |
dict
|
A dictionary containing the time taken for each step in the pipeline. |
task |
str
|
The task type, set to 'classify'. |
Source code in ultralytics/utils/metrics.py
1211 1212 1213 1214 1215 1216 |
|
curves
property
curves
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results
Return a list of curves for accessing specific metrics curves.
fitness
property
fitness
Return mean of top-1 and top-5 accuracies as fitness score.
keys
property
keys
Return a list of keys for the results_dict property.
results_dict
property
results_dict
Return a dictionary with model's performance metrics and fitness score.
process
process(targets, pred)
Process target classes and predicted classes to compute metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
targets
|
Tensor
|
Target classes. |
required |
pred
|
Tensor
|
Predicted classes. |
required |
Source code in ultralytics/utils/metrics.py
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 |
|
ultralytics.utils.metrics.OBBMetrics
OBBMetrics(save_dir=Path('.'), plot=False, names=())
Bases: SimpleClass
Metrics for evaluating oriented bounding box (OBB) detection.
Attributes:
Name | Type | Description |
---|---|---|
save_dir |
Path
|
Path to the directory where the output plots should be saved. |
plot |
bool
|
Whether to save the detection plots. |
names |
dict
|
Dictionary of class names. |
box |
Metric
|
An instance of the Metric class for storing detection results. |
speed |
dict
|
A dictionary for storing execution times of different parts of the detection process. |
References
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir
|
Path
|
Directory to save plots. |
Path('.')
|
plot
|
bool
|
Whether to plot precision-recall curves. |
False
|
names
|
dict
|
Dictionary mapping class indices to names. |
()
|
Source code in ultralytics/utils/metrics.py
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 |
|
ap_class_index
property
ap_class_index
Return the average precision index per class.
curves
property
curves
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results
Return a list of curves for accessing specific metrics curves.
fitness
property
fitness
Return the fitness of box object.
keys
property
keys
Return a list of keys for accessing specific metrics.
maps
property
maps
Return mean Average Precision (mAP) scores per class.
results_dict
property
results_dict
Return dictionary of computed performance metrics and statistics.
class_result
class_result(i)
Return the result of evaluating the performance of an object detection model on a specific class.
Source code in ultralytics/utils/metrics.py
1320 1321 1322 |
|
mean_results
mean_results()
Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.
Source code in ultralytics/utils/metrics.py
1316 1317 1318 |
|
process
process(tp, conf, pred_cls, target_cls, on_plot=None)
Process predicted results for object detection and update metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp
|
ndarray
|
True positive array. |
required |
conf
|
ndarray
|
Confidence array. |
required |
pred_cls
|
ndarray
|
Predicted class indices array. |
required |
target_cls
|
ndarray
|
Target class indices array. |
required |
on_plot
|
callable
|
Function to call after plots are generated. |
None
|
Source code in ultralytics/utils/metrics.py
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 |
|
ultralytics.utils.metrics.bbox_ioa
bbox_ioa(box1, box2, iou=False, eps=1e-07)
Calculate the intersection over box2 area given box1 and box2. Boxes are in x1y1x2y2 format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box1
|
ndarray
|
A numpy array of shape (n, 4) representing n bounding boxes. |
required |
box2
|
ndarray
|
A numpy array of shape (m, 4) representing m bounding boxes. |
required |
iou
|
bool
|
Calculate the standard IoU if True else return inter_area/box2_area. |
False
|
eps
|
float
|
A small value to avoid division by zero. |
1e-07
|
Returns:
Type | Description |
---|---|
ndarray
|
A numpy array of shape (n, m) representing the intersection over box2 area. |
Source code in ultralytics/utils/metrics.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
|
ultralytics.utils.metrics.box_iou
box_iou(box1, box2, eps=1e-07)
Calculate intersection-over-union (IoU) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format. Based on https://github.com/pytorch/vision/blob/main/torchvision/ops/boxes.py.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box1
|
Tensor
|
A tensor of shape (N, 4) representing N bounding boxes. |
required |
box2
|
Tensor
|
A tensor of shape (M, 4) representing M bounding boxes. |
required |
eps
|
float
|
A small value to avoid division by zero. |
1e-07
|
Returns:
Type | Description |
---|---|
Tensor
|
An NxM tensor containing the pairwise IoU values for every element in box1 and box2. |
Source code in ultralytics/utils/metrics.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
|
ultralytics.utils.metrics.bbox_iou
bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-07)
Calculate the Intersection over Union (IoU) between bounding boxes.
This function supports various shapes for box1
and box2
as long as the last dimension is 4.
For instance, you may pass tensors shaped like (4,), (N, 4), (B, N, 4), or (B, N, 1, 4).
Internally, the code will split the last dimension into (x, y, w, h) if xywh=True
,
or (x1, y1, x2, y2) if xywh=False
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box1
|
Tensor
|
A tensor representing one or more bounding boxes, with the last dimension being 4. |
required |
box2
|
Tensor
|
A tensor representing one or more bounding boxes, with the last dimension being 4. |
required |
xywh
|
bool
|
If True, input boxes are in (x, y, w, h) format. If False, input boxes are in (x1, y1, x2, y2) format. |
True
|
GIoU
|
bool
|
If True, calculate Generalized IoU. |
False
|
DIoU
|
bool
|
If True, calculate Distance IoU. |
False
|
CIoU
|
bool
|
If True, calculate Complete IoU. |
False
|
eps
|
float
|
A small value to avoid division by zero. |
1e-07
|
Returns:
Type | Description |
---|---|
Tensor
|
IoU, GIoU, DIoU, or CIoU values depending on the specified flags. |
Source code in ultralytics/utils/metrics.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
|
ultralytics.utils.metrics.mask_iou
mask_iou(mask1, mask2, eps=1e-07)
Calculate masks IoU.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mask1
|
Tensor
|
A tensor of shape (N, n) where N is the number of ground truth objects and n is the product of image width and height. |
required |
mask2
|
Tensor
|
A tensor of shape (M, n) where M is the number of predicted objects and n is the product of image width and height. |
required |
eps
|
float
|
A small value to avoid division by zero. |
1e-07
|
Returns:
Type | Description |
---|---|
Tensor
|
A tensor of shape (N, M) representing masks IoU. |
Source code in ultralytics/utils/metrics.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
|
ultralytics.utils.metrics.kpt_iou
kpt_iou(kpt1, kpt2, area, sigma, eps=1e-07)
Calculate Object Keypoint Similarity (OKS).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kpt1
|
Tensor
|
A tensor of shape (N, 17, 3) representing ground truth keypoints. |
required |
kpt2
|
Tensor
|
A tensor of shape (M, 17, 3) representing predicted keypoints. |
required |
area
|
Tensor
|
A tensor of shape (N,) representing areas from ground truth. |
required |
sigma
|
list
|
A list containing 17 values representing keypoint scales. |
required |
eps
|
float
|
A small value to avoid division by zero. |
1e-07
|
Returns:
Type | Description |
---|---|
Tensor
|
A tensor of shape (N, M) representing keypoint similarities. |
Source code in ultralytics/utils/metrics.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
|
ultralytics.utils.metrics._get_covariance_matrix
_get_covariance_matrix(boxes)
Generate covariance matrix from oriented bounding boxes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
boxes
|
Tensor
|
A tensor of shape (N, 5) representing rotated bounding boxes, with xywhr format. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Covariance matrices corresponding to original rotated bounding boxes. |
Source code in ultralytics/utils/metrics.py
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
|
ultralytics.utils.metrics.probiou
probiou(obb1, obb2, CIoU=False, eps=1e-07)
Calculate probabilistic IoU between oriented bounding boxes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obb1
|
Tensor
|
Ground truth OBBs, shape (N, 5), format xywhr. |
required |
obb2
|
Tensor
|
Predicted OBBs, shape (N, 5), format xywhr. |
required |
CIoU
|
bool
|
If True, calculate CIoU. |
False
|
eps
|
float
|
Small value to avoid division by zero. |
1e-07
|
Returns:
Type | Description |
---|---|
Tensor
|
OBB similarities, shape (N,). |
Notes
- OBB format: [center_x, center_y, width, height, rotation_angle].
- Implements the algorithm from https://arxiv.org/pdf/2106.06072v1.pdf.
Source code in ultralytics/utils/metrics.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
|
ultralytics.utils.metrics.batch_probiou
batch_probiou(obb1, obb2, eps=1e-07)
Calculate the probabilistic IoU between oriented bounding boxes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obb1
|
Tensor | ndarray
|
A tensor of shape (N, 5) representing ground truth obbs, with xywhr format. |
required |
obb2
|
Tensor | ndarray
|
A tensor of shape (M, 5) representing predicted obbs, with xywhr format. |
required |
eps
|
float
|
A small value to avoid division by zero. |
1e-07
|
Returns:
Type | Description |
---|---|
Tensor
|
A tensor of shape (N, M) representing obb similarities. |
References
Source code in ultralytics/utils/metrics.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
|
ultralytics.utils.metrics.smooth_bce
smooth_bce(eps=0.1)
Compute smoothed positive and negative Binary Cross-Entropy targets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
eps
|
float
|
The epsilon value for label smoothing. |
0.1
|
Returns:
Type | Description |
---|---|
tuple
|
A tuple containing the positive and negative label smoothing BCE targets. |
Source code in ultralytics/utils/metrics.py
279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
|
ultralytics.utils.metrics.smooth
smooth(y, f=0.05)
Box filter of fraction f.
Source code in ultralytics/utils/metrics.py
461 462 463 464 465 466 |
|
ultralytics.utils.metrics.plot_pr_curve
plot_pr_curve(
px, py, ap, save_dir=Path("pr_curve.png"), names={}, on_plot=None
)
Plot precision-recall curve.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
px
|
ndarray
|
X values for the PR curve. |
required |
py
|
ndarray
|
Y values for the PR curve. |
required |
ap
|
ndarray
|
Average precision values. |
required |
save_dir
|
Path
|
Path to save the plot. |
Path('pr_curve.png')
|
names
|
dict
|
Dictionary mapping class indices to class names. |
{}
|
on_plot
|
callable
|
Function to call after plot is saved. |
None
|
Source code in ultralytics/utils/metrics.py
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 |
|
ultralytics.utils.metrics.plot_mc_curve
plot_mc_curve(
px,
py,
save_dir=Path("mc_curve.png"),
names={},
xlabel="Confidence",
ylabel="Metric",
on_plot=None,
)
Plot metric-confidence curve.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
px
|
ndarray
|
X values for the metric-confidence curve. |
required |
py
|
ndarray
|
Y values for the metric-confidence curve. |
required |
save_dir
|
Path
|
Path to save the plot. |
Path('mc_curve.png')
|
names
|
dict
|
Dictionary mapping class indices to class names. |
{}
|
xlabel
|
str
|
X-axis label. |
'Confidence'
|
ylabel
|
str
|
Y-axis label. |
'Metric'
|
on_plot
|
callable
|
Function to call after plot is saved. |
None
|
Source code in ultralytics/utils/metrics.py
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
|
ultralytics.utils.metrics.compute_ap
compute_ap(recall, precision)
Compute the average precision (AP) given the recall and precision curves.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
recall
|
list
|
The recall curve. |
required |
precision
|
list
|
The precision curve. |
required |
Returns:
Type | Description |
---|---|
float
|
Average precision. |
ndarray
|
Precision envelope curve. |
ndarray
|
Modified recall curve with sentinel values added at the beginning and end. |
Source code in ultralytics/utils/metrics.py
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 |
|
ultralytics.utils.metrics.ap_per_class
ap_per_class(
tp,
conf,
pred_cls,
target_cls,
plot=False,
on_plot=None,
save_dir=Path(),
names={},
eps=1e-16,
prefix="",
)
Compute the average precision per class for object detection evaluation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp
|
ndarray
|
Binary array indicating whether the detection is correct (True) or not (False). |
required |
conf
|
ndarray
|
Array of confidence scores of the detections. |
required |
pred_cls
|
ndarray
|
Array of predicted classes of the detections. |
required |
target_cls
|
ndarray
|
Array of true classes of the detections. |
required |
plot
|
bool
|
Whether to plot PR curves or not. |
False
|
on_plot
|
func
|
A callback to pass plots path and data when they are rendered. |
None
|
save_dir
|
Path
|
Directory to save the PR curves. |
Path()
|
names
|
dict
|
Dict of class names to plot PR curves. |
{}
|
eps
|
float
|
A small value to avoid division by zero. |
1e-16
|
prefix
|
str
|
A prefix string for saving the plot files. |
''
|
Returns:
Name | Type | Description |
---|---|---|
tp |
ndarray
|
True positive counts at threshold given by max F1 metric for each class. |
fp |
ndarray
|
False positive counts at threshold given by max F1 metric for each class. |
p |
ndarray
|
Precision values at threshold given by max F1 metric for each class. |
r |
ndarray
|
Recall values at threshold given by max F1 metric for each class. |
f1 |
ndarray
|
F1-score values at threshold given by max F1 metric for each class. |
ap |
ndarray
|
Average precision for each class at different IoU thresholds. |
unique_classes |
ndarray
|
An array of unique classes that have data. |
p_curve |
ndarray
|
Precision curves for each class. |
r_curve |
ndarray
|
Recall curves for each class. |
f1_curve |
ndarray
|
F1-score curves for each class. |
x |
ndarray
|
X-axis values for the curves. |
prec_values |
ndarray
|
Precision values at mAP@0.5 for each class. |
Source code in ultralytics/utils/metrics.py
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 |
|