## 1. Project Overview & Quickstart (ultralytics/yolov5)

## File: README.md

Ultralytics YOLOv5 🚀 is a fast, accurate, and easy-to-use computer vision model developed by [Ultralytics](https://www.ultralytics.com/). Based on the [PyTorch](https://pytorch.org/) framework, YOLOv5 is renowned for its speed, accuracy, and simplicity. It incorporates insights and best practices from extensive research and development, making it a popular and reliable choice for a wide range of vision AI tasks, including [object detection](https://docs.ultralytics.com/tasks/detect), [image segmentation](https://docs.ultralytics.com/tasks/segment), and [image classification](https://docs.ultralytics.com/tasks/classify).

We hope the resources here help you get the most out of YOLOv5. Please browse the [YOLOv5 Docs](https://docs.ultralytics.com/yolov5) for detailed information, raise an issue on [GitHub](https://github.com/ultralytics/yolov5/issues/new/choose) for support, and join our [Discord community](https://discord.com/invite/ultralytics) for questions and discussions!

To request an Enterprise License, please complete the form at [Ultralytics Licensing](https://www.ultralytics.com/license).






## 🚀 Explore the Ultralytics YOLO Ecosystem

YOLOv5 is a mature, production-proven model that remains an excellent choice for fast and reliable [object detection](https://docs.ultralytics.com/tasks/detect), [instance segmentation](https://docs.ultralytics.com/tasks/segment), and [image classification](https://docs.ultralytics.com/tasks/classify). If your project calls for the newest architectures, additional tasks such as [pose estimation](https://docs.ultralytics.com/tasks/pose) and [oriented object detection (OBB)](https://docs.ultralytics.com/tasks/obb), or a unified Python and CLI interface, the actively maintained [`ultralytics`](https://github.com/ultralytics/ultralytics) package brings the latest [Ultralytics YOLO models](https://docs.ultralytics.com/models) together in one place. Explore the [Ultralytics Docs](https://docs.ultralytics.com/) to find the best fit for your use case.

```bash
# Install the ultralytics package for the latest Ultralytics YOLO models
pip install ultralytics
```



## 📚 Documentation

See the [YOLOv5 Docs](https://docs.ultralytics.com/yolov5) for full documentation on training, testing, and deployment. See below for quickstart examples.


Install

Clone the repository and install dependencies in a [**Python>=3.8.0**](https://www.python.org/) environment. Ensure you have [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/) installed.

```bash
# Clone the YOLOv5 repository
git clone https://github.com/ultralytics/yolov5

# Navigate to the cloned directory
cd yolov5

# Install required packages
pip install -r requirements.txt
```




Inference with PyTorch Hub

Use YOLOv5 via [PyTorch Hub](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading) for inference. [Models](https://github.com/ultralytics/yolov5/tree/master/models) are automatically downloaded from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).

```python
import torch

# Load a YOLOv5 model (options: yolov5n, yolov5s, yolov5m, yolov5l, yolov5x)
model = torch.hub.load("ultralytics/yolov5", "yolov5s")  # Default: yolov5s

# Define the input image source (URL, local file, PIL image, OpenCV frame, numpy array, or list)
img = "https://ultralytics.com/images/zidane.jpg"  # Example image

# Perform inference (handles batching, resizing, normalization automatically)
results = model(img)

# Process the results (options: .print(), .show(), .save(), .crop(), .pandas())
results.print()  # Print results to console
results.show()  # Display results in a window
results.save()  # Save results to runs/detect/exp
```




Inference with detect.py

The `detect.py` script runs inference on various sources. It automatically downloads [models](https://github.com/ultralytics/yolov5/tree/master/models) from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) and saves the results to the `runs/detect` directory.

```bash
# Run inference using a webcam
python detect.py --weights yolov5s.pt --source 0

# Run inference on a local image file
python detect.py --weights yolov5s.pt --source img.jpg

# Run inference on a local video file
python detect.py --weights yolov5s.pt --source vid.mp4

# Run inference on a screen capture
python detect.py --weights yolov5s.pt --source screen

# Run inference on a directory of images
python detect.py --weights yolov5s.pt --source path/to/images/

# Run inference on a text file listing image paths
python detect.py --weights yolov5s.pt --source list.txt

# Run inference on a text file listing stream URLs
python detect.py --weights yolov5s.pt --source list.streams

# Run inference using a glob pattern for images
python detect.py --weights yolov5s.pt --source 'path/to/*.jpg'

# Run inference on a YouTube video URL
python detect.py --weights yolov5s.pt --source 'https://youtu.be/LNwODJXcvt4'

# Run inference on an RTSP, RTMP, or HTTP stream
python detect.py --weights yolov5s.pt --source 'rtsp://example.com/media.mp4'
```




Training

The commands below demonstrate how to reproduce YOLOv5 [COCO dataset](https://docs.ultralytics.com/datasets/detect/coco) results. Both [models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) are downloaded automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases). Training times for YOLOv5n/s/m/l/x are approximately 1/2/4/6/8 days on a single [NVIDIA V100 GPU](https://www.nvidia.com/en-us/data-center/v100/). Using [Multi-GPU training](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training) can significantly reduce training time. Use the largest `--batch-size` your hardware allows, or use `--batch-size -1` for YOLOv5 [AutoBatch](https://github.com/ultralytics/yolov5/pull/5092). The batch sizes shown below are for V100-16GB GPUs.

```bash
# Train YOLOv5n on COCO for 300 epochs
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5n.yaml --batch-size 128

# Train YOLOv5s on COCO for 300 epochs
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5s.yaml --batch-size 64

# Train YOLOv5m on COCO for 300 epochs
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5m.yaml --batch-size 40

# Train YOLOv5l on COCO for 300 epochs
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5l.yaml --batch-size 24

# Train YOLOv5x on COCO for 300 epochs
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5x.yaml --batch-size 16
```






Tutorials

- **[Train Custom Data](https://docs.ultralytics.com/yolov5/tutorials/train_custom_data)** 🚀 **RECOMMENDED**: Learn how to train YOLOv5 on your own datasets.
- **[Tips for Best Training Results](https://docs.ultralytics.com/guides/model-training-tips)** ☘️: Improve your model's performance with expert tips.
- **[Multi-GPU Training](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training)**: Speed up training using multiple GPUs.
- **[PyTorch Hub Integration](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading)**: Easily load models using PyTorch Hub.
- **[Model Export (TFLite, ONNX, CoreML, TensorRT)](https://docs.ultralytics.com/yolov5/tutorials/model_export)** 🚀: Convert your models to various deployment formats like [ONNX](https://onnx.ai/) or [TensorRT](https://developer.nvidia.com/tensorrt).
- **[NVIDIA Jetson Deployment](https://docs.ultralytics.com/guides/nvidia-jetson)**: Deploy YOLOv5 on [NVIDIA Jetson](https://developer.nvidia.com/embedded-computing) devices.
- **[Test-Time Augmentation (TTA)](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation)**: Enhance prediction accuracy with TTA.
- **[Model Ensembling](https://docs.ultralytics.com/yolov5/tutorials/model_ensembling)**: Combine multiple models for better performance.
- **[Model Pruning/Sparsity](https://docs.ultralytics.com/yolov5/tutorials/model_pruning_and_sparsity)**: Optimize models for size and speed.
- **[Hyperparameter Evolution](https://docs.ultralytics.com/yolov5/tutorials/hyperparameter_evolution)**: Automatically find the best training hyperparameters.
- **[Transfer Learning with Frozen Layers](https://docs.ultralytics.com/yolov5/tutorials/transfer_learning_with_frozen_layers)**: Adapt pretrained models to new tasks efficiently using [transfer learning](https://www.ultralytics.com/glossary/transfer-learning).
- **[Architecture Summary](https://docs.ultralytics.com/yolov5/tutorials/architecture_description)**: Understand the YOLOv5 model architecture.
- **[Ultralytics Platform Training](https://platform.ultralytics.com)** 🚀 **RECOMMENDED**: Train and deploy YOLO models using Ultralytics Platform.
- **[ClearML Logging](https://docs.ultralytics.com/yolov5/tutorials/clearml_logging_integration)**: Integrate with [ClearML](https://clear.ml/) for experiment tracking.
- **[Neural Magic DeepSparse Integration](https://docs.ultralytics.com/yolov5/tutorials/neural_magic_pruning_quantization)**: Accelerate inference with DeepSparse.
- **[Comet Logging](https://docs.ultralytics.com/yolov5/tutorials/comet_logging_integration)**: Log experiments using [Comet ML](https://www.comet.com/site/).



## 🧩 Integrations

Our key integrations with leading AI platforms extend the functionality of Ultralytics' offerings, enhancing tasks like dataset labeling, training, visualization, and model management. Discover how Ultralytics, in collaboration with partners like [Weights & Biases](https://docs.ultralytics.com/integrations/weights-biases), [Comet ML](https://docs.ultralytics.com/integrations/comet), [Roboflow](https://docs.ultralytics.com/integrations/roboflow), and [Intel OpenVINO](https://docs.ultralytics.com/integrations/openvino), can optimize your AI workflow. Explore more at [Ultralytics Integrations](https://docs.ultralytics.com/integrations).

<a href="https://platform.ultralytics.com" target="_blank">
    
</a>

## 🤔 Why YOLOv5?

YOLOv5 is designed for simplicity and ease of use. We prioritize real-world performance and accessibility.



  YOLOv5-P5 640 Figure




  Figure Notes

- **COCO AP val** denotes the [mean Average Precision (mAP)](https://www.ultralytics.com/glossary/mean-average-precision-map) at [Intersection over Union (IoU)](https://www.ultralytics.com/glossary/intersection-over-union-iou) thresholds from 0.5 to 0.95, measured on the 5,000-image [COCO val2017 dataset](https://docs.ultralytics.com/datasets/detect/coco) across various inference sizes (256 to 1536 pixels).
- **GPU Speed** measures the average inference time per image on the [COCO val2017 dataset](https://docs.ultralytics.com/datasets/detect/coco) using an [AWS p3.2xlarge V100 instance](https://aws.amazon.com/ec2/instance-types/p4/) with a batch size of 32.
- **EfficientDet** data is sourced from the [google/automl repository](https://github.com/google/automl) at batch size 8.
- **Reproduce** these results using the command: `python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt`



### Pretrained Checkpoints

This table shows the performance metrics for various YOLOv5 models trained on the COCO dataset.

| Model                                                                                                                                                                    | Size<sup>(pixels) | mAP<sup>val50-95 | mAP<sup>val50 | Speed<sup>CPU b1(ms) | Speed<sup>V100 b1(ms) | Speed<sup>V100 b32(ms) | Params<sup>(M) | FLOPs<sup>@640 (B) |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------- | -------------------- | ----------------- | ---------------------------- | ----------------------------- | ------------------------------ | ------------------ | ---------------------- |
| [YOLOv5n](https://platform.ultralytics.com/ultralytics/yolov5/yolov5nu)                                                                                                  | 640                   | 28.0                 | 45.7              | **45**                       | **6.3**                       | **0.6**                        | **1.9**            | **4.5**                |
| [YOLOv5s](https://platform.ultralytics.com/ultralytics/yolov5/yolov5su)                                                                                                  | 640                   | 37.4                 | 56.8              | 98                           | 6.4                           | 0.9                            | 7.2                | 16.5                   |
| [YOLOv5m](https://platform.ultralytics.com/ultralytics/yolov5/yolov5mu)                                                                                                  | 640                   | 45.4                 | 64.1              | 224                          | 8.2                           | 1.7                            | 21.2               | 49.0                   |
| [YOLOv5l](https://platform.ultralytics.com/ultralytics/yolov5/yolov5lu)                                                                                                  | 640                   | 49.0                 | 67.3              | 430                          | 10.1                          | 2.7                            | 46.5               | 109.1                  |
| [YOLOv5x](https://platform.ultralytics.com/ultralytics/yolov5/yolov5xu)                                                                                                  | 640                   | 50.7                 | 68.9              | 766                          | 12.1                          | 4.8                            | 86.7               | 205.7                  |
|                                                                                                                                                                          |                       |                      |                   |                              |                               |                                |                    |                        |
| [YOLOv5n6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n6.pt)                                                                                     | 1280                  | 36.0                 | 54.4              | 153                          | 8.1                           | 2.1                            | 3.2                | 4.6                    |
| [YOLOv5s6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s6.pt)                                                                                     | 1280                  | 44.8                 | 63.7              | 385                          | 8.2                           | 3.6                            | 12.6               | 16.8                   |
| [YOLOv5m6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m6.pt)                                                                                     | 1280                  | 51.3                 | 69.3              | 887                          | 11.1                          | 6.8                            | 35.7               | 50.0                   |
| [YOLOv5l6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l6.pt)                                                                                     | 1280                  | 53.7                 | 71.3              | 1784                         | 15.8                          | 10.5                           | 76.8               | 111.4                  |
| [YOLOv5x6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x6.pt)+ [[TTA]](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation/) | 12801536          | 55.0**55.8**     | 72.7**72.7**  | 3136-                    | 26.2-                     | 19.4-                      | 140.7-         | 209.8-             |


  Table Notes

- The 640-pixel rows report the legacy anchor-based YOLOv5 checkpoints, while their links open the corresponding anchor-free YOLOv5u successor models on Ultralytics Platform. P6 links continue to download the legacy 1280-pixel checkpoints directly.
- All checkpoints were trained for 300 epochs using default settings. Nano (n) and Small (s) models use [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml) hyperparameters, while Medium (m), Large (l), and Extra-Large (x) models use [hyp.scratch-high.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-high.yaml).
- **mAP<sup>val</sup>** values represent single-model, single-scale performance on the [COCO val2017 dataset](https://docs.ultralytics.com/datasets/detect/coco).Reproduce using: `python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
- **Speed** metrics are averaged over COCO val images using an [AWS p3.2xlarge V100 instance](https://aws.amazon.com/ec2/instance-types/p4/). Non-Maximum Suppression (NMS) time (~1 ms/image) is not included.Reproduce using: `python val.py --data coco.yaml --img 640 --task speed --batch 1`
- **TTA** ([Test Time Augmentation](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation)) includes reflection and scale augmentations for improved accuracy.Reproduce using: `python val.py --data coco.yaml --img 1536 --iou 0.7 --augment`



## 🖼️ Segmentation

The YOLOv5 [release v7.0](https://github.com/ultralytics/yolov5/releases/v7.0) introduced [instance segmentation](https://docs.ultralytics.com/tasks/segment) models designed for easy training, validation, and deployment. For full details, see the [Release Notes](https://github.com/ultralytics/yolov5/releases/v7.0) and explore the [YOLOv5 Segmentation Colab Notebook](https://github.com/ultralytics/yolov5/blob/master/segment/tutorial.ipynb) for quickstart examples.


  Segmentation Checkpoints



YOLOv5 segmentation models were trained on the [COCO dataset](https://docs.ultralytics.com/datasets/segment/coco) for 300 epochs at an image size of 640 pixels using A100 GPUs. Models were exported to [ONNX](https://onnx.ai/) FP32 for CPU speed tests and [TensorRT](https://developer.nvidia.com/tensorrt) FP16 for GPU speed tests. All speed tests were conducted on Google [Colab Pro](https://colab.research.google.com/signup) notebooks for reproducibility.

| Model                                                                                      | Size<sup>(pixels) | mAP<sup>box50-95 | mAP<sup>mask50-95 | Train Time<sup>300 epochsA100 (hours) | Speed<sup>ONNX CPU(ms) | Speed<sup>TRT A100(ms) | Params<sup>(M) | FLOPs<sup>@640 (B) |
| ------------------------------------------------------------------------------------------ | --------------------- | -------------------- | --------------------- | --------------------------------------------- | ------------------------------ | ------------------------------ | ------------------ | ---------------------- |
| [YOLOv5n-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n-seg.pt) | 640                   | 27.6                 | 23.4                  | 80:17                                         | **62.7**                       | **1.2**                        | **2.0**            | **7.1**                |
| [YOLOv5s-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-seg.pt) | 640                   | 37.6                 | 31.7                  | 88:16                                         | 173.3                          | 1.4                            | 7.6                | 26.4                   |
| [YOLOv5m-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m-seg.pt) | 640                   | 45.0                 | 37.1                  | 108:36                                        | 427.0                          | 2.2                            | 22.0               | 70.8                   |
| [YOLOv5l-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l-seg.pt) | 640                   | 49.0                 | 39.9                  | 66:43 (2x)                                    | 857.4                          | 2.9                            | 47.9               | 147.7                  |
| [YOLOv5x-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x-seg.pt) | 640                   | **50.7**             | **41.4**              | 62:56 (3x)                                    | 1579.2                         | 4.5                            | 88.8               | 265.7                  |

- All checkpoints were trained for 300 epochs using the SGD optimizer with `lr0=0.01` and `weight_decay=5e-5` at an image size of 640 pixels, using default settings.Training runs are logged at [https://wandb.ai/glenn-jocher/YOLOv5_v70_official](https://wandb.ai/glenn-jocher/YOLOv5_v70_official).
- **Accuracy** values represent single-model, single-scale performance on the COCO dataset.Reproduce using: `python segment/val.py --data coco.yaml --weights yolov5s-seg.pt`
- **Speed** metrics are averaged over 100 inference images using a [Colab Pro A100 High-RAM instance](https://colab.research.google.com/signup). Values indicate inference speed only (NMS adds approximately 1ms per image).Reproduce using: `python segment/val.py --data coco.yaml --weights yolov5s-seg.pt --batch 1`
- **Export** to ONNX (FP32) and TensorRT (FP16) was performed using `export.py`.Reproduce using: `python export.py --weights yolov5s-seg.pt --include engine --device 0 --half`




  Segmentation Usage Examples &nbsp;[](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/segment/tutorial.ipynb)

### Train

YOLOv5 segmentation training supports automatic download of the [COCO128-seg dataset](https://docs.ultralytics.com/datasets/segment/coco128-seg) via the `--data coco128-seg.yaml` argument. For the full [COCO-segments dataset](https://docs.ultralytics.com/datasets/segment/coco), download it manually using `bash data/scripts/get_coco.sh --train --val --segments` and then train with `python segment/train.py --data coco.yaml`.

```bash
# Train on a single GPU
python segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640

# Train using Multi-GPU Distributed Data Parallel (DDP)
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640 --device 0,1,2,3
```

### Val

Validate the mask [mean Average Precision (mAP)](https://www.ultralytics.com/glossary/mean-average-precision-map) of YOLOv5s-seg on the COCO dataset:

```bash
# Download COCO validation segments split (780MB, 5000 images)
bash data/scripts/get_coco.sh --val --segments

# Validate the model
python segment/val.py --weights yolov5s-seg.pt --data coco.yaml --img 640
```

### Predict

Use the pretrained YOLOv5m-seg.pt model to perform segmentation on `bus.jpg`:

```bash
# Run prediction
python segment/predict.py --weights yolov5m-seg.pt --source data/images/bus.jpg
```

```python
# Load model from PyTorch Hub (Note: Inference support might vary)
model = torch.hub.load("ultralytics/yolov5", "custom", "yolov5m-seg.pt")
```

|  |  |
| :-----------------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------: |

### Export

Export the YOLOv5s-seg model to ONNX and TensorRT formats:

```bash
# Export model
python export.py --weights yolov5s-seg.pt --include onnx engine --img 640 --device 0
```



## 🏷️ Classification

YOLOv5 [release v6.2](https://github.com/ultralytics/yolov5/releases/v6.2) introduced support for [image classification](https://docs.ultralytics.com/tasks/classify) model training, validation, and deployment. Check the [Release Notes](https://github.com/ultralytics/yolov5/releases/v6.2) for details and the [YOLOv5 Classification Colab Notebook](https://github.com/ultralytics/yolov5/blob/master/classify/tutorial.ipynb) for quickstart guides.


  Classification Checkpoints



YOLOv5-cls classification models were trained on [ImageNet](https://docs.ultralytics.com/datasets/classify/imagenet) for 90 epochs using a 4xA100 instance. [ResNet](https://arxiv.org/abs/1512.03385) and [EfficientNet](https://arxiv.org/abs/1905.11946) models were trained alongside under identical settings for comparison. Models were exported to [ONNX](https://onnx.ai/) FP32 (CPU speed tests) and [TensorRT](https://developer.nvidia.com/tensorrt) FP16 (GPU speed tests). All speed tests were run on Google [Colab Pro](https://colab.research.google.com/signup) for reproducibility.

| Model                                                                                              | Size<sup>(pixels) | Acc<sup>top1 | Acc<sup>top5 | Training<sup>90 epochs4xA100 (hours) | Speed<sup>ONNX CPU(ms) | Speed<sup>TensorRT V100(ms) | Params<sup>(M) | FLOPs<sup>@224 (B) |
| -------------------------------------------------------------------------------------------------- | --------------------- | ---------------- | ---------------- | -------------------------------------------- | ------------------------------ | ----------------------------------- | ------------------ | ---------------------- |
| [YOLOv5n-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n-cls.pt)         | 224                   | 64.6             | 85.4             | 7:59                                         | **3.3**                        | **0.5**                             | **2.5**            | **0.5**                |
| [YOLOv5s-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-cls.pt)         | 224                   | 71.5             | 90.2             | 8:09                                         | 6.6                            | 0.6                                 | 5.4                | 1.4                    |
| [YOLOv5m-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m-cls.pt)         | 224                   | 75.9             | 92.9             | 10:06                                        | 15.5                           | 0.9                                 | 12.9               | 3.9                    |
| [YOLOv5l-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l-cls.pt)         | 224                   | 78.0             | 94.0             | 11:56                                        | 26.9                           | 1.4                                 | 26.5               | 8.5                    |
| [YOLOv5x-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x-cls.pt)         | 224                   | **79.0**         | **94.4**         | 15:04                                        | 54.3                           | 1.8                                 | 48.1               | 15.9                   |
|                                                                                                    |                       |                  |                  |                                              |                                |                                     |                    |                        |
| [ResNet18](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet18.pt)               | 224                   | 70.3             | 89.5             | **6:47**                                     | 11.2                           | 0.5                                 | 11.7               | 3.7                    |
| [ResNet34](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet34.pt)               | 224                   | 73.9             | 91.8             | 8:33                                         | 20.6                           | 0.9                                 | 21.8               | 7.4                    |
| [ResNet50](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet50.pt)               | 224                   | 76.8             | 93.4             | 11:10                                        | 23.4                           | 1.0                                 | 25.6               | 8.5                    |
| [ResNet101](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet101.pt)             | 224                   | 78.5             | 94.3             | 17:10                                        | 42.1                           | 1.9                                 | 44.5               | 15.9                   |
|                                                                                                    |                       |                  |                  |                                              |                                |                                     |                    |                        |
| [EfficientNet_b0](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b0.pt) | 224                   | 75.1             | 92.4             | 13:03                                        | 12.5                           | 1.3                                 | 5.3                | 1.0                    |
| [EfficientNet_b1](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b1.pt) | 224                   | 76.4             | 93.2             | 17:04                                        | 14.9                           | 1.6                                 | 7.8                | 1.5                    |
| [EfficientNet_b2](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b2.pt) | 224                   | 76.6             | 93.4             | 17:10                                        | 15.9                           | 1.6                                 | 9.1                | 1.7                    |
| [EfficientNet_b3](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b3.pt) | 224                   | 77.7             | 94.0             | 19:19                                        | 18.9                           | 1.9                                 | 12.2               | 2.4                    |


  Table Notes (click to expand)

- All checkpoints were trained for 90 epochs using the SGD optimizer with `lr0=0.001` and `weight_decay=5e-5` at an image size of 224 pixels, using default settings.Training runs are logged at [https://wandb.ai/glenn-jocher/YOLOv5-Classifier-v6-2](https://wandb.ai/glenn-jocher/YOLOv5-Classifier-v6-2).
- **Accuracy** values (top-1 and top-5) represent single-model, single-scale performance on the [ImageNet-1k dataset](https://docs.ultralytics.com/datasets/classify/imagenet).Reproduce using: `python classify/val.py --data ../datasets/imagenet --img 224`
- **Speed** metrics are averaged over 100 inference images using a Google [Colab Pro V100 High-RAM instance](https://colab.research.google.com/signup).Reproduce using: `python classify/val.py --data ../datasets/imagenet --img 224 --batch 1`
- **Export** to ONNX (FP32) and TensorRT (FP16) was performed using `export.py`.Reproduce using: `python export.py --weights yolov5s-cls.pt --include engine onnx --imgsz 224`





  Classification Usage Examples &nbsp;[](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/classify/tutorial.ipynb)

### Train

YOLOv5 classification training supports automatic download for datasets like [MNIST](https://docs.ultralytics.com/datasets/classify/mnist), [Fashion-MNIST](https://docs.ultralytics.com/datasets/classify/fashion-mnist), [CIFAR10](https://docs.ultralytics.com/datasets/classify/cifar10), [CIFAR100](https://docs.ultralytics.com/datasets/classify/cifar100), [Imagenette](https://docs.ultralytics.com/datasets/classify/imagenette), [Imagewoof](https://docs.ultralytics.com/datasets/classify/imagewoof), and [ImageNet](https://docs.ultralytics.com/datasets/classify/imagenet) using the `--data` argument. For example, start training on MNIST with `--data mnist`.

```bash
# Train on a single GPU using CIFAR-100 dataset
python classify/train.py --model yolov5s-cls.pt --data cifar100 --epochs 5 --img 224 --batch 128

# Train using Multi-GPU DDP on ImageNet dataset
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 classify/train.py --model yolov5s-cls.pt --data imagenet --epochs 5 --img 224 --device 0,1,2,3
```

### Val

Validate the accuracy of the YOLOv5m-cls model on the ImageNet-1k validation dataset:

```bash
# Download ImageNet validation split (6.3GB, 50,000 images)
bash data/scripts/get_imagenet.sh --val

# Validate the model
python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224
```

### Predict

Use the pretrained YOLOv5s-cls.pt model to classify the image `bus.jpg`:

```bash
# Run prediction
python classify/predict.py --weights yolov5s-cls.pt --source data/images/bus.jpg
```

```python
# Load model from PyTorch Hub
model = torch.hub.load("ultralytics/yolov5", "custom", "yolov5s-cls.pt")
```

### Export

Export trained YOLOv5s-cls, ResNet50, and EfficientNet_b0 models to ONNX and TensorRT formats:

```bash
# Export models
python export.py --weights yolov5s-cls.pt resnet50.pt efficientnet_b0.pt --include onnx engine --img 224
```



## ☁️ Environments

Get started quickly with our pre-configured environments. Click the icons below for setup details.



## 🤝 Contribute

We welcome your contributions! Making YOLOv5 accessible and effective is a community effort. Please see our [Contributing Guide](https://docs.ultralytics.com/help/contributing) to get started. Share your feedback through the [YOLOv5 Survey](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey). Thank you to all our contributors for making YOLOv5 better!

[](https://github.com/ultralytics/yolov5/graphs/contributors)

## 📜 License

Ultralytics provides two licensing options to meet different needs:

- **AGPL-3.0 License**: An [OSI-approved](https://opensource.org/license/agpl-3.0) open-source license ideal for academic research, personal projects, and testing. It promotes open collaboration and knowledge sharing. See the [LICENSE](https://github.com/ultralytics/yolov5/blob/master/LICENSE) file for details.
- **Enterprise License**: Tailored for commercial applications, this license allows seamless integration of Ultralytics software and AI models into commercial products and services, bypassing the open-source requirements of AGPL-3.0. For commercial use cases, please contact us via [Ultralytics Licensing](https://www.ultralytics.com/license).

## 📧 Contact

For bug reports and feature requests related to YOLOv5, please visit [GitHub Issues](https://github.com/ultralytics/yolov5/issues). For general questions, discussions, and community support, join our [Discord server](https://discord.com/invite/ultralytics)!

---

## File: utils/flask_rest_api/README.md

[](https://www.ultralytics.com/)

# Flask REST API for YOLOv5

[Representational State Transfer (REST)](https://en.wikipedia.org/wiki/Representational_state_transfer) [Application Programming Interfaces (APIs)](https://en.wikipedia.org/wiki/API) provide a standardized way to expose [Machine Learning (ML)](https://www.ultralytics.com/glossary/machine-learning-ml) models for use by other services or applications. This directory contains an example REST API built with the [Flask](https://flask.palletsprojects.com/en/stable/) web framework to serve the [Ultralytics YOLOv5s](https://docs.ultralytics.com/models/yolov5) model, loaded directly from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/). This setup allows you to easily integrate YOLOv5 [object detection](https://docs.ultralytics.com/tasks/detect) capabilities into your web applications or microservices, aligning with common [model deployment options](https://docs.ultralytics.com/guides/model-deployment-options).

## 💻 Requirements

The primary requirement is the [Flask](https://flask.palletsprojects.com/en/stable/) web framework. You can install it using pip:

```shell
pip install Flask
```

You will also need `torch` and `yolov5`. These are implicitly handled by the script when it loads the model from PyTorch Hub. Ensure you have a functioning Python environment set up.

## ▶️ Run the API

Once Flask is installed, you can start the API server using the following command:

```shell
python restapi.py --port 5000
```

The server will begin listening on the specified port (defaulting to 5000). You can then send inference requests to the API endpoint using tools like [curl](https://curl.se/) or any other HTTP client.

To test the API with a local image file (e.g., `zidane.jpg` located in the `yolov5/data/images` directory, which is `../../data/images/zidane.jpg` relative to the script):

```shell
curl -X POST -F image=@../../data/images/zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'
```

The API processes the submitted image using the YOLOv5s model and returns the detection results in [JSON](https://www.json.org/json-en.html) format. Each object within the JSON array represents a detected item, including its pixel [bounding box](https://www.ultralytics.com/glossary/bounding-box) coordinates (`xmin`, `ymin`, `xmax`, `ymax`), confidence score, class ID, and class name.

```json
[
  {
    "xmin": 749.5,
    "ymin": 43.5,
    "xmax": 1148.0,
    "ymax": 704.5,
    "confidence": 0.8900438547,
    "class": 0,
    "name": "person"
  },
  {
    "xmin": 113.5,
    "ymin": 196.0,
    "xmax": 1093.0,
    "ymax": 711.0,
    "confidence": 0.8440024257,
    "class": 0,
    "name": "person"
  },
  {
    "xmin": 437.5,
    "ymin": 433.5,
    "xmax": 529.5,
    "ymax": 717.5,
    "confidence": 0.3771208823,
    "class": 27,
    "name": "tie"
  },
  {
    "xmin": 1090.0,
    "ymin": 312.0,
    "xmax": 1135.0,
    "ymax": 410.0,
    "confidence": 0.3527112305,
    "class": 27,
    "name": "tie"
  }
]
```

An example Python script, `example_request.py`, is included to demonstrate how to perform inference using the popular [requests](https://requests.readthedocs.io/en/latest/) library. This script offers a straightforward method for interacting with the running API programmatically.

To require authentication, set `API_KEY` when starting the server and include it in each request:

```shell
API_KEY=mysecretkey python restapi.py --port 5000
curl -H 'X-API-Key: mysecretkey' -F image=@../../data/images/zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'
```

## 🤝 Contribute

Contributions to enhance this Flask API example are highly encouraged! Whether you're interested in adding support for different YOLO models, improving error handling, or implementing new features, please feel free to fork the repository, apply your changes, and submit a pull request. For more comprehensive contribution guidelines, please refer to the main [Ultralytics YOLOv5 repository](https://github.com/ultralytics/yolov5) and the general [Ultralytics documentation](https://docs.ultralytics.com/).

---

## File: utils/loggers/clearml/README.md

[](https://www.ultralytics.com/)

# ClearML Integration with Ultralytics YOLO



## ℹ️ About ClearML

[ClearML](https://clear.ml/) is an [open-source MLOps platform](https://github.com/clearml/clearml). Integrating it with [Ultralytics YOLO](https://docs.ultralytics.com/models/yolov5) provides experiment tracking, data management, and remote execution:

- **Experiment Management:** Track every [YOLO training run](https://docs.ultralytics.com/modes/train), including parameters, metrics, and outputs. Explore the [Ultralytics ClearML integration guide](https://docs.ultralytics.com/integrations/clearml) for step-by-step instructions.
- **Data Versioning:** Manage and access your custom training data with ClearML's Data Versioning Tool, similar to [DVC integration](https://docs.ultralytics.com/integrations/dvc).
- **Remote Execution:** Remotely train and monitor models using [ClearML Agent](https://docs.clear.ml/docs/latest/docs/clearml_agent) for seamless scaling.
- **Hyperparameter Optimization:** Boost your [mean average precision (mAP)](https://docs.ultralytics.com/guides/yolo-performance-metrics) with ClearML's [hyperparameter tuning](https://docs.ultralytics.com/guides/hyperparameter-tuning) capabilities.
- **Model Deployment:** Deploy your trained YOLO model as an API with ClearML Serving, complementing [Ultralytics model deployment options](https://docs.ultralytics.com/guides/model-deployment-options).

You can use ClearML's experiment manager alone or combine these features into a comprehensive [MLOps pipeline](https://www.ultralytics.com/glossary/machine-learning-operations-mlops).



## 🦾 Setting Up ClearML

ClearML requires a server to track experiments and data. You have two main options:

1. **ClearML Hosted Service:** Sign up for a free account at [app.clear.ml](https://app.clear.ml/).
2. **Self-Hosted Server:** Deploy your own ClearML server using the [official setup guide](https://docs.clear.ml/docs/latest/docs/deploying_clearml/clearml_server). The server is open-source, ensuring data privacy and control.

To get started:

1. **Install the ClearML Python package:**

   ```bash
   pip install clearml
   ```

   _Note: The `clearml` package is listed (commented out) in `requirements.txt` and is not installed by default — install it with the command above._

2. **Connect the ClearML SDK to your server:**  
   [Create credentials](https://app.clear.ml/settings/workspace-configuration) (Settings → Workspace → Create new credentials), then run:

   ```bash
   clearml-init
   ```

   Follow the prompts to complete setup.

For a general Ultralytics setup, see the [Quickstart Guide](https://docs.ultralytics.com/quickstart).

## 🚀 Training YOLO with ClearML

When the `clearml` package is installed, experiment tracking is automatically enabled for every [YOLO training run](https://docs.ultralytics.com/modes/train). All experiment details are captured and stored in the ClearML experiment manager.

To customize your project or task name in ClearML, use the `--project` and `--name` arguments. By default, the project is `YOLOv5` and the task is `Training`. ClearML uses `/` as a delimiter for subprojects.

**Example Training Command:**

```bash
# Train YOLO on COCO128 dataset for 3 epochs
python train.py --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt --cache
```

**Example with Custom Project and Task Names:**

```bash
# Train with custom project and experiment names
python train.py --project my_yolo_project --name experiment_001 --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt --cache
```

ClearML automatically logs:

- Source code and uncommitted changes
- Installed Python packages
- Hyperparameters and configuration settings
- Model checkpoints (use `--save-period n` to save every `n` epochs)
- Console output logs
- Performance metrics ([precision, recall](https://docs.ultralytics.com/guides/yolo-performance-metrics), [losses](https://docs.ultralytics.com/reference/utils/loss), [learning rates](https://www.ultralytics.com/glossary/learning-rate), mAP<sub>0.5</sub>, mAP<sub>0.5:0.95</sub>)
- System details (hardware specs, runtime, creation date)
- Generated plots (label correlogram, [confusion matrix](https://www.ultralytics.com/glossary/confusion-matrix))
- Images with bounding boxes per epoch
- Mosaic augmentation previews per epoch
- Validation images per epoch

All this information can be visualized in the ClearML UI. You can customize table views, sort experiments by metrics, and compare multiple runs. This enables advanced features like hyperparameter optimization and remote execution.

## 🔗 Dataset Version Management

Versioning your [datasets](https://docs.ultralytics.com/datasets) independently from code is essential for reproducibility and collaboration. ClearML's Data Versioning Tool streamlines this process. YOLO supports ClearML dataset version IDs, automatically downloading data as needed. The dataset ID is saved as a task parameter, ensuring traceability for every experiment.



### Prepare Your Dataset

YOLO uses [YAML files](https://www.ultralytics.com/glossary/yaml) to define dataset configurations. By default, datasets are expected in the `../datasets` directory relative to the repository root. For example, the [COCO128 dataset](https://docs.ultralytics.com/datasets/detect/coco128) structure:

```
../
├── yolov5/          # Your YOLO repository clone
└── datasets/
    └── coco128/
        ├── images/
        ├── labels/
        ├── LICENSE
        └── README.txt
```

Ensure your custom dataset follows a similar structure.

Next, ⚠️ **copy the corresponding dataset `.yaml` file into the root of your dataset folder**. This file contains essential information (`path`, `train`, `test`, `val`, `nc`, `names`) required by ClearML.

```
../
└── datasets/
    └── coco128/
        ├── images/
        ├── labels/
        ├── coco128.yaml  # <---- Place the YAML file here!
        ├── LICENSE
        └── README.txt
```

### Upload Your Dataset

Navigate to your dataset's root directory and use the `clearml-data` CLI tool:

```bash
cd ../datasets/coco128
clearml-data sync --project YOLO_Datasets --name coco128 --folder .
```

Alternatively, use the following commands:

```bash
# Create a new dataset entry in ClearML
clearml-data create --project YOLO_Datasets --name coco128

# Add the dataset files (use '.' for the current directory)
clearml-data add --files .

# Finalize and upload the dataset version
clearml-data close
```

_Tip: Use `--parent ` with `clearml-data create` to link versions and avoid re-uploading unchanged files._

### Run Training Using a ClearML Dataset

Once your dataset is versioned in ClearML, you can use it for training by providing the dataset ID via the `--data` argument with the `clearml://` prefix:

```bash
# Replace YOUR_DATASET_ID with the actual ID from ClearML
python train.py --img 640 --batch 16 --epochs 3 --data clearml://YOUR_DATASET_ID --weights yolov5s.pt --cache
```

## 👀 Hyperparameter Optimization

With experiments and data versioned, you can leverage ClearML for [hyperparameter optimization](https://docs.ultralytics.com/guides/hyperparameter-tuning). ClearML captures all necessary information (code, packages, environment), making experiments fully reproducible. Its HPO tools clone an existing experiment, modify hyperparameters, and rerun it automatically.

To run HPO locally, use the provided script `utils/loggers/clearml/hpo.py`. You'll need the ID of a previously run training task (the "template task") to clone. Update the script with this ID and run:

```bash
# Install Optuna, required by the optimizer used in the script
pip install optuna

# Run the HPO script
python utils/loggers/clearml/hpo.py
```

The script uses [Optuna](https://optuna.org/) (via `OptimizerOptuna`) to search the hyperparameter space, so the `optuna` package must be installed. To enqueue HPO tasks for a remote ClearML agent instead of running locally, replace `optimizer.start_locally()` with `optimizer.start()` in the script and provide an execution queue.



## 🤯 Remote Execution (Advanced)

ClearML Agent enables you to execute experiments on remote machines, including on-premise servers or cloud GPUs such as [AWS](https://aws.amazon.com/), [Google Cloud](https://cloud.google.com/), or [Azure](https://azure.microsoft.com/). The agent listens to task queues, reproduces the experiment environment, runs the task, and reports results back to the ClearML server.

Learn more about ClearML Agent:

- [YouTube Introduction to ClearML Agent](https://www.youtube.com/watch?v=MX3BrXnaULs)
- [Official ClearML Agent Documentation](https://docs.clear.ml/docs/latest/docs/clearml_agent)

Turn any machine into a ClearML agent by running:

```bash
# Replace QUEUES_TO_LISTEN_TO with your queue name(s)
clearml-agent daemon --queue QUEUES_TO_LISTEN_TO [--docker] # Use --docker to run in a Docker container
```

### Cloning, Editing, and Enqueuing Tasks

You can manage remote execution directly from the ClearML web UI:

1. **Clone:** Right-click an existing experiment to clone it.
2. **Edit:** Modify hyperparameters or other settings in the cloned task.
3. **Enqueue:** Right-click the modified task and select "Enqueue" to assign it to a specific queue for an agent to pick up.



### Executing a Task Remotely via Code

You can also modify your training script to automatically enqueue tasks for remote execution. Add `task.execute_remotely()` after the ClearML logger is initialized in `train.py`:

```python
# Inside train.py, after logger initialization...
if RANK in {-1, 0}:
    # Initialize loggers
    loggers = Loggers(save_dir, weights, opt, hyp, LOGGER)

    # Check if ClearML logger is active and enqueue the task
    if loggers.clearml:
        # Specify the queue name for the remote agent
        loggers.clearml.task.execute_remotely(queue_name="my_remote_queue")  # <------ ADD THIS LINE
        # data_dict might be populated by ClearML if using a ClearML dataset
        data_dict = loggers.clearml.data_dict
```

Running the script with this modification will package the code and its environment and send it to the specified queue, rather than executing locally.

### Autoscaling Workers

ClearML provides Autoscalers that automatically manage cloud resources (AWS, GCP, Azure). They spin up new virtual machines as ClearML agents when tasks appear in a queue, and shut them down when the queue is empty, optimizing cost.

Watch the Autoscalers getting started video:

[](https://youtu.be/j4XVMAaUt3E)

## 🤝 Contributing

Contributions to enhance the ClearML integration are welcome! Please see the [Ultralytics Contributing Guide](https://docs.ultralytics.com/help/contributing) for details on how to get involved.

---

[](https://github.com/ultralytics/ultralytics/graphs/contributors)

---

## File: utils/loggers/comet/README.md

[](https://www.ultralytics.com/)



# Using Ultralytics YOLO With Comet

This guide explains how to integrate [Ultralytics YOLO](https://github.com/ultralytics/yolov5) with [Comet](https://www.comet.com/site/) for monitoring training, logging results, managing datasets, and optimizing hyperparameters.

[](https://github.com/ultralytics/yolov5/actions/workflows/format.yml)
[](https://discord.com/invite/ultralytics)
[](https://community.ultralytics.com/)
[](https://reddit.com/r/ultralytics)

## 🧪 About Comet

[Comet](https://www.comet.com/site/) provides tools for data scientists, engineers, and teams to accelerate and optimize [deep learning](https://www.ultralytics.com/glossary/deep-learning-dl) and machine learning models.

With Comet, you can track and visualize model metrics in real time, save [hyperparameters](https://docs.ultralytics.com/guides/hyperparameter-tuning), datasets, and model checkpoints, and visualize predictions using Custom Panels. For more details, see the [Comet Documentation](https://www.comet.com/docs/v2/).

## 🚀 Getting Started

Follow these steps to set up Comet for your YOLO projects.

### Install Comet

Install the [comet_ml Python package](https://pypi.org/project/comet-ml/) using pip:

```shell
pip install comet_ml
```

### Configure Comet Credentials

You can configure Comet in two ways:

1. **Environment Variables:**  
   Set your credentials directly in your environment.

   ```shell
   export COMET_API_KEY=YOUR_COMET_API_KEY
   export COMET_PROJECT_NAME=YOUR_COMET_PROJECT_NAME # Defaults to 'yolov5' if not set
   ```

   Find your API key in your [Comet Account Settings](https://www.comet.com/account-settings/apiKeys).

2. **Configuration File:**  
   Create a `.comet.config` file in your working directory:

   ```ini
   [comet]
   api_key=YOUR_COMET_API_KEY
   project_name=YOUR_COMET_PROJECT_NAME # Defaults to 'yolov5' if not set
   ```

### Run the Training Script

Run the YOLO [training script](https://docs.ultralytics.com/modes/train). Comet will automatically log your run.

```shell
# Train YOLO on COCO128 for 5 epochs
python train.py --img 640 --batch 16 --epochs 5 --data coco128.yaml --weights yolov5s.pt
```

Comet automatically logs hyperparameters, command-line arguments, and training/validation metrics. Visualize and analyze your runs in the Comet UI. For more details, see the [Ultralytics training documentation](https://docs.ultralytics.com/modes/train).



## ✨ Try an Example!

Explore a completed YOLO training run tracked with Comet:

- **[View Example Run on Comet](https://www.comet.com/examples/comet-example-yolov5/a0e29e0e9b984e4a822db2a62d0cb357?experiment-tab=chart&showOutliers=true&smoothing=0&transformY=smoothing&xAxis=step&utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=github_readme)**

Run the example yourself using this [Google Colab](https://colab.research.google.com/) notebook:

[](https://colab.research.google.com/github/comet-ml/comet-examples/blob/master/integrations/model-training/yolov5/notebooks/Comet_and_YOLOv5.ipynb)

## 📊 Automatic Logging

Comet automatically logs the following information by default:

### Metrics

- **Losses:** Box Loss, Object Loss, Classification Loss (Training and Validation)
- **Performance:** [mAP@0.5](https://www.ultralytics.com/glossary/mean-average-precision-map), mAP@0.5:0.95 (Validation). Learn more in the [YOLO Performance Metrics guide](https://docs.ultralytics.com/guides/yolo-performance-metrics).
- **[Precision](https://www.ultralytics.com/glossary/precision) and [Recall](https://www.ultralytics.com/glossary/recall):** Validation data metrics

### Parameters

- **Model Hyperparameters:** Configuration used for the model
- **Command Line Arguments:** All arguments passed via the [CLI](https://docs.ultralytics.com/usage/cli)

### Visualizations

- **[Confusion Matrix](https://www.ultralytics.com/glossary/confusion-matrix):** Model predictions on validation data ([Wikipedia](https://en.wikipedia.org/wiki/Confusion_matrix))
- **Curves:** PR and F1 curves across all classes
- **Label Correlogram:** Correlation visualization of class labels

## ⚙️ Advanced Configuration

Customize Comet's logging behavior using command-line flags or environment variables.

```shell
# Environment Variables for Comet Configuration
export COMET_MODE=online                                    # 'online' or 'offline'. Default: online
export COMET_MODEL_NAME=YOUR_MODEL_NAME                     # Name for the saved model. Default: yolov5
export COMET_LOG_CONFUSION_MATRIX=false                     # Disable confusion matrix logging. Default: true
export COMET_MAX_IMAGE_UPLOADS=NUMBER                       # Max prediction images to log. Default: 100
export COMET_LOG_PER_CLASS_METRICS=true                     # Log metrics per class. Default: false
export COMET_DEFAULT_CHECKPOINT_FILENAME=checkpoint_file.pt # Checkpoint for resuming. Default: 'last.pt'
export COMET_LOG_BATCH_METRICS=true                         # Log training metrics per batch. Default: false
export COMET_LOG_PREDICTIONS=true                           # Disable prediction logging if set to false. Default: true
```

For more configuration options, see the [Comet documentation](https://www.comet.com/docs/v2/).

### Logging Checkpoints With Comet

Model checkpoint logging to Comet is disabled by default. Enable it using the `--save-period` argument during training to save checkpoints at the specified epoch interval.

```shell
python train.py \
  --img 640 \
  --batch 16 \
  --epochs 5 \
  --data coco128.yaml \
  --weights yolov5s.pt \
  --save-period 1 # Save checkpoint every epoch
```

Checkpoints will appear in the "Assets & Artifacts" tab of your Comet experiment. Learn more about model management in the [Comet Model Registry documentation](https://www.comet.com/docs/v2/guides/model-registry/using-model-registry/).

### Logging Model Predictions

By default, model predictions (images, ground truth labels, [bounding boxes](https://www.ultralytics.com/glossary/bounding-box)) for the validation set are logged. Control the logging frequency using the `--bbox_interval` argument, which specifies logging every Nth batch per epoch.

**Note:** The YOLO validation dataloader defaults to a batch size of 32. Adjust `--bbox_interval` as needed.

Visualize predictions using Comet's Object Detection Custom Panel. See an [example project using the Panel](https://www.comet.com/examples/comet-example-yolov5?shareable=YcwMiJaZSXfcEXpGOHDD12vA1&utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=github_readme).

```shell
python train.py \
  --img 640 \
  --batch 16 \
  --epochs 5 \
  --data coco128.yaml \
  --weights yolov5s.pt \
  --bbox_interval 2 # Log predictions every 2nd validation batch per epoch
```

#### Controlling the Number of Prediction Images

Adjust the maximum number of validation images logged using the `COMET_MAX_IMAGE_UPLOADS` environment variable.

```shell
env COMET_MAX_IMAGE_UPLOADS=200 python train.py \
  --img 640 \
  --batch 16 \
  --epochs 5 \
  --data coco128.yaml \
  --weights yolov5s.pt \
  --bbox_interval 1 # Log every batch
```

### Logging Class Level Metrics

Enable logging of mAP, precision, recall, and F1-score for each class using the `COMET_LOG_PER_CLASS_METRICS` environment variable.

```shell
env COMET_LOG_PER_CLASS_METRICS=true python train.py \
  --img 640 \
  --batch 16 \
  --epochs 5 \
  --data coco128.yaml \
  --weights yolov5s.pt
```

## 💾 Dataset Management With Comet Artifacts

Use [Comet Artifacts](https://www.comet.com/docs/v2/guides/artifacts/using-artifacts/) to version, store, and manage your datasets.

### Uploading a Dataset

Upload your dataset using the `--upload_dataset` flag. Ensure your dataset follows the structure described in the [Ultralytics Datasets documentation](https://docs.ultralytics.com/datasets) and that your dataset config [YAML](https://www.ultralytics.com/glossary/yaml) file matches the format of `coco128.yaml` (see the [COCO128 dataset docs](https://docs.ultralytics.com/datasets/detect/coco128)).

```shell
python train.py \
  --img 640 \
  --batch 16 \
  --epochs 5 \
  --data coco128.yaml \
  --weights yolov5s.pt \
  --upload_dataset # Upload the dataset specified in coco128.yaml
```

View the uploaded dataset in the Artifacts tab of your Comet Workspace.


Preview data directly in the Comet UI.


Artifacts are versioned and support metadata. Comet automatically logs metadata from your dataset YAML file.


### Using a Saved Artifact

To use a dataset stored in Comet Artifacts, update the `path` in your dataset YAML file to the Artifact resource URL:

```yaml
# contents of artifact.yaml
path: "comet://WORKSPACE_NAME/ARTIFACT_NAME:ARTIFACT_VERSION_OR_ALIAS"
train: images/train # Adjust subdirectory if needed
val: images/val # Adjust subdirectory if needed


# Other dataset configurations...
```

Then, pass this configuration file to your training script:

```shell
python train.py \
  --img 640 \
  --batch 16 \
  --epochs 5 \
  --data artifact.yaml \
  --weights yolov5s.pt
```

Artifacts track data lineage, showing which experiments used specific dataset versions.


## 🔄 Resuming Training Runs

If a training run is interrupted (for example, due to connection issues), you can resume it using the `--resume` flag with the Comet Run Path (`comet://YOUR_WORKSPACE/YOUR_PROJECT/EXPERIMENT_ID`).

This restores the model state, hyperparameters, arguments, and downloads necessary Artifacts, continuing logging to the existing Comet Experiment. Learn more about [resuming runs in the Comet documentation](https://www.comet.com/docs/v2/guides/experiment-management/resume-experiment/).

```shell
python train.py \
  --resume "comet://YOUR_WORKSPACE/YOUR_PROJECT/EXPERIMENT_ID"
```

## 🔍 Hyperparameter Optimization (HPO)

YOLO integrates with the [Comet Optimizer](https://www.comet.com/docs/v2/guides/optimizer/configure-optimizer/) for easy hyperparameter sweeps and visualization. This helps you find the best set of parameters for your model, a process often referred to as [Hyperparameter Tuning](https://docs.ultralytics.com/guides/hyperparameter-tuning).

### Configuring an Optimizer Sweep

Create a [JSON](https://www.ultralytics.com/glossary/json) configuration file defining the sweep parameters, search strategy, and objective metric. An example is provided at `utils/loggers/comet/optimizer_config.json`.

Run the sweep using the `hpo.py` script:

```shell
python utils/loggers/comet/hpo.py \
  --comet_optimizer_config "utils/loggers/comet/optimizer_config.json"
```

The `hpo.py` script accepts the same arguments as `train.py`. Pass additional fixed arguments for the sweep:

```shell
python utils/loggers/comet/hpo.py \
  --comet_optimizer_config "utils/loggers/comet/optimizer_config.json" \
  --save-period 1 \
  --bbox_interval 1
```

### Running a Sweep in Parallel

Execute multiple sweep trials concurrently using the `comet optimize` command:

```shell
comet optimize -j NUM_WORKERS \
  utils/loggers/comet/hpo.py utils/loggers/comet/optimizer_config.json
```

Replace `NUM_WORKERS` with the desired number of parallel processes.

### Visualizing HPO Results

Comet offers various visualizations for analyzing sweep results, such as parallel coordinate plots and parameter importance plots. Explore a [project with a completed sweep](https://www.comet.com/examples/comet-example-yolov5/view/PrlArHGuuhDTKC1UuBmTtOSXD/panels?utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=github_readme).



## 🤝 Contributing

Contributions to enhance the YOLO-Comet integration are welcome! Please see the [Ultralytics Contributing Guide](https://docs.ultralytics.com/help/contributing) for more information on how to get involved. Thank you for helping improve this integration!

---

## File: README.zh-CN.md

Ultralytics YOLOv5 🚀 是由 [Ultralytics](https://www.ultralytics.com/) 开发的一款快速、准确且易于使用的计算机视觉模型。基于 [PyTorch](https://pytorch.org/) 框架，YOLOv5 以其速度、准确性和简洁性而闻名。它融合了广泛研究和开发的见解与最佳实践，使其成为各种视觉 AI 任务中热门而可靠的选择，包括[目标检测](https://docs.ultralytics.com/tasks/detect)、[图像分割](https://docs.ultralytics.com/tasks/segment)和[图像分类](https://docs.ultralytics.com/tasks/classify)。

我们希望这里的资源能帮助您充分利用 YOLOv5。请浏览 [YOLOv5 文档](https://docs.ultralytics.com/yolov5)获取详细信息，在 [GitHub](https://github.com/ultralytics/yolov5/issues/new/choose) 上提出 issue 以获得支持，并加入我们的 [Discord 社区](https://discord.com/invite/ultralytics)进行提问和讨论！

如需申请企业许可证，请填写 [Ultralytics 授权许可](https://www.ultralytics.com/license) 表格。






## 🚀 探索 Ultralytics YOLO 生态系统

YOLOv5 是一个成熟、经过生产验证的模型，仍然是快速可靠的[目标检测](https://docs.ultralytics.com/tasks/detect)、[实例分割](https://docs.ultralytics.com/tasks/segment)和[图像分类](https://docs.ultralytics.com/tasks/classify)的绝佳选择。如果您的项目需要最新的架构、[姿态估计](https://docs.ultralytics.com/tasks/pose)和[旋转目标检测 (OBB)](https://docs.ultralytics.com/tasks/obb)等额外任务，或统一的 Python 与 CLI 接口，那么持续维护的 [`ultralytics`](https://github.com/ultralytics/ultralytics) 包将最新的 [Ultralytics YOLO 模型](https://docs.ultralytics.com/models)汇集于一处。浏览 [Ultralytics 文档](https://docs.ultralytics.com/)以找到最适合您用例的方案。

```bash
# 安装 ultralytics 包以获取最新的 Ultralytics YOLO 模型
pip install ultralytics
```



## 📚 文档

请参阅 [YOLOv5 文档](https://docs.ultralytics.com/yolov5)，了解有关训练、测试和部署的完整文档。请参阅下方的快速入门示例。


安装

克隆仓库并在 [**Python>=3.8.0**](https://www.python.org/) 环境中安装依赖项。确保您已安装 [**PyTorch>=1.8**](https://pytorch.org/get-started/locally/)。

```bash
# 克隆 YOLOv5 仓库
git clone https://github.com/ultralytics/yolov5

# 导航到克隆的目录
cd yolov5

# 安装所需的包
pip install -r requirements.txt
```




使用 PyTorch Hub 进行推理

通过 [PyTorch Hub](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading) 使用 YOLOv5 进行推理。[模型](https://github.com/ultralytics/yolov5/tree/master/models) 会自动从最新的 YOLOv5 [发布版本](https://github.com/ultralytics/yolov5/releases)下载。

```python
import torch

# 加载 YOLOv5 模型 (选项: yolov5n, yolov5s, yolov5m, yolov5l, yolov5x)
model = torch.hub.load("ultralytics/yolov5", "yolov5s")  # 默认: yolov5s

# 定义输入图像源 (URL、本地文件、PIL 图像、OpenCV 帧、numpy 数组或列表)
img = "https://ultralytics.com/images/zidane.jpg"  # 示例图像

# 执行推理 (自动处理批处理、调整大小、归一化)
results = model(img)

# 处理结果 (选项: .print(), .show(), .save(), .crop(), .pandas())
results.print()  # 将结果打印到控制台
results.show()  # 在窗口中显示结果
results.save()  # 将结果保存到 runs/detect/exp
```




使用 detect.py 进行推理

`detect.py` 脚本在各种来源上运行推理。它会自动从最新的 YOLOv5 [发布版本](https://github.com/ultralytics/yolov5/releases)下载[模型](https://github.com/ultralytics/yolov5/tree/master/models)，并将结果保存到 `runs/detect` 目录。

```bash
# 使用网络摄像头运行推理
python detect.py --weights yolov5s.pt --source 0

# 对本地图像文件运行推理
python detect.py --weights yolov5s.pt --source img.jpg

# 对本地视频文件运行推理
python detect.py --weights yolov5s.pt --source vid.mp4

# 对屏幕截图运行推理
python detect.py --weights yolov5s.pt --source screen

# 对图像目录运行推理
python detect.py --weights yolov5s.pt --source path/to/images/

# 对列出图像路径的文本文件运行推理
python detect.py --weights yolov5s.pt --source list.txt

# 对列出流 URL 的文本文件运行推理
python detect.py --weights yolov5s.pt --source list.streams

# 使用 glob 模式对图像运行推理
python detect.py --weights yolov5s.pt --source 'path/to/*.jpg'

# 对 YouTube 视频 URL 运行推理
python detect.py --weights yolov5s.pt --source 'https://youtu.be/LNwODJXcvt4'

# 对 RTSP、RTMP 或 HTTP 流运行推理
python detect.py --weights yolov5s.pt --source 'rtsp://example.com/media.mp4'
```




训练

以下命令演示了如何复现 YOLOv5 在 [COCO 数据集](https://docs.ultralytics.com/datasets/detect/coco)上的结果。[模型](https://github.com/ultralytics/yolov5/tree/master/models)和[数据集](https://github.com/ultralytics/yolov5/tree/master/data)都会自动从最新的 YOLOv5 [发布版本](https://github.com/ultralytics/yolov5/releases)下载。YOLOv5n/s/m/l/x 的训练时间在单个 [NVIDIA V100 GPU](https://www.nvidia.com/en-us/data-center/v100/) 上大约需要 1/2/4/6/8 天。使用[多 GPU 训练](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training)可以显著减少训练时间。请使用硬件允许的最大 `--batch-size`，或使用 `--batch-size -1` 以启用 YOLOv5 [AutoBatch](https://github.com/ultralytics/yolov5/pull/5092)。下面显示的批处理大小适用于 V100-16GB GPU。

```bash
# 在 COCO 上训练 YOLOv5n 300 个周期
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5n.yaml --batch-size 128

# 在 COCO 上训练 YOLOv5s 300 个周期
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5s.yaml --batch-size 64

# 在 COCO 上训练 YOLOv5m 300 个周期
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5m.yaml --batch-size 40

# 在 COCO 上训练 YOLOv5l 300 个周期
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5l.yaml --batch-size 24

# 在 COCO 上训练 YOLOv5x 300 个周期
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5x.yaml --batch-size 16
```






教程

- **[训练自定义数据](https://docs.ultralytics.com/yolov5/tutorials/train_custom_data)** 🚀 **推荐**：学习如何在您自己的数据集上训练 YOLOv5。
- **[获得最佳训练结果的技巧](https://docs.ultralytics.com/guides/model-training-tips)** ☘️：利用专家技巧提升模型性能。
- **[多 GPU 训练](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training)**：使用多个 GPU 加速训练。
- **[PyTorch Hub 集成](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading)**：使用 PyTorch Hub 轻松加载模型。
- **[模型导出 (TFLite, ONNX, CoreML, TensorRT)](https://docs.ultralytics.com/yolov5/tutorials/model_export)** 🚀：将您的模型转换为各种部署格式，如 [ONNX](https://onnx.ai/) 或 [TensorRT](https://developer.nvidia.com/tensorrt)。
- **[NVIDIA Jetson 部署](https://docs.ultralytics.com/guides/nvidia-jetson)**：在 [NVIDIA Jetson](https://developer.nvidia.com/embedded-computing) 设备上部署 YOLOv5。
- **[测试时增强 (TTA)](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation)**：使用 TTA 提高预测准确性。
- **[模型集成](https://docs.ultralytics.com/yolov5/tutorials/model_ensembling)**：组合多个模型以获得更好的性能。
- **[模型剪枝/稀疏化](https://docs.ultralytics.com/yolov5/tutorials/model_pruning_and_sparsity)**：优化模型的大小和速度。
- **[超参数进化](https://docs.ultralytics.com/yolov5/tutorials/hyperparameter_evolution)**：自动找到最佳训练超参数。
- **[使用冻结层的迁移学习](https://docs.ultralytics.com/yolov5/tutorials/transfer_learning_with_frozen_layers)**：使用[迁移学习](https://www.ultralytics.com/glossary/transfer-learning)高效地将预训练模型应用于新任务。
- **[架构摘要](https://docs.ultralytics.com/yolov5/tutorials/architecture_description)**：了解 YOLOv5 模型架构。
- **[Ultralytics Platform 训练](https://platform.ultralytics.com)** 🚀 **推荐**：使用 Ultralytics Platform 训练和部署 YOLO 模型。
- **[ClearML 日志记录](https://docs.ultralytics.com/yolov5/tutorials/clearml_logging_integration)**：与 [ClearML](https://clear.ml/) 集成以进行实验跟踪。
- **[Neural Magic DeepSparse 集成](https://docs.ultralytics.com/yolov5/tutorials/neural_magic_pruning_quantization)**：使用 DeepSparse 加速推理。
- **[Comet 日志记录](https://docs.ultralytics.com/yolov5/tutorials/comet_logging_integration)**：使用 [Comet ML](https://www.comet.com/site/) 记录实验。



## 🧩 集成

我们与领先 AI 平台的关键集成扩展了 Ultralytics 产品的功能，增强了诸如数据集标注、训练、可视化和模型管理等任务。了解 Ultralytics 如何与 [Weights & Biases](https://docs.ultralytics.com/integrations/weights-biases)、[Comet ML](https://docs.ultralytics.com/integrations/comet)、[Roboflow](https://docs.ultralytics.com/integrations/roboflow) 和 [Intel OpenVINO](https://docs.ultralytics.com/integrations/openvino) 等合作伙伴协作，优化您的 AI 工作流程。在 [Ultralytics 集成](https://docs.ultralytics.com/integrations) 探索更多信息。

<a href="https://platform.ultralytics.com" target="_blank">
    
</a>

## 🤔 为何选择 YOLOv5？

YOLOv5 的设计旨在简单易用。我们优先考虑实际性能和可访问性。



  YOLOv5-P5 640 图表




  图表说明

- **COCO AP val** 表示在 [交并比 (IoU)](https://www.ultralytics.com/glossary/intersection-over-union-iou) 阈值从 0.5 到 0.95 范围内的[平均精度均值 (mAP)](https://www.ultralytics.com/glossary/mean-average-precision-map)，在包含 5000 张图像的 [COCO val2017 数据集](https://docs.ultralytics.com/datasets/detect/coco)上，使用各种推理尺寸（256 到 1536 像素）测量得出。
- **GPU Speed** 使用批处理大小为 32 的 [AWS p3.2xlarge V100 实例](https://aws.amazon.com/ec2/instance-types/p4/)，测量在 [COCO val2017 数据集](https://docs.ultralytics.com/datasets/detect/coco)上每张图像的平均推理时间。
- **EfficientDet** 数据来源于 [google/automl 仓库](https://github.com/google/automl)，批处理大小为 8。
- **复现**这些结果请使用命令：`python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt`



### 预训练权重

此表显示了在 COCO 数据集上训练的各种 YOLOv5 模型的性能指标。

| 模型                                                                                                                                                                     | 尺寸<sup>(像素) | mAP<sup>val50-95 | mAP<sup>val50 | 速度<sup>CPU b1(毫秒) | 速度<sup>V100 b1(毫秒) | 速度<sup>V100 b32(毫秒) | 参数<sup>(M) | FLOPs<sup>@640 (B) |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------- | -------------------- | ----------------- | ----------------------------- | ------------------------------ | ------------------------------- | ---------------- | ---------------------- |
| [YOLOv5n](https://platform.ultralytics.com/ultralytics/yolov5/yolov5nu)                                                                                                  | 640                 | 28.0                 | 45.7              | **45**                        | **6.3**                        | **0.6**                         | **1.9**          | **4.5**                |
| [YOLOv5s](https://platform.ultralytics.com/ultralytics/yolov5/yolov5su)                                                                                                  | 640                 | 37.4                 | 56.8              | 98                            | 6.4                            | 0.9                             | 7.2              | 16.5                   |
| [YOLOv5m](https://platform.ultralytics.com/ultralytics/yolov5/yolov5mu)                                                                                                  | 640                 | 45.4                 | 64.1              | 224                           | 8.2                            | 1.7                             | 21.2             | 49.0                   |
| [YOLOv5l](https://platform.ultralytics.com/ultralytics/yolov5/yolov5lu)                                                                                                  | 640                 | 49.0                 | 67.3              | 430                           | 10.1                           | 2.7                             | 46.5             | 109.1                  |
| [YOLOv5x](https://platform.ultralytics.com/ultralytics/yolov5/yolov5xu)                                                                                                  | 640                 | 50.7                 | 68.9              | 766                           | 12.1                           | 4.8                             | 86.7             | 205.7                  |
|                                                                                                                                                                          |                     |                      |                   |                               |                                |                                 |                  |                        |
| [YOLOv5n6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n6.pt)                                                                                     | 1280                | 36.0                 | 54.4              | 153                           | 8.1                            | 2.1                             | 3.2              | 4.6                    |
| [YOLOv5s6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s6.pt)                                                                                     | 1280                | 44.8                 | 63.7              | 385                           | 8.2                            | 3.6                             | 12.6             | 16.8                   |
| [YOLOv5m6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m6.pt)                                                                                     | 1280                | 51.3                 | 69.3              | 887                           | 11.1                           | 6.8                             | 35.7             | 50.0                   |
| [YOLOv5l6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l6.pt)                                                                                     | 1280                | 53.7                 | 71.3              | 1784                          | 15.8                           | 10.5                            | 76.8             | 111.4                  |
| [YOLOv5x6](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x6.pt)+ [[TTA]](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation/) | 12801536        | 55.0**55.8**     | 72.7**72.7**  | 3136-                     | 26.2-                      | 19.4-                       | 140.7-       | 209.8-             |


  表格说明

- 640 像素行展示的是旧版基于锚框的 YOLOv5 权重及其指标，但链接会打开 Ultralytics Platform 上对应的无锚 YOLOv5u 后继模型。P6 链接仍直接下载旧版 1280 像素权重。
- 所有预训练权重均使用默认设置训练了 300 个周期。Nano (n) 和 Small (s) 模型使用 [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml) 超参数，而 Medium (m)、Large (l) 和 Extra-Large (x) 模型使用 [hyp.scratch-high.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-high.yaml)。
- **mAP<sup>val</sup>** 值表示在 [COCO val2017 数据集](https://docs.ultralytics.com/datasets/detect/coco)上的单模型、单尺度性能。复现请使用：`python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
- **速度**指标是在 [AWS p3.2xlarge V100 实例](https://aws.amazon.com/ec2/instance-types/p4/)上对 COCO val 图像进行平均测量的。不包括非极大值抑制 (NMS) 时间（约 1 毫秒/图像）。复现请使用：`python val.py --data coco.yaml --img 640 --task speed --batch 1`
- **TTA** ([测试时增强](https://docs.ultralytics.com/yolov5/tutorials/test_time_augmentation)) 包括反射和尺度增强以提高准确性。复现请使用：`python val.py --data coco.yaml --img 1536 --iou 0.7 --augment`



## 🖼️ 分割

YOLOv5 [v7.0 版本](https://github.com/ultralytics/yolov5/releases/v7.0) 引入了[实例分割](https://docs.ultralytics.com/tasks/segment)模型，设计用于轻松训练、验证和部署。有关完整详细信息，请参阅[发布说明](https://github.com/ultralytics/yolov5/releases/v7.0)，并探索 [YOLOv5 分割 Colab 笔记本](https://github.com/ultralytics/yolov5/blob/master/segment/tutorial.ipynb)以获取快速入门示例。


  分割预训练权重



YOLOv5 分割模型在 [COCO 数据集](https://docs.ultralytics.com/datasets/segment/coco)上使用 A100 GPU 以 640 像素的图像大小训练了 300 个周期。模型导出为 [ONNX](https://onnx.ai/) FP32 用于 CPU 速度测试，导出为 [TensorRT](https://developer.nvidia.com/tensorrt) FP16 用于 GPU 速度测试。所有速度测试均在 Google [Colab Pro](https://colab.research.google.com/signup) 笔记本上进行，以确保可复现性。

| 模型                                                                                       | 尺寸<sup>(像素) | mAP<sup>box50-95 | mAP<sup>mask50-95 | 训练时间<sup>300 周期A100 (小时) | 速度<sup>ONNX CPU(毫秒) | 速度<sup>TRT A100(毫秒) | 参数<sup>(M) | FLOPs<sup>@640 (B) |
| ------------------------------------------------------------------------------------------ | ------------------- | -------------------- | --------------------- | ---------------------------------------- | ------------------------------- | ------------------------------- | ---------------- | ---------------------- |
| [YOLOv5n-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n-seg.pt) | 640                 | 27.6                 | 23.4                  | 80:17                                    | **62.7**                        | **1.2**                         | **2.0**          | **7.1**                |
| [YOLOv5s-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-seg.pt) | 640                 | 37.6                 | 31.7                  | 88:16                                    | 173.3                           | 1.4                             | 7.6              | 26.4                   |
| [YOLOv5m-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m-seg.pt) | 640                 | 45.0                 | 37.1                  | 108:36                                   | 427.0                           | 2.2                             | 22.0             | 70.8                   |
| [YOLOv5l-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l-seg.pt) | 640                 | 49.0                 | 39.9                  | 66:43 (2x)                               | 857.4                           | 2.9                             | 47.9             | 147.7                  |
| [YOLOv5x-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x-seg.pt) | 640                 | **50.7**             | **41.4**              | 62:56 (3x)                               | 1579.2                          | 4.5                             | 88.8             | 265.7                  |

- 所有预训练权重均使用 SGD 优化器，`lr0=0.01` 和 `weight_decay=5e-5`，在 640 像素的图像大小下，使用默认设置训练了 300 个周期。训练运行记录在 [https://wandb.ai/glenn-jocher/YOLOv5_v70_official](https://wandb.ai/glenn-jocher/YOLOv5_v70_official)。
- **准确度**值表示在 COCO 数据集上的单模型、单尺度性能。复现请使用：`python segment/val.py --data coco.yaml --weights yolov5s-seg.pt`
- **速度**指标是在 [Colab Pro A100 High-RAM 实例](https://colab.research.google.com/signup)上对 100 张推理图像进行平均测量的。值仅表示推理速度（NMS 约增加 1 毫秒/图像）。复现请使用：`python segment/val.py --data coco.yaml --weights yolov5s-seg.pt --batch 1`
- **导出**到 ONNX (FP32) 和 TensorRT (FP16) 是使用 `export.py` 完成的。复现请使用：`python export.py --weights yolov5s-seg.pt --include engine --device 0 --half`




  分割使用示例 &nbsp;[](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/segment/tutorial.ipynb)

### 训练

YOLOv5 分割训练支持通过 `--data coco128-seg.yaml` 参数自动下载 [COCO128-seg 数据集](https://docs.ultralytics.com/datasets/segment/coco128-seg)。对于完整的 [COCO-segments 数据集](https://docs.ultralytics.com/datasets/segment/coco)，请使用 `bash data/scripts/get_coco.sh --train --val --segments` 手动下载，然后使用 `python segment/train.py --data coco.yaml` 进行训练。

```bash
# 在单个 GPU 上训练
python segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640

# 使用多 GPU 分布式数据并行 (DDP) 进行训练
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640 --device 0,1,2,3
```

### 验证

在 COCO 数据集上验证 YOLOv5s-seg 的掩码[平均精度均值 (mAP)](https://www.ultralytics.com/glossary/mean-average-precision-map)：

```bash
# 下载 COCO 验证分割集 (780MB, 5000 张图像)
bash data/scripts/get_coco.sh --val --segments

# 验证模型
python segment/val.py --weights yolov5s-seg.pt --data coco.yaml --img 640
```

### 预测

使用预训练的 YOLOv5m-seg.pt 模型对 `bus.jpg` 执行分割：

```bash
# 运行预测
python segment/predict.py --weights yolov5m-seg.pt --source data/images/bus.jpg
```

```python
# 从 PyTorch Hub 加载模型 (注意: 推理支持可能有所不同)
model = torch.hub.load("ultralytics/yolov5", "custom", "yolov5m-seg.pt")
```

|  |  |
| :-----------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------: |

### 导出

将 YOLOv5s-seg 模型导出为 ONNX 和 TensorRT 格式：

```bash
# 导出模型
python export.py --weights yolov5s-seg.pt --include onnx engine --img 640 --device 0
```



## 🏷️ 分类

YOLOv5 [v6.2 版本](https://github.com/ultralytics/yolov5/releases/v6.2) 引入了对[图像分类](https://docs.ultralytics.com/tasks/classify)模型训练、验证和部署的支持。请查看[发布说明](https://github.com/ultralytics/yolov5/releases/v6.2)了解详细信息，并参阅 [YOLOv5 分类 Colab 笔记本](https://github.com/ultralytics/yolov5/blob/master/classify/tutorial.ipynb)获取快速入门指南。


  分类预训练权重



YOLOv5-cls 分类模型在 [ImageNet](https://docs.ultralytics.com/datasets/classify/imagenet) 上使用 4xA100 实例训练了 90 个周期。[ResNet](https://arxiv.org/abs/1512.03385) 和 [EfficientNet](https://arxiv.org/abs/1905.11946) 模型在相同设置下一起训练以进行比较。模型导出为 [ONNX](https://onnx.ai/) FP32（用于 CPU 速度测试）和 [TensorRT](https://developer.nvidia.com/tensorrt) FP16（用于 GPU 速度测试）。所有速度测试均在 Google [Colab Pro](https://colab.research.google.com/signup) 上运行，以确保可复现性。

| 模型                                                                                               | 尺寸<sup>(像素) | 准确率<sup>top1 | 准确率<sup>top5 | 训练<sup>90 周期4xA100 (小时) | 速度<sup>ONNX CPU(毫秒) | 速度<sup>TensorRT V100(毫秒) | 参数<sup>(M) | FLOPs<sup>@224 (B) |
| -------------------------------------------------------------------------------------------------- | ------------------- | ------------------- | ------------------- | ------------------------------------- | ------------------------------- | ------------------------------------ | ---------------- | ---------------------- |
| [YOLOv5n-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n-cls.pt)         | 224                 | 64.6                | 85.4                | 7:59                                  | **3.3**                         | **0.5**                              | **2.5**          | **0.5**                |
| [YOLOv5s-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-cls.pt)         | 224                 | 71.5                | 90.2                | 8:09                                  | 6.6                             | 0.6                                  | 5.4              | 1.4                    |
| [YOLOv5m-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m-cls.pt)         | 224                 | 75.9                | 92.9                | 10:06                                 | 15.5                            | 0.9                                  | 12.9             | 3.9                    |
| [YOLOv5l-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l-cls.pt)         | 224                 | 78.0                | 94.0                | 11:56                                 | 26.9                            | 1.4                                  | 26.5             | 8.5                    |
| [YOLOv5x-cls](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x-cls.pt)         | 224                 | **79.0**            | **94.4**            | 15:04                                 | 54.3                            | 1.8                                  | 48.1             | 15.9                   |
|                                                                                                    |                     |                     |                     |                                       |                                 |                                      |                  |                        |
| [ResNet18](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet18.pt)               | 224                 | 70.3                | 89.5                | **6:47**                              | 11.2                            | 0.5                                  | 11.7             | 3.7                    |
| [ResNet34](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet34.pt)               | 224                 | 73.9                | 91.8                | 8:33                                  | 20.6                            | 0.9                                  | 21.8             | 7.4                    |
| [ResNet50](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet50.pt)               | 224                 | 76.8                | 93.4                | 11:10                                 | 23.4                            | 1.0                                  | 25.6             | 8.5                    |
| [ResNet101](https://github.com/ultralytics/yolov5/releases/download/v7.0/resnet101.pt)             | 224                 | 78.5                | 94.3                | 17:10                                 | 42.1                            | 1.9                                  | 44.5             | 15.9                   |
|                                                                                                    |                     |                     |                     |                                       |                                 |                                      |                  |                        |
| [EfficientNet_b0](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b0.pt) | 224                 | 75.1                | 92.4                | 13:03                                 | 12.5                            | 1.3                                  | 5.3              | 1.0                    |
| [EfficientNet_b1](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b1.pt) | 224                 | 76.4                | 93.2                | 17:04                                 | 14.9                            | 1.6                                  | 7.8              | 1.5                    |
| [EfficientNet_b2](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b2.pt) | 224                 | 76.6                | 93.4                | 17:10                                 | 15.9                            | 1.6                                  | 9.1              | 1.7                    |
| [EfficientNet_b3](https://github.com/ultralytics/yolov5/releases/download/v7.0/efficientnet_b3.pt) | 224                 | 77.7                | 94.0                | 19:19                                 | 18.9                            | 1.9                                  | 12.2             | 2.4                    |


  表格说明（点击展开）

- 所有预训练权重均使用 SGD 优化器，`lr0=0.001` 和 `weight_decay=5e-5`，在 224 像素的图像大小下，使用默认设置训练了 90 个周期。训练运行记录在 [https://wandb.ai/glenn-jocher/YOLOv5-Classifier-v6-2](https://wandb.ai/glenn-jocher/YOLOv5-Classifier-v6-2)。
- **准确度**值（top-1 和 top-5）表示在 [ImageNet-1k 数据集](https://docs.ultralytics.com/datasets/classify/imagenet)上的单模型、单尺度性能。复现请使用：`python classify/val.py --data ../datasets/imagenet --img 224`
- **速度**指标是在 Google [Colab Pro V100 High-RAM 实例](https://colab.research.google.com/signup)上对 100 张推理图像进行平均测量的。复现请使用：`python classify/val.py --data ../datasets/imagenet --img 224 --batch 1`
- **导出**到 ONNX (FP32) 和 TensorRT (FP16) 是使用 `export.py` 完成的。复现请使用：`python export.py --weights yolov5s-cls.pt --include engine onnx --imgsz 224`





  分类使用示例 &nbsp;[](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/classify/tutorial.ipynb)

### 训练

YOLOv5 分类训练支持使用 `--data` 参数自动下载诸如 [MNIST](https://docs.ultralytics.com/datasets/classify/mnist)、[Fashion-MNIST](https://docs.ultralytics.com/datasets/classify/fashion-mnist)、[CIFAR10](https://docs.ultralytics.com/datasets/classify/cifar10)、[CIFAR100](https://docs.ultralytics.com/datasets/classify/cifar100)、[Imagenette](https://docs.ultralytics.com/datasets/classify/imagenette)、[Imagewoof](https://docs.ultralytics.com/datasets/classify/imagewoof) 和 [ImageNet](https://docs.ultralytics.com/datasets/classify/imagenet) 等数据集。例如，使用 `--data mnist` 开始在 MNIST 上训练。

```bash
# 使用 CIFAR-100 数据集在单个 GPU 上训练
python classify/train.py --model yolov5s-cls.pt --data cifar100 --epochs 5 --img 224 --batch 128

# 在 ImageNet 数据集上使用多 GPU DDP 进行训练
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 classify/train.py --model yolov5s-cls.pt --data imagenet --epochs 5 --img 224 --device 0,1,2,3
```

### 验证

在 ImageNet-1k 验证数据集上验证 YOLOv5m-cls 模型的准确性：

```bash
# 下载 ImageNet 验证集 (6.3GB, 50,000 张图像)
bash data/scripts/get_imagenet.sh --val

# 验证模型
python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224
```

### 预测

使用预训练的 YOLOv5s-cls.pt 模型对图像 `bus.jpg` 进行分类：

```bash
# 运行预测
python classify/predict.py --weights yolov5s-cls.pt --source data/images/bus.jpg
```

```python
# 从 PyTorch Hub 加载模型
model = torch.hub.load("ultralytics/yolov5", "custom", "yolov5s-cls.pt")
```

### 导出

将训练好的 YOLOv5s-cls、ResNet50 和 EfficientNet_b0 模型导出为 ONNX 和 TensorRT 格式：

```bash
# 导出模型
python export.py --weights yolov5s-cls.pt resnet50.pt efficientnet_b0.pt --include onnx engine --img 224
```



## ☁️ 环境

使用我们预配置的环境快速开始。点击下面的图标查看设置详情。



## 🤝 贡献

我们欢迎您的贡献！让 YOLOv5 变得易于访问和有效是社区的共同努力。请参阅我们的[贡献指南](https://docs.ultralytics.com/help/contributing)开始。通过 [YOLOv5 调查](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey)分享您的反馈。感谢所有为使 YOLOv5 变得更好而做出贡献的人！

[](https://github.com/ultralytics/yolov5/graphs/contributors)

## 📜 许可证

Ultralytics 提供两种许可选项以满足不同需求：

- **AGPL-3.0 许可证**：一种 [OSI 批准的](https://opensource.org/license/agpl-3.0)开源许可证，非常适合学术研究、个人项目和测试。它促进开放协作和知识共享。详情请参阅 [LICENSE](https://github.com/ultralytics/yolov5/blob/master/LICENSE) 文件。
- **企业许可证**：专为商业应用量身定制，此许可证允许将 Ultralytics 软件和 AI 模型无缝集成到商业产品和服务中，绕过 AGPL-3.0 的开源要求。对于商业用例，请通过 [Ultralytics 授权许可](https://www.ultralytics.com/license)联系我们。

## 📧 联系

对于与 YOLOv5 相关的错误报告和功能请求，请访问 [GitHub Issues](https://github.com/ultralytics/yolov5/issues)。对于一般问题、讨论和社区支持，请加入我们的 [Discord 服务器](https://discord.com/invite/ultralytics)！

## 2. Official Technical Reference & Guides (ultralytics/docs)

[](https://www.ultralytics.com)

# 📚 Ultralytics Docs

Welcome to Ultralytics Docs, your comprehensive resource for understanding and utilizing our state-of-the-art [machine learning](https://www.ultralytics.com/glossary/machine-learning-ml) tools and models, including [Ultralytics YOLO](https://docs.ultralytics.com/models). These documents are actively maintained and deployed to [https://docs.ultralytics.com](https://docs.ultralytics.com) for easy access.

[](https://github.com/ultralytics/docs/actions/workflows/format.yml)
[](https://www.jsdelivr.com/package/gh/ultralytics/llm)

[](https://github.com/ultralytics/docs/actions/workflows/links.yml)

[](https://discord.com/invite/ultralytics)
[](https://community.ultralytics.com)
[](https://reddit.com/r/ultralytics)

## 🛠️ Ultralytics Package

[](https://pypi.org/project/ultralytics/)
[](https://clickpy.clickhouse.com/dashboard/ultralytics)
[](https://pypi.org/project/ultralytics/)

The badges above track the core `ultralytics` Python package documented by this site. To install that package in developer mode, which allows you to modify the source code directly, ensure you have [Git](https://git-scm.com/downloads/) and [Python](https://www.python.org/downloads/) 3.8 or later installed on your system. Then, follow these steps:

1.  Clone the `ultralytics` repository to your local machine using Git:

    ```bash
    git clone https://github.com/ultralytics/ultralytics.git
    ```

2.  Navigate to the cloned repository's root directory:

    ```bash
    cd ultralytics
    ```

3.  Install the package in editable mode (`-e`) along with its development dependencies (`[dev]`) using [pip](https://pip.pypa.io/en/stable/installation/):

    ```bash
    pip install -e '.[dev]'
    ```

    This command installs the `ultralytics` package such that changes to the source code are immediately reflected in your environment, ideal for development and contributing.

## 🧰 Technology Stack

- **[Next.js](https://nextjs.org/)** - Framework that renders the published documentation site
- **[Ultralytics Chat](https://github.com/ultralytics/llm)** - Realtime conversational AI with open-source [chat.js](https://github.com/ultralytics/llm) implementation
- **[Vercel](https://vercel.com/)** - Hosting and deployment
- **[GitHub Actions](https://github.com/features/actions)** - CI/CD automation

## 🔧 Repository Tooling

This repository contains documentation source plus maintenance workflows for published-site checks. Install the lightweight Python dependencies before running repository utilities locally:

```bash
uv pip install -r requirements.txt
```

For example, `utils/check_image_sizes.py` is used by the website link-check workflow to flag oversized images in downloaded pages.

## 🌍 Website Checks

The live documentation at [docs.ultralytics.com](https://docs.ultralytics.com) is maintained with scheduled and manual workflows in `.github/workflows/`:

- `links.yml` downloads rendered pages for `www.ultralytics.com`, `docs.ultralytics.com`, `academy.ultralytics.com`, and `handbook.ultralytics.com`, then checks links, spelling, and large images.
- `links_local.yml` checks repository Markdown and HTML links, with an optional broader link scan on manual runs.
- `download_websites.yml` can download public website pages for inspection.

Production combines this repository's content with the other documentation sources, validates the complete tree with `zensical build --strict`, and renders it through Ultralytics' centralized publishing service. This repository therefore has no standalone site build; use the workflows above to check published pages.

## 💡 Contribute

We deeply value contributions from the open-source community to enhance Ultralytics projects. Your input helps drive innovation in [computer vision](https://www.ultralytics.com/glossary/computer-vision-cv) and [AI](https://www.ultralytics.com/glossary/artificial-intelligence-ai)! Please review our [Contributing Guide](https://docs.ultralytics.com/help/contributing) for detailed information on how to get involved. You can also share your feedback and ideas through our quick [Survey](https://www.ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey). A heartfelt thank you 🙏 to all our contributors for their dedication and support!

[](https://github.com/ultralytics/ultralytics/graphs/contributors)

We look forward to your contributions!

## 📜 License

Ultralytics Docs are available under two licensing options to accommodate different usage scenarios:

- **AGPL-3.0 License**: Ideal for students, researchers, and enthusiasts involved in academic pursuits and open collaboration. See the [LICENSE](https://github.com/ultralytics/docs/blob/main/LICENSE) file for full details. This license promotes sharing improvements back with the community, fostering an open and collaborative environment.
- **Enterprise License**: Designed for commercial applications, this license allows seamless integration of Ultralytics software and [AI models](https://docs.ultralytics.com/models) into commercial products and services without the open-source requirements of AGPL-3.0. Visit [Ultralytics Licensing](https://www.ultralytics.com/license) for more information on obtaining an Enterprise License.

## ✉️ Contact

For bug reports, feature requests, and other issues related to the documentation, please use [GitHub Issues](https://github.com/ultralytics/docs/issues). For discussions, questions, and community support regarding Ultralytics software, the [Ultralytics Platform](https://docs.ultralytics.com/platform/quickstart), and more, join the conversation with peers and the Ultralytics team on our [Discord server](https://discord.com/invite/ultralytics)!