3

I am trying to run a custom object detection model using yolov5.

Did the following steps;

%cd yolov5
%pip install -qr requirements.txt # install dependencies


import torch
import os
from IPython.display import Image, clear_output  # to display images

print(f"Setup complete. Using torch {torch.__version__} ({torch.cuda.get_device_properties(0).name if torch.cuda.is_available() else 'CPU'})")

output-

Cloning into 'yolov5'... remote: Enumerating objects: 11888, done. remote: Counting objects: 100% (88/88), done. remote: Compressing objects: 100% (75/75), done. remote: Total 11888 (delta 40), reused 42 (delta 13), pack-reused 11800 Receiving objects: 100% (11888/11888), 12.46 MiB | 20.35 MiB/s, done. Resolving deltas: 100% (8152/8152), done. /content/yolov5 |████████████████████████████████| 1.6 MB 6.6 MB/s Setup complete. Using torch 1.12.1+cu113 (CPU)

!python train.py --img 320 --batch 2 --epochs 2 --data customdata.yaml --weights yolov5s.pt --cache

here in customdata.yaml, i have given the paths of my datasets (annoted)

After running the command, Model builds, but further it gives an error.

train: weights=yolov5s.pt, cfg=, data=customdata.yaml, hyp=data/hyps/hyp.scratch-low.yaml, epochs=2, batch_size=2, imgsz=320, rect=False, resume=False, nosave=False, noval=False, noautoanchor=False, noplots=False, evolve=None, bucket=, cache=ram, 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
github: up to date with https://github.com/ultralytics/yolov5 ✅
YOLOv5  v6.2-34-ge0700cc Python-3.7.13 torch-1.12.1+cu113 CPU

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
Weights & Biases: run 'pip install wandb' to automatically track and visualize YOLOv5  runs in Weights & Biases
ClearML: run 'pip install clearml' to automatically track, visualize and remotely train YOLOv5  in ClearML
TensorBoard: Start with 'tensorboard --logdir runs/train', view at http://localhost:6006/
Overriding model.yaml nc=80 with nc=6

                 from  n    params  module                                  arguments                     
  0                -1  1      3520  models.common.Conv                      [3, 32, 6, 2, 2]              
  1                -1  1     18560  models.common.Conv                      [32, 64, 3, 2]                
  2                -1  1     18816  models.common.C3                        [64, 64, 1]                   
  3                -1  1     73984  models.common.Conv                      [64, 128, 3, 2]               
  4                -1  2    115712  models.common.C3                        [128, 128, 2]                 
  5                -1  1    295424  models.common.Conv                      [128, 256, 3, 2]              
  6                -1  3    625152  models.common.C3                        [256, 256, 3]                 
  7                -1  1   1180672  models.common.Conv                      [256, 512, 3, 2]              
  8                -1  1   1182720  models.common.C3                        [512, 512, 1]                 
  9                -1  1    656896  models.common.SPPF                      [512, 512, 5]                 
 10                -1  1    131584  models.common.Conv                      [512, 256, 1, 1]              
 11                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          
 12           [-1, 6]  1         0  models.common.Concat                    [1]                           
 13                -1  1    361984  models.common.C3                        [512, 256, 1, False]          
 14                -1  1     33024  models.common.Conv                      [256, 128, 1, 1]              
 15                -1  1         0  torch.nn.modules.upsampling.Upsample    [None, 2, 'nearest']          
 16           [-1, 4]  1         0  models.common.Concat                    [1]                           
 17                -1  1     90880  models.common.C3                        [256, 128, 1, False]          
 18                -1  1    147712  models.common.Conv                      [128, 128, 3, 2]              
 19          [-1, 14]  1         0  models.common.Concat                    [1]                           
 20                -1  1    296448  models.common.C3                        [256, 256, 1, False]          
 21                -1  1    590336  models.common.Conv                      [256, 256, 3, 2]              
 22          [-1, 10]  1         0  models.common.Concat                    [1]                           
 23                -1  1   1182720  models.common.C3                        [512, 512, 1, False]          
 24      [17, 20, 23]  1     29667  models.yolo.Detect                      [6, [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]], [128, 256, 512]]
