ultralytics / yolov5

YOLOv5 🚀 in PyTorch > ONNX > CoreML > TFLite
https://docs.ultralytics.com
GNU Affero General Public License v3.0
51.24k stars 16.44k forks source link

Why percious and recall suddenly increased ? #10060

Closed GreenHandForCoding closed 1 year ago

GreenHandForCoding commented 2 years ago

Search before asking

Question

I'm trying used yolov5 in product flaws, then some issues come. The percious and recall suddenly increased in less 20 epoches. I trained about 240 pictures, and I find percious and recall suddenly increased to about 0.995, so why? Detect results are unsatisfactory.

Maybe yolov5 doesn't fit this type of object. Should I modify parameters or expand the number of examples used in train?

Additional

![Uploading image.png…]()

glenn-jocher commented 2 years ago

👋 Hello! Thanks for asking about improving YOLOv5 🚀 training results.

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

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

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.

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!

GreenHandForCoding commented 2 years ago

Thanks! Here is my another question: I put some pictures of products without flaw and the same quantity of empty labels in training data, will it improve the performance of model? I only used the defective products as my training data in the past.

ExtReMLapin commented 2 years ago

Thanks! Here is my another question: I put some pictures of products without flaw and the same quantity of empty labels in training data, will it improve the performance of model? I only used the defective products as my training data in the past.

You mean add background images ? Images with no annotations to reduce false positives, yes, you can use like 10~15%.

I first used 70% and I had lower final score

GreenHandForCoding commented 2 years ago

Thanks! Here is my another question: I put some pictures of products without flaw and the same quantity of empty labels in training data, will it improve the performance of model? I only used the defective products as my training data in the past.

You mean add background images ? Images with no annotations to reduce false positives, yes, you can use like 10~15%.

I first used 70% and I had lower final score

Yeah! I mean background images.

GreenHandForCoding commented 2 years ago

image image image

Here are two graphs about the training process. I think two graphs indicate overfiting. I trained about 600 pictures. Maybe too less training data or the characteristics of my data are not obvious lead to overfiting.

Here is one. image

ExtReMLapin commented 2 years ago

What worries me about your metrics is the signal amplitude, precidion goes up and down a lot.

