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
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. |
Source code in ultralytics/utils/metrics.py
matrix
plot
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
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
process_cls_preds
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
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. |
curves_results property
Returns a list of curves for accessing specific metrics curves.
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 mAP 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 mAP at an IoU threshold of 0.75. |
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
fitness
Model fitness as a weighted combination of metrics.
mean_results
update
Updates the evaluation metrics of the model with a new set of results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
results | tuple | A tuple containing the following evaluation metrics: - 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,). | required |
Side Effects
Updates the class attributes self.p
, self.r
, self.f1
, self.all_ap
, and self.ap_class_index
based on the values provided in the results
tuple.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.DetMetrics
Bases: SimpleClass
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 | dict of str | A dict 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 | dict of str | A dict 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. |
curves | TODO |
curves_results | TODO |
Source code in ultralytics/utils/metrics.py
curves_results property
Returns dictionary of computed performance metrics and statistics.
results_dict property
Returns dictionary of computed performance metrics and statistics.
class_result
Return the result of evaluating the performance of an object detection model on a specific class.
mean_results
process
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
curves_results property
Returns dictionary of computed performance metrics and statistics.
class_result
mean_results
process
Processes the detection and segmentation metrics over the given set of predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp | 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
curves_results property
Returns dictionary of computed performance metrics and statistics.
fitness property
Computes classification metrics and speed using the targets
and pred
inputs.
maps property
Returns the mean average precision (mAP) per class for both box and pose detections.
class_result
mean_results
process
Processes the detection and pose metrics over the given set of predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tp | 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. |
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
curves_results property
Returns a list of curves for accessing specific metrics curves.
results_dict property
Returns a dictionary with model's performance metrics and fitness score.
process
Target classes and predicted classes.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.OBBMetrics
Bases: SimpleClass
Metrics for evaluating oriented bounding box (OBB) detection, see https://arxiv.org/pdf/2106.06072.pdf.
Source code in ultralytics/utils/metrics.py
curves_results property
Returns a list of curves for accessing specific metrics curves.
results_dict property
Returns dictionary of computed performance metrics and statistics.
class_result
Return the result of evaluating the performance of an object detection model on a specific class.
mean_results
process
Process predicted results for object detection and update metrics.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.bbox_ioa
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. Defaults to 1e-7. | 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
ultralytics.utils.metrics.box_iou
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
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
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
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._get_covariance_matrix
Generating covariance matrix from obbs.
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
ultralytics.utils.metrics.probiou
Calculate probabilistic IoU between oriented bounding boxes.
Implements the algorithm from https://arxiv.org/pdf/2106.06072v1.pdf.
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. Defaults to False. | False |
eps | float | Small value to avoid division by zero. Defaults to 1e-7. | 1e-07 |
Returns:
Type | Description |
---|---|
Tensor | OBB similarities, shape (N,). |
Note
OBB format: [center_x, center_y, width, height, rotation_angle]. If CIoU is True, returns CIoU instead of IoU.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.batch_probiou
Calculate the prob IoU between oriented bounding boxes, https://arxiv.org/pdf/2106.06072v1.pdf.
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. Defaults to 1e-7. | 1e-07 |
Returns:
Type | Description |
---|---|
Tensor | A tensor of shape (N, M) representing obb similarities. |
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.smooth_BCE
Computes smoothed positive and negative Binary Cross-Entropy targets.
This function calculates positive and negative label smoothing BCE targets based on a given epsilon value. For implementation details, refer to https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
eps | float | The epsilon value for label smoothing. Defaults to 0.1. | 0.1 |
Returns:
Type | Description |
---|---|
tuple | A tuple containing the positive and negative label smoothing BCE targets. |
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.smooth
Box filter of fraction f.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.plot_pr_curve
Plots a precision-recall curve.
Source code in ultralytics/utils/metrics.py
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,
)
Plots a metric-confidence curve.
Source code in ultralytics/utils/metrics.py
ultralytics.utils.metrics.compute_ap
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
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 | dict | Dict 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 at threshold given by max F1 metric for each class.Shape: (nc,). fp (np.ndarray): False positive counts at threshold given by max F1 metric for each class. Shape: (nc,). p (np.ndarray): Precision values at threshold given by max F1 metric for each class. Shape: (nc,). r (np.ndarray): Recall values at threshold given by max F1 metric for each class. Shape: (nc,). f1 (np.ndarray): F1-score values at threshold given by max F1 metric for each class. Shape: (nc,). ap (np.ndarray): Average precision for each class at different IoU thresholds. Shape: (nc, 10). unique_classes (np.ndarray): An array of unique classes that have data. Shape: (nc,). p_curve (np.ndarray): Precision curves for each class. Shape: (nc, 1000). r_curve (np.ndarray): Recall curves for each class. Shape: (nc, 1000). f1_curve (np.ndarray): F1-score curves for each class. Shape: (nc, 1000). x (np.ndarray): X-axis values for the curves. Shape: (1000,). prec_values: Precision values at mAP@0.5 for each class. Shape: (nc, 1000). |
Source code in ultralytics/utils/metrics.py
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 |
|