Model summary: 270 layers, 7035811 parameters, 7035811 gradients, 16.0 GFLOPs

Transferred 343/349 items from yolov5s.pt
optimizer: SGD(lr=0.01) with parameter groups 57 weight(decay=0.0), 60 weight(decay=0.0005), 60 bias
albumentations: Blur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01), CLAHE(p=0.01, clip_limit=(1, 4.0), tile_grid_size=(8, 8))
train: Scanning '/content/datasets/coco128/labels/train201.cache' images and labels... 2 found, 0 missing, 0 empty, 0 corrupt: 100% 2/2 [00:00<?, ?it/s]
train: Caching images (0.0GB ram): 100% 2/2 [00:00<00:00, 420.78it/s]
val: Scanning '/content/datasets/coco128/labels/train202' images and labels...2 found, 0 missing, 0 empty, 0 corrupt: 100% 2/2 [00:00<00:00, 64.04it/s]
val: New cache created: /content/datasets/coco128/labels/train202.cache
val: Caching images (0.0GB ram): 100% 2/2 [00:00<00:00, 418.41it/s]

AutoAnchor: 6.20 anchors/target, 1.000 Best Possible Recall (BPR). Current anchors are a good fit to dataset ✅
Plotting labels to runs/train/exp9/labels.jpg... 
Image sizes 320 train, 320 val
Using 2 dataloader workers
Logging results to runs/train/exp9
Starting training for 2 epochs...

     Epoch   gpu_mem       box       obj       cls    labels  img_size
       0/1        0G    0.1249   0.01741   0.05573         7       320: 100% 1/1 [00:03<00:00,  3.61s/it]
               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 1/1 [00:00<00:00,  2.92it/s]
                 all          2          5    0.00324      0.333     0.0079    0.00237

     Epoch   gpu_mem       box       obj       cls    labels  img_size
       1/1        0G    0.1228    0.0139   0.06047         4       320: 100% 1/1 [00:01<00:00,  1.08s/it]
               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 1/1 [00:00<00:00,  3.07it/s]
                 all          2          5    0.00388      0.333     0.0065     0.0026

2 epochs completed in 0.002 hours.
Optimizer stripped from runs/train/exp9/weights/last.pt, 14.3MB
Optimizer stripped from runs/train/exp9/weights/best.pt, 14.3MB

Validating runs/train/exp9/weights/best.pt...
Fusing layers... 
Model summary: 213 layers, 7026307 parameters, 0 gradients, 15.8 GFLOPs
               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95:   0% 0/1 [00:00<?, ?it/s]Exception in thread Thread-16:
Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/content/yolov5/utils/plots.py", line 243, in plot_images
    cls = names[cls] if names else cls
KeyError: 0

               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 1/1 [00:00<00:00,  3.09it/s]
Exception in thread Thread-17:
Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/content/yolov5/utils/plots.py", line 243, in plot_images
    cls = names[cls] if names else cls
KeyError: 0

Traceback (most recent call last):
  File "train.py", line 627, in <module>
    main(opt)
  File "train.py", line 523, in main
    train(opt.hyp, opt, device, callbacks)
  File "train.py", line 419, in train
    compute_loss=compute_loss)  # val best model with plots
  File "/usr/local/lib/python3.7/dist-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "/content/yolov5/val.py", line 267, in run
    tp, fp, p, r, f1, ap, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
  File "/content/yolov5/utils/metrics.py", line 84, in ap_per_class
    plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
  File "/content/yolov5/utils/metrics.py", line 330, in plot_pr_curve
    ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}')  # plot(recall, precision)
KeyError: 2

Please suggest some solution.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
programmer
  • 43
  • 4

0 Answers0