Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interpreting training results and showing loss graph, YOLOv5s6 #8185

Closed
Carolinejone opened this issue Jun 13, 2022 · 14 comments
Closed

Interpreting training results and showing loss graph, YOLOv5s6 #8185

Carolinejone opened this issue Jun 13, 2022 · 14 comments
Labels
Stale Stale and schedule for closing soon

Comments

@Carolinejone
Copy link

Carolinejone commented Jun 13, 2022

Hello, I'm new to AI. I would like to ask for some guidance on my research. I'm doing my master thesis with YOLOv5. I'm trying to detect the anomaly of stay cables of cable-type bridges.
I used two datasets; Dataset- 1 has 2049 source images and 4159 images in total after combining with some augmented images to the training dataset, and Dataset- 2 has 1823 source images and 3673 images in total after combining with some augmented images to the training dataset. Train, validation and test dataset split is as follow,
Dataset -1, 3.2k: 614: 380
Dataset -2, 2.9k: 552: 299
I followed custom YOLOv5 training from Roboflow and also used the Roboflow annotator with rectangular bounding boxes. I used batch size 64 and epoch 100 with pre-trained weight YOLOv5s6 and trained on COLAB pro plus for both datasets and the rest is the same as the custom YOLOv5 training tutorial.
This is the result for Dataset-1
results
This is the result for Dataset-2
results

