Reference for ultralytics/models/yolo/detect/val.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/models/yolo/detect/val.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.models.yolo.detect.val.DetectionValidator
DetectionValidator(
dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None
)
Bases: BaseValidator
A class extending the BaseValidator class for validation based on a detection model.
This class implements validation functionality specific to object detection tasks, including metrics calculation, prediction processing, and visualization of results.
Attributes:
Name | Type | Description |
---|---|---|
nt_per_class |
ndarray
|
Number of targets per class. |
nt_per_image |
ndarray
|
Number of targets per image. |
is_coco |
bool
|
Whether the dataset is COCO. |
is_lvis |
bool
|
Whether the dataset is LVIS. |
class_map |
List[int]
|
Mapping from model class indices to dataset class indices. |
metrics |
DetMetrics
|
Object detection metrics calculator. |
iouv |
Tensor
|
IoU thresholds for mAP calculation. |
niou |
int
|
Number of IoU thresholds. |
lb |
List[Any]
|
List for storing ground truth labels for hybrid saving. |
jdict |
List[Dict[str, Any]]
|
List for storing JSON detection results. |
stats |
Dict[str, List[Tensor]]
|
Dictionary for storing statistics during validation. |
Examples:
>>> from ultralytics.models.yolo.detect import DetectionValidator
>>> args = dict(model="yolo11n.pt", data="coco8.yaml")
>>> validator = DetectionValidator(args=args)
>>> validator()
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataloader
|
DataLoader
|
Dataloader to use for validation. |
None
|
save_dir
|
Path
|
Directory to save results. |
None
|
pbar
|
Any
|
Progress bar for displaying progress. |
None
|
args
|
Dict[str, Any]
|
Arguments for the validator. |
None
|
_callbacks
|
List[Any]
|
List of callback functions. |
None
|
Source code in ultralytics/models/yolo/detect/val.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
build_dataset
build_dataset(
img_path: str, mode: str = "val", batch: Optional[int] = None
) -> torch.utils.data.Dataset
Build YOLO Dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
img_path
|
str
|
Path to the folder containing images. |
required |
mode
|
str
|
|
'val'
|
batch
|
int
|
Size of batches, this is for |
None
|
Returns:
Type | Description |
---|---|
Dataset
|
YOLO dataset. |
Source code in ultralytics/models/yolo/detect/val.py
286 287 288 289 290 291 292 293 294 295 296 297 298 |
|
eval_json
eval_json(stats: Dict[str, Any]) -> Dict[str, Any]
Evaluate YOLO output in JSON format and return performance statistics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stats
|
Dict[str, Any]
|
Current statistics dictionary. |
required |
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Updated statistics dictionary with COCO/LVIS evaluation results. |
Source code in ultralytics/models/yolo/detect/val.py
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 |
|
finalize_metrics
finalize_metrics() -> None
Set final values for metrics speed and confusion matrix.
Source code in ultralytics/models/yolo/detect/val.py
230 231 232 233 234 235 236 237 238 |
|
get_dataloader
get_dataloader(
dataset_path: str, batch_size: int
) -> torch.utils.data.DataLoader
Construct and return dataloader.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_path
|
str
|
Path to the dataset. |
required |
batch_size
|
int
|
Size of each batch. |
required |
Returns:
Type | Description |
---|---|
DataLoader
|
Dataloader for validation. |
Source code in ultralytics/models/yolo/detect/val.py
300 301 302 303 304 305 306 307 308 309 310 311 312 |
|
get_desc
get_desc() -> str
Return a formatted string summarizing class metrics of YOLO model.
Source code in ultralytics/models/yolo/detect/val.py
110 111 112 |
|
get_stats
get_stats() -> Dict[str, Any]
Calculate and return metrics statistics.
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Dictionary containing metrics results. |
Source code in ultralytics/models/yolo/detect/val.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
init_metrics
init_metrics(model: Module) -> None
Initialize evaluation metrics for YOLO detection validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Module
|
Model to validate. |
required |
Source code in ultralytics/models/yolo/detect/val.py
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 |
|
plot_predictions
plot_predictions(batch: Dict[str, Any], preds: List[Tensor], ni: int) -> None
Plot predicted bounding boxes on input images and save the result.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Dict[str, Any]
|
Batch containing images and annotations. |
required |
preds
|
List[Tensor]
|
List of predictions from the model. |
required |
ni
|
int
|
Batch index. |
required |
Source code in ultralytics/models/yolo/detect/val.py
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
|
plot_val_samples
plot_val_samples(batch: Dict[str, Any], ni: int) -> None
Plot validation image samples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Dict[str, Any]
|
Batch containing images and annotations. |
required |
ni
|
int
|
Batch index. |
required |
Source code in ultralytics/models/yolo/detect/val.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
|
postprocess
postprocess(preds: Tensor) -> List[torch.Tensor]
Apply Non-maximum suppression to prediction outputs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds
|
Tensor
|
Raw predictions from the model. |
required |
Returns:
Type | Description |
---|---|
List[Tensor]
|
Processed predictions after NMS. |
Source code in ultralytics/models/yolo/detect/val.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
|
pred_to_json
pred_to_json(predn: Tensor, filename: str) -> None
Serialize YOLO predictions to COCO json format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predn
|
Tensor
|
Predictions in the format (x1, y1, x2, y2, conf, class). |
required |
filename
|
str
|
Image filename. |
required |
Source code in ultralytics/models/yolo/detect/val.py
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
|
preprocess
preprocess(batch: Dict[str, Any]) -> Dict[str, Any]
Preprocess batch of images for YOLO validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Dict[str, Any]
|
Batch containing images and annotations. |
required |
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Preprocessed batch. |
Source code in ultralytics/models/yolo/detect/val.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
print_results
print_results() -> None
Print training/validation set metrics per class.
Source code in ultralytics/models/yolo/detect/val.py
255 256 257 258 259 260 261 262 263 264 265 266 267 |
|
save_one_txt
save_one_txt(
predn: Tensor, save_conf: bool, shape: Tuple[int, int], file: Path
) -> None
Save YOLO detections to a txt file in normalized coordinates in a specific format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predn
|
Tensor
|
Predictions in the format (x1, y1, x2, y2, conf, class). |
required |
save_conf
|
bool
|
Whether to save confidence scores. |
required |
shape
|
Tuple[int, int]
|
Shape of the original image. |
required |
file
|
Path
|
File path to save the detections. |
required |
Source code in ultralytics/models/yolo/detect/val.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
|
update_metrics
update_metrics(preds: List[Tensor], batch: Dict[str, Any]) -> None
Update metrics with new predictions and ground truth.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preds
|
List[Tensor]
|
List of predictions from the model. |
required |
batch
|
Dict[str, Any]
|
Batch data containing ground truth. |
required |
Source code in ultralytics/models/yolo/detect/val.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 |
|