Could you show some annotated images (ones from the runs/exp00 folder for example ?

GreenHandForCoding commented 2 years ago

Hey! thank you and here are the two annotated images. @ExtReMLapin

train_batch0 train_batch1

ExtReMLapin commented 2 years ago

What are your training settings ? Which model do you use and what are your images (resized) resolutions, show us the arguments

GreenHandForCoding commented 2 years ago

Traning settings: `def parse_opt(known=False): parser = argparse.ArgumentParser() parser.add_argument('--weights', type=str, default=ROOT / 'yolov5l.pt', help='initial weights path') parser.add_argument('--cfg', type=str, default='', help='model.yaml path') parser.add_argument('--data', type=str, default=ROOT / 'data/flaw.yaml', help='dataset.yaml path') parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path') parser.add_argument('--epochs', type=int, default=300, help='total training epochs') parser.add_argument('--batch-size', type=int, default=4, help='total batch size for all GPUs, -1 for autobatch') parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=1280, help='train, val image size (pixels)') parser.add_argument('--rect', action='store_true', help='rectangular training') parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training') parser.add_argument('--nosave', action='store_true', help='only save final checkpoint') parser.add_argument('--noval', action='store_true', help='only validate final epoch') parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor') parser.add_argument('--noplots', action='store_true', help='save no plot files') parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations') parser.add_argument('--bucket', type=str, default='', help='gsutil bucket') parser.add_argument('--cache', type=str, nargs='?', const='ram', help='image --cache ram/disk') parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%') parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class') parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer') parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode') parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)') parser.add_argument('--project', default=ROOT / 'runs/train', help='save to project/name') parser.add_argument('--name', default='exp', help='save to project/name') parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') parser.add_argument('--quad', action='store_true', help='quad dataloader') parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler') parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon') parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)') parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2') parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)') parser.add_argument('--seed', type=int, default=0, help='Global training seed') parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')

# Logger arguments
parser.add_argument('--entity', default=None, help='Entity')
parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='Upload data, "val" option')
parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval')
parser.add_argument('--artifact_alias', type=str, default='latest', help='Version of dataset artifact to use')

return parser.parse_known_args()[0] if known else parser.parse_args()`

@ExtReMLapin The image-size(1328*1168) is close to 1280, so 1280 is used.

ExtReMLapin commented 2 years ago

I was expecting your commandlines arguments, not python code but I guess the image resize is good enough. Try using the P2 model instead of the default ones

https://github.com/ultralytics/yolov5/blob/master/models/hub/yolov5-p2.yaml

GreenHandForCoding commented 2 years ago

@ExtReMLapin what? code you have seen is the one I downloaded in the official website and it's python. I'll try to use the p2 model. I will appreciate your suggestion

ExtReMLapin commented 2 years ago

Yes, I asked for YOUR training params, not to see the python code, I expected you to send us your command line you use to start the training

example : python train.py --img 2048 --batch 10 --epochs 1500 --data test_data.yaml --weights " " --cfg yolov5n6.yaml --hyp hyp.scratch-low.yaml --patience 0

Here you can see the model but there are others arguments like the image size, n of epochs etc

ExtReMLapin commented 2 years ago

To use th P2 model you would have to replace yolov5n6.yaml by yolov5-p2.yaml

GreenHandForCoding commented 2 years ago

@ExtReMLapin Here is information form console and it's in training. By the way do you have any advice on my later training ? Such as : set rect = True ...

Console: train: weights=best_1280.pt, cfg=yolov5-p2.yaml, data=data\flaw.yaml, hyp=data\hyps\hyp.scratch-low.yaml, epochs=300, batch_size=4, imgsz=1280, rect=False, resume=False, nosave=False, noval=False, noautoanchor=False, noplots=False, evolve=None, bucket=, cache=None, image_weights=False, device=, multi_scale=False, single_cls=False, optimizer=SGD, sync_bn=False, workers=8, project=runs\train, name=exp, exist_ok=False, quad=False, cos_lr=False, label_smoothing=0.0, patience=100, freeze=[0], save_period=-1, seed=0, local_rank=-1, entity=None, upload_dataset=False, bbox_interval=-1, artifact_alias=latest YOLOv5 2022-11-7 Python-3.9.7 torch-1.10.0+cu113 CUDA:0 (NVIDIA GeForce RTX 3060, 12287MiB)

hyperparameters: lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=0.05, cls=0.5, cls_pw=1.0, obj=1.0, obj_pw=1.0, iou_t=0.2, anchor_t=4.0, fl_gamma=0.0, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0 ClearML: run 'pip install clearml' to automatically track, visualize and remotely train YOLOv5 in ClearML Comet: run 'pip install comet_ml' to automatically track and visualize YOLOv5 runs in Comet TensorBoard: Start with 'tensorboard --logdir runs\train', view at http://localhost:6006/ Overriding model.yaml nc=80 with nc=6

ExtReMLapin commented 2 years ago

The console logs itself won't really help, please setup wandb as described in the console to save the metrics, and then share the metrics with us, or directly the csv file in yolov5/runs/xxx/xxx

GreenHandForCoding commented 2 years ago

results: results P_curve: P_curve PR_curve: PR_curve R_curve: R_curve train_batch0: train_batch0 val_batch0: val_batch0_labels @ExtReMLapin I've shown you some images. Tell me if you need more. Thank you.

ExtReMLapin commented 2 years ago

Alright, perfect, that's what we needed. I would suggest top ignore the "bump" at the first iterations of the recall and precision, as mAP is still Low.

I would suggest going oogabooga mode and just increase the number of iterations from 300 here to 600 and see if mAP keeps going up. As it keeps going up, you can "continue" training, here it's stopped a little soon I guess. Keep the selected settings, just increase the number of iteration, or triple/quadruple it if you have enough horsepower in your PC.

GreenHandForCoding commented 1 year ago

@ExtReMLapin OK, understand. I will set 600 epochs and see what will happen. But the precious and recall decrease sharply from 0.8+ to 0.6- in the beginning makes me conscious.

GreenHandForCoding commented 1 year ago

@ExtReMLapin results The result is not good...

github-actions[bot] commented 1 year ago

👋 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 ⭐!

ExtReMLapin commented 1 year ago

At the time you posted your answer, I had no idea, could you try to see if you didn't incorrectly annotate your images ?

Why are you using multiple classes ? I seems you're only trying to detect defects ? Can you try to make a copy of your dataset and change all the annotations to the same class ?

There are few defects you may have missed

image

You annotate this :

image

But not theses ?

image

image

github-actions[bot] commented 1 year ago

👋 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 ⭐!

glenn-jocher commented 1 year ago

@ExtReMLapin hi there! Thanks for sharing the results. It's possible that incorrect annotations or missed defects are affecting the performance. Given the nature of your task, you might consider simplifying your dataset to a single class and carefully reviewing your annotations. Additionally, it appears that some defects might have been missed during annotation. Feel free to dive deeper into your dataset and annotation, perhaps by creating a copy and ensuring all anomalies are appropriately annotated. This will likely lead to an improvement in your detection results. Good luck!