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(
names: dict[int, str] = [], task: str = "detect", save_matches: bool = False
)
Bases: DataExportMixin
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 category. |
names |
List[str]
|
The names of the classes, used as labels on the plot. |
matches |
dict
|
Contains the indices of ground truths and predictions categorized into TP, FP and FN. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
names
|
Dict[int, str]
|
Names of classes, used as labels on the plot. |
[]
|
task
|
str
|
Type of task, either 'detect' or 'classify'. |
'detect'
|
save_matches
|
bool
|
Save the indices of GTs, TPs, FPs, FNs for visualization. |
False
|
Source code in ultralytics/utils/metrics.py
325 326 327 328 329 330 331 332 333 334 335 336 337 338 |
|
matrix
matrix()
Return the confusion matrix.
Source code in ultralytics/utils/metrics.py
458 459 460 |
|
plot
plot(normalize: bool = True, save_dir: str = '', on_plot=None)
Plot the confusion matrix using matplotlib 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. |
''
|
on_plot
|
callable
|
An optional callback to pass plots path and data when they are rendered. |
None
|
Source code in ultralytics/utils/metrics.py
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 |
|
plot_matches
plot_matches(img: Tensor, im_file: str, save_dir: Path) -> None
Plot grid of GT, TP, FP, FN for each image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
img
|
Tensor
|
Image to plot onto. |
required |
im_file
|
str
|
Image filename to save visualizations. |
required |
save_dir
|
Path
|
Location to save the visualizations to. |
required |
Source code in ultralytics/utils/metrics.py
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 502 503 504 505 506 507 508 509 510 511 |
|
print
print()
Print the confusion matrix to the console.
Source code in ultralytics/utils/metrics.py
587 588 589 590 |
|
process_batch
process_batch(
detections: dict[str, Tensor],
batch: dict[str, Any],
conf: float = 0.25,
iou_thres: float = 0.45,
) -> None
Update confusion matrix for object detection task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detections
|
Dict[str, Tensor]
|
Dictionary containing detected bounding boxes and their associated information. Should contain 'cls', 'conf', and 'bboxes' keys, where 'bboxes' can be Array[N, 4] for regular boxes or Array[N, 5] for OBB with angle. |
required |
batch
|
Dict[str, Any]
|
Batch dictionary containing ground truth data with 'bboxes' (Array[M, 4]| Array[M, 5]) and 'cls' (Array[M]) keys, where M is the number of ground truth objects. |
required |
conf
|
float
|
Confidence threshold for detections. |
0.25
|
iou_thres
|
float
|
IoU threshold for matching detections to ground truth. |
0.45
|
Source code in ultralytics/utils/metrics.py
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 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 |
|
process_cls_preds
process_cls_preds(preds: list[Tensor], targets: list[Tensor]) -> None
Update confusion matrix for classification task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds
|
List[N, min(nc, 5)]
|
Predicted class labels. |
required |
targets
|
List[N, 1]
|
Ground truth class labels. |
required |
Source code in ultralytics/utils/metrics.py
366 367 368 369 370 371 372 373 374 375 376 |
|
summary
summary(normalize: bool = False, decimals: int = 5) -> list[dict[str, float]]
Generate a summarized representation of the confusion matrix as a list of dictionaries, with optional normalization. This is useful for exporting the matrix to various formats such as CSV, XML, HTML, JSON, or SQL.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
Whether to normalize the confusion matrix values. |
False
|
decimals
|
int
|
Number of decimal places to round the output values to. |
5
|
Returns:
Type | Description |
---|---|
List[Dict[str, float]]
|
A list of dictionaries, each representing one predicted class with corresponding values for all actual classes. |
Examples:
>>> results = model.val(data="coco8.yaml", plots=True)
>>> cm_dict = results.confusion_matrix.summary(normalize=True, decimals=5)
>>> print(cm_dict)
Source code in ultralytics/utils/metrics.py
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 |
|
tp_fp
tp_fp() -> tuple[np.ndarray, np.ndarray]
Return true positives and false positives.
Returns:
Name | Type | Description |
---|---|---|
tp |
ndarray
|
True positives. |
fp |
ndarray
|
False positives. |
Source code in ultralytics/utils/metrics.py
462 463 464 465 466 467 468 469 470 471 472 473 |
|
ultralytics.utils.metrics.Metric
Metric()
Bases: SimpleClass
Class for computing evaluation metrics for Ultralytics YOLO models.
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. |
ap |
AP at IoU thresholds from 0.5 to 0.95 for all classes. |
mp |
Mean precision of all classes. |
mr |
Mean recall of all classes. |
map50 |
Mean AP at IoU threshold of 0.5 for all classes. |
map75 |
Mean AP at IoU threshold of 0.75 for all classes. |
map |
Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. |
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. |
fitness |
Model fitness as a weighted combination of metrics. |
update |
Update metric attributes with new evaluation results. |
curves |
Provides a list of curves for accessing specific metrics like precision, recall, F1, etc. |
curves_results |
Provide a list of results for accessing specific metrics like precision, recall, F1, etc. |
Source code in ultralytics/utils/metrics.py
886 887 888 889 890 891 892 893 |
|
ap
property
ap: ndarray | list
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: ndarray | list
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: list
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results: list[list]
Return a list of curves for accessing specific metrics curves.
map
property
map: float
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: float
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: float
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: ndarray
Return mAP of each class.
mp
property
mp: float
Return the Mean Precision of all classes.
Returns:
Type | Description |
---|---|
float
|
The mean precision of all classes. |
mr
property
mr: float
Return the Mean Recall of all classes.
Returns:
Type | Description |
---|---|
float
|
The mean recall of all classes. |
class_result
class_result(i: int) -> tuple[float, float, float, float]
Return class-aware result, p[i], r[i], ap50[i], ap[i].
Source code in ultralytics/utils/metrics.py
969 970 971 |
|
fitness
fitness() -> float
Return model fitness as a weighted combination of metrics.
Source code in ultralytics/utils/metrics.py
981 982 983 984 |
|
mean_results
mean_results() -> list[float]
Return mean of results, mp, mr, map50, map.
Source code in ultralytics/utils/metrics.py
965 966 967 |
|
update
update(results: tuple)
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
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 |
|
ultralytics.utils.metrics.DetMetrics
DetMetrics(names: dict[int, str] = {})
Bases: SimpleClass
, DataExportMixin
Utility class for computing detection metrics such as precision, recall, and mean average precision (mAP).
Attributes:
Name | Type | Description |
---|---|---|
names |
Dict[int, str]
|
A dictionary of class names. |
box |
Metric
|
An instance of the Metric class for storing detection results. |
speed |
Dict[str, float]
|
A dictionary for storing execution times of different parts of the detection process. |
task |
str
|
The task type, set to 'detect'. |
stats |
Dict[str, List]
|
A dictionary containing lists for true positives, confidence scores, predicted classes, target classes, and target images. |
nt_per_class |
Number of targets per class. |
|
nt_per_image |
Number of targets per image. |
Methods:
Name | Description |
---|---|
update_stats |
Update statistics by appending new values to existing stat collections. |
process |
Process predicted results for object detection and update metrics. |
clear_stats |
Clear the stored statistics. |
keys |
Return a list of keys for accessing specific metrics. |
mean_results |
Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95. |
class_result |
Return the result of evaluating the performance of an object detection model on a specific class. |
maps |
Return mean Average Precision (mAP) scores per class. |
fitness |
Return the fitness of box object. |
ap_class_index |
Return the average precision index per class. |
results_dict |
Return dictionary of computed performance metrics and statistics. |
curves |
Return a list of curves for accessing specific metrics curves. |
curves_results |
Return a list of computed performance metrics and statistics. |
summary |
Generate a summarized representation of per-class detection metrics as a list of dictionaries. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
names
|
Dict[int, str]
|
Dictionary of class names. |
{}
|
Source code in ultralytics/utils/metrics.py
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 |
|
ap_class_index
property
ap_class_index: list
Return the average precision index per class.
curves
property
curves: list[str]
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results: list[list]
Return a list of computed performance metrics and statistics.
fitness
property
fitness: float
Return the fitness of box object.
keys
property
keys: list[str]
Return a list of keys for accessing specific metrics.
maps
property
maps: ndarray
Return mean Average Precision (mAP) scores per class.
results_dict
property
results_dict: dict[str, float]
Return dictionary of computed performance metrics and statistics.
class_result
class_result(i: int) -> tuple[float, float, float, float]
Return the result of evaluating the performance of an object detection model on a specific class.
Source code in ultralytics/utils/metrics.py
1133 1134 1135 |
|
clear_stats
clear_stats()
Clear the stored statistics.
Source code in ultralytics/utils/metrics.py
1119 1120 1121 1122 |
|
mean_results
mean_results() -> list[float]
Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.
Source code in ultralytics/utils/metrics.py
1129 1130 1131 |
|
process
process(
save_dir: Path = Path("."), plot: bool = False, on_plot=None
) -> dict[str, np.ndarray]
Process predicted results for object detection and update metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir
|
Path
|
Directory to save plots. Defaults to Path("."). |
Path('.')
|
plot
|
bool
|
Whether to plot precision-recall curves. Defaults to False. |
False
|
on_plot
|
callable
|
Function to call after plots are generated. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
Dict[str, ndarray]
|
Dictionary containing concatenated statistics arrays. |
Source code in ultralytics/utils/metrics.py
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 |
|
summary
summary(normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]
Generate a summarized representation of per-class detection metrics as a list of dictionaries. Includes shared scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
For Detect metrics, everything is normalized by default [0-1]. |
True
|
decimals
|
int
|
Number of decimal places to round the metrics values to. |
5
|
Returns:
Type | Description |
---|---|
List[Dict[str, Any]]
|
A list of dictionaries, each representing one class with corresponding metric values. |
Examples:
>>> results = model.val(data="coco8.yaml")
>>> detection_summary = results.summary()
>>> print(detection_summary)
Source code in ultralytics/utils/metrics.py
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 |
|
update_stats
update_stats(stat: dict[str, Any]) -> None
Update statistics by appending new values to existing stat collections.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stat
|
Dict[str, any]
|
Dictionary containing new statistical values to append. Keys should match existing keys in self.stats. |
required |
Source code in ultralytics/utils/metrics.py
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 |
|
ultralytics.utils.metrics.SegmentMetrics
SegmentMetrics(names: dict[int, str] = {})
Bases: DetMetrics
Calculate and aggregate detection and segmentation metrics over a given set of classes.
Attributes:
Name | Type | Description |
---|---|---|
names |
Dict[int, str]
|
Dictionary of class names. |
box |
Metric
|
An instance of the Metric class for storing detection results. |
seg |
Metric
|
An instance of the Metric class to calculate mask segmentation metrics. |
speed |
Dict[str, float]
|
A dictionary for storing execution times of different parts of the detection process. |
task |
str
|
The task type, set to 'segment'. |
stats |
Dict[str, List]
|
A dictionary containing lists for true positives, confidence scores, predicted classes, target classes, and target images. |
nt_per_class |
Number of targets per class. |
|
nt_per_image |
Number of targets per image. |
Methods:
Name | Description |
---|---|
process |
Process the detection and segmentation metrics over the given set of predictions. |
keys |
Return a list of keys for accessing metrics. |
mean_results |
Return the mean metrics for bounding box and segmentation results. |
class_result |
Return classification results for a specified class index. |
maps |
Return mAP scores for object detection and semantic segmentation models. |
fitness |
Return the fitness score for both segmentation and bounding box models. |
curves |
Return a list of curves for accessing specific metrics curves. |
curves_results |
Provide a list of computed performance metrics and statistics. |
summary |
Generate a summarized representation of per-class segmentation metrics as a list of dictionaries. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
names
|
Dict[int, str]
|
Dictionary of class names. |
{}
|
Source code in ultralytics/utils/metrics.py
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 |
|
curves
property
curves: list[str]
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results: list[list]
Return a list of computed performance metrics and statistics.
fitness
property
fitness: float
Return the fitness score for both segmentation and bounding box models.
keys
property
keys: list[str]
Return a list of keys for accessing metrics.
maps
property
maps: ndarray
Return mAP scores for object detection and semantic segmentation models.
class_result
class_result(i: int) -> list[float]
Return classification results for a specified class index.
Source code in ultralytics/utils/metrics.py
1284 1285 1286 |
|
mean_results
mean_results() -> list[float]
Return the mean metrics for bounding box and segmentation results.
Source code in ultralytics/utils/metrics.py
1280 1281 1282 |
|
process
process(
save_dir: Path = Path("."), plot: bool = False, on_plot=None
) -> dict[str, np.ndarray]
Process the detection and segmentation metrics over the given set of predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir
|
Path
|
Directory to save plots. Defaults to Path("."). |
Path('.')
|
plot
|
bool
|
Whether to plot precision-recall curves. Defaults to False. |
False
|
on_plot
|
callable
|
Function to call after plots are generated. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
Dict[str, ndarray]
|
Dictionary containing concatenated statistics arrays. |
Source code in ultralytics/utils/metrics.py
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 |
|
summary
summary(normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]
Generate a summarized representation of per-class segmentation metrics as a list of dictionaries. Includes both box and mask scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
For Segment metrics, everything is normalized by default [0-1]. |
True
|
decimals
|
int
|
Number of decimal places to round the metrics values to. |
5
|
Returns:
Type | Description |
---|---|
List[Dict[str, Any]]
|
A list of dictionaries, each representing one class with corresponding metric values. |
Examples:
>>> results = model.val(data="coco8-seg.yaml")
>>> seg_summary = results.summary(decimals=4)
>>> print(seg_summary)
Source code in ultralytics/utils/metrics.py
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 |
|
ultralytics.utils.metrics.PoseMetrics
PoseMetrics(names: dict[int, str] = {})
Bases: DetMetrics
Calculate and aggregate detection and pose metrics over a given set of classes.
Attributes:
Name | Type | Description |
---|---|---|
names |
Dict[int, str]
|
Dictionary of class names. |
pose |
Metric
|
An instance of the Metric class to calculate pose metrics. |
box |
Metric
|
An instance of the Metric class for storing detection results. |
speed |
Dict[str, float]
|
A dictionary for storing execution times of different parts of the detection process. |
task |
str
|
The task type, set to 'pose'. |
stats |
Dict[str, List]
|
A dictionary containing lists for true positives, confidence scores, predicted classes, target classes, and target images. |
nt_per_class |
Number of targets per class. |
|
nt_per_image |
Number of targets per image. |
Methods:
Name | Description |
---|---|
process |
Process the detection and pose metrics over the given set of predictions. R |
keys |
Return a list of keys for accessing metrics. |
mean_results |
Return the mean results of box and pose. |
class_result |
Return the class-wise detection results for a specific class i. |
maps |
Return the mean average precision (mAP) per class for both box and pose detections. |
fitness |
Return combined fitness score for pose and box detection. |
curves |
Return a list of curves for accessing specific metrics curves. |
curves_results |
Provide a list of computed performance metrics and statistics. |
summary |
Generate a summarized representation of per-class pose metrics as a list of dictionaries. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
names
|
Dict[int, str]
|
Dictionary of class names. |
{}
|
Source code in ultralytics/utils/metrics.py
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 |
|
curves
property
curves: list[str]
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results: list[list]
Return a list of computed performance metrics and statistics.
fitness
property
fitness: float
Return combined fitness score for pose and box detection.
keys
property
keys: list[str]
Return a list of evaluation metric keys.
maps
property
maps: ndarray
Return the mean average precision (mAP) per class for both box and pose detections.
class_result
class_result(i: int) -> list[float]
Return the class-wise detection results for a specific class i.
Source code in ultralytics/utils/metrics.py
1421 1422 1423 |
|
mean_results
mean_results() -> list[float]
Return the mean results of box and pose.
Source code in ultralytics/utils/metrics.py
1417 1418 1419 |
|
process
process(
save_dir: Path = Path("."), plot: bool = False, on_plot=None
) -> dict[str, np.ndarray]
Process the detection and pose metrics over the given set of predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
save_dir
|
Path
|
Directory to save plots. Defaults to Path("."). |
Path('.')
|
plot
|
bool
|
Whether to plot precision-recall curves. Defaults to False. |
False
|
on_plot
|
callable
|
Function to call after plots are generated. |
None
|
Returns:
Type | Description |
---|---|
Dict[str, ndarray]
|
Dictionary containing concatenated statistics arrays. |
Source code in ultralytics/utils/metrics.py
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 |
|
summary
summary(normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]
Generate a summarized representation of per-class pose metrics as a list of dictionaries. Includes both box and pose scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
For Pose metrics, everything is normalized by default [0-1]. |
True
|
decimals
|
int
|
Number of decimal places to round the metrics values to. |
5
|
Returns:
Type | Description |
---|---|
List[Dict[str, Any]]
|
A list of dictionaries, each representing one class with corresponding metric values. |
Examples:
>>> results = model.val(data="coco8-pose.yaml")
>>> pose_summary = results.summary(decimals=4)
>>> print(pose_summary)
Source code in ultralytics/utils/metrics.py
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 |
|
ultralytics.utils.metrics.ClassifyMetrics
ClassifyMetrics()
Bases: SimpleClass
, DataExportMixin
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'. |
Methods:
Name | Description |
---|---|
process |
Process target classes and predicted classes to compute metrics. |
fitness |
Return mean of top-1 and top-5 accuracies as fitness score. |
results_dict |
Return a dictionary with model's performance metrics and fitness score. |
keys |
Return a list of keys for the results_dict property. |
curves |
Return a list of curves for accessing specific metrics curves. |
curves_results |
Provide a list of computed performance metrics and statistics. |
summary |
Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy). |
Source code in ultralytics/utils/metrics.py
1502 1503 1504 1505 1506 1507 |
|
curves
property
curves: list
Return a list of curves for accessing specific metrics curves.
curves_results
property
curves_results: list
Return a list of curves for accessing specific metrics curves.
fitness
property
fitness: float
Return mean of top-1 and top-5 accuracies as fitness score.
keys
property
keys: list[str]
Return a list of keys for the results_dict property.
results_dict
property
results_dict: dict[str, float]
Return a dictionary with model's performance metrics and fitness score.
process
process(targets: Tensor, pred: Tensor)
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
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 |
|
summary
summary(normalize: bool = True, decimals: int = 5) -> list[dict[str, float]]
Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
normalize
|
bool
|
For Classify metrics, everything is normalized by default [0-1]. |
True
|
decimals
|
int
|
Number of decimal places to round the metrics values to. |
5
|
Returns:
Type | Description |
---|---|
List[Dict[str, float]]
|
A list with one dictionary containing Top-1 and Top-5 classification accuracy. |
Examples:
>>> results = model.val(data="imagenet10")
>>> classify_summary = results.summary(decimals=4)
>>> print(classify_summary)
Source code in ultralytics/utils/metrics.py
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 |
|
ultralytics.utils.metrics.OBBMetrics
OBBMetrics(names: dict[int, str] = {})
Bases: DetMetrics
Metrics for evaluating oriented bounding box (OBB) detection.
Attributes:
Name | Type | Description |
---|---|---|
names |
Dict[int, str]
|
Dictionary of class names. |
box |
Metric
|
An instance of the Metric class for storing detection results. |
speed |
Dict[str, float]
|
A dictionary for storing execution times of different parts of the detection process. |
task |
str
|
The task type, set to 'obb'. |
stats |
Dict[str, List]
|
A dictionary containing lists for true positives, confidence scores, predicted classes, target classes, and target images. |
nt_per_class |
Number of targets per class. |
|
nt_per_image |
Number of targets per image. |
References
Parameters:
Name | Type | Description | Default |
---|---|---|---|
names
|
Dict[int, str]
|
Dictionary of class names. |
{}
|
Source code in ultralytics/utils/metrics.py
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 |
|
ultralytics.utils.metrics.bbox_ioa
bbox_ioa(
box1: ndarray, box2: ndarray, iou: bool = False, eps: float = 1e-07
) -> np.ndarray
Calculate the intersection over box2 area given box1 and box2.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box1
|
ndarray
|
A numpy array of shape (N, 4) representing N bounding boxes in x1y1x2y2 format. |
required |
box2
|
ndarray
|
A numpy array of shape (M, 4) representing M bounding boxes in x1y1x2y2 format. |
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
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 50 51 52 |
|
ultralytics.utils.metrics.box_iou
box_iou(box1: Tensor, box2: Tensor, eps: float = 1e-07) -> torch.Tensor
Calculate intersection-over-union (IoU) of boxes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box1
|
Tensor
|
A tensor of shape (N, 4) representing N bounding boxes in (x1, y1, x2, y2) format. |
required |
box2
|
Tensor
|
A tensor of shape (M, 4) representing M bounding boxes in (x1, y1, x2, y2) format. |
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
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
|
ultralytics.utils.metrics.bbox_iou
bbox_iou(
box1: Tensor,
box2: Tensor,
xywh: bool = True,
GIoU: bool = False,
DIoU: bool = False,
CIoU: bool = False,
eps: float = 1e-07,
) -> torch.Tensor
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
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 135 136 137 138 139 140 141 142 143 144 145 146 147 |
|
ultralytics.utils.metrics.mask_iou
mask_iou(mask1: Tensor, mask2: Tensor, eps: float = 1e-07) -> torch.Tensor
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
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
|
ultralytics.utils.metrics.kpt_iou
kpt_iou(
kpt1: Tensor,
kpt2: Tensor,
area: Tensor,
sigma: list[float],
eps: float = 1e-07,
) -> torch.Tensor
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
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
|
ultralytics.utils.metrics._get_covariance_matrix
_get_covariance_matrix(
boxes: Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]
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
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
|
ultralytics.utils.metrics.probiou
probiou(
obb1: Tensor, obb2: Tensor, CIoU: bool = False, eps: float = 1e-07
) -> torch.Tensor
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].
References
Source code in ultralytics/utils/metrics.py
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 |
|
ultralytics.utils.metrics.batch_probiou
batch_probiou(
obb1: Tensor | ndarray, obb2: Tensor | ndarray, eps: float = 1e-07
) -> torch.Tensor
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
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 |
|
ultralytics.utils.metrics.smooth_bce
smooth_bce(eps: float = 0.1) -> tuple[float, float]
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:
Name | Type | Description |
---|---|---|
pos |
float
|
Positive label smoothing BCE target. |
neg |
float
|
Negative label smoothing BCE target. |
Source code in ultralytics/utils/metrics.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
|
ultralytics.utils.metrics.smooth
smooth(y: ndarray, f: float = 0.05) -> np.ndarray
Box filter of fraction f.
Source code in ultralytics/utils/metrics.py
629 630 631 632 633 634 |
|
ultralytics.utils.metrics.plot_pr_curve
plot_pr_curve(
px: ndarray,
py: ndarray,
ap: ndarray,
save_dir: Path = Path("pr_curve.png"),
names: dict[int, str] = {},
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[int, str]
|
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
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 |
|
ultralytics.utils.metrics.plot_mc_curve
plot_mc_curve(
px: ndarray,
py: ndarray,
save_dir: Path = Path("mc_curve.png"),
names: dict[int, str] = {},
xlabel: str = "Confidence",
ylabel: str = "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[int, str]
|
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
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 715 716 717 718 719 720 721 722 723 724 |
|
ultralytics.utils.metrics.compute_ap
compute_ap(
recall: list[float], precision: list[float]
) -> tuple[float, np.ndarray, np.ndarray]
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:
Name | Type | Description |
---|---|---|
ap |
float
|
Average precision. |
mpre |
ndarray
|
Precision envelope curve. |
mrec |
ndarray
|
Modified recall curve with sentinel values added at the beginning and end. |
Source code in ultralytics/utils/metrics.py
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 |
|
ultralytics.utils.metrics.ap_per_class
ap_per_class(
tp: ndarray,
conf: ndarray,
pred_cls: ndarray,
target_cls: ndarray,
plot: bool = False,
on_plot=None,
save_dir: Path = Path(),
names: dict[int, str] = {},
eps: float = 1e-16,
prefix: str = "",
) -> tuple
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
|
callable
|
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[int, str]
|
Dictionary 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
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 824 825 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 |
|