├── models
├── __init__.py
├── yolov3-tiny.yaml
├── yolov3-tiny-SPPD.yaml
├── yolov3-tiny-spp.yaml
├── yolov3.yaml
├── yolov3-spp.yaml
├── LF-YOLO-0.5.yaml
├── LF-YOLO-0.75.yaml
├── LF-YOLO.yaml
├── LF-YOLO-1.25.yaml
├── export.py
├── experimental.py
├── yolo.py
└── common.py
├── utils
├── __init__.py
├── aws
│ ├── __init__.py
│ ├── mime.sh
│ ├── resume.py
│ └── userdata.sh
├── wandb_logging
│ ├── __init__.py
│ ├── log_dataset.py
│ └── wandb_utils.py
├── google_app_engine
│ ├── additional_requirements.txt
│ ├── app.yaml
│ └── Dockerfile
├── activations.py
├── google_utils.py
├── autoanchor.py
├── metrics.py
├── loss.py
├── torch_utils.py
└── plots.py
├── .idea
├── .gitignore
├── vcs.xml
├── inspectionProfiles
│ └── profiles_settings.xml
├── modules.xml
├── misc.xml
└── LF-YOLO.iml
├── data
├── images
│ ├── bus.jpg
│ └── zidane.jpg
├── voc.yaml
├── argoverse_hd.yaml
├── hyp.finetune.yaml
├── scripts
│ ├── get_coco.sh
│ ├── get_argoverse_hd.sh
│ └── get_voc.sh
├── coco128.yaml
├── coco.yaml
└── hyp.scratch.yaml
├── .gitattributes
├── weights
└── download_weights.sh
├── requirements.txt
├── Dockerfile
├── .dockerignore
├── hubconf.py
├── README.md
├── detect.py
└── test.py
/models/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/utils/aws/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/utils/wandb_logging/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/data/images/bus.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lmomoy/LF-YOLO/HEAD/data/images/bus.jpg
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # this drop notebooks from GitHub language stats
2 | *.ipynb linguist-vendored
3 |
--------------------------------------------------------------------------------
/data/images/zidane.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lmomoy/LF-YOLO/HEAD/data/images/zidane.jpg
--------------------------------------------------------------------------------
/utils/google_app_engine/additional_requirements.txt:
--------------------------------------------------------------------------------
1 | # add these requirements in your app on top of the existing ones
2 | pip==18.1
3 | Flask==1.0.2
4 | gunicorn==19.9.0
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/utils/google_app_engine/app.yaml:
--------------------------------------------------------------------------------
1 | runtime: custom
2 | env: flex
3 |
4 | service: yolov3app
5 |
6 | liveness_check:
7 | initial_delay_sec: 600
8 |
9 | manual_scaling:
10 | instances: 1
11 | resources:
12 | cpu: 1
13 | memory_gb: 4
14 | disk_size_gb: 20
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/LF-YOLO.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/weights/download_weights.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Download latest models from https://github.com/ultralytics/yolov3/releases
3 | # Usage:
4 | # $ bash weights/download_weights.sh
5 |
6 | python - <=3.2.2
5 | numpy>=1.18.5
6 | opencv-python>=4.1.2
7 | Pillow
8 | PyYAML>=5.3.1
9 | scipy>=1.4.1
10 | torch>=1.7.0
11 | torchvision>=0.8.1
12 | tqdm>=4.41.0
13 |
14 | # logging -------------------------------------
15 | tensorboard>=2.4.1
16 | # wandb
17 |
18 | # plotting ------------------------------------
19 | seaborn>=0.11.0
20 | pandas
21 |
22 | # export --------------------------------------
23 | # coremltools>=4.1
24 | # onnx>=1.8.1
25 | # scikit-learn==0.19.2 # for coreml quantization
26 |
27 | # extras --------------------------------------
28 | thop # FLOPS computation
29 | pycocotools>=2.0 # COCO mAP
30 |
--------------------------------------------------------------------------------
/data/voc.yaml:
--------------------------------------------------------------------------------
1 | # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/
2 | # Train command: python train.py --data voc.yaml
3 | # Default dataset location is next to /yolov3:
4 | # /parent_folder
5 | # /VOC
6 | # /yolov3
7 |
8 |
9 | # download command/URL (optional)
10 | download: bash data/scripts/get_voc.sh
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train: ../VOC/images/train/ # 16551 images
14 | val: ../VOC/images/val/ # 4952 images
15 |
16 | # number of classes
17 | nc: 20
18 |
19 | # class names
20 | names: [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
21 | 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ]
22 |
--------------------------------------------------------------------------------
/utils/aws/mime.sh:
--------------------------------------------------------------------------------
1 | # AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/
2 | # This script will run on every instance restart, not only on first start
3 | # --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA ---
4 |
5 | Content-Type: multipart/mixed; boundary="//"
6 | MIME-Version: 1.0
7 |
8 | --//
9 | Content-Type: text/cloud-config; charset="us-ascii"
10 | MIME-Version: 1.0
11 | Content-Transfer-Encoding: 7bit
12 | Content-Disposition: attachment; filename="cloud-config.txt"
13 |
14 | #cloud-config
15 | cloud_final_modules:
16 | - [scripts-user, always]
17 |
18 | --//
19 | Content-Type: text/x-shellscript; charset="us-ascii"
20 | MIME-Version: 1.0
21 | Content-Transfer-Encoding: 7bit
22 | Content-Disposition: attachment; filename="userdata.txt"
23 |
24 | #!/bin/bash
25 | # --- paste contents of userdata.sh here ---
26 | --//
27 |
--------------------------------------------------------------------------------
/data/argoverse_hd.yaml:
--------------------------------------------------------------------------------
1 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/
2 | # Train command: python train.py --data argoverse_hd.yaml
3 | # Default dataset location is next to /yolov5:
4 | # /parent_folder
5 | # /argoverse
6 | # /yolov5
7 |
8 |
9 | # download command/URL (optional)
10 | download: bash data/scripts/get_argoverse_hd.sh
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train: ../argoverse/Argoverse-1.1/images/train/ # 39384 images
14 | val: ../argoverse/Argoverse-1.1/images/val/ # 15062 iamges
15 | test: ../argoverse/Argoverse-1.1/images/test/ # Submit to: https://eval.ai/web/challenges/challenge-page/800/overview
16 |
17 | # number of classes
18 | nc: 8
19 |
20 | # class names
21 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign' ]
22 |
--------------------------------------------------------------------------------
/utils/wandb_logging/log_dataset.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | import yaml
4 |
5 | from wandb_utils import WandbLogger
6 |
7 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
8 |
9 |
10 | def create_dataset_artifact(opt):
11 | with open(opt.data) as f:
12 | data = yaml.load(f, Loader=yaml.SafeLoader) # data dict
13 | logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation')
14 |
15 |
16 | if __name__ == '__main__':
17 | parser = argparse.ArgumentParser()
18 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
19 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
20 | parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project')
21 | opt = parser.parse_args()
22 | opt.resume = False # Explicitly disallow resume check for dataset upload job
23 |
24 | create_dataset_artifact(opt)
25 |
--------------------------------------------------------------------------------
/utils/google_app_engine/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM gcr.io/google-appengine/python
2 |
3 | # Create a virtualenv for dependencies. This isolates these packages from
4 | # system-level packages.
5 | # Use -p python3 or -p python3.7 to select python version. Default is version 2.
6 | RUN virtualenv /env -p python3
7 |
8 | # Setting these environment variables are the same as running
9 | # source /env/bin/activate.
10 | ENV VIRTUAL_ENV /env
11 | ENV PATH /env/bin:$PATH
12 |
13 | RUN apt-get update && apt-get install -y python-opencv
14 |
15 | # Copy the application's requirements.txt and run pip to install all
16 | # dependencies into the virtualenv.
17 | ADD requirements.txt /app/requirements.txt
18 | RUN pip install -r /app/requirements.txt
19 |
20 | # Add the application source code.
21 | ADD . /app
22 |
23 | # Run a WSGI server to serve the application. gunicorn must be declared as
24 | # a dependency in requirements.txt.
25 | CMD gunicorn -b :$PORT main:app
26 |
--------------------------------------------------------------------------------
/data/hyp.finetune.yaml:
--------------------------------------------------------------------------------
1 | # Hyperparameters for VOC finetuning
2 | # python train.py --batch 64 --weights yolov5m.pt --data voc.yaml --img 512 --epochs 50
3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4 |
5 |
6 | # Hyperparameter Evolution Results
7 | # Generations: 306
8 | # P R mAP.5 mAP.5:.95 box obj cls
9 | # Metrics: 0.6 0.936 0.896 0.684 0.0115 0.00805 0.00146
10 |
11 | lr0: 0.0032
12 | lrf: 0.12
13 | momentum: 0.843
14 | weight_decay: 0.00036
15 | warmup_epochs: 2.0
16 | warmup_momentum: 0.5
17 | warmup_bias_lr: 0.05
18 | box: 0.0296
19 | cls: 0.243
20 | cls_pw: 0.631
21 | obj: 0.301
22 | obj_pw: 0.911
23 | iou_t: 0.2
24 | anchor_t: 2.91
25 | # anchors: 3.63
26 | fl_gamma: 0.0
27 | hsv_h: 0.0138
28 | hsv_s: 0.664
29 | hsv_v: 0.464
30 | degrees: 0.373
31 | translate: 0.245
32 | scale: 0.898
33 | shear: 0.602
34 | perspective: 0.0
35 | flipud: 0.00856
36 | fliplr: 0.5
37 | mosaic: 1.0
38 | mixup: 0.243
39 |
--------------------------------------------------------------------------------
/data/scripts/get_coco.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # COCO 2017 dataset http://cocodataset.org
3 | # Download command: bash data/scripts/get_coco.sh
4 | # Train command: python train.py --data coco.yaml
5 | # Default dataset location is next to /yolov3:
6 | # /parent_folder
7 | # /coco
8 | # /yolov3
9 |
10 | # Download/unzip labels
11 | d='../' # unzip directory
12 | url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
13 | f='coco2017labels.zip' # or 'coco2017labels-segments.zip', 68 MB
14 | echo 'Downloading' $url$f ' ...'
15 | curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
16 |
17 | # Download/unzip images
18 | d='../coco/images' # unzip directory
19 | url=http://images.cocodataset.org/zips/
20 | f1='train2017.zip' # 19G, 118k images
21 | f2='val2017.zip' # 1G, 5k images
22 | f3='test2017.zip' # 7G, 41k images (optional)
23 | for f in $f1 $f2; do
24 | echo 'Downloading' $url$f '...'
25 | curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & # download, unzip, remove in background
26 | done
27 | wait # finish background tasks
28 |
--------------------------------------------------------------------------------
/utils/aws/resume.py:
--------------------------------------------------------------------------------
1 | # Resume all interrupted trainings in yolov5/ dir including DDP trainings
2 | # Usage: $ python utils/aws/resume.py
3 |
4 | import os
5 | import sys
6 | from pathlib import Path
7 |
8 | import torch
9 | import yaml
10 |
11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories
12 |
13 | port = 0 # --master_port
14 | path = Path('').resolve()
15 | for last in path.rglob('*/**/last.pt'):
16 | ckpt = torch.load(last)
17 | if ckpt['optimizer'] is None:
18 | continue
19 |
20 | # Load opt.yaml
21 | with open(last.parent.parent / 'opt.yaml') as f:
22 | opt = yaml.load(f, Loader=yaml.SafeLoader)
23 |
24 | # Get device count
25 | d = opt['device'].split(',') # devices
26 | nd = len(d) # number of devices
27 | ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel
28 |
29 | if ddp: # multi-GPU
30 | port += 1
31 | cmd = f'python -m torch.distributed.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}'
32 | else: # single-GPU
33 | cmd = f'python train.py --resume {last}'
34 |
35 | cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread
36 | print(cmd)
37 | os.system(cmd)
38 |
--------------------------------------------------------------------------------
/utils/aws/userdata.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
3 | # This script will run only once on first instance start (for a re-start script see mime.sh)
4 | # /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir
5 | # Use >300 GB SSD
6 |
7 | cd home/ubuntu
8 | if [ ! -d yolov5 ]; then
9 | echo "Running first-time script." # install dependencies, download COCO, pull Docker
10 | git clone https://github.com/ultralytics/yolov5 && sudo chmod -R 777 yolov5
11 | cd yolov5
12 | bash data/scripts/get_coco.sh && echo "Data done." &
13 | sudo docker pull ultralytics/yolov5:latest && echo "Docker done." &
14 | python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." &
15 | wait && echo "All tasks done." # finish background tasks
16 | else
17 | echo "Running re-start script." # resume interrupted runs
18 | i=0
19 | list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour'
20 | while IFS= read -r id; do
21 | ((i++))
22 | echo "restarting container $i: $id"
23 | sudo docker start $id
24 | # sudo docker exec -it $id python train.py --resume # single-GPU
25 | sudo docker exec -d $id python utils/aws/resume.py # multi-scenario
26 | done <<<"$list"
27 | fi
28 |
--------------------------------------------------------------------------------
/models/yolov3-tiny.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,14, 23,27, 37,58] # P4/16
9 | - [81,82, 135,169, 344,319] # P5/32
10 |
11 | # YOLOv3-tiny backbone
12 | backbone:
13 | # [from, number, module, args]
14 | [[-1, 1, Conv, [16, 3, 1]], # 0
15 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
16 | [-1, 1, Conv, [32, 3, 1]],
17 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
18 | [-1, 1, Conv, [64, 3, 1]],
19 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
20 | [-1, 1, Conv, [128, 3, 1]],
21 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
22 | [-1, 1, Conv, [256, 3, 1]],
23 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
24 | [-1, 1, Conv, [512, 3, 1]],
25 | [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
26 | [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
27 | ]
28 |
29 | # YOLOv3-tiny head
30 | head:
31 | [[-1, 1, Conv, [1024, 3, 1]],
32 | [-1, 1, Conv, [256, 1, 1]],
33 | [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
34 |
35 | [-2, 1, Conv, [128, 1, 1]],
36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
38 | [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
39 |
40 | [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
41 | ]
42 |
--------------------------------------------------------------------------------
/models/yolov3-tiny-SPPD.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,14, 23,27, 37,58] # P4/16
9 | - [81,82, 135,169, 344,319] # P5/32
10 |
11 | # YOLOv3-tiny backbone
12 | backbone:
13 | # [from, number, module, args]
14 | [[-1, 1, Conv, [16, 3, 1]], # 0
15 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
16 | [-1, 1, Conv, [32, 3, 1]],
17 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
18 | [-1, 1, Conv, [64, 3, 1]],
19 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
20 | [-1, 1, Conv, [128, 3, 1]],
21 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
22 | [-1, 1, Conv, [256, 3, 1]],
23 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
24 | [-1, 1, Conv, [512, 3, 1]],
25 | [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
26 | [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
27 | ]
28 |
29 | # YOLOv3-tiny head
30 | head:
31 | [[-1, 1, Conv, [1024, 3, 1]],
32 | [-1, 1, SPPDilated, [6144]],
33 | [-1, 1, Conv, [256, 1, 1]],
34 | [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
35 |
36 | [-2, 1, Conv, [128, 1, 1]],
37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
39 | [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
40 |
41 | [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
42 | ]
43 |
--------------------------------------------------------------------------------
/models/yolov3-tiny-spp.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,14, 23,27, 37,58] # P4/16
9 | - [81,82, 135,169, 344,319] # P5/32
10 |
11 | # YOLOv3-tiny backbone
12 | backbone:
13 | # [from, number, module, args]
14 | [[-1, 1, Conv, [16, 3, 1]], # 0
15 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
16 | [-1, 1, Conv, [32, 3, 1]],
17 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
18 | [-1, 1, Conv, [64, 3, 1]],
19 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
20 | [-1, 1, Conv, [128, 3, 1]],
21 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
22 | [-1, 1, Conv, [256, 3, 1]],
23 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
24 | [-1, 1, Conv, [512, 3, 1]],
25 | [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
26 | [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
27 | ]
28 |
29 | # YOLOv3-tiny head
30 | head:
31 | [[-1, 1, Conv, [1024, 3, 1]],
32 | [-1, 1, SPP, [512, [5, 9, 13]]],
33 | [-1, 1, Conv, [256, 1, 1]],
34 | [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
35 |
36 | [-2, 1, Conv, [128, 1, 1]],
37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
39 | [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
40 |
41 | [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
42 | ]
43 |
--------------------------------------------------------------------------------
/data/coco128.yaml:
--------------------------------------------------------------------------------
1 | # COCO 2017 dataset http://cocodataset.org - first 128 training images
2 | # Train command: python train.py --data coco128.yaml
3 | # Default dataset location is next to /yolov3:
4 | # /parent_folder
5 | # /coco128
6 | # /yolov3
7 |
8 |
9 | # download command/URL (optional)
10 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train: ../coco128/images/train2017/ # 128 images
14 | val: ../coco128/images/train2017/ # 128 images
15 |
16 | # number of classes
17 | nc: 80
18 |
19 | # class names
20 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
21 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
22 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
23 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
24 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
25 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
26 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
27 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
28 | 'hair drier', 'toothbrush' ]
29 |
--------------------------------------------------------------------------------
/models/yolov3.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [32, 3, 1]], # 0
16 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17 | [-1, 1, Bottleneck, [64]],
18 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19 | [-1, 2, Bottleneck, [128]],
20 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21 | [-1, 8, Bottleneck, [256]],
22 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23 | [-1, 8, Bottleneck, [512]],
24 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25 | [-1, 4, Bottleneck, [1024]], # 10
26 | ]
27 |
28 | # YOLOv3 head
29 | head:
30 | [[-1, 1, Bottleneck, [1024, False]],
31 | [-1, 1, Conv, [512, [1, 1]]],
32 | [-1, 1, Conv, [1024, 3, 1]],
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35 |
36 |
37 | [-2, 1, Conv, [256, 1, 1]],
38 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
40 | [-1, 1, Bottleneck, [512, False]],
41 | [-1, 1, Bottleneck, [512, False]],
42 | [-1, 1, Conv, [256, 1, 1]],
43 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
44 |
45 | [-2, 1, Conv, [128, 1, 1]],
46 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
47 | [[-1, 6], 1, Concat, [1]], # cat backbone P3
48 | [-1, 1, Bottleneck, [256, False]],
49 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
50 |
51 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
52 | ]
53 |
--------------------------------------------------------------------------------
/models/yolov3-spp.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [32, 3, 1]], # 0
16 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17 | [-1, 1, Bottleneck, [64]],
18 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19 | [-1, 2, Bottleneck, [128]],
20 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21 | [-1, 8, Bottleneck, [256]],
22 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23 | [-1, 8, Bottleneck, [512]],
24 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25 | [-1, 4, Bottleneck, [1024]], # 10
26 | ]
27 |
28 | # YOLOv3-SPP head
29 | head:
30 | [[-1, 1, Bottleneck, [1024, False]],
31 | [-1, 1, SPP, [512, [5, 9, 13]]],
32 | [-1, 1, Conv, [1024, 3, 1]],
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35 |
36 | [-2, 1, Conv, [256, 1, 1]],
37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
39 | [-1, 1, Bottleneck, [512, False]],
40 | [-1, 1, Bottleneck, [512, False]],
41 | [-1, 1, Conv, [256, 1, 1]],
42 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43 |
44 | [-2, 1, Conv, [128, 1, 1]],
45 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46 | [[-1, 6], 1, Concat, [1]], # cat backbone P3
47 | [-1, 1, Bottleneck, [256, False]],
48 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49 |
50 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51 | ]
52 |
--------------------------------------------------------------------------------
/data/coco.yaml:
--------------------------------------------------------------------------------
1 | # COCO 2017 dataset http://cocodataset.org
2 | # Train command: python train.py --data coco.yaml
3 | # Default dataset location is next to /yolov3:
4 | # /parent_folder
5 | # /coco
6 | # /yolov3
7 |
8 |
9 | # download command/URL (optional)
10 | download: bash data/scripts/get_coco.sh
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train: ../coco/train2017.txt # 118287 images
14 | val: ../coco/val2017.txt # 5000 images
15 | test: ../coco/test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
16 |
17 | # number of classes
18 | nc: 80
19 |
20 | # class names
21 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
22 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
23 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
24 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
25 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
26 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
27 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
28 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
29 | 'hair drier', 'toothbrush' ]
30 |
31 | # Print classes
32 | # with open('data/coco.yaml') as f:
33 | # d = yaml.load(f, Loader=yaml.FullLoader) # dict
34 | # for i, x in enumerate(d['names']):
35 | # print(i, x)
36 |
--------------------------------------------------------------------------------
/models/LF-YOLO-0.5.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [16, 3, 1]], # 0
16 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
17 | [-1, 1, EFE, [16, 1, 1]],
18 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
19 | [-1, 1, EFE, [32, 1, 1]],
20 | [-1, 1, EFE, [32, 1, 1]],
21 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
22 | [-1, 1, EFE, [64, 1, 1]],
23 | [-1, 1, EFE, [64, 1, 1]],
24 | [-1, 1, EFE, [64, 1, 1]],
25 | [-1, 1, EFE, [64, 1, 1]], # 10
26 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
27 | [-1, 1, EFE, [128, 1, 1]],
28 | [-1, 1, EFE, [128, 1, 1]],
29 | [-1, 1, EFE, [128, 1, 1]],
30 | [-1, 1, EFE, [128, 1, 1]], # 15
31 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
32 | [-1, 1, EFE, [256, 1, 1]],
33 | [-1, 1, EFE, [256, 1, 1]], # 18
34 | ]
35 |
36 | # YOLOv3-SPP head
37 | head:
38 | [[-1, 1, RMF, [1536]],
39 | [-1, 1, Conv, [256, 1, 1]],
40 | [-1, 1, GhostModule, [512]],
41 | [-1, 1, Conv, [128, 1, 1]], # 22 (P5/32-large)
42 |
43 | [-4, 1, Conv, [128, 1, 1]],
44 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
45 | [[-1, 15], 1, Concat, [1]], # cat backbone P4
46 | [-1, 1, Conv, [128, 1, 1]],
47 | [-1, 1, GhostModule, [256]],
48 | [-1, 1, Conv, [128, 1, 1]], # 28 (P4/16-medium)
49 |
50 | [-4, 1, Conv, [64, 1, 1]],
51 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
52 | [[-1, 10], 1, Concat, [1]], # cat backbone P3
53 | [-1, 1, Conv, [64, 1, 1]],
54 | [-1, 1, GhostModule, [128]],
55 | [-1, 1, Conv, [128, 1, 1]], # 34 (P3/8-small)
56 | [[34, 28, 22], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
57 | ]
--------------------------------------------------------------------------------
/models/LF-YOLO-0.75.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [16, 3, 1]], # 0
16 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
17 | [-1, 1, EFE, [24, 1, 1]],
18 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
19 | [-1, 1, EFE, [48, 1, 1]],
20 | [-1, 1, EFE, [48, 1, 1]],
21 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
22 | [-1, 1, EFE, [96, 1, 1]],
23 | [-1, 1, EFE, [96, 1, 1]],
24 | [-1, 1, EFE, [96, 1, 1]],
25 | [-1, 1, EFE, [96, 1, 1]], # 10
26 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
27 | [-1, 1, EFE, [192, 1, 1]],
28 | [-1, 1, EFE, [192, 1, 1]],
29 | [-1, 1, EFE, [192, 1, 1]],
30 | [-1, 1, EFE, [192, 1, 1]], # 15
31 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
32 | [-1, 1, EFE, [384, 1, 1]],
33 | [-1, 1, EFE, [384, 1, 1]], # 18
34 | ]
35 |
36 | # YOLOv3-SPP head
37 | head:
38 | [[-1, 1, RMF, [2304]],
39 | [-1, 1, Conv, [384, 1, 1]],
40 | [-1, 1, GhostModule, [768]],
41 | [-1, 1, Conv, [192, 1, 1]], # 22 (P5/32-large)
42 |
43 | [-4, 1, Conv, [192, 1, 1]],
44 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
45 | [[-1, 15], 1, Concat, [1]], # cat backbone P4
46 | [-1, 1, Conv, [192, 1, 1]],
47 | [-1, 1, GhostModule, [384]],
48 | [-1, 1, Conv, [192, 1, 1]], # 28 (P4/16-medium)
49 |
50 | [-4, 1, Conv, [96, 1, 1]],
51 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
52 | [[-1, 10], 1, Concat, [1]], # cat backbone P3
53 | [-1, 1, Conv, [96, 1, 1]],
54 | [-1, 1, GhostModule, [192]],
55 | [-1, 1, Conv, [192, 1, 1]], # 34 (P3/8-small)
56 | [[34, 28, 22], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
57 | ]
58 |
--------------------------------------------------------------------------------
/models/LF-YOLO.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [16, 3, 1]], # 0
16 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
17 | [-1, 1, EFE, [32, 1, 1]],
18 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
19 | [-1, 1, EFE, [64, 1, 1]],
20 | [-1, 1, EFE, [64, 1, 1]],
21 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
22 | [-1, 1, EFE, [128, 1, 1]],
23 | [-1, 1, EFE, [128, 1, 1]],
24 | [-1, 1, EFE, [128, 1, 1]],
25 | [-1, 1, EFE, [128, 1, 1]], # 10
26 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
27 | [-1, 1, EFE, [256, 1, 1]],
28 | [-1, 1, EFE, [256, 1, 1]],
29 | [-1, 1, EFE, [256, 1, 1]],
30 | [-1, 1, EFE, [256, 1, 1]], # 15
31 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
32 | [-1, 1, EFE, [512, 1, 1]],
33 | [-1, 1, EFE, [512, 1, 1]], # 18
34 | ]
35 |
36 | # YOLOv3-SPP head
37 | head:
38 | [[-1, 1, RMF, [3072]],
39 | [-1, 1, Conv, [512, 1, 1]],
40 | [-1, 1, GhostModule, [1024]],
41 | [-1, 1, Conv, [256, 1, 1]], # 22 (P5/32-large)
42 |
43 | [-4, 1, Conv, [256, 1, 1]],
44 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
45 | [[-1, 15], 1, Concat, [1]], # cat backbone P4
46 | [-1, 1, Conv, [256, 1, 1]],
47 | [-1, 1, GhostModule, [512]],
48 | [-1, 1, Conv, [256, 1, 1]], # 28 (P4/16-medium)
49 |
50 | [-4, 1, Conv, [128, 1, 1]],
51 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
52 | [[-1, 10], 1, Concat, [1]], # cat backbone P3
53 | [-1, 1, Conv, [128, 1, 1]],
54 | [-1, 1, GhostModule, [256]],
55 | [-1, 1, Conv, [256, 1, 1]], # 34 (P3/8-small)
56 | [[34, 28, 22], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
57 | ]
58 |
--------------------------------------------------------------------------------
/models/LF-YOLO-1.25.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [16, 3, 1]], # 0
16 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
17 | [-1, 1, EFE, [40, 1, 1]],
18 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
19 | [-1, 1, EFE, [80, 1, 1]],
20 | [-1, 1, EFE, [80, 1, 1]],
21 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
22 | [-1, 1, EFE, [160, 1, 1]],
23 | [-1, 1, EFE, [160, 1, 1]],
24 | [-1, 1, EFE, [160, 1, 1]],
25 | [-1, 1, EFE, [160, 1, 1]], # 10
26 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
27 | [-1, 1, EFE, [320, 1, 1]],
28 | [-1, 1, EFE, [320, 1, 1]],
29 | [-1, 1, EFE, [320, 1, 1]],
30 | [-1, 1, EFE, [320, 1, 1]], # 15
31 | [-1, 1, nn.MaxPool2d, [3, 2, 1]],
32 | [-1, 1, EFE, [640, 1, 1]],
33 | [-1, 1, EFE, [640, 1, 1]], # 18
34 | ]
35 |
36 | # YOLOv3-SPP head
37 | head:
38 | [[-1, 1, RMF, [3840]],
39 | [-1, 1, Conv, [640, 1, 1]],
40 | [-1, 1, GhostModule, [1280]],
41 | [-1, 1, Conv, [320, 1, 1]], # 22 (P5/32-large)
42 |
43 | [-4, 1, Conv, [320, 1, 1]],
44 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
45 | [[-1, 15], 1, Concat, [1]], # cat backbone P4
46 | [-1, 1, Conv, [320, 1, 1]],
47 | [-1, 1, GhostModule, [640]],
48 | [-1, 1, Conv, [320, 1, 1]], # 28 (P4/16-medium)
49 |
50 | [-4, 1, Conv, [160, 1, 1]],
51 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
52 | [[-1, 10], 1, Concat, [1]], # cat backbone P3
53 | [-1, 1, Conv, [160, 1, 1]],
54 | [-1, 1, GhostModule, [320]],
55 | [-1, 1, Conv, [320, 1, 1]], # 34 (P3/8-small)
56 | [[34, 28, 22], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
57 | ]
58 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch
2 | FROM nvcr.io/nvidia/pytorch:21.03-py3
3 |
4 | # Install linux packages
5 | RUN apt update && apt install -y zip htop screen libgl1-mesa-glx
6 |
7 | # Install python dependencies
8 | COPY requirements.txt .
9 | RUN python -m pip install --upgrade pip
10 | RUN pip uninstall -y nvidia-tensorboard nvidia-tensorboard-plugin-dlprof
11 | RUN pip install --no-cache -r requirements.txt coremltools onnx gsutil notebook
12 |
13 | # Create working directory
14 | RUN mkdir -p /usr/src/app
15 | WORKDIR /usr/src/app
16 |
17 | # Copy contents
18 | COPY . /usr/src/app
19 |
20 | # Set environment variables
21 | ENV HOME=/usr/src/app
22 |
23 |
24 | # --------------------------------------------------- Extras Below ---------------------------------------------------
25 |
26 | # Build and Push
27 | # t=ultralytics/yolov3:latest && sudo docker build -t $t . && sudo docker push $t
28 | # for v in {300..303}; do t=ultralytics/coco:v$v && sudo docker build -t $t . && sudo docker push $t; done
29 |
30 | # Pull and Run
31 | # t=ultralytics/yolov3:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t
32 |
33 | # Pull and Run with local directory access
34 | # t=ultralytics/yolov3:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/coco:/usr/src/coco $t
35 |
36 | # Kill all
37 | # sudo docker kill $(sudo docker ps -q)
38 |
39 | # Kill all image-based
40 | # sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest)
41 |
42 | # Bash into running container
43 | # sudo docker exec -it 5a9b5863d93d bash
44 |
45 | # Bash into stopped container
46 | # id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash
47 |
48 | # Send weights to GCP
49 | # python -c "from utils.general import *; strip_optimizer('runs/train/exp0_*/weights/best.pt', 'tmp.pt')" && gsutil cp tmp.pt gs://*.pt
50 |
51 | # Clean up
52 | # docker system prune -a --volumes
53 |
--------------------------------------------------------------------------------
/data/hyp.scratch.yaml:
--------------------------------------------------------------------------------
1 | # Hyperparameters for COCO training from scratch
2 | # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4 |
5 |
6 | #lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7 | #lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
8 | #momentum: 0.937 # SGD momentum/Adam beta1
9 | #weight_decay: 0.0005 # optimizer weight decay 5e-4
10 | #warmup_epochs: 3.0 # warmup epochs (fractions ok)
11 | #warmup_momentum: 0.8 # warmup initial momentum
12 | #warmup_bias_lr: 0.1 # warmup initial bias lr
13 | #box: 0.05 # box loss gain
14 | #cls: 0.5 # cls loss gain
15 | #cls_pw: 1.0 # cls BCELoss positive_weight
16 | #obj: 1.0 # obj loss gain (scale with pixels)
17 | #obj_pw: 1.0 # obj BCELoss positive_weight
18 | #iou_t: 0.20 # IoU training threshold
19 | #anchor_t: 4.0 # anchor-multiple threshold
20 | ## anchors: 3 # anchors per output layer (0 to ignore)
21 | #fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
22 | #hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
23 | #hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
24 | #hsv_v: 0.4 # image HSV-Value augmentation (fraction)
25 | #degrees: 0.0 # image rotation (+/- deg)
26 | #translate: 0.0 # image translation (+/- fraction)
27 | #scale: 0.0 # image scale (+/- gain)
28 | #shear: 0.0 # image shear (+/- deg)
29 | #perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
30 | #flipud: 0.0 # image flip up-down (probability)
31 | #fliplr: 0.0 # image flip left-right (probability)
32 | #mosaic: 0.5 # image mosaic (probability)
33 | #mixup: 0.0 # image mixup (probability)
34 |
35 | lr0: 0.01
36 | lrf: 0.2
37 | momentum: 0.937
38 | weight_decay: 0.0005
39 | warmup_epochs: 3.0
40 | warmup_momentum: 0.8
41 | warmup_bias_lr: 0.1
42 | box: 0.05
43 | cls: 0.5
44 | cls_pw: 1.0
45 | obj: 1.0
46 | obj_pw: 1.0
47 | iou_t: 0.2
48 | anchor_t: 4.0
49 | fl_gamma: 0.0
50 | hsv_h: 0.015
51 | hsv_s: 0.7
52 | hsv_v: 0.4
53 | degrees: 0.0
54 | translate: 0.1
55 | scale: 0.5
56 | shear: 0.0
57 | perspective: 0.0
58 | flipud: 0.0
59 | fliplr: 0.0
60 | mosaic: 1.0
61 | mixup: 0.0
62 |
--------------------------------------------------------------------------------
/data/scripts/get_argoverse_hd.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/
3 | # Download command: bash data/scripts/get_argoverse_hd.sh
4 | # Train command: python train.py --data argoverse_hd.yaml
5 | # Default dataset location is next to /yolov5:
6 | # /parent_folder
7 | # /argoverse
8 | # /yolov5
9 |
10 | # Download/unzip images
11 | d='../argoverse/' # unzip directory
12 | mkdir $d
13 | url=https://argoverse-hd.s3.us-east-2.amazonaws.com/
14 | f=Argoverse-HD-Full.zip
15 | curl -L $url$f -o $f && unzip -q $f -d $d && rm $f download, unzip, remove in background
16 | wait # finish background tasks
17 |
18 | cd ../argoverse/Argoverse-1.1/
19 | ln -s tracking images
20 |
21 | cd ../Argoverse-HD/annotations/
22 |
23 | python3 - "$@" <train.txt
82 | cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt >train.all.txt
83 |
84 | python3 - "$@" < 1E6 # check
41 | except Exception as e: # GCP
42 | print(f'Download error: {e}')
43 | assert redundant, 'No secondary mirror'
44 | url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'
45 | print(f'Downloading {url} to {file}...')
46 | os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)
47 | finally:
48 | if not file.exists() or file.stat().st_size < 1E6: # check
49 | file.unlink(missing_ok=True) # remove partial downloads
50 | print(f'ERROR: Download failure: {msg}')
51 | print('')
52 | return
53 |
54 |
55 | def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
56 | # Downloads a file from Google Drive. from yolov3.utils.google_utils import *; gdrive_download()
57 | t = time.time()
58 | file = Path(file)
59 | cookie = Path('cookie') # gdrive cookie
60 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
61 | file.unlink(missing_ok=True) # remove existing file
62 | cookie.unlink(missing_ok=True) # remove existing cookie
63 |
64 | # Attempt file download
65 | out = "NUL" if platform.system() == "Windows" else "/dev/null"
66 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
67 | if os.path.exists('cookie'): # large file
68 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
69 | else: # small file
70 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
71 | r = os.system(s) # execute, capture return
72 | cookie.unlink(missing_ok=True) # remove existing cookie
73 |
74 | # Error check
75 | if r != 0:
76 | file.unlink(missing_ok=True) # remove partial
77 | print('Download error ') # raise Exception('Download error')
78 | return r
79 |
80 | # Unzip if archive
81 | if file.suffix == '.zip':
82 | print('unzipping... ', end='')
83 | os.system(f'unzip -q {file}') # unzip
84 | file.unlink() # remove zip to free space
85 |
86 | print(f'Done ({time.time() - t:.1f}s)')
87 | return r
88 |
89 |
90 | def get_token(cookie="./cookie"):
91 | with open(cookie) as f:
92 | for line in f:
93 | if "download" in line:
94 | return line.split()[-1]
95 | return ""
96 |
97 | # def upload_blob(bucket_name, source_file_name, destination_blob_name):
98 | # # Uploads a file to a bucket
99 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
100 | #
101 | # storage_client = storage.Client()
102 | # bucket = storage_client.get_bucket(bucket_name)
103 | # blob = bucket.blob(destination_blob_name)
104 | #
105 | # blob.upload_from_filename(source_file_name)
106 | #
107 | # print('File {} uploaded to {}.'.format(
108 | # source_file_name,
109 | # destination_blob_name))
110 | #
111 | #
112 | # def download_blob(bucket_name, source_blob_name, destination_file_name):
113 | # # Uploads a blob from a bucket
114 | # storage_client = storage.Client()
115 | # bucket = storage_client.get_bucket(bucket_name)
116 | # blob = bucket.blob(source_blob_name)
117 | #
118 | # blob.download_to_filename(destination_file_name)
119 | #
120 | # print('Blob {} downloaded to {}.'.format(
121 | # source_blob_name,
122 | # destination_file_name))
123 |
--------------------------------------------------------------------------------
/models/experimental.py:
--------------------------------------------------------------------------------
1 | # YOLOv3 experimental modules
2 |
3 | import numpy as np
4 | import torch
5 | import torch.nn as nn
6 |
7 | from models.common import Conv, DWConv
8 | from utils.google_utils import attempt_download
9 |
10 |
11 | class CrossConv(nn.Module):
12 | # Cross Convolution Downsample
13 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
14 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
15 | super(CrossConv, self).__init__()
16 | c_ = int(c2 * e) # hidden channels
17 | self.cv1 = Conv(c1, c_, (1, k), (1, s))
18 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
19 | self.add = shortcut and c1 == c2
20 |
21 | def forward(self, x):
22 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
23 |
24 |
25 | class Sum(nn.Module):
26 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
27 | def __init__(self, n, weight=False): # n: number of inputs
28 | super(Sum, self).__init__()
29 | self.weight = weight # apply weights boolean
30 | self.iter = range(n - 1) # iter object
31 | if weight:
32 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
33 |
34 | def forward(self, x):
35 | y = x[0] # no weight
36 | if self.weight:
37 | w = torch.sigmoid(self.w) * 2
38 | for i in self.iter:
39 | y = y + x[i + 1] * w[i]
40 | else:
41 | for i in self.iter:
42 | y = y + x[i + 1]
43 | return y
44 |
45 |
46 | class GhostConv(nn.Module):
47 | # Ghost Convolution https://github.com/huawei-noah/ghostnet
48 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
49 | super(GhostConv, self).__init__()
50 | c_ = c2 // 2 # hidden channels
51 | self.cv1 = Conv(c1, c_, k, s, None, g, act)
52 | self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
53 |
54 | def forward(self, x):
55 | y = self.cv1(x)
56 | return torch.cat([y, self.cv2(y)], 1)
57 |
58 |
59 | class GhostBottleneck(nn.Module):
60 | # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
61 | def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
62 | super(GhostBottleneck, self).__init__()
63 | c_ = c2 // 2
64 | self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
65 | DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
66 | GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
67 | self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
68 | Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
69 |
70 | def forward(self, x):
71 | return self.conv(x) + self.shortcut(x)
72 |
73 |
74 | class MixConv2d(nn.Module):
75 | # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
76 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
77 | super(MixConv2d, self).__init__()
78 | groups = len(k)
79 | if equal_ch: # equal c_ per group
80 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
81 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
82 | else: # equal weight.numel() per group
83 | b = [c2] + [0] * groups
84 | a = np.eye(groups + 1, groups, k=-1)
85 | a -= np.roll(a, 1, axis=1)
86 | a *= np.array(k) ** 2
87 | a[0] = 1
88 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
89 |
90 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
91 | self.bn = nn.BatchNorm2d(c2)
92 | self.act = nn.LeakyReLU(0.1, inplace=True)
93 |
94 | def forward(self, x):
95 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
96 |
97 |
98 | class Ensemble(nn.ModuleList):
99 | # Ensemble of models
100 | def __init__(self):
101 | super(Ensemble, self).__init__()
102 |
103 | def forward(self, x, augment=False):
104 | y = []
105 | for module in self:
106 | y.append(module(x, augment)[0])
107 | # y = torch.stack(y).max(0)[0] # max ensemble
108 | # y = torch.stack(y).mean(0) # mean ensemble
109 | y = torch.cat(y, 1) # nms ensemble
110 | return y, None # inference, train output
111 |
112 |
113 | def attempt_load(weights, map_location=None):
114 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
115 | model = Ensemble()
116 | for w in weights if isinstance(weights, list) else [weights]:
117 | attempt_download(w)
118 | ckpt = torch.load(w, map_location=map_location) # load
119 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
120 |
121 | # Compatibility updates
122 | for m in model.modules():
123 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
124 | m.inplace = True # pytorch 1.7.0 compatibility
125 | elif type(m) is Conv:
126 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
127 |
128 | if len(model) == 1:
129 | return model[-1] # return model
130 | else:
131 | print('Ensemble created with %s\n' % weights)
132 | for k in ['names', 'stride']:
133 | setattr(model, k, getattr(model[-1], k))
134 | return model # return ensemble
135 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This project is based on [ultralytics/yolov3](https://github.com/ultralytics/yolov3).
2 |
3 | LF-YOLO (Lighter and Faster YOLO) is used to detect defect of X-ray weld image. The related paper is available [here](https://ieeexplore.ieee.org/document/10054502).
4 |
5 |
6 |
7 | ## Download
8 |
9 | ```download
10 | $ git clone https://github.com/lmomoy/LF-YOLO
11 | ```
12 | ## Train
13 | We provide multiple versions of LF-YOLO with different widths.
14 |
15 | ```train
16 | $ python train.py --data coco.yaml --cfg LF-YOLO.yaml --weights '' --batch-size 1
17 | LF-YOLO-1.25.yaml 1
18 | LF-YOLO-0.75.yaml 1
19 | LF-YOLO-0.5.yaml 1
20 | ```
21 |
22 | ## Results
23 | We test LF-YOLO on our weld defect image dataset. Other methods are trained and tested based on [MMDetection](https://github.com/open-mmlab/mmdetection).
24 |
25 | Model |size (pixels) |mAP50test
|params (M) |FLOPS (B)
26 | --- |--- |--- |--- |---
27 | Cascasde-RCNN (ResNet50) |(1333, 800) |90.0 |68.9 |243.2
28 | Cascasde-RCNN (ResNet101) |(1333, 800) |90.7 |87.9 |323.1
29 | Faster-RCNN (ResNet50) |(1333, 800) |90.1 |41.1 |215.4
30 | Faster-RCNN (ResNet101) |(1333, 800) |92.2 |60.1 |295.3
31 | Dynamic-RCNN (ResNet50) |(1333, 800) |90.3 |41.1 |215.4
32 | RetinaNet (ResNet50) |(1333, 800) |80.0 |36.2 |205.2
33 | VFNet (ResNet50) |(1333, 800) |87.0 |32.5 |197.8
34 | VFNet (ResNet101) |(1333, 800) |87.2 |51.5 |277.7
35 | Reppoints (ResNet101) |(1333, 800) |82.7 |36.6 |199.0
36 | SSD300 (VGGNet) |300 |88.1 |24.0 |30.6
37 | YOLOv3 (Darknet52) |416 |91.0 |62.0 |33.1
38 | SSD (MobileNet v2) |320 |82.3 |3.1 |0.7
39 | YOLOv3 (MobileNet v2) |320 |90.2 |3.7 |1.6
40 | LF-YOLO-0.5 |320 |90.7 |1.8 |1.1
41 | LF-YOLO |320 |92.9 |7.3 |4.0
42 |
43 |
44 | We test our model on public dataset MS COCO, and it also achieves competitive results.
45 |
46 | Model |size (pixels) |mAP50test
|params (M) |FLOPS (B)
47 | --- |--- |--- |--- |---
48 | YOLOv3-tiny |640 |34.8 |8.8 |13.2
49 | YOLOv3 |320 |51.5 |39.0 |61.9
50 | SSD |300 |41.2 |35.2 |34.3
51 | SSD |512 |46.5 |99.5 |34.3
52 | Faster R-CNN (VGG16) |shorter size: 800 |43.9 |- |278.0
53 | R-FCN (ResNet50) |shorter size: 800 |49.0 |- |133.0
54 | R-FCN (ResNet101) |shorter size: 800 |52.9 |- |206.0
55 | LF-YOLO |640 |47.8 |7.4 |17.1
56 |
57 |
58 |
59 |
60 | [comment]: <> ()
61 |
62 | [comment]: <> ( Table Notes (click to expand)
)
63 |
64 | [comment]: <> ( * APtest denotes COCO [test-dev2017](http://cocodataset.org/#upload) server results, all other AP results denote val2017 accuracy. )
65 |
66 | [comment]: <> ( * AP values are for single-model single-scale unless otherwise noted. **Reproduce mAP** by `python test.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65` )
67 |
68 | [comment]: <> ( * SpeedGPU averaged over 5000 COCO val2017 images using a GCP [n1-standard-16](https://cloud.google.com/compute/docs/machine-types#n1_standard_machine_types) V100 instance, and includes FP16 inference, postprocessing and NMS. **Reproduce speed** by `python test.py --data coco.yaml --img 640 --conf 0.25 --iou 0.45` )
69 |
70 | [comment]: <> ( * All checkpoints are trained to 300 epochs with default settings and hyperparameters (no autoaugmentation). )
71 |
72 | [comment]: <> ( )
73 |
74 |
75 | ## Requirements
76 |
77 | Python 3.8 or later with all [requirements.txt](https://github.com/ultralytics/yolov3/blob/master/requirements.txt) dependencies installed, including `torch>=1.7`. To install run:
78 | ```bash
79 | $ pip install -r requirements.txt
80 | ```
81 | ## Inference
82 | ```bash
83 | $ python detect.py --source data/images --weights LF-YOLO.pt --conf 0.25
84 | ```
85 |
86 | ## Citation
87 | Please consider citing my work as follows if it is helpful for you.
88 | ```
89 | @article{liu2023lf,
90 | title={LF-YOLO: A lighter and faster yolo for weld defect detection of X-ray image},
91 | author={Liu, Moyun and Chen, Youping and Xie, Jingming and He, Lei and Zhang, Yang},
92 | journal={IEEE Sensors Journal},
93 | volume={23},
94 | number={7},
95 | pages={7430--7439},
96 | year={2023},
97 | publisher={IEEE}
98 | }
99 |
100 | @article{liu2021lf,
101 | title={LF-YOLO: A Lighter and Faster YOLO for Weld Defect Detection of X-ray Image},
102 | author={Liu, Moyun and Chen, Youping and He, Lei and Zhang, Yang and Xie, Jingming},
103 | journal={arXiv preprint arXiv:2110.15045},
104 | year={2021}
105 | }
106 | ```
107 |
108 |
--------------------------------------------------------------------------------
/utils/autoanchor.py:
--------------------------------------------------------------------------------
1 | # Auto-anchor utils
2 |
3 | import numpy as np
4 | import torch
5 | import yaml
6 | from scipy.cluster.vq import kmeans
7 | from tqdm import tqdm
8 |
9 | from utils.general import colorstr
10 |
11 |
12 | def check_anchor_order(m):
13 | # Check anchor order against stride order for YOLOv3 Detect() module m, and correct if necessary
14 | a = m.anchor_grid.prod(-1).view(-1) # anchor area
15 | da = a[-1] - a[0] # delta a
16 | ds = m.stride[-1] - m.stride[0] # delta s
17 | if da.sign() != ds.sign(): # same order
18 | print('Reversing anchor order')
19 | m.anchors[:] = m.anchors.flip(0)
20 | m.anchor_grid[:] = m.anchor_grid.flip(0)
21 |
22 |
23 | def check_anchors(dataset, model, thr=4.0, imgsz=640):
24 | # Check anchor fit to data, recompute if necessary
25 | prefix = colorstr('autoanchor: ')
26 | print(f'\n{prefix}Analyzing anchors... ', end='')
27 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
28 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
29 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
30 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
31 |
32 | def metric(k): # compute metric
33 | r = wh[:, None] / k[None]
34 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
35 | best = x.max(1)[0] # best_x
36 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
37 | bpr = (best > 1. / thr).float().mean() # best possible recall
38 | return bpr, aat
39 |
40 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
41 | bpr, aat = metric(anchors)
42 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
43 | if bpr < 0.98: # threshold to recompute
44 | print('. Attempting to improve anchors, please wait...')
45 | na = m.anchor_grid.numel() // 2 # number of anchors
46 | try:
47 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
48 | except Exception as e:
49 | print(f'{prefix}ERROR: {e}')
50 | new_bpr = metric(anchors)[0]
51 | if new_bpr > bpr: # replace anchors
52 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
53 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
54 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
55 | check_anchor_order(m)
56 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
57 | else:
58 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
59 | print('') # newline
60 |
61 |
62 | def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
63 | """ Creates kmeans-evolved anchors from training dataset
64 |
65 | Arguments:
66 | path: path to dataset *.yaml, or a loaded dataset
67 | n: number of anchors
68 | img_size: image size used for training
69 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
70 | gen: generations to evolve anchors using genetic algorithm
71 | verbose: print all results
72 |
73 | Return:
74 | k: kmeans evolved anchors
75 |
76 | Usage:
77 | from utils.autoanchor import *; _ = kmean_anchors()
78 | """
79 | thr = 1. / thr
80 | prefix = colorstr('autoanchor: ')
81 |
82 | def metric(k, wh): # compute metrics
83 | r = wh[:, None] / k[None]
84 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
85 | # x = wh_iou(wh, torch.tensor(k)) # iou metric
86 | return x, x.max(1)[0] # x, best_x
87 |
88 | def anchor_fitness(k): # mutation fitness
89 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
90 | return (best * (best > thr).float()).mean() # fitness
91 |
92 | def print_results(k):
93 | k = k[np.argsort(k.prod(1))] # sort small to large
94 | x, best = metric(k, wh0)
95 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
96 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
97 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
98 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
99 | for i, x in enumerate(k):
100 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
101 | return k
102 |
103 | if isinstance(path, str): # *.yaml file
104 | with open(path) as f:
105 | data_dict = yaml.load(f, Loader=yaml.SafeLoader) # model dict
106 | from utils.datasets import LoadImagesAndLabels
107 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
108 | else:
109 | dataset = path # dataset
110 |
111 | # Get label wh
112 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
113 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
114 |
115 | # Filter
116 | i = (wh0 < 3.0).any(1).sum()
117 | if i:
118 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
119 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
120 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
121 |
122 | # Kmeans calculation
123 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
124 | s = wh.std(0) # sigmas for whitening
125 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
126 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
127 | k *= s
128 | wh = torch.tensor(wh, dtype=torch.float32) # filtered
129 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
130 | k = print_results(k)
131 |
132 | # Plot
133 | # k, d = [None] * 20, [None] * 20
134 | # for i in tqdm(range(1, 21)):
135 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
136 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
137 | # ax = ax.ravel()
138 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
139 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
140 | # ax[0].hist(wh[wh[:, 0]<100, 0],400)
141 | # ax[1].hist(wh[wh[:, 1]<100, 1],400)
142 | # fig.savefig('wh.png', dpi=200)
143 |
144 | # Evolve
145 | npr = np.random
146 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
147 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar
148 | for _ in pbar:
149 | v = np.ones(sh)
150 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
151 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
152 | kg = (k.copy() * v).clip(min=2.0)
153 | fg = anchor_fitness(kg)
154 | if fg > f:
155 | f, k = fg, kg.copy()
156 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
157 | if verbose:
158 | print_results(k)
159 |
160 | return print_results(k)
161 |
--------------------------------------------------------------------------------
/utils/metrics.py:
--------------------------------------------------------------------------------
1 | # Model validation metrics
2 |
3 | from pathlib import Path
4 |
5 | import matplotlib.pyplot as plt
6 | import numpy as np
7 | import torch
8 |
9 | from . import general
10 |
11 |
12 | def fitness(x):
13 | # Model fitness as a weighted combination of metrics
14 | w = [0.0, 0.0, 1.0, 0.0] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
15 | return (x[:, :4] * w).sum(1)
16 |
17 |
18 | def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()):
19 | """ Compute the average precision, given the recall and precision curves.
20 | Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
21 | # Arguments
22 | tp: True positives (nparray, nx1 or nx10).
23 | conf: Objectness value from 0-1 (nparray).
24 | pred_cls: Predicted object classes (nparray).
25 | target_cls: True object classes (nparray).
26 | plot: Plot precision-recall curve at mAP@0.5
27 | save_dir: Plot save directory
28 | # Returns
29 | The average precision as computed in py-faster-rcnn.
30 | """
31 |
32 | # Sort by objectness
33 | i = np.argsort(-conf)
34 | tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
35 |
36 | # Find unique classes
37 | unique_classes = np.unique(target_cls)
38 | nc = unique_classes.shape[0] # number of classes, number of detections
39 |
40 | # Create Precision-Recall curve and compute AP for each class
41 | px, py = np.linspace(0, 1, 1000), [] # for plotting
42 | ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
43 | for ci, c in enumerate(unique_classes):
44 | i = pred_cls == c
45 | n_l = (target_cls == c).sum() # number of labels
46 | n_p = i.sum() # number of predictions
47 |
48 | if n_p == 0 or n_l == 0:
49 | continue
50 | else:
51 | # Accumulate FPs and TPs
52 | fpc = (1 - tp[i]).cumsum(0)
53 | tpc = tp[i].cumsum(0)
54 |
55 | # Recall
56 | recall = tpc / (n_l + 1e-16) # recall curve
57 | r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
58 |
59 | # Precision
60 | precision = tpc / (tpc + fpc) # precision curve
61 | p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
62 |
63 | # AP from recall-precision curve
64 | for j in range(tp.shape[1]):
65 | ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
66 | if plot and j == 0:
67 | py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
68 |
69 | # Compute F1 (harmonic mean of precision and recall)
70 | f1 = 2 * p * r / (p + r + 1e-16)
71 | if plot:
72 | plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
73 | plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
74 | plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
75 | plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
76 |
77 | i = f1.mean(0).argmax() # max F1 index
78 | return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
79 |
80 |
81 | def compute_ap(recall, precision):
82 | """ Compute the average precision, given the recall and precision curves
83 | # Arguments
84 | recall: The recall curve (list)
85 | precision: The precision curve (list)
86 | # Returns
87 | Average precision, precision curve, recall curve
88 | """
89 |
90 | # Append sentinel values to beginning and end
91 | mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))
92 | mpre = np.concatenate(([1.], precision, [0.]))
93 |
94 | # Compute the precision envelope
95 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
96 |
97 | # Integrate area under curve
98 | method = 'interp' # methods: 'continuous', 'interp'
99 | if method == 'interp':
100 | x = np.linspace(0, 1, 101) # 101-point interp (COCO)
101 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
102 | else: # 'continuous'
103 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
104 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
105 |
106 | return ap, mpre, mrec
107 |
108 |
109 | class ConfusionMatrix:
110 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
111 | def __init__(self, nc, conf=0.25, iou_thres=0.45):
112 | self.matrix = np.zeros((nc + 1, nc + 1))
113 | self.nc = nc # number of classes
114 | self.conf = conf
115 | self.iou_thres = iou_thres
116 |
117 | def process_batch(self, detections, labels):
118 | """
119 | Return intersection-over-union (Jaccard index) of boxes.
120 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
121 | Arguments:
122 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class
123 | labels (Array[M, 5]), class, x1, y1, x2, y2
124 | Returns:
125 | None, updates confusion matrix accordingly
126 | """
127 | detections = detections[detections[:, 4] > self.conf]
128 | gt_classes = labels[:, 0].int()
129 | detection_classes = detections[:, 5].int()
130 | iou = general.box_iou(labels[:, 1:], detections[:, :4])
131 |
132 | x = torch.where(iou > self.iou_thres)
133 | if x[0].shape[0]:
134 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
135 | if x[0].shape[0] > 1:
136 | matches = matches[matches[:, 2].argsort()[::-1]]
137 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
138 | matches = matches[matches[:, 2].argsort()[::-1]]
139 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
140 | else:
141 | matches = np.zeros((0, 3))
142 |
143 | n = matches.shape[0] > 0
144 | m0, m1, _ = matches.transpose().astype(np.int16)
145 | for i, gc in enumerate(gt_classes):
146 | j = m0 == i
147 | if n and sum(j) == 1:
148 | self.matrix[gc, detection_classes[m1[j]]] += 1 # correct
149 | else:
150 | self.matrix[self.nc, gc] += 1 # background FP
151 |
152 | if n:
153 | for i, dc in enumerate(detection_classes):
154 | if not any(m1 == i):
155 | self.matrix[dc, self.nc] += 1 # background FN
156 |
157 | def matrix(self):
158 | return self.matrix
159 |
160 | def plot(self, save_dir='', names=()):
161 | try:
162 | import seaborn as sn
163 |
164 | array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize
165 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
166 |
167 | fig = plt.figure(figsize=(12, 9), tight_layout=True)
168 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
169 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
170 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
171 | xticklabels=names + ['background FP'] if labels else "auto",
172 | yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
173 | fig.axes[0].set_xlabel('True')
174 | fig.axes[0].set_ylabel('Predicted')
175 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
176 | except Exception as e:
177 | pass
178 |
179 | def print(self):
180 | for i in range(self.nc + 1):
181 | print(' '.join(map(str, self.matrix[i])))
182 |
183 |
184 | # Plots ----------------------------------------------------------------------------------------------------------------
185 |
186 | def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
187 | # Precision-recall curve
188 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
189 | py = np.stack(py, axis=1)
190 |
191 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
192 | for i, y in enumerate(py.T):
193 | ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
194 | else:
195 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
196 |
197 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
198 | ax.set_xlabel('Recall')
199 | ax.set_ylabel('Precision')
200 | ax.set_xlim(0, 1)
201 | ax.set_ylim(0, 1)
202 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
203 | fig.savefig(Path(save_dir), dpi=250)
204 |
205 |
206 | def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
207 | # Metric-confidence curve
208 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
209 |
210 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
211 | for i, y in enumerate(py):
212 | ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
213 | else:
214 | ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
215 |
216 | y = py.mean(0)
217 | ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
218 | ax.set_xlabel(xlabel)
219 | ax.set_ylabel(ylabel)
220 | ax.set_xlim(0, 1)
221 | ax.set_ylim(0, 1)
222 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
223 | fig.savefig(Path(save_dir), dpi=250)
224 |
--------------------------------------------------------------------------------
/utils/loss.py:
--------------------------------------------------------------------------------
1 | # Loss functions
2 |
3 | import torch
4 | import torch.nn as nn
5 |
6 | from utils.general import bbox_iou
7 | from utils.torch_utils import is_parallel
8 |
9 |
10 | def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
11 | # return positive, negative label smoothing BCE targets
12 | return 1.0 - 0.5 * eps, 0.5 * eps
13 |
14 |
15 | class BCEBlurWithLogitsLoss(nn.Module):
16 | # BCEwithLogitLoss() with reduced missing label effects.
17 | def __init__(self, alpha=0.05):
18 | super(BCEBlurWithLogitsLoss, self).__init__()
19 | self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
20 | self.alpha = alpha
21 |
22 | def forward(self, pred, true):
23 | loss = self.loss_fcn(pred, true)
24 | pred = torch.sigmoid(pred) # prob from logits
25 | dx = pred - true # reduce only missing label effects
26 | # dx = (pred - true).abs() # reduce missing label and false label effects
27 | alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
28 | loss *= alpha_factor
29 | return loss.mean()
30 |
31 |
32 | class FocalLoss(nn.Module):
33 | # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
34 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
35 | super(FocalLoss, self).__init__()
36 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
37 | self.gamma = gamma
38 | self.alpha = alpha
39 | self.reduction = loss_fcn.reduction
40 | self.loss_fcn.reduction = 'none' # required to apply FL to each element
41 |
42 | def forward(self, pred, true):
43 | loss = self.loss_fcn(pred, true)
44 | # p_t = torch.exp(-loss)
45 | # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
46 |
47 | # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
48 | pred_prob = torch.sigmoid(pred) # prob from logits
49 | p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
50 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
51 | modulating_factor = (1.0 - p_t) ** self.gamma
52 | loss *= alpha_factor * modulating_factor
53 |
54 | if self.reduction == 'mean':
55 | return loss.mean()
56 | elif self.reduction == 'sum':
57 | return loss.sum()
58 | else: # 'none'
59 | return loss
60 |
61 |
62 | class QFocalLoss(nn.Module):
63 | # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
64 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
65 | super(QFocalLoss, self).__init__()
66 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
67 | self.gamma = gamma
68 | self.alpha = alpha
69 | self.reduction = loss_fcn.reduction
70 | self.loss_fcn.reduction = 'none' # required to apply FL to each element
71 |
72 | def forward(self, pred, true):
73 | loss = self.loss_fcn(pred, true)
74 |
75 | pred_prob = torch.sigmoid(pred) # prob from logits
76 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
77 | modulating_factor = torch.abs(true - pred_prob) ** self.gamma
78 | loss *= alpha_factor * modulating_factor
79 |
80 | if self.reduction == 'mean':
81 | return loss.mean()
82 | elif self.reduction == 'sum':
83 | return loss.sum()
84 | else: # 'none'
85 | return loss
86 |
87 |
88 | class ComputeLoss:
89 | # Compute losses
90 | def __init__(self, model, autobalance=False):
91 | super(ComputeLoss, self).__init__()
92 | device = next(model.parameters()).device # get model device
93 | h = model.hyp # hyperparameters
94 |
95 | # Define criteria
96 | BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
97 | BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
98 |
99 | # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
100 | self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
101 |
102 | # Focal loss
103 | g = h['fl_gamma'] # focal loss gamma
104 | if g > 0:
105 | BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
106 |
107 | det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
108 | self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
109 | self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
110 | self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
111 | for k in 'na', 'nc', 'nl', 'anchors':
112 | setattr(self, k, getattr(det, k))
113 |
114 | def __call__(self, p, targets): # predictions, targets, model
115 | device = targets.device
116 | lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
117 | tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
118 |
119 | # Losses
120 | for i, pi in enumerate(p): # layer index, layer predictions
121 | b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
122 | tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
123 |
124 | n = b.shape[0] # number of targets
125 | if n:
126 | ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
127 |
128 | # Regression
129 | pxy = ps[:, :2].sigmoid() * 2. - 0.5
130 | pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
131 | pbox = torch.cat((pxy, pwh), 1) # predicted box
132 | iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
133 | lbox += (1.0 - iou).mean() # iou loss
134 |
135 | # Objectness
136 | tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
137 |
138 | # Classification
139 | if self.nc > 1: # cls loss (only if multiple classes)
140 | t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
141 | t[range(n), tcls[i]] = self.cp
142 | lcls += self.BCEcls(ps[:, 5:], t) # BCE
143 |
144 | # Append targets to text file
145 | # with open('targets.txt', 'a') as file:
146 | # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
147 |
148 | obji = self.BCEobj(pi[..., 4], tobj)
149 | lobj += obji * self.balance[i] # obj loss
150 | if self.autobalance:
151 | self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
152 |
153 | if self.autobalance:
154 | self.balance = [x / self.balance[self.ssi] for x in self.balance]
155 | lbox *= self.hyp['box']
156 | lobj *= self.hyp['obj']
157 | lcls *= self.hyp['cls']
158 | bs = tobj.shape[0] # batch size
159 |
160 | loss = lbox + lobj + lcls
161 | return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
162 |
163 | def build_targets(self, p, targets):
164 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
165 | na, nt = self.na, targets.shape[0] # number of anchors, targets
166 | tcls, tbox, indices, anch = [], [], [], []
167 | gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
168 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
169 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
170 |
171 | g = 0.5 # bias
172 | off = torch.tensor([[0, 0],
173 | # [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
174 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
175 | ], device=targets.device).float() * g # offsets
176 |
177 | for i in range(self.nl):
178 | anchors = self.anchors[i]
179 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
180 |
181 | # Match targets to anchors
182 | t = targets * gain
183 | if nt:
184 | # Matches
185 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio
186 | j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
187 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
188 | t = t[j] # filter
189 |
190 | # Offsets
191 | gxy = t[:, 2:4] # grid xy
192 | gxi = gain[[2, 3]] - gxy # inverse
193 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T
194 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T
195 | j = torch.stack((torch.ones_like(j),))
196 | t = t.repeat((off.shape[0], 1, 1))[j]
197 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
198 | else:
199 | t = targets[0]
200 | offsets = 0
201 |
202 | # Define
203 | b, c = t[:, :2].long().T # image, class
204 | gxy = t[:, 2:4] # grid xy
205 | gwh = t[:, 4:6] # grid wh
206 | gij = (gxy - offsets).long()
207 | gi, gj = gij.T # grid xy indices
208 |
209 | # Append
210 | a = t[:, 6].long() # anchor indices
211 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
212 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
213 | anch.append(anchors[a]) # anchors
214 | tcls.append(c) # class
215 |
216 | return tcls, tbox, indices, anch
217 |
--------------------------------------------------------------------------------
/detect.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import time
3 | from pathlib import Path
4 |
5 | import cv2
6 | import torch
7 | import torch.backends.cudnn as cudnn
8 | from numpy import random
9 |
10 | from models.experimental import attempt_load
11 | from utils.datasets import LoadStreams, LoadImages
12 | from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
13 | scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
14 | from utils.plots import plot_one_box
15 | from utils.torch_utils import select_device, load_classifier, time_synchronized
16 |
17 | import os
18 | import numpy as np
19 |
20 |
21 | def make_dirs(path):
22 | if os.path.exists(path) is False:
23 | os.makedirs(path)
24 |
25 |
26 | def feature_map(intermediate_features, imgname):
27 | dst = 'features+/'
28 | therd_size = 320
29 | index = 0
30 | for layer, j in intermediate_features.items():
31 | index += 1
32 | layer = str(index)
33 | features = j[0]
34 | iter_range = features.shape[0]
35 |
36 | resolution = j.shape[2]
37 |
38 | add_img = np.zeros(((resolution, resolution, 3)))
39 | for i in range(iter_range):
40 |
41 | channel = iter_range
42 | # plt.imshow(x[0].data.numpy()[0,i,:,:],cmap='jet')
43 |
44 | feature = features.data.cpu().numpy()
45 | feature_img = feature[i, :, :]
46 | feature_img = np.asarray(feature_img * 255, dtype=np.uint8)
47 |
48 | dst_path = os.path.join(dst, imgname)
49 |
50 | make_dirs(dst_path)
51 | feature_img = cv2.applyColorMap(feature_img, cv2.COLORMAP_JET)
52 | if feature_img.shape[0] < therd_size:
53 | dst_file = os.path.join(dst_path, str(layer) + '/')
54 | make_dirs(dst_file)
55 | dst_file = os.path.join(dst_file, str(i) + '.png')
56 | cv2.imwrite(dst_file, feature_img)
57 |
58 | tmp_file = os.path.join(dst_path, str(layer) + '/')
59 | make_dirs(tmp_file)
60 | tmp_file = os.path.join(tmp_file, str(i) + '_' + str(therd_size) + '.png')
61 | tmp_img = feature_img.copy()
62 | # tmp_img = cv2.resize(tmp_img, (therd_size, therd_size), interpolation=cv2.INTER_NEAREST)
63 | add_img = tmp_img/channel + add_img
64 | cv2.imwrite(tmp_file, tmp_img)
65 | add_img.astype(int)
66 | add_file = os.path.join(dst, imgname, str(layer) + '/')
67 | make_dirs(add_file)
68 | add_file = os.path.join(add_file, 'add' + '.png')
69 | cv2.imwrite(add_file, add_img)
70 |
71 |
72 | def detect(save_img=False):
73 | source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
74 | save_img = not opt.nosave and not source.endswith('.txt') # save inference images
75 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
76 | ('rtsp://', 'rtmp://', 'http://', 'https://'))
77 |
78 | # Directories
79 | save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
80 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
81 |
82 | # Initialize
83 | set_logging()
84 | device = select_device(opt.device)
85 | half = device.type != 'cpu' # half precision only supported on CUDA
86 |
87 | # Load model
88 | model = attempt_load(weights, map_location=device) # load FP32 model
89 | stride = int(model.stride.max()) # model stride
90 | imgsz = check_img_size(imgsz, s=stride) # check img_size
91 | if half:
92 | model.half() # to FP16
93 |
94 | # Second-stage classifier
95 | classify = False
96 | if classify:
97 | modelc = load_classifier(name='resnet101', n=2) # initialize
98 | modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
99 |
100 | # Set Dataloader
101 | vid_path, vid_writer = None, None
102 | if webcam:
103 | view_img = check_imshow()
104 | cudnn.benchmark = True # set True to speed up constant image size inference
105 | dataset = LoadStreams(source, img_size=imgsz, stride=stride)
106 | else:
107 | dataset = LoadImages(source, img_size=imgsz, stride=stride)
108 |
109 | # Get names and colors
110 | names = model.module.names if hasattr(model, 'module') else model.names
111 | colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
112 |
113 | # Run inference
114 | if device.type != 'cpu':
115 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
116 | t0 = time.time()
117 | for path, img, im0s, vid_cap in dataset:
118 | img = torch.from_numpy(img).to(device)
119 | img = img.half() if half else img.float() # uint8 to fp16/32
120 | img /= 255.0 # 0 - 255 to 0.0 - 1.0
121 | if img.ndimension() == 3:
122 | img = img.unsqueeze(0)
123 |
124 | imgname = path.split('/')[-1]
125 | # Inference
126 | t1 = time_synchronized()
127 | pred = model(img, augment=opt.augment, imgname=imgname)[0]
128 |
129 | # Apply NMS
130 | pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
131 | t2 = time_synchronized()
132 |
133 | # Apply Classifier
134 | if classify:
135 | pred = apply_classifier(pred, modelc, img, im0s)
136 |
137 | # Process detections
138 | for i, det in enumerate(pred): # detections per image
139 | if webcam: # batch_size >= 1
140 | p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
141 | else:
142 | p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
143 |
144 | p = Path(p) # to Path
145 | save_path = str(save_dir / p.name) # img.jpg
146 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
147 | s += '%gx%g ' % img.shape[2:] # print string
148 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
149 | if len(det):
150 | # Rescale boxes from img_size to im0 size
151 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
152 |
153 | # Print results
154 | for c in det[:, -1].unique():
155 | n = (det[:, -1] == c).sum() # detections per class
156 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
157 |
158 | # Write results
159 | for *xyxy, conf, cls in reversed(det):
160 | if save_txt: # Write to file
161 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
162 | line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
163 | with open(txt_path + '.txt', 'a') as f:
164 | f.write(('%g ' * len(line)).rstrip() % line + '\n')
165 |
166 | if save_img or view_img: # Add bbox to image
167 | # label = f'{names[int(cls)]} {conf:.2f}'
168 | label = f'{names[int(cls)]}'
169 | plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
170 |
171 | # Print time (inference + NMS)
172 | print(f'{s}Done. ({t2 - t1:.3f}s)')
173 |
174 | # Stream results
175 | if view_img:
176 | cv2.imshow(str(p), im0)
177 | cv2.waitKey(1) # 1 millisecond
178 |
179 | # Save results (image with detections)
180 | if save_img:
181 | if dataset.mode == 'image':
182 | cv2.imwrite(save_path, im0)
183 | else: # 'video' or 'stream'
184 | if vid_path != save_path: # new video
185 | vid_path = save_path
186 | if isinstance(vid_writer, cv2.VideoWriter):
187 | vid_writer.release() # release previous video writer
188 | if vid_cap: # video
189 | fps = vid_cap.get(cv2.CAP_PROP_FPS)
190 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
191 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
192 | else: # stream
193 | fps, w, h = 30, im0.shape[1], im0.shape[0]
194 | save_path += '.mp4'
195 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
196 | vid_writer.write(im0)
197 |
198 | if save_txt or save_img:
199 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
200 | print(f"Results saved to {save_dir}{s}")
201 |
202 | print(f'Done. ({time.time() - t0:.3f}s)')
203 |
204 |
205 | if __name__ == '__main__':
206 | parser = argparse.ArgumentParser()
207 | parser.add_argument('--weights', nargs='+', type=str, default='', help='model.pt path(s)')
208 | parser.add_argument('--source', type=str, default='', help='source') # file/folder, 0 for webcam
209 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
210 | parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
211 | parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
212 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
213 | parser.add_argument('--view-img', action='store_true', help='display results')
214 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
215 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
216 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
217 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
218 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
219 | parser.add_argument('--augment', action='store_true', help='augmented inference')
220 | parser.add_argument('--update', action='store_true', help='update all models')
221 | parser.add_argument('--project', default='runs/detect', help='save results to project/name')
222 | parser.add_argument('--name', default='exp', help='save results to project/name')
223 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
224 | opt = parser.parse_args()
225 | print(opt)
226 | check_requirements(exclude=('pycocotools', 'thop'))
227 |
228 | with torch.no_grad():
229 | if opt.update: # update all models (to fix SourceChangeWarning)
230 | for opt.weights in ['yolov3.pt', 'yolov3-spp.pt', 'yolov3-tiny.pt']:
231 | detect()
232 | strip_optimizer(opt.weights)
233 | else:
234 | detect()
235 |
--------------------------------------------------------------------------------
/models/yolo.py:
--------------------------------------------------------------------------------
1 | # YOLOv3 YOLO-specific modules
2 |
3 | import argparse
4 | import logging
5 | import sys
6 | from copy import deepcopy
7 |
8 | sys.path.append('./') # to run '$ python *.py' files in subdirectories
9 | logger = logging.getLogger(__name__)
10 |
11 | from models.common import *
12 | from models.experimental import *
13 | from utils.autoanchor import check_anchor_order
14 | from utils.general import make_divisible, check_file, set_logging
15 | from utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \
16 | select_device, copy_attr
17 |
18 | from detect import feature_map
19 |
20 | try:
21 | import thop # for FLOPS computation
22 | except ImportError:
23 | thop = None
24 |
25 |
26 | class Detect(nn.Module):
27 | stride = None # strides computed during build
28 | export = False # onnx export
29 |
30 | def __init__(self, nc=80, anchors=(), ch=()): # detection layer
31 | super(Detect, self).__init__()
32 | self.nc = nc # number of classes
33 | self.no = nc + 5 # number of outputs per anchor
34 | self.nl = len(anchors) # number of detection layers
35 | self.na = len(anchors[0]) // 2 # number of anchors
36 | self.grid = [torch.zeros(1)] * self.nl # init grid
37 | a = torch.tensor(anchors).float().view(self.nl, -1, 2)
38 | self.register_buffer('anchors', a) # shape(nl,na,2)
39 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
40 | self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
41 |
42 | def forward(self, x):
43 | # x = x.copy() # for profiling
44 | z = [] # inference output
45 | self.training |= self.export
46 | for i in range(self.nl):
47 | x[i] = self.m[i](x[i]) # conv
48 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
49 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
50 |
51 | if not self.training: # inference
52 | if self.grid[i].shape[2:4] != x[i].shape[2:4]:
53 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
54 |
55 | y = x[i].sigmoid()
56 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
57 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
58 | z.append(y.view(bs, -1, self.no))
59 |
60 | return x if self.training else (torch.cat(z, 1), x)
61 |
62 | @staticmethod
63 | def _make_grid(nx=20, ny=20):
64 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
65 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
66 |
67 |
68 | class Model(nn.Module):
69 | def __init__(self, cfg='yolov3.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
70 | super(Model, self).__init__()
71 | if isinstance(cfg, dict):
72 | self.yaml = cfg # model dict
73 | else: # is *.yaml
74 | import yaml # for torch hub
75 | self.yaml_file = Path(cfg).name
76 | with open(cfg) as f:
77 | self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict
78 |
79 | # Define model
80 | ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
81 | if nc and nc != self.yaml['nc']:
82 | logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
83 | self.yaml['nc'] = nc # override yaml value
84 | if anchors:
85 | logger.info(f'Overriding model.yaml anchors with anchors={anchors}')
86 | self.yaml['anchors'] = round(anchors) # override yaml value
87 | self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
88 | self.names = [str(i) for i in range(self.yaml['nc'])] # default names
89 | # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
90 |
91 | # Build strides, anchors
92 | m = self.model[-1] # Detect()
93 | if isinstance(m, Detect):
94 | s = 256 # 2x min stride
95 | m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
96 | m.anchors /= m.stride.view(-1, 1, 1)
97 | check_anchor_order(m)
98 | self.stride = m.stride
99 | self._initialize_biases() # only run once
100 | # print('Strides: %s' % m.stride.tolist())
101 |
102 | # Init weights, biases
103 | initialize_weights(self)
104 | self.info()
105 | logger.info('')
106 |
107 | def forward(self, x, augment=False, profile=False, imgname=''):
108 | if augment:
109 | img_size = x.shape[-2:] # height, width
110 | s = [1, 0.83, 0.67] # scales
111 | f = [None, 3, None] # flips (2-ud, 3-lr)
112 | y = [] # outputs
113 | for si, fi in zip(s, f):
114 | xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
115 | yi = self.forward_once(xi)[0] # forward
116 | # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
117 | yi[..., :4] /= si # de-scale
118 | if fi == 2:
119 | yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
120 | elif fi == 3:
121 | yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
122 | y.append(yi)
123 | return torch.cat(y, 1), None # augmented inference, train
124 | else:
125 | return self.forward_once(x, profile, imgname) # single-scale inference, train
126 |
127 | def forward_once(self, x, profile=False, imgname=''):
128 | y, dt = [], [] # outputs
129 | intermediate_features = {}
130 | i = 0
131 | for m in self.model:
132 | i += 1
133 | if m.f != -1: # if not from previous layer
134 | x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
135 |
136 | if profile:
137 | o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS
138 | t = time_synchronized()
139 | for _ in range(10):
140 | _ = m(x)
141 | dt.append((time_synchronized() - t) * 100)
142 | print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))
143 |
144 | x = m(x) # run
145 | # if i in range(0, 8):
146 | # intermediate_features[m] = x
147 | y.append(x if m.i in self.save else None) # save output
148 |
149 | if profile:
150 | print('%.1fms total' % sum(dt))
151 | feature_map(intermediate_features, imgname)
152 | return x
153 |
154 |
155 | def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
156 | # https://arxiv.org/abs/1708.02002 section 3.3
157 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
158 | m = self.model[-1] # Detect() module
159 | for mi, s in zip(m.m, m.stride): # from
160 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
161 | b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
162 | b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
163 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
164 |
165 | def _print_biases(self):
166 | m = self.model[-1] # Detect() module
167 | for mi in m.m: # from
168 | b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
169 | print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
170 |
171 | # def _print_weights(self):
172 | # for m in self.model.modules():
173 | # if type(m) is Bottleneck:
174 | # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
175 |
176 | def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
177 | print('Fusing layers... ')
178 | for m in self.model.modules():
179 | if type(m) is Conv and hasattr(m, 'bn'):
180 | m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
181 | delattr(m, 'bn') # remove batchnorm
182 | m.forward = m.fuseforward # update forward
183 | self.info()
184 | return self
185 |
186 | def nms(self, mode=True): # add or remove NMS module
187 | present = type(self.model[-1]) is NMS # last layer is NMS
188 | if mode and not present:
189 | print('Adding NMS... ')
190 | m = NMS() # module
191 | m.f = -1 # from
192 | m.i = self.model[-1].i + 1 # index
193 | self.model.add_module(name='%s' % m.i, module=m) # add
194 | self.eval()
195 | elif not mode and present:
196 | print('Removing NMS... ')
197 | self.model = self.model[:-1] # remove
198 | return self
199 |
200 | def autoshape(self): # add autoShape module
201 | print('Adding autoShape... ')
202 | m = autoShape(self) # wrap model
203 | copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
204 | return m
205 |
206 | def info(self, verbose=False, img_size=640): # print model information
207 | model_info(self, verbose, img_size)
208 |
209 |
210 | def parse_model(d, ch): # model_dict, input_channels(3)
211 | logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
212 | anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
213 | na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
214 | no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
215 |
216 | layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
217 | for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
218 | m = eval(m) if isinstance(m, str) else m # eval strings
219 | for j, a in enumerate(args):
220 | try:
221 | args[j] = eval(a) if isinstance(a, str) else a # eval strings
222 | except:
223 | pass
224 |
225 | n = max(round(n * gd), 1) if n > 1 else n # depth gain
226 | if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP,
227 | C3, C3TR, RMF, EFE, MySpp, GhostModule]:
228 | c1, c2 = ch[f], args[0]
229 | if c2 != no: # if not output
230 | c2 = make_divisible(c2 * gw, 8)
231 |
232 | args = [c1, c2, *args[1:]]
233 | if m in [BottleneckCSP, C3, C3TR]:
234 | args.insert(2, n) # number of repeats
235 | n = 1
236 | elif m is nn.BatchNorm2d:
237 | args = [ch[f]]
238 | elif m is Concat:
239 | c2 = sum([ch[x] for x in f])
240 | elif m is Detect:
241 | args.append([ch[x] for x in f])
242 | if isinstance(args[1], int): # number of anchors
243 | args[1] = [list(range(args[1] * 2))] * len(f)
244 | elif m is Contract:
245 | c2 = ch[f] * args[0] ** 2
246 | elif m is Expand:
247 | c2 = ch[f] // args[0] ** 2
248 | else:
249 | c2 = ch[f]
250 |
251 | m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
252 | t = str(m)[8:-2].replace('__main__.', '') # module type
253 | np = sum([x.numel() for x in m_.parameters()]) # number params
254 | m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
255 | logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
256 | save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
257 | layers.append(m_)
258 | if i == 0:
259 | ch = []
260 | ch.append(c2)
261 | return nn.Sequential(*layers), sorted(save)
262 |
263 |
264 | if __name__ == '__main__':
265 | parser = argparse.ArgumentParser()
266 | parser.add_argument('--cfg', type=str, default='yolov3.yaml', help='model.yaml')
267 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
268 | opt = parser.parse_args()
269 | opt.cfg = check_file(opt.cfg) # check file
270 | set_logging()
271 | device = select_device(opt.device)
272 |
273 | # Create model
274 | model = Model(opt.cfg).to(device)
275 | model.train()
276 |
277 | # Profile
278 | # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
279 | # y = model(img, profile=True)
280 |
281 | # Tensorboard
282 | # from torch.utils.tensorboard import SummaryWriter
283 | # tb_writer = SummaryWriter()
284 | # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/")
285 | # tb_writer.add_graph(model.model, img) # add model to tensorboard
286 | # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard
287 |
--------------------------------------------------------------------------------
/utils/torch_utils.py:
--------------------------------------------------------------------------------
1 | # YOLOv3 PyTorch utils
2 |
3 | import datetime
4 | import logging
5 | import math
6 | import os
7 | import platform
8 | import subprocess
9 | import time
10 | from contextlib import contextmanager
11 | from copy import deepcopy
12 | from pathlib import Path
13 |
14 | import torch
15 | import torch.backends.cudnn as cudnn
16 | import torch.nn as nn
17 | import torch.nn.functional as F
18 | import torchvision
19 |
20 | from torchstat import stat
21 |
22 | try:
23 | import thop # for FLOPS computation
24 | except ImportError:
25 | thop = None
26 | logger = logging.getLogger(__name__)
27 |
28 |
29 | @contextmanager
30 | def torch_distributed_zero_first(local_rank: int):
31 | """
32 | Decorator to make all processes in distributed training wait for each local_master to do something.
33 | """
34 | if local_rank not in [-1, 0]:
35 | torch.distributed.barrier()
36 | yield
37 | if local_rank == 0:
38 | torch.distributed.barrier()
39 |
40 |
41 | def init_torch_seeds(seed=0):
42 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
43 | torch.manual_seed(seed)
44 | if seed == 0: # slower, more reproducible
45 | cudnn.benchmark, cudnn.deterministic = False, True
46 | else: # faster, less reproducible
47 | cudnn.benchmark, cudnn.deterministic = True, False
48 |
49 |
50 | def date_modified(path=__file__):
51 | # return human-readable file modification date, i.e. '2021-3-26'
52 | t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
53 | return f'{t.year}-{t.month}-{t.day}'
54 |
55 |
56 | def git_describe(path=Path(__file__).parent): # path must be a directory
57 | # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
58 | s = f'git -C {path} describe --tags --long --always'
59 | try:
60 | return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
61 | except subprocess.CalledProcessError as e:
62 | return '' # not a git repository
63 |
64 |
65 | def select_device(device='', batch_size=None):
66 | # device = 'cpu' or '0' or '0,1,2,3'
67 | s = f'YOLOv3 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
68 | cpu = device.lower() == 'cpu'
69 | if cpu:
70 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
71 | elif device: # non-cpu device requested
72 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
73 | assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
74 |
75 | cuda = not cpu and torch.cuda.is_available()
76 | if cuda:
77 | n = torch.cuda.device_count()
78 | if n > 1 and batch_size: # check that batch_size is compatible with device_count
79 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
80 | space = ' ' * len(s)
81 | for i, d in enumerate(device.split(',') if device else range(n)):
82 | p = torch.cuda.get_device_properties(i)
83 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
84 | else:
85 | s += 'CPU\n'
86 |
87 | logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
88 | return torch.device('cuda:0' if cuda else 'cpu')
89 |
90 |
91 | def time_synchronized():
92 | # pytorch-accurate time
93 | if torch.cuda.is_available():
94 | torch.cuda.synchronize()
95 | return time.time()
96 |
97 |
98 | def profile(x, ops, n=100, device=None):
99 | # profile a pytorch module or list of modules. Example usage:
100 | # x = torch.randn(16, 3, 640, 640) # input
101 | # m1 = lambda x: x * torch.sigmoid(x)
102 | # m2 = nn.SiLU()
103 | # profile(x, [m1, m2], n=100) # profile speed over 100 iterations
104 |
105 | device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
106 | x = x.to(device)
107 | x.requires_grad = True
108 | print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '')
109 | print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}")
110 | for m in ops if isinstance(ops, list) else [ops]:
111 | m = m.to(device) if hasattr(m, 'to') else m # device
112 | m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type
113 | dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward
114 | try:
115 | flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS
116 | except:
117 | flops = 0
118 |
119 | for _ in range(n):
120 | t[0] = time_synchronized()
121 | y = m(x)
122 | t[1] = time_synchronized()
123 | try:
124 | _ = y.sum().backward()
125 | t[2] = time_synchronized()
126 | except: # no backward method
127 | t[2] = float('nan')
128 | dtf += (t[1] - t[0]) * 1000 / n # ms per op forward
129 | dtb += (t[2] - t[1]) * 1000 / n # ms per op backward
130 |
131 | s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
132 | s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
133 | p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters
134 | print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}')
135 |
136 |
137 | def is_parallel(model):
138 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
139 |
140 |
141 | def intersect_dicts(da, db, exclude=()):
142 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
143 | return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
144 |
145 |
146 | def initialize_weights(model):
147 | for m in model.modules():
148 | t = type(m)
149 | if t is nn.Conv2d:
150 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
151 | elif t is nn.BatchNorm2d:
152 | m.eps = 1e-3
153 | m.momentum = 0.03
154 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
155 | m.inplace = True
156 |
157 |
158 | def find_modules(model, mclass=nn.Conv2d):
159 | # Finds layer indices matching module class 'mclass'
160 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
161 |
162 |
163 | def sparsity(model):
164 | # Return global model sparsity
165 | a, b = 0., 0.
166 | for p in model.parameters():
167 | a += p.numel()
168 | b += (p == 0).sum()
169 | return b / a
170 |
171 |
172 | def prune(model, amount=0.3):
173 | # Prune model to requested global sparsity
174 | import torch.nn.utils.prune as prune
175 | print('Pruning model... ', end='')
176 | for name, m in model.named_modules():
177 | if isinstance(m, nn.Conv2d):
178 | prune.l1_unstructured(m, name='weight', amount=amount) # prune
179 | prune.remove(m, 'weight') # make permanent
180 | print(' %.3g global sparsity' % sparsity(model))
181 |
182 |
183 | def fuse_conv_and_bn(conv, bn):
184 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
185 | fusedconv = nn.Conv2d(conv.in_channels,
186 | conv.out_channels,
187 | kernel_size=conv.kernel_size,
188 | stride=conv.stride,
189 | padding=conv.padding,
190 | groups=conv.groups,
191 | bias=True).requires_grad_(False).to(conv.weight.device)
192 |
193 | # prepare filters
194 | w_conv = conv.weight.clone().view(conv.out_channels, -1)
195 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
196 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
197 |
198 | # prepare spatial bias
199 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
200 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
201 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
202 |
203 | return fusedconv
204 |
205 |
206 | def model_info(model, verbose=False, img_size=640):
207 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
208 | n_p = sum(x.numel() for x in model.parameters()) # number parameters
209 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
210 | if verbose:
211 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
212 | for i, (name, p) in enumerate(model.named_parameters()):
213 | name = name.replace('module_list.', '')
214 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
215 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
216 |
217 | try: # FLOPS
218 | from thop import profile
219 | stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
220 | img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
221 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS
222 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
223 | fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS
224 | except (ImportError, Exception):
225 | fs = ''
226 |
227 | logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
228 |
229 |
230 | def load_classifier(name='resnet101', n=2):
231 | # Loads a pretrained model reshaped to n-class output
232 | model = torchvision.models.__dict__[name](pretrained=True)
233 |
234 | # ResNet model properties
235 | # input_size = [3, 224, 224]
236 | # input_space = 'RGB'
237 | # input_range = [0, 1]
238 | # mean = [0.485, 0.456, 0.406]
239 | # std = [0.229, 0.224, 0.225]
240 |
241 | # Reshape output to n classes
242 | filters = model.fc.weight.shape[1]
243 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
244 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
245 | model.fc.out_features = n
246 | return model
247 |
248 |
249 | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
250 | # scales img(bs,3,y,x) by ratio constrained to gs-multiple
251 | if ratio == 1.0:
252 | return img
253 | else:
254 | h, w = img.shape[2:]
255 | s = (int(h * ratio), int(w * ratio)) # new size
256 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
257 | if not same_shape: # pad/crop img
258 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
259 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
260 |
261 |
262 | def copy_attr(a, b, include=(), exclude=()):
263 | # Copy attributes from b to a, options to only include [...] and to exclude [...]
264 | for k, v in b.__dict__.items():
265 | if (len(include) and k not in include) or k.startswith('_') or k in exclude:
266 | continue
267 | else:
268 | setattr(a, k, v)
269 |
270 |
271 | class ModelEMA:
272 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
273 | Keep a moving average of everything in the model state_dict (parameters and buffers).
274 | This is intended to allow functionality like
275 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
276 | A smoothed version of the weights is necessary for some training schemes to perform well.
277 | This class is sensitive where it is initialized in the sequence of model init,
278 | GPU assignment and distributed training wrappers.
279 | """
280 |
281 | def __init__(self, model, decay=0.9999, updates=0):
282 | # Create EMA
283 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
284 | # if next(model.parameters()).device.type != 'cpu':
285 | # self.ema.half() # FP16 EMA
286 | self.updates = updates # number of EMA updates
287 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
288 | for p in self.ema.parameters():
289 | p.requires_grad_(False)
290 |
291 | def update(self, model):
292 | # Update EMA parameters
293 | with torch.no_grad():
294 | self.updates += 1
295 | d = self.decay(self.updates)
296 |
297 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
298 | for k, v in self.ema.state_dict().items():
299 | if v.dtype.is_floating_point:
300 | v *= d
301 | v += (1. - d) * msd[k].detach()
302 |
303 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
304 | # Update EMA attributes
305 | copy_attr(self.ema, model, include, exclude)
306 |
--------------------------------------------------------------------------------
/utils/wandb_logging/wandb_utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import sys
3 | from pathlib import Path
4 |
5 | import torch
6 | import yaml
7 | from tqdm import tqdm
8 |
9 | sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path
10 | from utils.datasets import LoadImagesAndLabels
11 | from utils.datasets import img2label_paths
12 | from utils.general import colorstr, xywh2xyxy, check_dataset
13 |
14 | try:
15 | import wandb
16 | from wandb import init, finish
17 | except ImportError:
18 | wandb = None
19 |
20 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
21 |
22 |
23 | def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):
24 | return from_string[len(prefix):]
25 |
26 |
27 | def check_wandb_config_file(data_config_file):
28 | wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path
29 | if Path(wandb_config).is_file():
30 | return wandb_config
31 | return data_config_file
32 |
33 |
34 | def get_run_info(run_path):
35 | run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))
36 | run_id = run_path.stem
37 | project = run_path.parent.stem
38 | model_artifact_name = 'run_' + run_id + '_model'
39 | return run_id, project, model_artifact_name
40 |
41 |
42 | def check_wandb_resume(opt):
43 | process_wandb_config_ddp_mode(opt) if opt.global_rank not in [-1, 0] else None
44 | if isinstance(opt.resume, str):
45 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
46 | if opt.global_rank not in [-1, 0]: # For resuming DDP runs
47 | run_id, project, model_artifact_name = get_run_info(opt.resume)
48 | api = wandb.Api()
49 | artifact = api.artifact(project + '/' + model_artifact_name + ':latest')
50 | modeldir = artifact.download()
51 | opt.weights = str(Path(modeldir) / "last.pt")
52 | return True
53 | return None
54 |
55 |
56 | def process_wandb_config_ddp_mode(opt):
57 | with open(opt.data) as f:
58 | data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict
59 | train_dir, val_dir = None, None
60 | if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):
61 | api = wandb.Api()
62 | train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)
63 | train_dir = train_artifact.download()
64 | train_path = Path(train_dir) / 'data/images/'
65 | data_dict['train'] = str(train_path)
66 |
67 | if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):
68 | api = wandb.Api()
69 | val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)
70 | val_dir = val_artifact.download()
71 | val_path = Path(val_dir) / 'data/images/'
72 | data_dict['val'] = str(val_path)
73 | if train_dir or val_dir:
74 | ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')
75 | with open(ddp_data_path, 'w') as f:
76 | yaml.dump(data_dict, f)
77 | opt.data = ddp_data_path
78 |
79 |
80 | class WandbLogger():
81 | def __init__(self, opt, name, run_id, data_dict, job_type='Training'):
82 | # Pre-training routine --
83 | self.job_type = job_type
84 | self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run, data_dict
85 | # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call
86 | if isinstance(opt.resume, str): # checks resume from artifact
87 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
88 | run_id, project, model_artifact_name = get_run_info(opt.resume)
89 | model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name
90 | assert wandb, 'install wandb to resume wandb runs'
91 | # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config
92 | self.wandb_run = wandb.init(id=run_id, project=project, resume='allow')
93 | opt.resume = model_artifact_name
94 | elif self.wandb:
95 | self.wandb_run = wandb.init(config=opt,
96 | resume="allow",
97 | project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
98 | name=name,
99 | job_type=job_type,
100 | id=run_id) if not wandb.run else wandb.run
101 | if self.wandb_run:
102 | if self.job_type == 'Training':
103 | if not opt.resume:
104 | wandb_data_dict = self.check_and_upload_dataset(opt) if opt.upload_dataset else data_dict
105 | # Info useful for resuming from artifacts
106 | self.wandb_run.config.opt = vars(opt)
107 | self.wandb_run.config.data_dict = wandb_data_dict
108 | self.data_dict = self.setup_training(opt, data_dict)
109 | if self.job_type == 'Dataset Creation':
110 | self.data_dict = self.check_and_upload_dataset(opt)
111 | else:
112 | prefix = colorstr('wandb: ')
113 | print(f"{prefix}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)")
114 |
115 | def check_and_upload_dataset(self, opt):
116 | assert wandb, 'Install wandb to upload dataset'
117 | check_dataset(self.data_dict)
118 | config_path = self.log_dataset_artifact(opt.data,
119 | opt.single_cls,
120 | 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem)
121 | print("Created dataset config file ", config_path)
122 | with open(config_path) as f:
123 | wandb_data_dict = yaml.load(f, Loader=yaml.SafeLoader)
124 | return wandb_data_dict
125 |
126 | def setup_training(self, opt, data_dict):
127 | self.log_dict, self.current_epoch, self.log_imgs = {}, 0, 16 # Logging Constants
128 | self.bbox_interval = opt.bbox_interval
129 | if isinstance(opt.resume, str):
130 | modeldir, _ = self.download_model_artifact(opt)
131 | if modeldir:
132 | self.weights = Path(modeldir) / "last.pt"
133 | config = self.wandb_run.config
134 | opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str(
135 | self.weights), config.save_period, config.total_batch_size, config.bbox_interval, config.epochs, \
136 | config.opt['hyp']
137 | data_dict = dict(self.wandb_run.config.data_dict) # eliminates the need for config file to resume
138 | if 'val_artifact' not in self.__dict__: # If --upload_dataset is set, use the existing artifact, don't download
139 | self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'),
140 | opt.artifact_alias)
141 | self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'),
142 | opt.artifact_alias)
143 | self.result_artifact, self.result_table, self.val_table, self.weights = None, None, None, None
144 | if self.train_artifact_path is not None:
145 | train_path = Path(self.train_artifact_path) / 'data/images/'
146 | data_dict['train'] = str(train_path)
147 | if self.val_artifact_path is not None:
148 | val_path = Path(self.val_artifact_path) / 'data/images/'
149 | data_dict['val'] = str(val_path)
150 | self.val_table = self.val_artifact.get("val")
151 | self.map_val_table_path()
152 | if self.val_artifact is not None:
153 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
154 | self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
155 | if opt.bbox_interval == -1:
156 | self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
157 | return data_dict
158 |
159 | def download_dataset_artifact(self, path, alias):
160 | if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
161 | dataset_artifact = wandb.use_artifact(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
162 | assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
163 | datadir = dataset_artifact.download()
164 | return datadir, dataset_artifact
165 | return None, None
166 |
167 | def download_model_artifact(self, opt):
168 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
169 | model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
170 | assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
171 | modeldir = model_artifact.download()
172 | epochs_trained = model_artifact.metadata.get('epochs_trained')
173 | total_epochs = model_artifact.metadata.get('total_epochs')
174 | assert epochs_trained < total_epochs, 'training to %g epochs is finished, nothing to resume.' % (
175 | total_epochs)
176 | return modeldir, model_artifact
177 | return None, None
178 |
179 | def log_model(self, path, opt, epoch, fitness_score, best_model=False):
180 | model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
181 | 'original_url': str(path),
182 | 'epochs_trained': epoch + 1,
183 | 'save period': opt.save_period,
184 | 'project': opt.project,
185 | 'total_epochs': opt.epochs,
186 | 'fitness_score': fitness_score
187 | })
188 | model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
189 | wandb.log_artifact(model_artifact,
190 | aliases=['latest', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
191 | print("Saving model artifact on epoch ", epoch + 1)
192 |
193 | def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
194 | with open(data_file) as f:
195 | data = yaml.load(f, Loader=yaml.SafeLoader) # data dict
196 | nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])
197 | names = {k: v for k, v in enumerate(names)} # to index dictionary
198 | self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(
199 | data['train']), names, name='train') if data.get('train') else None
200 | self.val_artifact = self.create_dataset_table(LoadImagesAndLabels(
201 | data['val']), names, name='val') if data.get('val') else None
202 | if data.get('train'):
203 | data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')
204 | if data.get('val'):
205 | data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')
206 | path = data_file if overwrite_config else '_wandb.'.join(data_file.rsplit('.', 1)) # updated data.yaml path
207 | data.pop('download', None)
208 | with open(path, 'w') as f:
209 | yaml.dump(data, f)
210 |
211 | if self.job_type == 'Training': # builds correct artifact pipeline graph
212 | self.wandb_run.use_artifact(self.val_artifact)
213 | self.wandb_run.use_artifact(self.train_artifact)
214 | self.val_artifact.wait()
215 | self.val_table = self.val_artifact.get('val')
216 | self.map_val_table_path()
217 | else:
218 | self.wandb_run.log_artifact(self.train_artifact)
219 | self.wandb_run.log_artifact(self.val_artifact)
220 | return path
221 |
222 | def map_val_table_path(self):
223 | self.val_table_map = {}
224 | print("Mapping dataset")
225 | for i, data in enumerate(tqdm(self.val_table.data)):
226 | self.val_table_map[data[3]] = data[0]
227 |
228 | def create_dataset_table(self, dataset, class_to_id, name='dataset'):
229 | # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
230 | artifact = wandb.Artifact(name=name, type="dataset")
231 | img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
232 | img_files = tqdm(dataset.img_files) if not img_files else img_files
233 | for img_file in img_files:
234 | if Path(img_file).is_dir():
235 | artifact.add_dir(img_file, name='data/images')
236 | labels_path = 'labels'.join(dataset.path.rsplit('images', 1))
237 | artifact.add_dir(labels_path, name='data/labels')
238 | else:
239 | artifact.add_file(img_file, name='data/images/' + Path(img_file).name)
240 | label_file = Path(img2label_paths([img_file])[0])
241 | artifact.add_file(str(label_file),
242 | name='data/labels/' + label_file.name) if label_file.exists() else None
243 | table = wandb.Table(columns=["id", "train_image", "Classes", "name"])
244 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
245 | for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):
246 | height, width = shapes[0]
247 | labels[:, 2:] = (xywh2xyxy(labels[:, 2:].view(-1, 4))) * torch.Tensor([width, height, width, height])
248 | box_data, img_classes = [], {}
249 | for cls, *xyxy in labels[:, 1:].tolist():
250 | cls = int(cls)
251 | box_data.append({"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
252 | "class_id": cls,
253 | "box_caption": "%s" % (class_to_id[cls]),
254 | "scores": {"acc": 1},
255 | "domain": "pixel"})
256 | img_classes[cls] = class_to_id[cls]
257 | boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
258 | table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes),
259 | Path(paths).name)
260 | artifact.add(table, name)
261 | return artifact
262 |
263 | def log_training_progress(self, predn, path, names):
264 | if self.val_table and self.result_table:
265 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
266 | box_data = []
267 | total_conf = 0
268 | for *xyxy, conf, cls in predn.tolist():
269 | if conf >= 0.25:
270 | box_data.append(
271 | {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
272 | "class_id": int(cls),
273 | "box_caption": "%s %.3f" % (names[cls], conf),
274 | "scores": {"class_score": conf},
275 | "domain": "pixel"})
276 | total_conf = total_conf + conf
277 | boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
278 | id = self.val_table_map[Path(path).name]
279 | self.result_table.add_data(self.current_epoch,
280 | id,
281 | wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),
282 | total_conf / max(1, len(box_data))
283 | )
284 |
285 | def log(self, log_dict):
286 | if self.wandb_run:
287 | for key, value in log_dict.items():
288 | self.log_dict[key] = value
289 |
290 | def end_epoch(self, best_result=False):
291 | if self.wandb_run:
292 | wandb.log(self.log_dict)
293 | self.log_dict = {}
294 | if self.result_artifact:
295 | train_results = wandb.JoinedTable(self.val_table, self.result_table, "id")
296 | self.result_artifact.add(train_results, 'result')
297 | wandb.log_artifact(self.result_artifact, aliases=['latest', 'epoch ' + str(self.current_epoch),
298 | ('best' if best_result else '')])
299 | self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
300 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
301 |
302 | def finish_run(self):
303 | if self.wandb_run:
304 | if self.log_dict:
305 | wandb.log(self.log_dict)
306 | wandb.run.finish()
307 |
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import json
3 | import os
4 | from pathlib import Path
5 | from threading import Thread
6 |
7 | import numpy as np
8 | import torch
9 | import yaml
10 | from tqdm import tqdm
11 |
12 | from models.experimental import attempt_load
13 | from utils.datasets import create_dataloader
14 | from utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, check_requirements, \
15 | box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, set_logging, increment_path, colorstr
16 | from utils.metrics import ap_per_class, ConfusionMatrix
17 | from utils.plots import plot_images, output_to_target, plot_study_txt
18 | from utils.torch_utils import select_device, time_synchronized
19 |
20 |
21 | def test(data,
22 | weights=None,
23 | batch_size=32,
24 | imgsz=640,
25 | conf_thres=0.001,
26 | iou_thres=0.6, # for NMS
27 | save_json=False,
28 | single_cls=False,
29 | augment=False,
30 | verbose=False,
31 | model=None,
32 | dataloader=None,
33 | save_dir=Path(''), # for saving images
34 | save_txt=False, # for auto-labelling
35 | save_hybrid=False, # for hybrid auto-labelling
36 | save_conf=False, # save auto-label confidences
37 | plots=True,
38 | wandb_logger=None,
39 | compute_loss=None,
40 | half_precision=True,
41 | is_coco=False):
42 | # Initialize/load model and set device
43 | training = model is not None
44 | if training: # called by train.py
45 | device = next(model.parameters()).device # get model device
46 |
47 | else: # called directly
48 | set_logging()
49 | device = select_device(opt.device, batch_size=batch_size)
50 |
51 | # Directories
52 | save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
53 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
54 |
55 | # Load model
56 | model = attempt_load(weights, map_location=device) # load FP32 model
57 | gs = max(int(model.stride.max()), 32) # grid size (max stride)
58 | imgsz = check_img_size(imgsz, s=gs) # check img_size
59 |
60 | # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99
61 | # if device.type != 'cpu' and torch.cuda.device_count() > 1:
62 | # model = nn.DataParallel(model)
63 |
64 | # Half
65 | half = device.type != 'cpu' and half_precision # half precision only supported on CUDA
66 | if half:
67 | model.half()
68 |
69 | # Configure
70 | model.eval()
71 | if isinstance(data, str):
72 | is_coco = data.endswith('coco.yaml')
73 | with open(data) as f:
74 | data = yaml.load(f, Loader=yaml.SafeLoader)
75 | check_dataset(data) # check
76 | nc = 1 if single_cls else int(data['nc']) # number of classes
77 | iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
78 | niou = iouv.numel()
79 |
80 | # Logging
81 | log_imgs = 0
82 | if wandb_logger and wandb_logger.wandb:
83 | log_imgs = min(wandb_logger.log_imgs, 100)
84 | # Dataloader
85 | if not training:
86 | if device.type != 'cpu':
87 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
88 | task = opt.task if opt.task in ('train', 'val', 'test') else 'val' # path to train/val/test images
89 | dataloader = create_dataloader(data[task], imgsz, batch_size, gs, opt, pad=0.5, rect=True,
90 | prefix=colorstr(f'{task}: '))[0]
91 |
92 | seen = 0
93 | confusion_matrix = ConfusionMatrix(nc=nc)
94 | names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
95 | coco91class = coco80_to_coco91_class()
96 | s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Labels', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
97 | p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
98 | loss = torch.zeros(3, device=device)
99 | jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []
100 | for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
101 | img = img.to(device, non_blocking=True)
102 | img = img.half() if half else img.float() # uint8 to fp16/32
103 | img /= 255.0 # 0 - 255 to 0.0 - 1.0
104 | targets = targets.to(device)
105 | nb, _, height, width = img.shape # batch size, channels, height, width
106 |
107 | with torch.no_grad():
108 | # Run model
109 | t = time_synchronized()
110 | out, train_out = model(img, augment=augment) # inference and training outputs
111 | t0 += time_synchronized() - t
112 |
113 | # Compute loss
114 | if compute_loss:
115 | loss += compute_loss([x.float() for x in train_out], targets)[1][:3] # box, obj, cls
116 |
117 | # Run NMS
118 | targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels
119 | lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
120 | t = time_synchronized()
121 | out = non_max_suppression(out, conf_thres=conf_thres, iou_thres=iou_thres, labels=lb, multi_label=True)
122 | t1 += time_synchronized() - t
123 |
124 | # Statistics per image
125 | for si, pred in enumerate(out):
126 | labels = targets[targets[:, 0] == si, 1:]
127 | nl = len(labels)
128 | tcls = labels[:, 0].tolist() if nl else [] # target class
129 | path = Path(paths[si])
130 | seen += 1
131 |
132 | if len(pred) == 0:
133 | if nl:
134 | stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
135 | continue
136 |
137 | # Predictions
138 | predn = pred.clone()
139 | scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred
140 |
141 | # Append to text file
142 | if save_txt:
143 | gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh
144 | for *xyxy, conf, cls in predn.tolist():
145 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
146 | line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
147 | with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f:
148 | f.write(('%g ' * len(line)).rstrip() % line + '\n')
149 |
150 | # W&B logging - Media Panel Plots
151 | if len(wandb_images) < log_imgs and wandb_logger.current_epoch > 0: # Check for test operation
152 | if wandb_logger.current_epoch % wandb_logger.bbox_interval == 0:
153 | box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
154 | "class_id": int(cls),
155 | "box_caption": "%s %.3f" % (names[cls], conf),
156 | "scores": {"class_score": conf},
157 | "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
158 | boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
159 | wandb_images.append(wandb_logger.wandb.Image(img[si], boxes=boxes, caption=path.name))
160 | wandb_logger.log_training_progress(predn, path, names) if wandb_logger and wandb_logger.wandb_run else None
161 |
162 | # Append to pycocotools JSON dictionary
163 | if save_json:
164 | # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
165 | image_id = int(path.stem) if path.stem.isnumeric() else path.stem
166 |
167 | box = xyxy2xywh(predn[:, :4]) # xywh
168 | box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
169 | for p, b in zip(pred.tolist(), box.tolist()):
170 | jdict.append({'image_id': image_id,
171 | 'category_id': coco91class[int(p[5])] if is_coco else int(p[5]),
172 | 'bbox': [round(x, 3) for x in b],
173 | 'score': round(p[4], 5)})
174 |
175 | # Assign all predictions as incorrect
176 | correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
177 | if nl:
178 | detected = [] # target indices
179 | tcls_tensor = labels[:, 0]
180 |
181 | # target boxes
182 | tbox = xywh2xyxy(labels[:, 1:5])
183 | scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels
184 | if plots:
185 | confusion_matrix.process_batch(predn, torch.cat((labels[:, 0:1], tbox), 1))
186 |
187 | # Per target class
188 | for cls in torch.unique(tcls_tensor):
189 | ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices
190 | pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices
191 |
192 | # Search for detections
193 | if pi.shape[0]:
194 | # Prediction to target ious
195 | ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices
196 |
197 | # Append detections
198 | detected_set = set()
199 | for j in (ious > iouv[0]).nonzero(as_tuple=False):
200 | d = ti[i[j]] # detected target
201 | if d.item() not in detected_set:
202 | detected_set.add(d.item())
203 | detected.append(d)
204 | correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
205 | if len(detected) == nl: # all targets already located in image
206 | break
207 |
208 | # Append statistics (correct, conf, pcls, tcls)
209 | stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
210 |
211 | # Plot images
212 | if plots and batch_i < 3:
213 | f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels
214 | Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start()
215 | f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions
216 | Thread(target=plot_images, args=(img, output_to_target(out), paths, f, names), daemon=True).start()
217 |
218 | # Compute statistics
219 | stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
220 | if len(stats) and stats[0].any():
221 | p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
222 | ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95
223 | mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
224 | nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
225 | else:
226 | nt = torch.zeros(1)
227 |
228 | # Print results
229 | pf = '%20s' + '%12i' * 2 + '%12.3g' * 4 # print format
230 | print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
231 |
232 | # Print results per class
233 | if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
234 | for i, c in enumerate(ap_class):
235 | print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
236 |
237 | # Print speeds
238 | t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
239 | if not training:
240 | print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
241 |
242 | # Plots
243 | if plots:
244 | confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
245 | if wandb_logger and wandb_logger.wandb:
246 | val_batches = [wandb_logger.wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))]
247 | wandb_logger.log({"Validation": val_batches})
248 | if wandb_images:
249 | wandb_logger.log({"Bounding Box Debugger/Images": wandb_images})
250 |
251 | # Save JSON
252 | if save_json and len(jdict):
253 | w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
254 | anno_json = '../coco/annotations/instances_val2017.json' # annotations json
255 | pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
256 | print('\nEvaluating pycocotools mAP... saving %s...' % pred_json)
257 | with open(pred_json, 'w') as f:
258 | json.dump(jdict, f)
259 |
260 | try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
261 | from pycocotools.coco import COCO
262 | from pycocotools.cocoeval import COCOeval
263 |
264 | anno = COCO(anno_json) # init annotations api
265 | pred = anno.loadRes(pred_json) # init predictions api
266 | eval = COCOeval(anno, pred, 'bbox')
267 | if is_coco:
268 | eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate
269 | eval.evaluate()
270 | eval.accumulate()
271 | eval.summarize()
272 | map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
273 | except Exception as e:
274 | print(f'pycocotools unable to run: {e}')
275 |
276 | # Return results
277 | model.float() # for training
278 | if not training:
279 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
280 | print(f"Results saved to {save_dir}{s}")
281 | maps = np.zeros(nc) + map
282 | for i, c in enumerate(ap_class):
283 | maps[c] = ap[i]
284 | return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
285 |
286 |
287 | if __name__ == '__main__':
288 | parser = argparse.ArgumentParser(prog='test.py')
289 | parser.add_argument('--weights', nargs='+', type=str, default='', help='model.pt path(s)')
290 | parser.add_argument('--data', type=str, default='data/coco.yaml', help='*.data path')
291 | parser.add_argument('--batch-size', type=int, default=1, help='size of each image batch')
292 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
293 | parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
294 | parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS')
295 | parser.add_argument('--task', default='val', help='train, val, test, speed or study')
296 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
297 | parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
298 | parser.add_argument('--augment', action='store_true', help='augmented inference')
299 | parser.add_argument('--verbose', action='store_true', help='report mAP by class')
300 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
301 | parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
302 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
303 | parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
304 | parser.add_argument('--project', default='runs/test', help='save to project/name')
305 | parser.add_argument('--name', default='exp', help='save to project/name')
306 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
307 | opt = parser.parse_args()
308 | opt.save_json |= opt.data.endswith('coco.yaml')
309 | opt.data = check_file(opt.data) # check file
310 | print(opt)
311 | check_requirements()
312 |
313 | if opt.task in ('train', 'val', 'test'): # run normally
314 | test(opt.data,
315 | opt.weights,
316 | opt.batch_size,
317 | opt.img_size,
318 | opt.conf_thres,
319 | opt.iou_thres,
320 | opt.save_json,
321 | opt.single_cls,
322 | opt.augment,
323 | opt.verbose,
324 | save_txt=opt.save_txt | opt.save_hybrid,
325 | save_hybrid=opt.save_hybrid,
326 | save_conf=opt.save_conf,
327 | )
328 |
329 | elif opt.task == 'speed': # speed benchmarks
330 | for w in opt.weights:
331 | test(opt.data, w, opt.batch_size, opt.img_size, 0.25, 0.45, save_json=False, plots=False)
332 |
333 | elif opt.task == 'study': # run over a range of settings and save/plot
334 | # python test.py --task study --data coco.yaml --iou 0.7 --weights yolov3.pt yolov3-spp.pt yolov3-tiny.pt
335 | x = list(range(256, 1536 + 128, 128)) # x axis (image sizes)
336 | for w in opt.weights:
337 | f = f'study_{Path(opt.data).stem}_{Path(w).stem}.txt' # filename to save to
338 | y = [] # y axis
339 | for i in x: # img-size
340 | print(f'\nRunning {f} point {i}...')
341 | r, _, t = test(opt.data, w, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json,
342 | plots=False)
343 | y.append(r + t) # results and times
344 | np.savetxt(f, y, fmt='%10.4g') # save
345 | os.system('zip -r study.zip study_*.txt')
346 | plot_study_txt(x=x) # plot
347 |
--------------------------------------------------------------------------------
/utils/plots.py:
--------------------------------------------------------------------------------
1 | # Plotting utils
2 |
3 | import glob
4 | import math
5 | import os
6 | import random
7 | from copy import copy
8 | from pathlib import Path
9 |
10 | import cv2
11 | import matplotlib
12 | import matplotlib.pyplot as plt
13 | import numpy as np
14 | import pandas as pd
15 | import seaborn as sns
16 | import torch
17 | import yaml
18 | from PIL import Image, ImageDraw, ImageFont
19 | from scipy.signal import butter, filtfilt
20 |
21 | from utils.general import xywh2xyxy, xyxy2xywh
22 | from utils.metrics import fitness
23 |
24 | # Settings
25 | matplotlib.rc('font', **{'size': 11})
26 | matplotlib.use('Agg') # for writing to files only
27 |
28 |
29 | def color_list():
30 | # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
31 | def hex2rgb(h):
32 | return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
33 |
34 | return [hex2rgb(h) for h in matplotlib.colors.TABLEAU_COLORS.values()] # or BASE_ (8), CSS4_ (148), XKCD_ (949)
35 |
36 |
37 | def hist2d(x, y, n=100):
38 | # 2d histogram used in labels.png and evolve.png
39 | xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
40 | hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
41 | xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
42 | yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
43 | return np.log(hist[xidx, yidx])
44 |
45 |
46 | def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
47 | # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
48 | def butter_lowpass(cutoff, fs, order):
49 | nyq = 0.5 * fs
50 | normal_cutoff = cutoff / nyq
51 | return butter(order, normal_cutoff, btype='low', analog=False)
52 |
53 | b, a = butter_lowpass(cutoff, fs, order=order)
54 | return filtfilt(b, a, data) # forward-backward filter
55 |
56 |
57 | def plot_one_box(x, img, color=None, label=None, line_thickness=3):
58 | # Plots one bounding box on image img
59 | tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
60 | color = color or [random.randint(0, 255) for _ in range(3)]
61 | c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
62 | cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
63 | if label:
64 | tf = max(tl - 1, 1) # font thickness
65 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
66 | c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
67 | cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
68 | cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
69 |
70 |
71 | def plot_one_box_PIL(box, img, color=None, label=None, line_thickness=None):
72 | img = Image.fromarray(img)
73 | draw = ImageDraw.Draw(img)
74 | line_thickness = line_thickness or max(int(min(img.size) / 200), 2)
75 | draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot
76 | if label:
77 | fontsize = max(round(max(img.size) / 40), 12)
78 | font = ImageFont.truetype("Arial.ttf", fontsize)
79 | txt_width, txt_height = font.getsize(label)
80 | draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color))
81 | draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font)
82 | return np.asarray(img)
83 |
84 |
85 | def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
86 | # Compares the two methods for width-height anchor multiplication
87 | # https://github.com/ultralytics/yolov3/issues/168
88 | x = np.arange(-4.0, 4.0, .1)
89 | ya = np.exp(x)
90 | yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
91 |
92 | fig = plt.figure(figsize=(6, 3), tight_layout=True)
93 | plt.plot(x, ya, '.-', label='YOLOv3')
94 | plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
95 | plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
96 | plt.xlim(left=-4, right=4)
97 | plt.ylim(bottom=0, top=6)
98 | plt.xlabel('input')
99 | plt.ylabel('output')
100 | plt.grid()
101 | plt.legend()
102 | fig.savefig('comparison.png', dpi=200)
103 |
104 |
105 | def output_to_target(output):
106 | # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
107 | targets = []
108 | for i, o in enumerate(output):
109 | for *box, conf, cls in o.cpu().numpy():
110 | targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
111 | return np.array(targets)
112 |
113 |
114 | def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
115 | # Plot image grid with labels
116 |
117 | if isinstance(images, torch.Tensor):
118 | images = images.cpu().float().numpy()
119 | if isinstance(targets, torch.Tensor):
120 | targets = targets.cpu().numpy()
121 |
122 | # un-normalise
123 | if np.max(images[0]) <= 1:
124 | images *= 255
125 |
126 | tl = 3 # line thickness
127 | tf = max(tl - 1, 1) # font thickness
128 | bs, _, h, w = images.shape # batch size, _, height, width
129 | bs = min(bs, max_subplots) # limit plot images
130 | ns = np.ceil(bs ** 0.5) # number of subplots (square)
131 |
132 | # Check if we should resize
133 | scale_factor = max_size / max(h, w)
134 | if scale_factor < 1:
135 | h = math.ceil(scale_factor * h)
136 | w = math.ceil(scale_factor * w)
137 |
138 | colors = color_list() # list of colors
139 | mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
140 | for i, img in enumerate(images):
141 | if i == max_subplots: # if last batch has fewer images than we expect
142 | break
143 |
144 | block_x = int(w * (i // ns))
145 | block_y = int(h * (i % ns))
146 |
147 | img = img.transpose(1, 2, 0)
148 | if scale_factor < 1:
149 | img = cv2.resize(img, (w, h))
150 |
151 | mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
152 | if len(targets) > 0:
153 | image_targets = targets[targets[:, 0] == i]
154 | boxes = xywh2xyxy(image_targets[:, 2:6]).T
155 | classes = image_targets[:, 1].astype('int')
156 | labels = image_targets.shape[1] == 6 # labels if no conf column
157 | conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
158 |
159 | if boxes.shape[1]:
160 | if boxes.max() <= 1.01: # if normalized with tolerance 0.01
161 | boxes[[0, 2]] *= w # scale to pixels
162 | boxes[[1, 3]] *= h
163 | elif scale_factor < 1: # absolute coords need scale if image scales
164 | boxes *= scale_factor
165 | boxes[[0, 2]] += block_x
166 | boxes[[1, 3]] += block_y
167 | for j, box in enumerate(boxes.T):
168 | cls = int(classes[j])
169 | color = colors[cls % len(colors)]
170 | cls = names[cls] if names else cls
171 | if labels or conf[j] > 0.25: # 0.25 conf thresh
172 | label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
173 | plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
174 |
175 | # Draw image filename labels
176 | if paths:
177 | label = Path(paths[i]).name[:40] # trim to 40 char
178 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
179 | cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
180 | lineType=cv2.LINE_AA)
181 |
182 | # Image border
183 | cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
184 |
185 | if fname:
186 | r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
187 | mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
188 | # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
189 | Image.fromarray(mosaic).save(fname) # PIL save
190 | return mosaic
191 |
192 |
193 | def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
194 | # Plot LR simulating training for full epochs
195 | optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
196 | y = []
197 | for _ in range(epochs):
198 | scheduler.step()
199 | y.append(optimizer.param_groups[0]['lr'])
200 | plt.plot(y, '.-', label='LR')
201 | plt.xlabel('epoch')
202 | plt.ylabel('LR')
203 | plt.grid()
204 | plt.xlim(0, epochs)
205 | plt.ylim(0)
206 | plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
207 | plt.close()
208 |
209 |
210 | def plot_test_txt(): # from utils.plots import *; plot_test()
211 | # Plot test.txt histograms
212 | x = np.loadtxt('test.txt', dtype=np.float32)
213 | box = xyxy2xywh(x[:, :4])
214 | cx, cy = box[:, 0], box[:, 1]
215 |
216 | fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
217 | ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
218 | ax.set_aspect('equal')
219 | plt.savefig('hist2d.png', dpi=300)
220 |
221 | fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
222 | ax[0].hist(cx, bins=600)
223 | ax[1].hist(cy, bins=600)
224 | plt.savefig('hist1d.png', dpi=200)
225 |
226 |
227 | def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
228 | # Plot targets.txt histograms
229 | x = np.loadtxt('targets.txt', dtype=np.float32).T
230 | s = ['x targets', 'y targets', 'width targets', 'height targets']
231 | fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
232 | ax = ax.ravel()
233 | for i in range(4):
234 | ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
235 | ax[i].legend()
236 | ax[i].set_title(s[i])
237 | plt.savefig('targets.jpg', dpi=200)
238 |
239 |
240 | def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
241 | # Plot study.txt generated by test.py
242 | fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
243 | # ax = ax.ravel()
244 |
245 | fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
246 | # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov3-tiny', 'yolov3', 'yolov3-spp', 'yolov5l']]:
247 | for f in sorted(Path(path).glob('study*.txt')):
248 | y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
249 | x = np.arange(y.shape[1]) if x is None else np.array(x)
250 | s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
251 | # for i in range(7):
252 | # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
253 | # ax[i].set_title(s[i])
254 |
255 | j = y[3].argmax() + 1
256 | ax2.plot(y[6, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
257 | label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
258 |
259 | ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
260 | 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
261 |
262 | ax2.grid(alpha=0.2)
263 | ax2.set_yticks(np.arange(20, 60, 5))
264 | ax2.set_xlim(0, 57)
265 | ax2.set_ylim(15, 55)
266 | ax2.set_xlabel('GPU Speed (ms/img)')
267 | ax2.set_ylabel('COCO AP val')
268 | ax2.legend(loc='lower right')
269 | plt.savefig(str(Path(path).name) + '.png', dpi=300)
270 |
271 |
272 | def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):
273 | # plot dataset labels
274 | print('Plotting labels... ')
275 | c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
276 | nc = int(c.max() + 1) # number of classes
277 | colors = color_list()
278 | x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
279 |
280 | # seaborn correlogram
281 | sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
282 | plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
283 | plt.close()
284 |
285 | # matplotlib labels
286 | matplotlib.use('svg') # faster
287 | ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
288 | ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
289 | ax[0].set_ylabel('instances')
290 | if 0 < len(names) < 30:
291 | ax[0].set_xticks(range(len(names)))
292 | ax[0].set_xticklabels(names, rotation=90, fontsize=10)
293 | else:
294 | ax[0].set_xlabel('classes')
295 | sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
296 | sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
297 |
298 | # rectangles
299 | labels[:, 1:3] = 0.5 # center
300 | labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
301 | img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
302 | for cls, *box in labels[:1000]:
303 | ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot
304 | ax[1].imshow(img)
305 | ax[1].axis('off')
306 |
307 | for a in [0, 1, 2, 3]:
308 | for s in ['top', 'right', 'left', 'bottom']:
309 | ax[a].spines[s].set_visible(False)
310 | plt.savefig(save_dir / 'labels.jpg', dpi=200)
311 | matplotlib.use('Agg')
312 | plt.close()
313 |
314 | # loggers
315 | for k, v in loggers.items() or {}:
316 | if k == 'wandb' and v:
317 | v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)
318 |
319 |
320 | def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
321 | # Plot hyperparameter evolution results in evolve.txt
322 | with open(yaml_file) as f:
323 | hyp = yaml.load(f, Loader=yaml.SafeLoader)
324 | x = np.loadtxt('evolve.txt', ndmin=2)
325 | f = fitness(x)
326 | # weights = (f - f.min()) ** 2 # for weighted results
327 | plt.figure(figsize=(10, 12), tight_layout=True)
328 | matplotlib.rc('font', **{'size': 8})
329 | for i, (k, v) in enumerate(hyp.items()):
330 | y = x[:, i + 7]
331 | # mu = (y * weights).sum() / weights.sum() # best weighted result
332 | mu = y[f.argmax()] # best single result
333 | plt.subplot(6, 5, i + 1)
334 | plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
335 | plt.plot(mu, f.max(), 'k+', markersize=15)
336 | plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
337 | if i % 5 != 0:
338 | plt.yticks([])
339 | print('%15s: %.3g' % (k, mu))
340 | plt.savefig('evolve.png', dpi=200)
341 | print('\nPlot saved as evolve.png')
342 |
343 |
344 | def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
345 | # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
346 | ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
347 | s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
348 | files = list(Path(save_dir).glob('frames*.txt'))
349 | for fi, f in enumerate(files):
350 | try:
351 | results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
352 | n = results.shape[1] # number of rows
353 | x = np.arange(start, min(stop, n) if stop else n)
354 | results = results[:, x]
355 | t = (results[0] - results[0].min()) # set t0=0s
356 | results[0] = x
357 | for i, a in enumerate(ax):
358 | if i < len(results):
359 | label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
360 | a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
361 | a.set_title(s[i])
362 | a.set_xlabel('time (s)')
363 | # if fi == len(files) - 1:
364 | # a.set_ylim(bottom=0)
365 | for side in ['top', 'right']:
366 | a.spines[side].set_visible(False)
367 | else:
368 | a.remove()
369 | except Exception as e:
370 | print('Warning: Plotting error for %s; %s' % (f, e))
371 |
372 | ax[1].legend()
373 | plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
374 |
375 |
376 | def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
377 | # Plot training 'results*.txt', overlaying train and val losses
378 | s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
379 | t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
380 | for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
381 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
382 | n = results.shape[1] # number of rows
383 | x = range(start, min(stop, n) if stop else n)
384 | fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
385 | ax = ax.ravel()
386 | for i in range(5):
387 | for j in [i, i + 5]:
388 | y = results[j, x]
389 | ax[i].plot(x, y, marker='.', label=s[j])
390 | # y_smooth = butter_lowpass_filtfilt(y)
391 | # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
392 |
393 | ax[i].set_title(t[i])
394 | ax[i].legend()
395 | ax[i].set_ylabel(f) if i == 0 else None # add filename
396 | fig.savefig(f.replace('.txt', '.png'), dpi=200)
397 |
398 |
399 | def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
400 | # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
401 | fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
402 | ax = ax.ravel()
403 | s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
404 | 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
405 | if bucket:
406 | # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
407 | files = ['results%g.txt' % x for x in id]
408 | c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
409 | os.system(c)
410 | else:
411 | files = list(Path(save_dir).glob('results*.txt'))
412 | assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
413 | for fi, f in enumerate(files):
414 | try:
415 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
416 | n = results.shape[1] # number of rows
417 | x = range(start, min(stop, n) if stop else n)
418 | for i in range(10):
419 | y = results[i, x]
420 | if i in [0, 1, 2, 5, 6, 7]:
421 | y[y == 0] = np.nan # don't show zero loss values
422 | # y /= y[0] # normalize
423 | label = labels[fi] if len(labels) else f.stem
424 | ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
425 | ax[i].set_title(s[i])
426 | # if i in [5, 6, 7]: # share train and val loss y axes
427 | # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
428 | except Exception as e:
429 | print('Warning: Plotting error for %s; %s' % (f, e))
430 |
431 | ax[1].legend()
432 | fig.savefig(Path(save_dir) / 'results.png', dpi=200)
433 |
--------------------------------------------------------------------------------
/models/common.py:
--------------------------------------------------------------------------------
1 | # YOLOv3 common modules
2 |
3 | import math
4 | from copy import copy
5 | from pathlib import Path
6 |
7 | import numpy as np
8 | import pandas as pd
9 | import requests
10 | import torch
11 | import torch.nn as nn
12 | from PIL import Image
13 | from torch.cuda import amp
14 |
15 | from utils.datasets import letterbox
16 | from utils.general import non_max_suppression, make_divisible, scale_coords, increment_path, xyxy2xywh
17 | from utils.plots import color_list, plot_one_box
18 | from utils.torch_utils import time_synchronized
19 |
20 |
21 | def autopad(k, p=None): # kernel, padding
22 | # Pad to 'same'
23 | if p is None:
24 | p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
25 | return p
26 |
27 |
28 | def DWConv(c1, c2, k=1, s=1, act=True):
29 | # Depthwise convolution
30 | return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
31 |
32 |
33 | class Conv(nn.Module):
34 | # Standard convolution
35 | def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
36 | super(Conv, self).__init__()
37 | self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
38 | self.bn = nn.BatchNorm2d(c2)
39 | self.act = nn.LeakyReLU(0.1) if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
40 |
41 | def forward(self, x):
42 | return self.act(self.bn(self.conv(x)))
43 |
44 | def fuseforward(self, x):
45 | return self.act(self.conv(x))
46 |
47 |
48 | class TransformerLayer(nn.Module):
49 | # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
50 | def __init__(self, c, num_heads):
51 | super().__init__()
52 | self.q = nn.Linear(c, c, bias=False)
53 | self.k = nn.Linear(c, c, bias=False)
54 | self.v = nn.Linear(c, c, bias=False)
55 | self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
56 | self.fc1 = nn.Linear(c, c, bias=False)
57 | self.fc2 = nn.Linear(c, c, bias=False)
58 |
59 | def forward(self, x):
60 | x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
61 | x = self.fc2(self.fc1(x)) + x
62 | return x
63 |
64 |
65 | class TransformerBlock(nn.Module):
66 | # Vision Transformer https://arxiv.org/abs/2010.11929
67 | def __init__(self, c1, c2, num_heads, num_layers):
68 | super().__init__()
69 | self.conv = None
70 | if c1 != c2:
71 | self.conv = Conv(c1, c2)
72 | self.linear = nn.Linear(c2, c2) # learnable position embedding
73 | self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)])
74 | self.c2 = c2
75 |
76 | def forward(self, x):
77 | if self.conv is not None:
78 | x = self.conv(x)
79 | b, _, w, h = x.shape
80 | p = x.flatten(2)
81 | p = p.unsqueeze(0)
82 | p = p.transpose(0, 3)
83 | p = p.squeeze(3)
84 | e = self.linear(p)
85 | x = p + e
86 |
87 | x = self.tr(x)
88 | x = x.unsqueeze(3)
89 | x = x.transpose(0, 3)
90 | x = x.reshape(b, self.c2, w, h)
91 | return x
92 |
93 |
94 | class Bottleneck(nn.Module):
95 | # Standard bottleneck
96 | def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
97 | super(Bottleneck, self).__init__()
98 | c_ = int(c2 * e) # hidden channels
99 | self.cv1 = Conv(c1, c_, 1, 1)
100 | self.cv2 = Conv(c_, c2, 3, 1, g=g)
101 | self.add = shortcut and c1 == c2
102 |
103 | def forward(self, x):
104 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
105 |
106 |
107 | class BottleneckCSP(nn.Module):
108 | # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
109 | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
110 | super(BottleneckCSP, self).__init__()
111 | c_ = int(c2 * e) # hidden channels
112 | self.cv1 = Conv(c1, c_, 1, 1)
113 | self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
114 | self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
115 | self.cv4 = Conv(2 * c_, c2, 1, 1)
116 | self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
117 | self.act = nn.LeakyReLU(0.1, inplace=True)
118 | self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
119 |
120 | def forward(self, x):
121 | y1 = self.cv3(self.m(self.cv1(x)))
122 | y2 = self.cv2(x)
123 | return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
124 |
125 |
126 | class C3(nn.Module):
127 | # CSP Bottleneck with 3 convolutions
128 | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
129 | super(C3, self).__init__()
130 | c_ = int(c2 * e) # hidden channels
131 | self.cv1 = Conv(c1, c_, 1, 1)
132 | self.cv2 = Conv(c1, c_, 1, 1)
133 | self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
134 | self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
135 | # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
136 |
137 | def forward(self, x):
138 | return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
139 |
140 |
141 | class C3TR(C3):
142 | # C3 module with TransformerBlock()
143 | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
144 | super().__init__(c1, c2, n, shortcut, g, e)
145 | c_ = int(c2 * e)
146 | self.m = TransformerBlock(c_, c_, 4, n)
147 |
148 |
149 | class SPP(nn.Module):
150 | # Spatial pyramid pooling layer used in YOLOv3-SPP
151 | def __init__(self, c1, c2, k=(5, 9, 13)):
152 | super(SPP, self).__init__()
153 | c_ = c1 // 2 # hidden channels
154 | self.cv1 = Conv(c1, c_, 1, 1)
155 | self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
156 | self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
157 |
158 | def forward(self, x):
159 | x = self.cv1(x)
160 | x = self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
161 | return x
162 |
163 |
164 | class GDConv(nn.Module):
165 | def __init__(self, inp, oup, kernel_size=1, ratio=2, dw_size=3, stride=1, relu=True, dialte=1):
166 | super(GDConv, self).__init__()
167 | self.oup = oup
168 | # ratio = oup
169 | init_channels = math.ceil(oup / ratio)
170 | # init_channels = 8
171 | new_channels = init_channels*(ratio-1)
172 | # new_channels = oup - init_channels
173 |
174 | self.primary_conv = nn.Sequential(
175 | nn.Conv2d(inp, init_channels, kernel_size, stride, kernel_size//2, bias=False),
176 | nn.BatchNorm2d(init_channels),
177 | nn.ReLU(inplace=True) if relu else nn.Sequential(),
178 | )
179 |
180 | self.cheap_operation = nn.Sequential(
181 | nn.Conv2d(init_channels, new_channels, dw_size, 1, dialte, groups=init_channels, dilation=dialte, bias=False),
182 | nn.BatchNorm2d(new_channels),
183 | nn.ReLU(inplace=True) if relu else nn.Sequential(),
184 | )
185 |
186 | def forward(self, x):
187 | x1 = self.primary_conv(x)
188 | x2 = self.cheap_operation(x1)
189 | out = torch.cat([x1, x2], dim=1)
190 | return out[:, :self.oup, :, :]
191 |
192 |
193 | class RMF(nn.Module):
194 | def __init__(self, inp, oup):
195 | super(RMF, self).__init__()
196 | ratio = 12
197 | oup = oup//ratio
198 | self.Dilation0_1 = GDConv(inp, oup, dialte=1)
199 | self.Dilation0_3 = GDConv(inp, oup, dialte=3)
200 | self.Dilation0_5 = GDConv(inp, oup, dialte=5)
201 |
202 | self.SPPmax5 = nn.MaxPool2d(kernel_size=5, stride=1, padding=2)
203 | self.Dilation1_1 = GDConv(inp, oup, dialte=1)
204 | self.Dilation1_3 = GDConv(inp, oup, dialte=3)
205 | self.Dilation1_5 = GDConv(inp, oup, dialte=5)
206 |
207 | self.SPPmax9 = nn.MaxPool2d(kernel_size=9, stride=1, padding=4)
208 | self.Dilation2_1 = GDConv(inp, oup, dialte=1)
209 | self.Dilation2_3 = GDConv(inp, oup, dialte=3)
210 | self.Dilation2_5 = GDConv(inp, oup, dialte=5)
211 |
212 | self.SPPmax13 = nn.MaxPool2d(kernel_size=13, stride=1, padding=6)
213 | self.Dilation3_1 = GDConv(inp, oup, dialte=1)
214 | self.Dilation3_3 = GDConv(inp, oup, dialte=3)
215 | self.Dilation3_5 = GDConv(inp, oup, dialte=5)
216 |
217 | def forward(self, x):
218 | x_d0_1 = self.Dilation0_1(x)
219 | x_d0_3 = self.Dilation0_3(x)
220 | x_d0_5 = self.Dilation0_5(x)
221 | x_d0 = torch.cat((x_d0_1, x_d0_3, x_d0_5), 1)
222 |
223 | x_spp5 = self.SPPmax5(x)
224 | x_d1_1 = self.Dilation1_1(x_spp5)
225 | x_d1_3 = self.Dilation1_3(x_spp5)
226 | x_d1_5 = self.Dilation1_5(x_spp5)
227 | x_d1 = torch.cat((x_d1_1, x_d1_3, x_d1_5), 1)
228 |
229 | x_spp9 = self.SPPmax9(x)
230 | x_d2_1 = self.Dilation2_1(x_spp9)
231 | x_d2_3 = self.Dilation2_3(x_spp9)
232 | x_d2_5 = self.Dilation2_5(x_spp9)
233 | x_d2 = torch.cat((x_d2_1, x_d2_3, x_d2_5), 1)
234 |
235 | x_spp13 = self.SPPmax13(x)
236 | x_d3_1 = self.Dilation3_1(x_spp13)
237 | x_d3_3 = self.Dilation3_3(x_spp13)
238 | x_d3_5 = self.Dilation3_5(x_spp13)
239 | x_d3 = torch.cat((x_d3_1, x_d3_3, x_d3_5), 1)
240 |
241 | xend = torch.cat((x_d0, x_d1, x_d2, x_d3), 1)
242 | return xend
243 |
244 |
245 | class MySpp(nn.Module):
246 | def __init__(self, inp, oup):
247 | super(MySpp, self).__init__()
248 | input = inp
249 | self.SPP1 = nn.MaxPool2d(kernel_size=5, stride=1, padding=2)
250 | self.SPP2 = nn.MaxPool2d(kernel_size=9, stride=1, padding=4)
251 | self.SPP3 = nn.MaxPool2d(kernel_size=13, stride=1, padding=6)
252 |
253 | def forward(self, x):
254 | x1 = self.SPP1(x)
255 | x2 = self.SPP2(x)
256 | x3 = self.SPP3(x)
257 | xend = torch.cat((x, x1, x2, x3), 1)
258 |
259 | return xend
260 |
261 |
262 | class GhostModule(nn.Module):
263 | def __init__(self, inp, oup, kernel_size=1, ratio=2, dw_size=3, stride=1, relu=True):
264 | super(GhostModule, self).__init__()
265 | self.oup = oup
266 | # ratio = oup
267 | init_channels = math.ceil(oup / ratio)
268 | # init_channels = 8
269 | new_channels = init_channels*(ratio-1)
270 | # new_channels = oup - init_channels
271 |
272 | self.primary_conv = nn.Sequential(
273 | nn.Conv2d(inp, init_channels, kernel_size, stride, kernel_size//2, bias=False),
274 | nn.BatchNorm2d(init_channels),
275 | nn.ReLU(inplace=True) if relu else nn.Sequential(),
276 | )
277 |
278 | self.cheap_operation = nn.Sequential(
279 | nn.Conv2d(init_channels, new_channels, dw_size, 1, dw_size//2, groups=init_channels, bias=False),
280 | nn.BatchNorm2d(new_channels),
281 | nn.ReLU(inplace=True) if relu else nn.Sequential(),
282 | )
283 |
284 | def forward(self, x):
285 | x1 = self.primary_conv(x)
286 | x2 = self.cheap_operation(x1)
287 | out = torch.cat([x1, x2], dim=1)
288 | return out[:, :self.oup, :, :]
289 |
290 |
291 | class CspGhost(nn.Module):
292 |
293 | def __init__(self, in_channels, op_channels):
294 | super(CspGhost, self).__init__()
295 | part_ratio = 0.25
296 | self.part1_chnls = int(in_channels * part_ratio)
297 | self.part2_chnls = in_channels - self.part1_chnls
298 | self.num_layers = op_channels - self.part1_chnls
299 | self.dense = GhostModule(self.part2_chnls, self.num_layers)
300 |
301 | def forward(self, x):
302 | part1 = x[:, :self.part1_chnls, :, :]
303 | part2 = x[:, self.part1_chnls:, :, :]
304 | part2 = self.dense(part2)
305 | # part2 = self.transtion(part2)
306 | out = torch.cat((part1, part2), 1)
307 | return out
308 |
309 |
310 | class EFE(nn.Module):
311 | def __init__(self, inp, oup, k=1, s=1, channel_change=True):
312 | super(EFE, self).__init__()
313 | self.conv1x1_1 = nn.Sequential(nn.Conv2d(inp, oup, kernel_size=k, stride=s, padding=0),
314 | nn.BatchNorm2d(oup, momentum=0.03, eps=1E-4))
315 | self.Ghost = CspGhost(oup, oup*2)
316 | self.conv1x1_2 = nn.Sequential(nn.Conv2d(oup*2, oup, kernel_size=k, stride=s, padding=0),
317 | nn.BatchNorm2d(oup, momentum=0.03, eps=1E-4))
318 |
319 | def forward(self, x):
320 | x = self.conv1x1_1(x)
321 | residual = x
322 | x = self.Ghost(x)
323 | x = self.conv1x1_2(x)
324 | x = residual + x
325 |
326 | return x
327 |
328 |
329 | class Focus(nn.Module):
330 | # Focus wh information into c-space
331 | def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
332 | super(Focus, self).__init__()
333 | self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
334 | # self.contract = Contract(gain=2)
335 |
336 | def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
337 | return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
338 | # return self.conv(self.contract(x))
339 |
340 |
341 | class Contract(nn.Module):
342 | # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
343 | def __init__(self, gain=2):
344 | super().__init__()
345 | self.gain = gain
346 |
347 | def forward(self, x):
348 | N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain'
349 | s = self.gain
350 | x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2)
351 | x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
352 | return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40)
353 |
354 |
355 | class Expand(nn.Module):
356 | # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
357 | def __init__(self, gain=2):
358 | super().__init__()
359 | self.gain = gain
360 |
361 | def forward(self, x):
362 | N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
363 | s = self.gain
364 | x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80)
365 | x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
366 | return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160)
367 |
368 |
369 | class Concat(nn.Module):
370 | # Concatenate a list of tensors along dimension
371 | def __init__(self, dimension=1):
372 | super(Concat, self).__init__()
373 | self.d = dimension
374 |
375 | def forward(self, x):
376 | return torch.cat(x, self.d)
377 |
378 |
379 | class NMS(nn.Module):
380 | # Non-Maximum Suppression (NMS) module
381 | conf = 0.25 # confidence threshold
382 | iou = 0.45 # IoU threshold
383 | classes = None # (optional list) filter by class
384 |
385 | def __init__(self):
386 | super(NMS, self).__init__()
387 |
388 | def forward(self, x):
389 | return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes)
390 |
391 |
392 | class autoShape(nn.Module):
393 | # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
394 | conf = 0.25 # NMS confidence threshold
395 | iou = 0.45 # NMS IoU threshold
396 | classes = None # (optional list) filter by class
397 |
398 | def __init__(self, model):
399 | super(autoShape, self).__init__()
400 | self.model = model.eval()
401 |
402 | def autoshape(self):
403 | print('autoShape already enabled, skipping... ') # model already converted to model.autoshape()
404 | return self
405 |
406 | @torch.no_grad()
407 | def forward(self, imgs, size=640, augment=False, profile=False):
408 | # Inference from various sources. For height=640, width=1280, RGB images example inputs are:
409 | # filename: imgs = 'data/samples/zidane.jpg'
410 | # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg'
411 | # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
412 | # PIL: = Image.open('image.jpg') # HWC x(640,1280,3)
413 | # numpy: = np.zeros((640,1280,3)) # HWC
414 | # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
415 | # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
416 |
417 | t = [time_synchronized()]
418 | p = next(self.model.parameters()) # for device and type
419 | if isinstance(imgs, torch.Tensor): # torch
420 | with amp.autocast(enabled=p.device.type != 'cpu'):
421 | return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
422 |
423 | # Pre-process
424 | n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
425 | shape0, shape1, files = [], [], [] # image and inference shapes, filenames
426 | for i, im in enumerate(imgs):
427 | f = f'image{i}' # filename
428 | if isinstance(im, str): # filename or uri
429 | im, f = np.asarray(Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im)), im
430 | elif isinstance(im, Image.Image): # PIL Image
431 | im, f = np.asarray(im), getattr(im, 'filename', f) or f
432 | files.append(Path(f).with_suffix('.jpg').name)
433 | if im.shape[0] < 5: # image in CHW
434 | im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
435 | im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input
436 | s = im.shape[:2] # HWC
437 | shape0.append(s) # image shape
438 | g = (size / max(s)) # gain
439 | shape1.append([y * g for y in s])
440 | imgs[i] = im # update
441 | shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
442 | x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
443 | x = np.stack(x, 0) if n > 1 else x[0][None] # stack
444 | x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
445 | x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32
446 | t.append(time_synchronized())
447 |
448 | with amp.autocast(enabled=p.device.type != 'cpu'):
449 | # Inference
450 | y = self.model(x, augment, profile)[0] # forward
451 | t.append(time_synchronized())
452 |
453 | # Post-process
454 | y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) # NMS
455 | for i in range(n):
456 | scale_coords(shape1, y[i][:, :4], shape0[i])
457 |
458 | t.append(time_synchronized())
459 | return Detections(imgs, y, files, t, self.names, x.shape)
460 |
461 |
462 | class Detections:
463 | # detections class for YOLOv3 inference results
464 | def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
465 | super(Detections, self).__init__()
466 | d = pred[0].device # device
467 | gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations
468 | self.imgs = imgs # list of images as numpy arrays
469 | self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
470 | self.names = names # class names
471 | self.files = files # image filenames
472 | self.xyxy = pred # xyxy pixels
473 | self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
474 | self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
475 | self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
476 | self.n = len(self.pred) # number of images (batch size)
477 | self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
478 | self.s = shape # inference BCHW shape
479 |
480 | def display(self, pprint=False, show=False, save=False, render=False, save_dir=''):
481 | colors = color_list()
482 | for i, (img, pred) in enumerate(zip(self.imgs, self.pred)):
483 | str = f'image {i + 1}/{len(self.pred)}: {img.shape[0]}x{img.shape[1]} '
484 | if pred is not None:
485 | for c in pred[:, -1].unique():
486 | n = (pred[:, -1] == c).sum() # detections per class
487 | str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
488 | if show or save or render:
489 | for *box, conf, cls in pred: # xyxy, confidence, class
490 | label = f'{self.names[int(cls)]} {conf:.2f}'
491 | plot_one_box(box, img, label=label, color=colors[int(cls) % 10])
492 | img = Image.fromarray(img.astype(np.uint8)) if isinstance(img, np.ndarray) else img # from np
493 | if pprint:
494 | print(str.rstrip(', '))
495 | if show:
496 | img.show(self.files[i]) # show
497 | if save:
498 | f = self.files[i]
499 | img.save(Path(save_dir) / f) # save
500 | print(f"{'Saved' * (i == 0)} {f}", end=',' if i < self.n - 1 else f' to {save_dir}\n')
501 | if render:
502 | self.imgs[i] = np.asarray(img)
503 |
504 | def print(self):
505 | self.display(pprint=True) # print results
506 | print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t)
507 |
508 | def show(self):
509 | self.display(show=True) # show results
510 |
511 | def save(self, save_dir='runs/hub/exp'):
512 | save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/hub/exp') # increment save_dir
513 | Path(save_dir).mkdir(parents=True, exist_ok=True)
514 | self.display(save=True, save_dir=save_dir) # save results
515 |
516 | def render(self):
517 | self.display(render=True) # render results
518 | return self.imgs
519 |
520 | def pandas(self):
521 | # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
522 | new = copy(self) # return copy
523 | ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
524 | cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
525 | for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
526 | a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
527 | setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
528 | return new
529 |
530 | def tolist(self):
531 | # return a list of Detections objects, i.e. 'for result in results.tolist():'
532 | x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
533 | for d in x:
534 | for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
535 | setattr(d, k, getattr(d, k)[0]) # pop out of list
536 | return x
537 |
538 | def __len__(self):
539 | return self.n
540 |
541 |
542 | class Classify(nn.Module):
543 | # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
544 | def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
545 | super(Classify, self).__init__()
546 | self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
547 | self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
548 | self.flat = nn.Flatten()
549 |
550 | def forward(self, x):
551 | z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
552 | return self.flat(self.conv(z)) # flatten to x(b,c2)
553 |
--------------------------------------------------------------------------------