Reference for ultralytics/utils/metrics.py
Note
Full source code for this file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/utils/metrics.py. Help us fix any issues you see by submitting a Pull Request 🛠️. Thank you 🙏!
ultralytics.utils.metrics.ConfusionMatrix
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 |
array
|
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. |
Source code in ultralytics/utils/metrics.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 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 240 241 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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 |
|
__init__(nc, conf=0.25, iou_thres=0.45, task='detect')
Initialize attributes for the YOLO model.
Source code in ultralytics/utils/metrics.py
matrix()
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
print()
process_batch(detections, labels)
Update confusion matrix for object detection task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detections |
Array[N, 6]
|
Detected bounding boxes and their associated information. Each row should contain (x1, y1, x2, y2, conf, class). |
required |
labels |
Array[M, 5]
|
Ground truth bounding boxes and their associated class labels. Each row should contain (class, x1, y1, x2, y2). |
required |
Source code in ultralytics/utils/metrics.py
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
tp_fp()
Returns true positives and false positives.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.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
498 499 500 501 502 503 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 538 539 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 571 572 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 |
|
ap
property
Returns 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
Returns 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. |
map
property
Returns 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
Returns the mean Average Precision (mAP) at an IoU threshold of 0.5.
Returns:
Type | Description |
---|---|
float
|
The mAP50 at an IoU threshold of 0.5. |
map75
property
Returns the mean Average Precision (mAP) at an IoU threshold of 0.75.
Returns:
Type | Description |
---|---|
float
|
The mAP50 at an IoU threshold of 0.75. |
maps
property
mAP of each class.
mp
property
Returns the Mean Precision of all classes.
Returns:
Type | Description |
---|---|
float
|
The mean precision of all classes. |
mr
property
Returns the Mean Recall of all classes.
Returns:
Type | Description |
---|---|
float
|
The mean recall of all classes. |
class_result(i)
fitness()
Model fitness as a weighted combination of metrics.
mean_results()
update(results)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
results |
tuple
|
A tuple of (p, r, ap, f1, ap_class) |
required |
ultralytics.utils.metrics.DetMetrics
Bases: SimpleClass
This class is a utility class for computing detection metrics such as precision, recall, and mean average precision (mAP) of an object detection model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir |
Path
|
A path to the directory where the output plots will be saved. Defaults to current directory. |
Path('.')
|
plot |
bool
|
A flag that indicates whether to plot precision-recall curves for each class. Defaults to False. |
False
|
on_plot |
func
|
An optional callback to pass plots path and data when they are rendered. Defaults to None. |
None
|
names |
tuple of str
|
A tuple of strings that represents the names of the classes. Defaults to an empty tuple. |
()
|
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 the precision-recall curves for each class. |
on_plot |
func
|
An optional callback to pass plots path and data when they are rendered. |
names |
tuple of str
|
A tuple of strings that represents the names of the classes. |
box |
Metric
|
An instance of the Metric class for storing the results of the detection metrics. |
speed |
dict
|
A dictionary for storing the execution time of different parts of the detection process. |
Methods:
Name | Description |
---|---|
process |
Updates the metric results with the latest batch of predictions. |
keys |
Returns a list of keys for accessing the computed detection metrics. |
mean_results |
Returns a list of mean values for the computed detection metrics. |
class_result |
Returns a list of values for the computed detection metrics for a specific class. |
maps |
Returns a dictionary of mean average precision (mAP) values for different IoU thresholds. |
fitness |
Computes the fitness score based on the computed detection metrics. |
ap_class_index |
Returns a list of class indices sorted by their average precision (AP) values. |
results_dict |
Returns a dictionary that maps detection metric keys to their computed values. |
Source code in ultralytics/utils/metrics.py
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 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 |
|
ap_class_index
property
Returns the average precision index per class.
fitness
property
Returns the fitness of box object.
keys
property
Returns a list of keys for accessing specific metrics.
maps
property
Returns mean Average Precision (mAP) scores per class.
results_dict
property
Returns dictionary of computed performance metrics and statistics.
class_result(i)
Return the result of evaluating the performance of an object detection model on a specific class.
mean_results()
process(tp, conf, pred_cls, target_cls)
Process predicted results for object detection and update metrics.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.SegmentMetrics
Bases: SimpleClass
Calculates and aggregates detection and segmentation metrics over a given set of classes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir |
Path
|
Path to the directory where the output plots should be saved. Default is the current directory. |
Path('.')
|
plot |
bool
|
Whether to save the detection and segmentation plots. Default is False. |
False
|
on_plot |
func
|
An optional callback to pass plots path and data when they are rendered. Defaults to None. |
None
|
names |
list
|
List of class names. Default is an empty list. |
()
|
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. |
on_plot |
func
|
An optional callback to pass plots path and data when they are rendered. |
names |
list
|
List 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. |
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. |
Source code in ultralytics/utils/metrics.py
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 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 818 819 820 821 822 823 |
|
ap_class_index
property
Boxes and masks have the same ap_class_index.
fitness
property
Get the fitness score for both segmentation and bounding box models.
keys
property
Returns a list of keys for accessing metrics.
maps
property
Returns mAP scores for object detection and semantic segmentation models.
results_dict
property
Returns results of object detection model for evaluation.
class_result(i)
mean_results()
process(tp_b, tp_m, conf, pred_cls, target_cls)
Processes the detection and segmentation metrics over the given set of predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp_b |
list
|
List of True Positive boxes. |
required |
tp_m |
list
|
List of True Positive masks. |
required |
conf |
list
|
List of confidence scores. |
required |
pred_cls |
list
|
List of predicted classes. |
required |
target_cls |
list
|
List of target classes. |
required |
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.PoseMetrics
Bases: SegmentMetrics
Calculates and aggregates detection and pose metrics over a given set of classes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir |
Path
|
Path to the directory where the output plots should be saved. Default is the current directory. |
Path('.')
|
plot |
bool
|
Whether to save the detection and segmentation plots. Default is False. |
False
|
on_plot |
func
|
An optional callback to pass plots path and data when they are rendered. Defaults to None. |
None
|
names |
list
|
List of class names. Default is an empty list. |
()
|
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. |
on_plot |
func
|
An optional callback to pass plots path and data when they are rendered. |
names |
list
|
List 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 mask segmentation metrics. |
speed |
dict
|
Dictionary to store the time taken in different phases of inference. |
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. |
Source code in ultralytics/utils/metrics.py
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 |
|
fitness
property
Computes classification metrics and speed using the targets
and pred
inputs.
keys
property
Returns list of evaluation metric keys.
maps
property
Returns the mean average precision (mAP) per class for both box and pose detections.
class_result(i)
mean_results()
process(tp_b, tp_p, conf, pred_cls, target_cls)
Processes the detection and pose metrics over the given set of predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp_b |
list
|
List of True Positive boxes. |
required |
tp_p |
list
|
List of True Positive keypoints. |
required |
conf |
list
|
List of confidence scores. |
required |
pred_cls |
list
|
List of predicted classes. |
required |
target_cls |
list
|
List of target classes. |
required |
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.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[str, float]
|
A dictionary containing the time taken for each step in the pipeline. |
Properties
fitness (float): The fitness of the model, which is equal to top-5 accuracy. results_dict (Dict[str, Union[float, str]]): A dictionary containing the classification metrics and fitness. keys (List[str]): A list of keys for the results_dict.
Methods:
Name | Description |
---|---|
process |
Processes the targets and predictions to compute classification metrics. |
Source code in ultralytics/utils/metrics.py
fitness
property
Returns mean of top-1 and top-5 accuracies as fitness score.
keys
property
Returns a list of keys for the results_dict property.
results_dict
property
Returns a dictionary with model's performance metrics and fitness score.
process(targets, pred)
Target classes and predicted classes.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.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 |
array
|
A numpy array of shape (n, 4) representing n bounding boxes. |
required |
box2 |
array
|
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. Defaults to 1e-7. |
1e-07
|
Returns:
Type | Description |
---|---|
array
|
A numpy array of shape (n, m) representing the intersection over box2 area. |
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.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/master/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. Defaults to 1e-7. |
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
ultralytics.utils.metrics.bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-07)
Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box1 |
Tensor
|
A tensor representing a single bounding box with shape (1, 4). |
required |
box2 |
Tensor
|
A tensor representing n bounding boxes with shape (n, 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. Defaults to True. |
True
|
GIoU |
bool
|
If True, calculate Generalized IoU. Defaults to False. |
False
|
DIoU |
bool
|
If True, calculate Distance IoU. Defaults to False. |
False
|
CIoU |
bool
|
If True, calculate Complete IoU. Defaults to False. |
False
|
eps |
float
|
A small value to avoid division by zero. Defaults to 1e-7. |
1e-07
|
Returns:
Type | Description |
---|---|
Tensor
|
IoU, GIoU, DIoU, or CIoU values depending on the specified flags. |
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.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. Defaults to 1e-7. |
1e-07
|
Returns:
Type | Description |
---|---|
Tensor
|
A tensor of shape (N, M) representing masks IoU. |
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.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. Defaults to 1e-7. |
1e-07
|
Returns:
Type | Description |
---|---|
Tensor
|
A tensor of shape (N, M) representing keypoint similarities. |
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.smooth_BCE(eps=0.1)
ultralytics.utils.metrics.smooth(y, f=0.05)
Box filter of fraction f.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=(), on_plot=None)
Plots a precision-recall curve.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric', on_plot=None)
Plots a metric-confidence curve.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.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
ultralytics.utils.metrics.ap_per_class(tp, conf, pred_cls, target_cls, plot=False, on_plot=None, save_dir=Path(), names=(), eps=1e-16, prefix='')
Computes 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. Defaults to False. |
False
|
on_plot |
func
|
A callback to pass plots path and data when they are rendered. Defaults to None. |
None
|
save_dir |
Path
|
Directory to save the PR curves. Defaults to an empty path. |
Path()
|
names |
tuple
|
Tuple of class names to plot PR curves. Defaults to an empty tuple. |
()
|
eps |
float
|
A small value to avoid division by zero. Defaults to 1e-16. |
1e-16
|
prefix |
str
|
A prefix string for saving the plot files. Defaults to an empty string. |
''
|
Returns:
Type | Description |
---|---|
tuple
|
A tuple of six arrays and one array of unique classes, where: tp (np.ndarray): True positive counts for each class. fp (np.ndarray): False positive counts for each class. p (np.ndarray): Precision values at each confidence threshold. r (np.ndarray): Recall values at each confidence threshold. f1 (np.ndarray): F1-score values at each confidence threshold. ap (np.ndarray): Average precision for each class at different IoU thresholds. unique_classes (np.ndarray): An array of unique classes that have data. |
Source code in ultralytics/utils/metrics.py
408 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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 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 |
|