My question is,

  1. Is the 100 epochs enough to train the model for both datasets 1 and 2?.
  2. How to interpret the result tables including confusion matrics? (I already learned about Precision, Recall, mAP and F1 graph)
  3. Which evaluation matric should I use, mAP or F1 or both? (Cause I've read that for class imbalance problem F1 score is the appropriate metric even though I believe that my model does not suffer from class imbalance effect.)
  4. Is my model good enough or is it overfitting or is it needed to improve?
  5. Is the validation loss the only way to check overfitting?
  6. Please provide some useful articles or papers for reference.
    Thank you so much for your help.
    Edit: adding more questions:
  7. What is the difference between the label graph from result tables and the class balance from the health check of Roboflow.
  8. How to interpret the results of label graph?
    Dataset-1 label graph
    labels
    Dataset-2 label graph
    labels
    Dataset-1 Class Balance
    Capture
    Dataset-2 Class Balance
    Capture
@github-actions
Copy link
Contributor

github-actions bot commented Jun 13, 2022

👋 Hello @Carolinejone, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://ultralytics.com or email support@ultralytics.com.

Requirements

Python>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), validation (val.py), inference (detect.py) and export (export.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit.

@glenn-jocher
Copy link
Member

glenn-jocher commented Jun 13, 2022

@Carolinejone 👋 Hello! Thanks for asking about improving YOLOv5 🚀 training results. I would combine both your datasets into a single dataset for best results. Also you must train longer until you see overfitting, otherwise you have not trained long enough.

Most of the time good results can be obtained with no changes to the models or training settings, provided your dataset is sufficiently large and well labelled. If at first you don't get good results, there are steps you might be able to take to improve, but we always recommend users first train with all default settings before considering any changes. This helps establish a performance baseline and spot areas for improvement.

If you have questions about your training results we recommend you provide the maximum amount of information possible if you expect a helpful response, including results plots (train losses, val losses, P, R, mAP), PR curve, confusion matrix, training mosaics, test results and dataset statistics images such as labels.png. All of these are located in your project/name directory, typically yolov5/runs/train/exp.

We've put together a full guide for users looking to get the best results on their YOLOv5 trainings below.

Dataset

  • Images per class. ≥ 1500 images per class recommended
  • Instances per class. ≥ 10000 instances (labeled objects) per class recommended
  • Image variety. Must be representative of deployed environment. For real-world use cases we recommend images from different times of day, different seasons, different weather, different lighting, different angles, different sources (scraped online, collected locally, different cameras) etc.
  • Label consistency. All instances of all classes in all images must be labelled. Partial labelling will not work.
  • Label accuracy. Labels must closely enclose each object. No space should exist between an object and it's bounding box. No objects should be missing a label.
  • Label verification. View train_batch*.jpg on train start to verify your labels appear correct, i.e. see example mosaic.
  • Background images. Background images are images with no objects that are added to a dataset to reduce False Positives (FP). We recommend about 0-10% background images to help reduce FPs (COCO has 1000 background images for reference, 1% of the total). No labels are required for background images.

COCO Analysis

Model Selection

Larger models like YOLOv5x and YOLOv5x6 will produce better results in nearly all cases, but have more parameters, require more CUDA memory to train, and are slower to run. For mobile deployments we recommend YOLOv5s/m, for cloud deployments we recommend YOLOv5l/x. See our README table for a full comparison of all models.

YOLOv5 Models

  • Start from Pretrained weights. Recommended for small to medium sized datasets (i.e. VOC, VisDrone, GlobalWheat). Pass the name of the model to the --weights argument. Models download automatically from the latest YOLOv5 release.
python train.py --data custom.yaml --weights yolov5s.pt
                                             yolov5m.pt
                                             yolov5l.pt
                                             yolov5x.pt
                                             custom_pretrained.pt
  • Start from Scratch. Recommended for large datasets (i.e. COCO, Objects365, OIv6). Pass the model architecture yaml you are interested in, along with an empty --weights '' argument:
python train.py --data custom.yaml --weights '' --cfg yolov5s.yaml
                                                      yolov5m.yaml
                                                      yolov5l.yaml
                                                      yolov5x.yaml

Training Settings

Before modifying anything, first train with default settings to establish a performance baseline. A full list of train.py settings can be found in the train.py argparser.

  • Epochs. Start with 300 epochs. If this overfits early then you can reduce epochs. If overfitting does not occur after 300 epochs, train longer, i.e. 600, 1200 etc epochs.
  • Image size. COCO trains at native resolution of --img 640, though due to the high amount of small objects in the dataset it can benefit from training at higher resolutions such as --img 1280. If there are many small objects then custom datasets will benefit from training at native or higher resolution. Best inference results are obtained at the same --img as the training was run at, i.e. if you train at --img 1280 you should also test and detect at --img 1280.
  • Batch size. Use the largest --batch-size that your hardware allows for. Small batch sizes produce poor batchnorm statistics and should be avoided.
  • Hyperparameters. Default hyperparameters are in hyp.scratch-low.yaml. We recommend you train with default hyperparameters first before thinking of modifying any. In general, increasing augmentation hyperparameters will reduce and delay overfitting, allowing for longer trainings and higher final mAP. Reduction in loss component gain hyperparameters like hyp['obj'] will help reduce overfitting in those specific loss components. For an automated method of optimizing these hyperparameters, see our Hyperparameter Evolution Tutorial.

Further Reading

If you'd like to know more a good place to start is Karpathy's 'Recipe for Training Neural Networks', which has great ideas for training that apply broadly across all ML domains: http://karpathy.github.io/2019/04/25/recipe/

Good luck 🍀 and let us know if you have any other questions!

@Carolinejone
Copy link
Author

@glenn-jocher Thank you so much for your explanation. I intentionally separate the dataset into two as I would like to compare the impact on the model's accuracy by the two different test datasets having different drone distances from the target object. For that reason, I couldn't combine the two datasets to make it larger.
I've tried to train the model for 300 epochs and the results show like this for dataset-1, the model overfits earlier. (I'm still running the dataset-2 but I'm sure the result will be the same).

!python train.py --img 640 --batch 64 --epochs 300 --data {dataset.location}/data.yaml --weights yolov5s6.pt --cache

Could you please explain how to prevent overfitting and if possible explain with some coding examples?

R_curve
P_curve
PR_curve
F1_curve

results
confusion_matrix

labels

@Carolinejone
Copy link
Author

Carolinejone commented Jun 13, 2022

This is the updated result for dataset-2 after running 300 epochs using the same codes as above.
confusion_matrix
F1_curve
labels
P_curve
PR_curve
R_curve
results

@glenn-jocher
Copy link
Member

glenn-jocher commented Jun 13, 2022

@Carolinejone follow recommendations in our complete guide in #8185 (comment).

To reduce overfitting you can try using higher augmentation yamls in data/hyps or customize with more Albumentations.

YOLOv5 🚀 applies online imagespace and colorspace augmentations in the trainloader (but not the val_loader) to present a new and unique augmented Mosaic (original image + 3 random images) each time an image is loaded for training. Images are never presented twice in the same way.

YOLOv5 augmentation

Augmentation Hyperparameters

The hyperparameters used to define these augmentations are in your hyperparameter file (default data/hyp.scratch.yaml) defined when training:

python train.py --hyp hyp.scratch-low.yaml

lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr: 0.1 # warmup initial bias lr
box: 0.05 # box loss gain
cls: 0.5 # cls loss gain
cls_pw: 1.0 # cls BCELoss positive_weight
obj: 1.0 # obj loss gain (scale with pixels)
obj_pw: 1.0 # obj BCELoss positive_weight
iou_t: 0.20 # IoU training threshold
anchor_t: 4.0 # anchor-multiple threshold
# anchors: 3 # anchors per output layer (0 to ignore)
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
degrees: 0.0 # image rotation (+/- deg)
translate: 0.1 # image translation (+/- fraction)
scale: 0.5 # image scale (+/- gain)
shear: 0.0 # image shear (+/- deg)
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
flipud: 0.0 # image flip up-down (probability)
fliplr: 0.5 # image flip left-right (probability)
mosaic: 1.0 # image mosaic (probability)
mixup: 0.0 # image mixup (probability)
copy_paste: 0.0 # segment copy-paste (probability)

Augmentation Previews

You can view the effect of your augmentation policy in your train_batch*.jpg images once training starts. These images will be in your train logging directory, typically yolov5/runs/train/exp:

train_batch0.jpg shows train batch 0 mosaics and labels:

YOLOv5 Albumentations Integration

YOLOv5 🚀 is now fully integrated with Albumentations, a popular open-source image augmentation package. Now you can train the world's best Vision AI models even better with custom Albumentations 😃!

PR #3882 implements this integration, which will automatically apply Albumentations transforms during YOLOv5 training if albumentations>=1.0.3 is installed in your environment. See #3882 for full details.

Example train_batch0.jpg on COCO128 dataset with Blur, MedianBlur and ToGray. See the YOLOv5 Notebooks to reproduce: Open In Colab Open In Kaggle

Good luck 🍀 and let us know if you have any other questions!

@Carolinejone
Copy link
Author

@glenn-jocher I can't thank you enough. You're my lifesaver. Your explanation is very effective and useful. I changed the model hyperparameters from low to high. Is it called fine-tuning? ( I admit that I had little knowledge about fine-tuning)
!python train.py --hyp hyp.scratch-high.yaml --img 640 --batch 64 --epochs 300 --data {dataset.location}/data.yaml --weights yolov5s6.pt --cache
This is the latest result I got for my Dataset-1. Does it overfit? Should I train more epochs?
I'll update the result for Dataset-2 when I finished running.
confusion_matrix
F1_curve
labels
P_curve
PR_curve
R_curve
results

@glenn-jocher
Copy link
Member

Seems like it’s now overfitting less, and you can now train longer

@Carolinejone
Copy link
Author

@glenn-jocher Thank you so much. Now I've trained the Dataset-1 for 600 epochs and it starts overfitting after 500 epochs. (the model also stopped showing improvements after 484 epochs which I got the best results). So should I stop at epoch 500?
This is the updated result for Dataset-1. Your kind help is deeply appreciated.
Capture
confusion_matrix
F1_curve
labels
P_curve
PR_curve
R_curve
results

@glenn-jocher
Copy link
Member

@Carolinejone results look good!

@Carolinejone
Copy link
Author

@glenn-jocher Thank you so much. I'll update the other results after training all datasets with different epochs. Again, your kind guidance is deeply appreciated.

@github-actions
Copy link
Contributor

github-actions bot commented Jul 15, 2022

👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs.

Access additional YOLOv5 🚀 resources:

Access additional Ultralytics ⚡ resources:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐!

@github-actions github-actions bot added the Stale Stale and schedule for closing soon label Jul 15, 2022
@glenn-jocher
Copy link
Member

@Carolinejone you're welcome! Feel free to reach out if you have any more questions. Good luck with your training, and I'm looking forward to seeing your results for the other datasets. Keep up the great work!

@pratikshac15
Copy link

@glenn-jocher
Hello Glenn, I am not able to understand the background class and how it is calculated. Could you please explain me? also while calculating FN, FP, TN from the confusion matrix do I need to consider background class?
Your reply would be appreciated. thank you in advance.

@glenn-jocher
Copy link
Member

@pratikshac15 in YOLOv5, the background class refers to the class that represents the absence of any object in the image. When calculating FN (False Negative), FP (False Positive), and TN (True Negative) from the confusion matrix, these metrics are typically considered with respect to the classes that are being detected, and the background class is not factored into these calculations. Thank you for your question!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Stale Stale and schedule for closing soon
Projects
None yet
Development

No branches or pull requests

3 participants