├── .dockerignore
├── .gitignore
├── Dockerfile
├── README.md
├── READMEYolov.md
├── allbn.txt
├── data
├── GlobalWheat2020.yaml
├── VisDrone.yaml
├── argoverse_hd.yaml
├── coco.yaml
├── coco128.yaml
├── hyp.finetune.yaml
├── hyp.finetune_objects365.yaml
├── hyp.scratch.yaml
├── images
│ ├── bus.jpg
│ └── zidane.jpg
├── objects365.yaml
├── scripts
│ ├── get_argoverse_hd.sh
│ ├── get_coco.sh
│ ├── get_coco128.sh
│ └── get_voc.sh
└── voc.yaml
├── detect.py
├── detect_prune.py
├── finetune_prune_conv.py
├── finetune_pruned.py
├── finetune_pruned2.py
├── getweight.py
├── hubconf.py
├── img
├── Screenshot from 2021-05-23 20-19-08.png
├── Screenshot from 2021-05-23 20-19-30.png
├── Screenshot from 2021-05-24 22-17-16.png
├── Screenshot from 2021-05-25 00-26-23.png
├── Screenshot from 2021-05-25 00-26-45.png
├── Screenshot from 2021-05-25 00-28-15.png
├── Screenshot from 2021-05-25 00-28-52.png
├── Screenshot from 2021-05-27 22-20-33.png
├── Screenshot from 2021-05-28 08-33-25.png
├── Screenshot from 2021-05-31 22-29-12.png
├── Screenshot from 2021-05-31 22-30-21.png
├── Screenshot from 2021-06-05 00-06-27.png
└── Selection_007.png
├── map.txt
├── model_change.txt
├── modelparse.py
├── models
├── __init__.py
├── common.py
├── experimental.py
├── export.py
├── hub
│ ├── anchors.yaml
│ ├── yolov3-spp.yaml
│ ├── yolov3-tiny.yaml
│ ├── yolov3.yaml
│ ├── yolov5-fpn.yaml
│ ├── yolov5-p2.yaml
│ ├── yolov5-p6.yaml
│ ├── yolov5-p7.yaml
│ ├── yolov5-panet.yaml
│ ├── yolov5l6.yaml
│ ├── yolov5m6.yaml
│ ├── yolov5s-transformer.yaml
│ ├── yolov5s6.yaml
│ └── yolov5x6.yaml
├── modul.txt
├── pruned_common.py
├── yolo.py
├── yolov5l.yaml
├── yolov5m.yaml
├── yolov5s-opt.param
├── yolov5s.yaml
├── yolov5slite.yaml
├── yolov5sprune.yaml
└── yolov5x.yaml
├── prune.py
├── prune2.py
├── prune_conv.py
├── prune_convbn.py
├── prune_utils.py
├── reprune.py
├── requirements.txt
├── showbn.py
├── test.py
├── testprune.py
├── train.py
├── train_prune_sparsity.py
├── train_sparsity.py
├── train_sparsity2.py
├── train_sparsity3.py
├── train_sparsity4.py
├── tutorial.ipynb
├── utils
├── __init__.py
├── activations.py
├── autoanchor.py
├── aws
│ ├── __init__.py
│ ├── mime.sh
│ ├── resume.py
│ └── userdata.sh
├── datasets.py
├── flask_rest_api
│ ├── README.md
│ ├── example_request.py
│ └── restapi.py
├── general.py
├── google_app_engine
│ ├── Dockerfile
│ ├── additional_requirements.txt
│ └── app.yaml
├── google_utils.py
├── loss.py
├── metrics.py
├── plots.py
├── torch_utils.py
└── wandb_logging
│ ├── __init__.py
│ ├── log_dataset.py
│ └── wandb_utils.py
├── weights
└── download_weights.sh
└── yolov5prune.md
/.dockerignore:
--------------------------------------------------------------------------------
1 | # Repo-specific DockerIgnore -------------------------------------------------------------------------------------------
2 | #.git
3 | .cache
4 | .idea
5 | runs
6 | output
7 | coco
8 | storage.googleapis.com
9 |
10 | data/samples/*
11 | **/results*.txt
12 | *.jpg
13 |
14 | # Neural Network weights -----------------------------------------------------------------------------------------------
15 | **/*.weights
16 | **/*.pt
17 | **/*.pth
18 | **/*.onnx
19 | **/*.mlmodel
20 | **/*.torchscript
21 |
22 |
23 | # Below Copied From .gitignore -----------------------------------------------------------------------------------------
24 | # Below Copied From .gitignore -----------------------------------------------------------------------------------------
25 |
26 |
27 | # GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
28 | # Byte-compiled / optimized / DLL files
29 | __pycache__/
30 | *.py[cod]
31 | *$py.class
32 |
33 | # C extensions
34 | *.so
35 |
36 | # Distribution / packaging
37 | .Python
38 | env/
39 | build/
40 | develop-eggs/
41 | dist/
42 | downloads/
43 | eggs/
44 | .eggs/
45 | lib/
46 | lib64/
47 | parts/
48 | sdist/
49 | var/
50 | wheels/
51 | *.egg-info/
52 | wandb/
53 | .installed.cfg
54 | *.egg
55 |
56 | # PyInstaller
57 | # Usually these files are written by a python script from a template
58 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
59 | *.manifest
60 | *.spec
61 |
62 | # Installer logs
63 | pip-log.txt
64 | pip-delete-this-directory.txt
65 |
66 | # Unit test / coverage reports
67 | htmlcov/
68 | .tox/
69 | .coverage
70 | .coverage.*
71 | .cache
72 | nosetests.xml
73 | coverage.xml
74 | *.cover
75 | .hypothesis/
76 |
77 | # Translations
78 | *.mo
79 | *.pot
80 |
81 | # Django stuff:
82 | *.log
83 | local_settings.py
84 |
85 | # Flask stuff:
86 | instance/
87 | .webassets-cache
88 |
89 | # Scrapy stuff:
90 | .scrapy
91 |
92 | # Sphinx documentation
93 | docs/_build/
94 |
95 | # PyBuilder
96 | target/
97 |
98 | # Jupyter Notebook
99 | .ipynb_checkpoints
100 |
101 | # pyenv
102 | .python-version
103 |
104 | # celery beat schedule file
105 | celerybeat-schedule
106 |
107 | # SageMath parsed files
108 | *.sage.py
109 |
110 | # dotenv
111 | .env
112 |
113 | # virtualenv
114 | .venv*
115 | venv*/
116 | ENV*/
117 |
118 | # Spyder project settings
119 | .spyderproject
120 | .spyproject
121 |
122 | # Rope project settings
123 | .ropeproject
124 |
125 | # mkdocs documentation
126 | /site
127 |
128 | # mypy
129 | .mypy_cache/
130 |
131 |
132 | # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
133 |
134 | # General
135 | .DS_Store
136 | .AppleDouble
137 | .LSOverride
138 |
139 | # Icon must end with two \r
140 | Icon
141 | Icon?
142 |
143 | # Thumbnails
144 | ._*
145 |
146 | # Files that might appear in the root of a volume
147 | .DocumentRevisions-V100
148 | .fseventsd
149 | .Spotlight-V100
150 | .TemporaryItems
151 | .Trashes
152 | .VolumeIcon.icns
153 | .com.apple.timemachine.donotpresent
154 |
155 | # Directories potentially created on remote AFP share
156 | .AppleDB
157 | .AppleDesktop
158 | Network Trash Folder
159 | Temporary Items
160 | .apdisk
161 |
162 |
163 | # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
164 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
165 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
166 |
167 | # User-specific stuff:
168 | .idea/*
169 | .idea/**/workspace.xml
170 | .idea/**/tasks.xml
171 | .idea/dictionaries
172 | .html # Bokeh Plots
173 | .pg # TensorFlow Frozen Graphs
174 | .avi # videos
175 |
176 | # Sensitive or high-churn files:
177 | .idea/**/dataSources/
178 | .idea/**/dataSources.ids
179 | .idea/**/dataSources.local.xml
180 | .idea/**/sqlDataSources.xml
181 | .idea/**/dynamic.xml
182 | .idea/**/uiDesigner.xml
183 |
184 | # Gradle:
185 | .idea/**/gradle.xml
186 | .idea/**/libraries
187 |
188 | # CMake
189 | cmake-build-debug/
190 | cmake-build-release/
191 |
192 | # Mongo Explorer plugin:
193 | .idea/**/mongoSettings.xml
194 |
195 | ## File-based project format:
196 | *.iws
197 |
198 | ## Plugin-specific files:
199 |
200 | # IntelliJ
201 | out/
202 |
203 | # mpeltonen/sbt-idea plugin
204 | .idea_modules/
205 |
206 | # JIRA plugin
207 | atlassian-ide-plugin.xml
208 |
209 | # Cursive Clojure plugin
210 | .idea/replstate.xml
211 |
212 | # Crashlytics plugin (for Android Studio and IntelliJ)
213 | com_crashlytics_export_strings.xml
214 | crashlytics.properties
215 | crashlytics-build.properties
216 | fabric.properties
217 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Repo-specific GitIgnore ----------------------------------------------------------------------------------------------
2 | *.jpg
3 | *.jpeg
4 | *.bmp
5 | *.tif
6 | *.tiff
7 | *.heic
8 | *.JPG
9 | *.JPEG
10 | *.PNG
11 | *.BMP
12 | *.TIF
13 | *.TIFF
14 | *.HEIC
15 | *.mp4
16 | *.mov
17 | *.MOV
18 | *.avi
19 | *.data
20 | *.json
21 | *.pt
22 | *.pth
23 | data/Mini
24 | runs/*
25 | data/ztdiva.names
26 | data/mini.yaml
27 | runs
28 | runs/*
29 | data/test
30 | data/test/*
31 | *.pybk
32 |
33 | *.cfg
34 | !cfg/yolov3*.cfg
35 |
36 | storage.googleapis.com
37 | runs/*
38 |
39 | !data/images/zidane.jpg
40 | !data/images/bus.jpg
41 | !data/coco.names
42 | !data/coco_paper.names
43 | !data/coco.data
44 | !data/coco_*.data
45 | !data/coco_*.txt
46 | !data/trainvalno5k.shapes
47 | !data/*.sh
48 |
49 | pycocotools/*
50 | results*.txt
51 | gcp_test*.sh
52 |
53 | # Datasets -------------------------------------------------------------------------------------------------------------
54 | coco/
55 | coco128/
56 | VOC/
57 |
58 | # MATLAB GitIgnore -----------------------------------------------------------------------------------------------------
59 | *.m~
60 | *.mat
61 | !targets*.mat
62 |
63 | # Neural Network weights -----------------------------------------------------------------------------------------------
64 | *.weights
65 | *.pt
66 | *.onnx
67 | *.mlmodel
68 | *.torchscript
69 | darknet53.conv.74
70 | yolov3-tiny.conv.15
71 |
72 | # GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
73 | # Byte-compiled / optimized / DLL files
74 | __pycache__/
75 | *.py[cod]
76 | *$py.class
77 |
78 | # C extensions
79 | *.so
80 |
81 | # Distribution / packaging
82 | .Python
83 | env/
84 | build/
85 | develop-eggs/
86 | dist/
87 | downloads/
88 | eggs/
89 | .eggs/
90 | lib/
91 | lib64/
92 | parts/
93 | sdist/
94 | var/
95 | wheels/
96 | *.egg-info/
97 | wandb/
98 | .installed.cfg
99 | *.egg
100 |
101 |
102 | # PyInstaller
103 | # Usually these files are written by a python script from a template
104 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
105 | *.manifest
106 | *.spec
107 |
108 | # Installer logs
109 | pip-log.txt
110 | pip-delete-this-directory.txt
111 |
112 | # Unit test / coverage reports
113 | htmlcov/
114 | .tox/
115 | .coverage
116 | .coverage.*
117 | .cache
118 | nosetests.xml
119 | coverage.xml
120 | *.cover
121 | .hypothesis/
122 |
123 | # Translations
124 | *.mo
125 | *.pot
126 |
127 | # Django stuff:
128 | *.log
129 | local_settings.py
130 |
131 | # Flask stuff:
132 | instance/
133 | .webassets-cache
134 |
135 | # Scrapy stuff:
136 | .scrapy
137 |
138 | # Sphinx documentation
139 | docs/_build/
140 |
141 | # PyBuilder
142 | target/
143 |
144 | # Jupyter Notebook
145 | .ipynb_checkpoints
146 |
147 | # pyenv
148 | .python-version
149 |
150 | # celery beat schedule file
151 | celerybeat-schedule
152 |
153 | # SageMath parsed files
154 | *.sage.py
155 |
156 | # dotenv
157 | .env
158 |
159 | # virtualenv
160 | .venv*
161 | venv*/
162 | ENV*/
163 |
164 | # Spyder project settings
165 | .spyderproject
166 | .spyproject
167 |
168 | # Rope project settings
169 | .ropeproject
170 |
171 | # mkdocs documentation
172 | /site
173 |
174 | # mypy
175 | .mypy_cache/
176 |
177 |
178 | # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
179 |
180 | # General
181 | .DS_Store
182 | .AppleDouble
183 | .LSOverride
184 |
185 | # Icon must end with two \r
186 | Icon
187 | Icon?
188 |
189 | # Thumbnails
190 | ._*
191 |
192 | # Files that might appear in the root of a volume
193 | .DocumentRevisions-V100
194 | .fseventsd
195 | .Spotlight-V100
196 | .TemporaryItems
197 | .Trashes
198 | .VolumeIcon.icns
199 | .com.apple.timemachine.donotpresent
200 |
201 | # Directories potentially created on remote AFP share
202 | .AppleDB
203 | .AppleDesktop
204 | Network Trash Folder
205 | Temporary Items
206 | .apdisk
207 |
208 |
209 | # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
210 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
211 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
212 |
213 | # User-specific stuff:
214 | .idea/*
215 | .idea/**/workspace.xml
216 | .idea/**/tasks.xml
217 | .idea/dictionaries
218 | .html # Bokeh Plots
219 | .pg # TensorFlow Frozen Graphs
220 | .avi # videos
221 |
222 | # Sensitive or high-churn files:
223 | .idea/**/dataSources/
224 | .idea/**/dataSources.ids
225 | .idea/**/dataSources.local.xml
226 | .idea/**/sqlDataSources.xml
227 | .idea/**/dynamic.xml
228 | .idea/**/uiDesigner.xml
229 |
230 | # Gradle:
231 | .idea/**/gradle.xml
232 | .idea/**/libraries
233 |
234 | # CMake
235 | cmake-build-debug/
236 | cmake-build-release/
237 |
238 | # Mongo Explorer plugin:
239 | .idea/**/mongoSettings.xml
240 |
241 | ## File-based project format:
242 | *.iws
243 |
244 | ## Plugin-specific files:
245 |
246 | # IntelliJ
247 | out/
248 |
249 | # mpeltonen/sbt-idea plugin
250 | .idea_modules/
251 |
252 | # JIRA plugin
253 | atlassian-ide-plugin.xml
254 |
255 | # Cursive Clojure plugin
256 | .idea/replstate.xml
257 |
258 | # Crashlytics plugin (for Android Studio and IntelliJ)
259 | com_crashlytics_export_strings.xml
260 | crashlytics.properties
261 | crashlytics-build.properties
262 | fabric.properties
263 |
--------------------------------------------------------------------------------
/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/yolov5: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/yolov5: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/yolov5: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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # yolov5模型剪枝
2 |
3 | **`2022-1-4`**: 已更新v5.0版本m/l/x模型剪枝,理论上yolov5l6等模型也支持.
4 |
5 | **`2022-1-1`**: 已更新v6.0版本剪枝:https://github.com/midasklr/yolov5prune/tree/v6.0
6 |
7 | **`2021-12-14`**:近期会更新v6.0版本剪枝和蒸馏.
8 |
9 |
10 | 基于yolov5最新v5.0进行剪枝,采用yolov5s模型,目前仅支持s模型。
11 |
12 | 相关原理:
13 |
14 | Learning Efficient Convolutional Networks Through Network Slimming(https://arxiv.org/abs/1708.06519)
15 |
16 | Pruning Filters for Efficient ConvNets(https://arxiv.org/abs/1608.08710)
17 |
18 | 相关原理见https://blog.csdn.net/IEEE_FELLOW/article/details/117236025
19 |
20 | 这里实验了三种剪枝方式
21 |
22 | ## 剪枝方法1
23 |
24 | 基于BN层系数gamma剪枝。
25 |
26 | 在一个卷积-BN-激活模块中,BN层可以实现通道的缩放。如下:
27 |
28 |
29 |
30 |
31 |
32 | BN层的具体操作有两部分:
33 |
34 |
35 |
36 |
37 |
38 | 在归一化后会进行线性变换,那么当系数gamma很小时候,对应的激活(Zout)会相应很小。这些响应很小的输出可以裁剪掉,这样就实现了bn层的通道剪枝。
39 |
40 | 通过在loss函数中添加gamma的L1正则约束,可以实现gamma的稀疏化。
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | 上面损失函数L右边第一项是原始的损失函数,第二项是约束,其中g(s) = |s|,λ是正则系数,根据数据集调整
49 |
50 | 实际训练的时候,就是在优化L最小,依据梯度下降算法:
51 |
52 | 𝐿′=∑𝑙′+𝜆∑𝑔′(𝛾)=∑𝑙′+𝜆∑|𝛾|′=∑𝑙′+𝜆∑𝛾∗𝑠𝑖𝑔𝑛(𝛾)
53 |
54 | 所以只需要在BP传播时候,在BN层权重乘以权重的符号函数输出和系数即可,对应添加如下代码:
55 |
56 | ```python
57 | # Backward
58 | loss.backward()
59 | # scaler.scale(loss).backward()
60 | # # ============================= sparsity training ========================== #
61 | srtmp = opt.sr*(1 - 0.9*epoch/epochs)
62 | if opt.st:
63 | ignore_bn_list = []
64 | for k, m in model.named_modules():
65 | if isinstance(m, Bottleneck):
66 | if m.add:
67 | ignore_bn_list.append(k.rsplit(".", 2)[0] + ".cv1.bn")
68 | ignore_bn_list.append(k + '.cv1.bn')
69 | ignore_bn_list.append(k + '.cv2.bn')
70 | if isinstance(m, nn.BatchNorm2d) and (k not in ignore_bn_list):
71 | m.weight.grad.data.add_(srtmp * torch.sign(m.weight.data)) # L1
72 | m.bias.grad.data.add_(opt.sr*10 * torch.sign(m.bias.data)) # L1
73 | # # ============================= sparsity training ========================== #
74 |
75 | optimizer.step()
76 | # scaler.step(optimizer) # optimizer.step
77 | # scaler.update()
78 | optimizer.zero_grad()
79 | ```
80 |
81 | 这里并未对所有BN层gamma进行约束,详情见yolov5s每个模块 https://blog.csdn.net/IEEE_FELLOW/article/details/117536808
82 | 分析,这里对C3结构中的Bottleneck结构中有shortcut的层不进行剪枝,主要是为了保持tensor维度可以加:
83 |
84 |
85 |
86 |
87 |
88 | 实际上,在yolov5中,只有backbone中的Bottleneck是有shortcut的,Head中全部没有shortcut.
89 |
90 | 如果不加L1正则约束,训练结束后的BN层gamma分布近似正太分布:
91 |
92 |
93 |
94 |
95 |
96 | 是无法进行剪枝的。
97 |
98 | 稀疏训练后的分布:
99 |
100 |
101 |
102 |
103 |
104 | 可以看到,随着训练epoch进行,越来越多的gamma逼近0.
105 |
106 | 训练完成后可以进行剪枝,一个基本的原则是阈值不能大于任何通道bn的最大gamma。然后根据设定的裁剪比例剪枝。
107 |
108 | 剪掉一个BN层,需要将对应上一层的卷积核裁剪掉,同时将下一层卷积核对应的通道减掉。
109 |
110 | 这里在某个数据集上实验。
111 |
112 | 首先使用train.py进行正常训练:
113 |
114 | ```
115 | python train.py --weights yolov5s.pt --adam --epochs 100
116 | ```
117 |
118 | 然后稀疏训练:
119 |
120 | ```
121 | python train_sparsity.py --st --sr 0.0001 --weights yolov5s.pt --adam --epochs 100
122 | ```
123 |
124 | sr的选择需要根据数据集调整,可以通过观察tensorboard的map,gamma变化直方图等选择。
125 | 在run/train/exp*/目录下:
126 | ```
127 | tensorboard --logdir .
128 | ```
129 | 然后点击出现的链接观察训练中的各项指标.
130 |
131 | 训练完成后进行剪枝:
132 |
133 | ```
134 | python prune.py --weights runs/train/exp1/weights/last.pt --percent 0.5 --cfg models/yolov5s.yaml
135 | ```
136 |
137 | 裁剪比例percent根据效果调整,可以从小到大试。注意cfg的模型文件需要和weights对应上,否则会出现[运行prune 过程中出现键值不对应的问题](https://github.com/midasklr/yolov5prune/issues/65),裁剪完成会保存对应的模型pruned_model.pt。
138 |
139 | 微调:
140 |
141 | ```
142 | python finetune_pruned.py --weights pruned_model.pt --adam --epochs 100
143 | ```
144 |
145 | 在VOC2007数据集上实验,训练集为VOC07 trainval, 测试集为VOC07 test.作为对比,这里列举了faster rcnn和SSD512在相同数据集上的实验结果, yolov5输入大小为512.为了节省时间,这里使用AdamW训练100 epoch.
146 |
147 | | model | optim&epoch | sparity | mAP@.5 | mode size | forward time |
148 | | ----------------- | ----------- | ------- | ----------- | --------- | ------------ |
149 | | faster rcnn | | - | 69.9(paper) | | |
150 | | SSD512 | | - | 71.6(paper) | | |
151 | | yolov5s | sgd 300 | 0 | 67.4 | | |
152 | | yolov5s | adamw 100 | 0 | 66.3 | | |
153 | | yolov5s | adamw 100 | 0.0001 | 69.2 | | |
154 | | yolov5s | sgd 300 | 0.001 | Inf. error | | |
155 | | yolov5s | adamw 100 | 0.001 | 65.7 | 28.7 | 7.32 ms |
156 | | 55% prune yolov5s | | | 64.1 | 8.6 | 7.30 ms |
157 | | fine-tune above | | | 67.3 | | 7.21 ms |
158 | | yolov5l | adamw 100 | 0 | 70.1 | | |
159 | | yolov5l | adamw 100 | 0.001 | 0.659 | | 12.95 ms |
160 |
161 |
162 |
163 | 在自己数据集上的实验结果:
164 |
165 | | model | sparity | map | mode size |
166 | | --------------------- | ------- | ----- | --------- |
167 | | yolov5s | 0 | 0.322 | 28.7 M |
168 | | sparity train yolov5s | 0.001 | 0.325 | 28.7 M |
169 | | 65% pruned yolov5s | 0.001 | 0.318 | 6.8 M |
170 | | fine-tune | 0 | 0.325 | 6.8 M |
171 |
172 | ## 剪枝方法2
173 |
174 | 对于Bottleneck结构:
175 |
176 |
177 |
178 |
179 |
180 | 如果有右边的参差很小,那么就只剩下左边shortcut连接,相当于整个模块都裁剪掉。可以进行约束让参差逼近0.见train_sparsity2.py。
181 |
182 | backbone一共有3个bottleneck,裁剪全部bottleneck:
183 |
184 | | model | sparity | map | model size |
185 | | --------------------------- | ------- | ----- | ---------- |
186 | | yolov5s-prune all bottlenet | 0.001 | 0.167 | 28.7 M |
187 | | 85%+Bottlenet | | 0.151 | 1.1 M |
188 | | finetune | | 0.148 | |
189 |
190 | | 裁剪Bottleneck数 | map |
191 | | ----------------- | ----- |
192 | | 所有bottle res | 0.167 |
193 | | 第2,3的bottle res | 0.174 |
194 | | 第3的bottle res | 0.198 |
195 |
196 | 可以看到实际效果并不好,从bn层分布也可以看到,浅层特征很少被裁减掉。
197 |
198 | ## 剪枝方法3
199 |
200 | 卷积核剪枝,那些权重很小的卷积核对应输出也较小,那么对kernel进行约束,是可以对卷积核进行裁剪的。
201 |
202 | 裁剪卷积核需要将下一层BN层对应裁剪,同时裁剪下一层卷积层的输出通道。见train_sparsity3.py
203 |
204 | | | s | model size | map |
205 | | ---------------- | ---- | ---------- | ----- |
206 | | sparity train | 1e-5 | 28.7 M | 0.335 |
207 | | 50% kernel prune | | 8.4 M | 0.151 |
208 | | finetune | | 8.4 M | 0.332 |
209 |
210 | ## 剪枝方法4
211 |
212 | 混合1和3,见train_sparsity4.py
213 |
214 | | | map | model size |
215 | | --------------------------- | ----- | ---------- |
216 | | conv+bn sparity train | 0.284 | 28.7 M |
217 | | 85% bn prune | 0.284 | 3.7 M |
218 | | 78% conv prune | 0.284 | 3.9 M |
219 | | 85% bn prune+78% conv prune | 0.284 | 3.7 M |
220 |
221 |
222 | ## 替换backbone
223 |
224 | | model | size | mAPval 0.5:0.95 | mAPval 0.5 |
225 | | --------------------------- | ----- | ---------- | ------- |
226 | | yolov5s | 640 | 0.357 | 0.558 |
227 | | mobilenetv3small 0.75 | 640 | 0.24 | 0.421 |
228 |
229 |
230 |
231 | ## 调参
232 | 1. 浅层尽量少剪,从训练完成后gamma每一层的分布也可以看出来.
233 | 2. 系数λ的选择需要平衡map和剪枝力度.首先通过train.py训练一个正常情况下的baseline.然后在稀疏训练过程中观察MAP和gamma直方图变化,MAP掉点严重和gamma稀疏过快等情况下,可以适当降低λ.反之如果你想压缩一个尽量小的模型,可以适当调整λ.
234 | 3. 稀疏训练=>剪枝=>微调 可以反复迭代这个过程多次剪枝.
235 | 4. 使用yolov5默认的一些参数通常效果能获得不错的效果,比如使用SGD训练300 epoch,lr 0.01->0.001等,这里实验为了快速选用adamw训练了100 epoch。
236 | 5. 看到许多小伙伴提出了很多问题,有的我也没碰到,能解答的尽量解答。
237 | 6. 剪枝多少参数,有的是时候和数据集关系很大,我分别在简单任务(5k images,40+ class)和复杂数据集(20w+ images, 120+ class)实验过,简单任务可以将模型剪到很小(小模型也相对不够鲁棒);复杂的任务最终参数较难稀疏,能剪的参数很少(<20%)。
238 | 7. yolov5的s,m,l,x四个模型结构是一样的,只是深度和宽度两个维度的缩放系数不同,所以本代码应该也适用m,l,x模型。
239 | 8. 可以试试用大模型开始剪枝,比如用yolov5l,可能比直接用yolov5s开始剪枝效果更好?大模型的搜索空间通常更大。
240 | 9. 在自己的数据集上,设置合理的输入往往很重要, 公开数据集VOC和COCO等通常做了处理,例如VOC长边都是500, COCO长边都是640, 这也是SSD设置输入300和512, yolov5设置输入640的一个重要原因.如果要在自己数据集上获得较好的性能,可以试试调整输入.
241 |
242 | ## 常见问题
243 | 1. 稀疏训练是非常种重要的,也是调参的重点,多观察bn直方图变化,过快或者过慢都不适合,所以需要平衡你的sr, lr等.一般情况下,稀疏训练的结果和正常训练map是比较接近的.
244 | 2. 剪枝时候多试试不同的ratio,一个基本的准则是每层bn层至少保留一个channel,所以有时候稀疏训练不到位,而ratio设置的很大,会看到remaining channel里面会有0出现,这时候要么设置更小的ratio,要么重新稀疏训练,获得更稀疏的参数.
245 | 3. 如果想要移植到移动端,可以使用ncnn加速,另外剪枝时控制剩余channel为2^n能有效提升推理速度;GPU可以使用TensorRT加速。
246 |
--------------------------------------------------------------------------------
/data/GlobalWheat2020.yaml:
--------------------------------------------------------------------------------
1 | # Global Wheat 2020 dataset http://www.global-wheat.com/
2 | # Train command: python train.py --data GlobalWheat2020.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /datasets/GlobalWheat2020
6 | # /yolov5
7 |
8 |
9 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
10 | train: # 3422 images
11 | - ../datasets/GlobalWheat2020/images/arvalis_1
12 | - ../datasets/GlobalWheat2020/images/arvalis_2
13 | - ../datasets/GlobalWheat2020/images/arvalis_3
14 | - ../datasets/GlobalWheat2020/images/ethz_1
15 | - ../datasets/GlobalWheat2020/images/rres_1
16 | - ../datasets/GlobalWheat2020/images/inrae_1
17 | - ../datasets/GlobalWheat2020/images/usask_1
18 |
19 | val: # 748 images (WARNING: train set contains ethz_1)
20 | - ../datasets/GlobalWheat2020/images/ethz_1
21 |
22 | test: # 1276
23 | - ../datasets/GlobalWheat2020/images/utokyo_1
24 | - ../datasets/GlobalWheat2020/images/utokyo_2
25 | - ../datasets/GlobalWheat2020/images/nau_1
26 | - ../datasets/GlobalWheat2020/images/uq_1
27 |
28 | # number of classes
29 | nc: 1
30 |
31 | # class names
32 | names: [ 'wheat_head' ]
33 |
34 |
35 | # download command/URL (optional) --------------------------------------------------------------------------------------
36 | download: |
37 | from utils.general import download, Path
38 |
39 | # Download
40 | dir = Path('../datasets/GlobalWheat2020') # dataset directory
41 | urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
42 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']
43 | download(urls, dir=dir)
44 |
45 | # Make Directories
46 | for p in 'annotations', 'images', 'labels':
47 | (dir / p).mkdir(parents=True, exist_ok=True)
48 |
49 | # Move
50 | for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
51 | 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
52 | (dir / p).rename(dir / 'images' / p) # move to /images
53 | f = (dir / p).with_suffix('.json') # json file
54 | if f.exists():
55 | f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
56 |
--------------------------------------------------------------------------------
/data/VisDrone.yaml:
--------------------------------------------------------------------------------
1 | # VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset
2 | # Train command: python train.py --data VisDrone.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /VisDrone
6 | # /yolov5
7 |
8 |
9 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
10 | train: ../VisDrone/VisDrone2019-DET-train/images # 6471 images
11 | val: ../VisDrone/VisDrone2019-DET-val/images # 548 images
12 | test: ../VisDrone/VisDrone2019-DET-test-dev/images # 1610 images
13 |
14 | # number of classes
15 | nc: 10
16 |
17 | # class names
18 | names: [ 'pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor' ]
19 |
20 |
21 | # download command/URL (optional) --------------------------------------------------------------------------------------
22 | download: |
23 | from utils.general import download, os, Path
24 |
25 | def visdrone2yolo(dir):
26 | from PIL import Image
27 | from tqdm import tqdm
28 |
29 | def convert_box(size, box):
30 | # Convert VisDrone box to YOLO xywh box
31 | dw = 1. / size[0]
32 | dh = 1. / size[1]
33 | return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
34 |
35 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
36 | pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
37 | for f in pbar:
38 | img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
39 | lines = []
40 | with open(f, 'r') as file: # read annotation.txt
41 | for row in [x.split(',') for x in file.read().strip().splitlines()]:
42 | if row[4] == '0': # VisDrone 'ignored regions' class 0
43 | continue
44 | cls = int(row[5]) - 1
45 | box = convert_box(img_size, tuple(map(int, row[:4])))
46 | lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
47 | with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl:
48 | fl.writelines(lines) # write label.txt
49 |
50 |
51 | # Download
52 | dir = Path('../VisDrone') # dataset directory
53 | urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',
54 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',
55 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',
56 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']
57 | download(urls, dir=dir)
58 |
59 | # Convert
60 | for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
61 | visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
62 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 YOLOv5:
4 | # /parent_folder
5 | # /coco
6 | # /yolov5
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.safe_load(f) # dict
34 | # for i, x in enumerate(d['names']):
35 | # print(i, x)
36 |
--------------------------------------------------------------------------------
/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 YOLOv5:
4 | # /parent_folder
5 | # /coco128
6 | # /yolov5
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 |
--------------------------------------------------------------------------------
/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.001
12 | lrf: 0.2
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/hyp.finetune_objects365.yaml:
--------------------------------------------------------------------------------
1 | lr0: 0.00258
2 | lrf: 0.17
3 | momentum: 0.779
4 | weight_decay: 0.00058
5 | warmup_epochs: 1.33
6 | warmup_momentum: 0.86
7 | warmup_bias_lr: 0.0711
8 | box: 0.0539
9 | cls: 0.299
10 | cls_pw: 0.825
11 | obj: 0.632
12 | obj_pw: 1.0
13 | iou_t: 0.2
14 | anchor_t: 3.44
15 | anchors: 3.2
16 | fl_gamma: 0.0
17 | hsv_h: 0.0188
18 | hsv_s: 0.704
19 | hsv_v: 0.36
20 | degrees: 0.0
21 | translate: 0.0902
22 | scale: 0.491
23 | shear: 0.0
24 | perspective: 0.0
25 | flipud: 0.0
26 | fliplr: 0.5
27 | mosaic: 1.0
28 | mixup: 0.0
29 |
--------------------------------------------------------------------------------
/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.001 # initial learning rate (SGD=1E-2, Adam=1E-3)
7 | lrf: 0.1 # 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.1 # image translation (+/- fraction)
27 | scale: 0.5 # 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.5 # image flip left-right (probability)
32 | mosaic: 1.0 # image mosaic (probability)
33 | mixup: 0.0 # image mixup (probability)
34 |
--------------------------------------------------------------------------------
/data/images/bus.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/data/images/bus.jpg
--------------------------------------------------------------------------------
/data/images/zidane.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/data/images/zidane.jpg
--------------------------------------------------------------------------------
/data/objects365.yaml:
--------------------------------------------------------------------------------
1 | # Objects365 dataset https://www.objects365.org/
2 | # Train command: python train.py --data objects365.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /datasets/objects365
6 | # /yolov5
7 |
8 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
9 | train: ../datasets/objects365/images/train # 1742289 images
10 | val: ../datasets/objects365/images/val # 5570 images
11 |
12 | # number of classes
13 | nc: 365
14 |
15 | # class names
16 | names: [ 'Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup',
17 | 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book',
18 | 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag',
19 | 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV',
20 | 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle',
21 | 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird',
22 | 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck',
23 | 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning',
24 | 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife',
25 | 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock',
26 | 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish',
27 | 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan',
28 | 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard',
29 | 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign',
30 | 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat',
31 | 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard',
32 | 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry',
33 | 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks',
34 | 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors',
35 | 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape',
36 | 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck',
37 | 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette',
38 | 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket',
39 | 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine',
40 | 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine',
41 | 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon',
42 | 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse',
43 | 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball',
44 | 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin',
45 | 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts',
46 | 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit',
47 | 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD',
48 | 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder',
49 | 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips',
50 | 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab',
51 | 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal',
52 | 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart',
53 | 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French',
54 | 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell',
55 | 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil',
56 | 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis' ]
57 |
58 |
59 | # download command/URL (optional) --------------------------------------------------------------------------------------
60 | download: |
61 | from pycocotools.coco import COCO
62 | from tqdm import tqdm
63 |
64 | from utils.general import download, Path
65 |
66 | # Make Directories
67 | dir = Path('../datasets/objects365') # dataset directory
68 | for p in 'images', 'labels':
69 | (dir / p).mkdir(parents=True, exist_ok=True)
70 | for q in 'train', 'val':
71 | (dir / p / q).mkdir(parents=True, exist_ok=True)
72 |
73 | # Download
74 | url = "https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/"
75 | download([url + 'zhiyuan_objv2_train.tar.gz'], dir=dir, delete=False) # annotations json
76 | download([url + f for f in [f'patch{i}.tar.gz' for i in range(51)]], dir=dir / 'images' / 'train',
77 | curl=True, delete=False, threads=8)
78 |
79 | # Move
80 | train = dir / 'images' / 'train'
81 | for f in tqdm(train.rglob('*.jpg'), desc=f'Moving images'):
82 | f.rename(train / f.name) # move to /images/train
83 |
84 | # Labels
85 | coco = COCO(dir / 'zhiyuan_objv2_train.json')
86 | names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
87 | for cid, cat in enumerate(names):
88 | catIds = coco.getCatIds(catNms=[cat])
89 | imgIds = coco.getImgIds(catIds=catIds)
90 | for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):
91 | width, height = im["width"], im["height"]
92 | path = Path(im["file_name"]) # image filename
93 | try:
94 | with open(dir / 'labels' / 'train' / path.with_suffix('.txt').name, 'a') as file:
95 | annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None)
96 | for a in coco.loadAnns(annIds):
97 | x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner)
98 | x, y = x + w / 2, y + h / 2 # xy to center
99 | file.write(f"{cid} {x / width:.5f} {y / height:.5f} {w / width:.5f} {h / height:.5f}\n")
100 |
101 | except Exception as e:
102 | print(e)
103 |
--------------------------------------------------------------------------------
/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
84 | cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt >train.all.txt
85 |
86 | mkdir ../VOC ../VOC/images ../VOC/images/train ../VOC/images/val
87 | mkdir ../VOC/labels ../VOC/labels/train ../VOC/labels/val
88 |
89 | python3 - "$@" <= 1
87 | p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
88 | else:
89 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
90 |
91 | p = Path(p) # to Path
92 | save_path = str(save_dir / p.name) # img.jpg
93 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
94 | s += '%gx%g ' % img.shape[2:] # print string
95 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
96 | if len(det):
97 | # Rescale boxes from img_size to im0 size
98 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
99 |
100 | # Print results
101 | for c in det[:, -1].unique():
102 | n = (det[:, -1] == c).sum() # detections per class
103 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
104 |
105 | # Write results
106 | for *xyxy, conf, cls in reversed(det):
107 | if save_txt: # Write to file
108 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
109 | line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
110 | with open(txt_path + '.txt', 'a') as f:
111 | f.write(('%g ' * len(line)).rstrip() % line + '\n')
112 |
113 | if save_img or opt.save_crop or view_img: # Add bbox to image
114 | c = int(cls) # integer class
115 | label = None if opt.hide_labels else (names[c] if opt.hide_conf else f'{names[c]} {conf:.2f}')
116 |
117 | plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=opt.line_thickness)
118 | if opt.save_crop:
119 | save_one_box(xyxy, im0s, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
120 |
121 | # Print time (inference + NMS)
122 | print(f'{s}Done. ({t2 - t1:.3f}s)')
123 |
124 | # Stream results
125 | if view_img:
126 | cv2.imshow(str(p), im0)
127 | cv2.waitKey(1) # 1 millisecond
128 |
129 | # Save results (image with detections)
130 | if save_img:
131 | if dataset.mode == 'image':
132 | cv2.imwrite(save_path, im0)
133 | else: # 'video' or 'stream'
134 | if vid_path != save_path: # new video
135 | vid_path = save_path
136 | if isinstance(vid_writer, cv2.VideoWriter):
137 | vid_writer.release() # release previous video writer
138 | if vid_cap: # video
139 | fps = vid_cap.get(cv2.CAP_PROP_FPS)
140 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
141 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
142 | else: # stream
143 | fps, w, h = 30, im0.shape[1], im0.shape[0]
144 | save_path += '.mp4'
145 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
146 | vid_writer.write(im0)
147 |
148 | if save_txt or save_img:
149 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
150 | print(f"Results saved to {save_dir}{s}")
151 |
152 | print(f'Done. ({time.time() - t0:.3f}s) average inference time : {totaltime/len(dataset)} s')
153 |
154 |
155 | if __name__ == '__main__':
156 | parser = argparse.ArgumentParser()
157 | parser.add_argument('--weights', nargs='+', type=str, default='runs/train/exp20/weights/last.pt', help='model.pt path(s)')
158 | parser.add_argument('--source', type=str, default='VOC/images/test', help='source') # file/folder, 0 for webcam
159 | parser.add_argument('--img-size', type=int, default=512, help='inference size (pixels)')
160 | parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
161 | parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
162 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
163 | parser.add_argument('--view-img', action='store_true', help='display results')
164 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
165 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
166 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
167 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
168 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
169 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
170 | parser.add_argument('--augment', action='store_true', help='augmented inference')
171 | parser.add_argument('--update', action='store_true', help='update all models')
172 | parser.add_argument('--project', default='runs/detect', help='save results to project/name')
173 | parser.add_argument('--name', default='exp', help='save results to project/name')
174 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
175 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
176 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
177 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
178 | opt = parser.parse_args()
179 | print(opt)
180 | check_requirements(exclude=('tensorboard', 'pycocotools', 'thop'))
181 |
182 | with torch.no_grad():
183 | if opt.update: # update all models (to fix SourceChangeWarning)
184 | for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
185 | detect(opt=opt)
186 | strip_optimizer(opt.weights)
187 | else:
188 | detect(opt=opt)
189 |
--------------------------------------------------------------------------------
/detect_prune.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, save_one_box
14 | from utils.plots import colors, plot_one_box
15 | from utils.torch_utils import select_device, load_classifier, time_synchronized
16 | import time
17 |
18 | def detect(opt):
19 | source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
20 | save_img = not opt.nosave and not source.endswith('.txt') # save inference images
21 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
22 | ('rtsp://', 'rtmp://', 'http://', 'https://'))
23 |
24 | # Directories
25 | save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
26 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
27 |
28 | # Initialize
29 | set_logging()
30 | device = select_device(opt.device)
31 | half = device.type != 'cpu' # half precision only supported on CUDA
32 |
33 | # Load model
34 | model = attempt_load(weights, map_location=device) # load FP32 model
35 | stride = int(model.stride.max()) # model stride
36 | imgsz = check_img_size(imgsz, s=stride) # check img_size
37 | names = model.module.names if hasattr(model, 'module') else model.names # get class names
38 | if half:
39 | model.half() # to FP16
40 |
41 | # Second-stage classifier
42 | classify = False
43 | if classify:
44 | modelc = load_classifier(name='resnet101', n=2) # initialize
45 | modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
46 |
47 | # Set Dataloader
48 | vid_path, vid_writer = None, None
49 | if webcam:
50 | view_img = check_imshow()
51 | cudnn.benchmark = True # set True to speed up constant image size inference
52 | dataset = LoadStreams(source, img_size=imgsz, stride=stride)
53 | else:
54 | dataset = LoadImages(source, img_size=imgsz, stride=stride)
55 |
56 | # Run inference
57 | if device.type != 'cpu':
58 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
59 | t0 = time.time()
60 | totaltime = 0
61 | for path, img, im0s, vid_cap in dataset:
62 | img = torch.from_numpy(img).to(device)
63 | img = img.half() if half else img.float() # uint8 to fp16/32
64 | img /= 255.0 # 0 - 255 to 0.0 - 1.0
65 | if img.ndimension() == 3:
66 | img = img.unsqueeze(0)
67 |
68 | # Inference
69 | t1 = time_synchronized()
70 | start = time.time()
71 | pred = model(img, augment=opt.augment)[0]
72 | end = time.time()
73 | infertime = end - start
74 | totaltime += infertime
75 | # Apply NMS
76 | pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
77 | t2 = time_synchronized()
78 |
79 | # Apply Classifier
80 | if classify:
81 | pred = apply_classifier(pred, modelc, img, im0s)
82 |
83 | # Process detections
84 | for i, det in enumerate(pred): # detections per image
85 | if webcam: # batch_size >= 1
86 | p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
87 | else:
88 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
89 |
90 | p = Path(p) # to Path
91 | save_path = str(save_dir / p.name) # img.jpg
92 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
93 | s += '%gx%g ' % img.shape[2:] # print string
94 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
95 | if len(det):
96 | # Rescale boxes from img_size to im0 size
97 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
98 |
99 | # Print results
100 | for c in det[:, -1].unique():
101 | n = (det[:, -1] == c).sum() # detections per class
102 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
103 |
104 | # Write results
105 | for *xyxy, conf, cls in reversed(det):
106 | if save_txt: # Write to file
107 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
108 | line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
109 | with open(txt_path + '.txt', 'a') as f:
110 | f.write(('%g ' * len(line)).rstrip() % line + '\n')
111 |
112 | if save_img or opt.save_crop or view_img: # Add bbox to image
113 | c = int(cls) # integer class
114 | label = None if opt.hide_labels else (names[c] if opt.hide_conf else f'{names[c]} {conf:.2f}')
115 |
116 | plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=opt.line_thickness)
117 | if opt.save_crop:
118 | save_one_box(xyxy, im0s, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
119 |
120 | # Print time (inference + NMS)
121 | print(f'{s}Done. ({t2 - t1:.3f}s)')
122 |
123 | # Stream results
124 | if view_img:
125 | cv2.imshow(str(p), im0)
126 | cv2.waitKey(1) # 1 millisecond
127 |
128 | # Save results (image with detections)
129 | if save_img:
130 | if dataset.mode == 'image':
131 | cv2.imwrite(save_path, im0)
132 | else: # 'video' or 'stream'
133 | if vid_path != save_path: # new video
134 | vid_path = save_path
135 | if isinstance(vid_writer, cv2.VideoWriter):
136 | vid_writer.release() # release previous video writer
137 | if vid_cap: # video
138 | fps = vid_cap.get(cv2.CAP_PROP_FPS)
139 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
140 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
141 | else: # stream
142 | fps, w, h = 30, im0.shape[1], im0.shape[0]
143 | save_path += '.mp4'
144 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
145 | vid_writer.write(im0)
146 |
147 | if save_txt or save_img:
148 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
149 | print(f"Results saved to {save_dir}{s}")
150 |
151 | print(f'Done. ({time.time() - t0:.3f}s) average inference time : {totaltime/len(dataset)} s')
152 |
153 |
154 | if __name__ == '__main__':
155 | parser = argparse.ArgumentParser()
156 | parser.add_argument('--weights', nargs='+', type=str, default='runs/train/exp23/weights/last.pt', help='model.pt path(s)')
157 | parser.add_argument('--source', type=str, default='VOC/images/test', help='source') # file/folder, 0 for webcam
158 | parser.add_argument('--img-size', type=int, default=512, help='inference size (pixels)')
159 | parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
160 | parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
161 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
162 | parser.add_argument('--view-img', action='store_true', help='display results')
163 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
164 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
165 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
166 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
167 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
168 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
169 | parser.add_argument('--augment', action='store_true', help='augmented inference')
170 | parser.add_argument('--update', action='store_true', help='update all models')
171 | parser.add_argument('--project', default='runs/detect', help='save results to project/name')
172 | parser.add_argument('--name', default='exp', help='save results to project/name')
173 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
174 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
175 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
176 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
177 | opt = parser.parse_args()
178 | print(opt)
179 | check_requirements(exclude=('tensorboard', 'pycocotools', 'thop'))
180 |
181 | with torch.no_grad():
182 | if opt.update: # update all models (to fix SourceChangeWarning)
183 | for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
184 | detect(opt=opt)
185 | strip_optimizer(opt.weights)
186 | else:
187 | detect(opt=opt)
188 |
--------------------------------------------------------------------------------
/getweight.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | with open("map.txt","r") as f:
4 | lines = f.readlines()
5 |
6 |
7 | w = []
8 |
9 | for line in lines:
10 | w.append(line.split()[-2])
11 |
12 | w = [float(i) for i in w]
13 | print(w)
14 |
--------------------------------------------------------------------------------
/hubconf.py:
--------------------------------------------------------------------------------
1 | """YOLOv5 PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
2 |
3 | Usage:
4 | import torch
5 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
6 | """
7 |
8 | from pathlib import Path
9 |
10 | import torch
11 |
12 | from models.yolo import Model, attempt_load
13 | from utils.general import check_requirements, set_logging
14 | from utils.google_utils import attempt_download
15 | from utils.torch_utils import select_device
16 |
17 | dependencies = ['torch', 'yaml']
18 | check_requirements(Path(__file__).parent / 'requirements.txt', exclude=('tensorboard', 'pycocotools', 'thop'))
19 |
20 |
21 | def create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
22 | """Creates a specified YOLOv5 model
23 |
24 | Arguments:
25 | name (str): name of model, i.e. 'yolov5s'
26 | pretrained (bool): load pretrained weights into the model
27 | channels (int): number of input channels
28 | classes (int): number of model classes
29 | autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
30 | verbose (bool): print all information to screen
31 |
32 | Returns:
33 | YOLOv5 pytorch model
34 | """
35 | set_logging(verbose=verbose)
36 | fname = Path(name).with_suffix('.pt') # checkpoint filename
37 | try:
38 | if pretrained and channels == 3 and classes == 80:
39 | model = attempt_load(fname, map_location=torch.device('cpu')) # download/load FP32 model
40 | else:
41 | cfg = list((Path(__file__).parent / 'models').rglob(f'{name}.yaml'))[0] # model.yaml path
42 | model = Model(cfg, channels, classes) # create model
43 | if pretrained:
44 | attempt_download(fname) # download if not found locally
45 | ckpt = torch.load(fname, map_location=torch.device('cpu')) # load
46 | msd = model.state_dict() # model state_dict
47 | csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
48 | csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
49 | model.load_state_dict(csd, strict=False) # load
50 | if len(ckpt['model'].names) == classes:
51 | model.names = ckpt['model'].names # set class names attribute
52 | if autoshape:
53 | model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
54 | device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
55 | return model.to(device)
56 |
57 | except Exception as e:
58 | help_url = 'https://github.com/ultralytics/yolov5/issues/36'
59 | s = 'Cache may be out of date, try `force_reload=True`. See %s for help.' % help_url
60 | raise Exception(s) from e
61 |
62 |
63 | def custom(path='path/to/model.pt', autoshape=True, verbose=True):
64 | # YOLOv5 custom or local model
65 | return create(path, autoshape=autoshape, verbose=verbose)
66 |
67 |
68 | def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
69 | # YOLOv5-small model https://github.com/ultralytics/yolov5
70 | return create('yolov5s', pretrained, channels, classes, autoshape, verbose)
71 |
72 |
73 | def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
74 | # YOLOv5-medium model https://github.com/ultralytics/yolov5
75 | return create('yolov5m', pretrained, channels, classes, autoshape, verbose)
76 |
77 |
78 | def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
79 | # YOLOv5-large model https://github.com/ultralytics/yolov5
80 | return create('yolov5l', pretrained, channels, classes, autoshape, verbose)
81 |
82 |
83 | def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
84 | # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
85 | return create('yolov5x', pretrained, channels, classes, autoshape, verbose)
86 |
87 |
88 | def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
89 | # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
90 | return create('yolov5s6', pretrained, channels, classes, autoshape, verbose)
91 |
92 |
93 | def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
94 | # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
95 | return create('yolov5m6', pretrained, channels, classes, autoshape, verbose)
96 |
97 |
98 | def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
99 | # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
100 | return create('yolov5l6', pretrained, channels, classes, autoshape, verbose)
101 |
102 |
103 | def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
104 | # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
105 | return create('yolov5x6', pretrained, channels, classes, autoshape, verbose)
106 |
107 |
108 | if __name__ == '__main__':
109 | model = create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained
110 | # model = custom(path='path/to/model.pt') # custom
111 |
112 | # Verify inference
113 | import cv2
114 | import numpy as np
115 | from PIL import Image
116 |
117 | imgs = ['data/images/zidane.jpg', # filename
118 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg', # URI
119 | cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
120 | Image.open('data/images/bus.jpg'), # PIL
121 | np.zeros((320, 640, 3))] # numpy
122 |
123 | results = model(imgs) # batched inference
124 | results.print()
125 | results.save()
126 |
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-23 20-19-08.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-23 20-19-08.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-23 20-19-30.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-23 20-19-30.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-24 22-17-16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-24 22-17-16.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-25 00-26-23.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-25 00-26-23.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-25 00-26-45.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-25 00-26-45.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-25 00-28-15.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-25 00-28-15.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-25 00-28-52.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-25 00-28-52.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-27 22-20-33.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-27 22-20-33.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-28 08-33-25.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-28 08-33-25.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-31 22-29-12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-31 22-29-12.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-05-31 22-30-21.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-05-31 22-30-21.png
--------------------------------------------------------------------------------
/img/Screenshot from 2021-06-05 00-06-27.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Screenshot from 2021-06-05 00-06-27.png
--------------------------------------------------------------------------------
/img/Selection_007.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/img/Selection_007.png
--------------------------------------------------------------------------------
/map.txt:
--------------------------------------------------------------------------------
1 | person 999 3500 0.76 0.648 0.698 0.345
2 | chair 999 464 0.601 0.364 0.411 0.183
3 | vehicle 999 2153 0.765 0.786 0.815 0.557
4 | motorbike 999 826 0.624 0.558 0.579 0.292
5 | tablet_ad 999 1311 0.653 0.712 0.714 0.41
6 | trafficsign 999 164 0.568 0.457 0.476 0.293
7 | table 999 96 0.389 0.331 0.207 0.0921
8 | normal_tree 999 678 0.61 0.451 0.473 0.162
9 | rect_stall 999 111 0.543 0.225 0.251 0.0976
10 | tricycle 999 105 0.655 0.343 0.389 0.18
11 | bucket 999 228 0.577 0.487 0.481 0.261
12 | truck 999 89 0.503 0.461 0.471 0.295
13 | light_body 999 128 0.498 0.0776 0.14 0.0418
14 | cluster 999 177 0.34 0.0734 0.092 0.0418
15 | billboard_ad 999 261 0.411 0.264 0.237 0.125
16 | umbrella 999 186 0.804 0.747 0.781 0.46
17 | pedestrain_pile 999 178 0.684 0.292 0.324 0.153
18 | traffic_rail 999 180 0.462 0.434 0.374 0.157
19 | flat_stall 999 323 0.557 0.211 0.269 0.101
20 | vendor_business 999 229 0.59 0.393 0.383 0.128
21 | clothes 999 102 0.411 0.353 0.32 0.126
22 | basket_stall 999 140 0.333 0.243 0.216 0.103
23 |
24 |
25 |
26 |
27 |
28 | Class Images Labels P R mAP@.5 mAP@.5:.95: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████| 32/32 [00:10<00:00, 2.93it/s]
29 | all 999 11629 0.549 0.392 0.408 0.208
30 | person 999 3500 0.735 0.637 0.687 0.338
31 | chair 999 464 0.615 0.315 0.382 0.18
32 | vehicle 999 2153 0.752 0.787 0.828 0.563
33 | motorbike 999 826 0.635 0.567 0.585 0.293
34 | tablet_ad 999 1311 0.622 0.715 0.71 0.41
35 | trafficsign 999 164 0.549 0.5 0.476 0.295
36 | table 999 96 0.515 0.276 0.267 0.134
37 | normal_tree 999 678 0.574 0.441 0.455 0.165
38 | rect_stall 999 111 0.444 0.261 0.221 0.077
39 | tricycle 999 105 0.586 0.305 0.349 0.167
40 | bucket 999 228 0.618 0.421 0.459 0.248
41 | truck 999 89 0.535 0.551 0.523 0.327
42 | light_body 999 128 0.513 0.0495 0.154 0.0455
43 | cluster 999 177 0.267 0.0621 0.0681 0.0309
44 | billboard_ad 999 261 0.479 0.276 0.266 0.147
45 | umbrella 999 186 0.766 0.737 0.78 0.454
46 | pedestrain_pile 999 178 0.613 0.275 0.333 0.157
47 | traffic_rail 999 180 0.437 0.417 0.348 0.14
48 | flat_stall 999 323 0.563 0.232 0.286 0.0965
49 | vendor_business 999 229 0.521 0.31 0.318 0.114
50 | clothes 999 102 0.442 0.333 0.3 0.108
51 | basket_stall 999 140 0.304 0.157 0.173 0.0799
52 |
53 |
54 |
55 | Class Images Labels P R mAP@.5 mAP@.5:.95: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████| 250/250 [00:13<00:00, 18.34it/s]
56 | all 999 11629 0.539 0.392 0.401 0.201
57 | person 999 3500 0.743 0.635 0.685 0.339
58 | chair 999 464 0.547 0.351 0.383 0.176
59 | vehicle 999 2153 0.756 0.795 0.824 0.561
60 | motorbike 999 826 0.626 0.541 0.58 0.295
61 | tablet_ad 999 1311 0.619 0.732 0.702 0.406
62 | trafficsign 999 164 0.552 0.488 0.474 0.276
63 | table 999 96 0.302 0.323 0.221 0.103
64 | normal_tree 999 678 0.622 0.42 0.462 0.15
65 | rect_stall 999 111 0.406 0.148 0.171 0.0613
66 | tricycle 999 105 0.607 0.309 0.365 0.176
67 | bucket 999 228 0.666 0.464 0.471 0.246
68 | truck 999 89 0.476 0.506 0.509 0.324
69 | light_body 999 128 0.434 0.0859 0.121 0.0331
70 | cluster 999 177 0.305 0.0847 0.079 0.0277
71 | billboard_ad 999 261 0.382 0.199 0.212 0.109
72 | umbrella 999 186 0.765 0.726 0.757 0.432
73 | pedestrain_pile 999 178 0.708 0.287 0.328 0.152
74 | traffic_rail 999 180 0.396 0.433 0.345 0.153
75 | flat_stall 999 323 0.544 0.207 0.256 0.0846
76 | vendor_business 999 229 0.575 0.301 0.324 0.0996
77 | clothes 999 102 0.44 0.392 0.364 0.142
78 | basket_stall 999 140 0.382 0.186 0.18 0.0757
79 |
80 |
81 |
82 |
83 |
84 |
85 |
--------------------------------------------------------------------------------
/model_change.txt:
--------------------------------------------------------------------------------
1 | model.model[0].conv.conv = Conv2d(12, 31, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
2 | model.model[0].conv.bn = BatchNorm2d(31, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
3 | model.model[1].conv = Conv2d(32, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
4 | model.model[1].bn = BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
5 | model.model[2].cv1.conv = Conv2d(64, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
6 | model.model[2].cv1.bn = BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
7 | model.model[2].cv2.conv = Conv2d(64, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
8 | model.model[2].cv2.bn = BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
9 | model.model[2].cv3.conv = Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
10 | model.model[2].cv3.bn = BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
11 | model.model[2].m[0].cv1.conv = Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
12 | model.model[2].m[0].cv1.bn = BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
13 | model.model[3].conv = Conv2d(64, 127, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
14 | model.model[3].bn = BatchNorm2d(127, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
15 | model.model[4].cv1.conv = Conv2d(128, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
16 | model.model[4].cv1.bn = BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
17 | model.model[4].cv2.conv = Conv2d(128, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
18 | model.model[4].cv2.bn = BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
19 | model.model[4].cv3.conv = Conv2d(128, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
20 | model.model[4].cv3.bn = BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
21 | model.model[4].m[0].cv1.conv = Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
22 | model.model[4].m[0].cv1.bn = BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
23 | model.model[4].m[1].cv1.conv = Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
24 | model.model[4].m[1].cv1.bn = BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
25 | model.model[4].m[2].cv1.conv = Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
26 | model.model[4].m[2].cv1.bn = BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
27 | model.model[5].conv = Conv2d(128, 225, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
28 | model.model[5].bn = BatchNorm2d(225, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
29 | model.model[6].cv1.conv = Conv2d(256, 110, kernel_size=(1, 1), stride=(1, 1), bias=False)
30 | model.model[6].cv1.bn = BatchNorm2d(110, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
31 | model.model[6].cv2.conv = Conv2d(256, 90, kernel_size=(1, 1), stride=(1, 1), bias=False)
32 | model.model[6].cv2.bn = BatchNorm2d(90, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
33 | model.model[6].cv3.conv = Conv2d(256, 195, kernel_size=(1, 1), stride=(1, 1), bias=False)
34 | model.model[6].cv3.bn = BatchNorm2d(195, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
35 | model.model[6].m[0].cv1.conv = Conv2d(128, 102, kernel_size=(1, 1), stride=(1, 1), bias=False)
36 | model.model[6].m[0].cv1.bn = BatchNorm2d(102, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
37 | model.model[6].m[1].cv1.conv = Conv2d(128, 116, kernel_size=(1, 1), stride=(1, 1), bias=False)
38 | model.model[6].m[1].cv1.bn = BatchNorm2d(116, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
39 | model.model[6].m[2].cv1.conv = Conv2d(128, 106, kernel_size=(1, 1), stride=(1, 1), bias=False)
40 | model.model[6].m[2].cv1.bn = BatchNorm2d(106, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
41 | model.model[7].conv = Conv2d(256, 127, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
42 | model.model[7].bn = BatchNorm2d(127, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
43 | model.model[8].cv1.conv = Conv2d(512, 118, kernel_size=(1, 1), stride=(1, 1), bias=False)
44 | model.model[8].cv1.bn = BatchNorm2d(118, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
45 | model.model[8].cv2.conv = Conv2d(1024, 53, kernel_size=(1, 1), stride=(1, 1), bias=False)
46 | model.model[8].cv2.bn = BatchNorm2d(53, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
47 | model.model[9].cv1.conv = Conv2d(512, 14, kernel_size=(1, 1), stride=(1, 1), bias=False)
48 | model.model[9].cv1.bn = BatchNorm2d(14, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
49 | model.model[9].cv2.conv = Conv2d(512, 27, kernel_size=(1, 1), stride=(1, 1), bias=False)
50 | model.model[9].cv2.bn = BatchNorm2d(27, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
51 | model.model[9].cv3.conv = Conv2d(512, 34, kernel_size=(1, 1), stride=(1, 1), bias=False)
52 | model.model[9].cv3.bn = BatchNorm2d(34, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
53 | model.model[9].m[0].cv1.conv = Conv2d(256, 18, kernel_size=(1, 1), stride=(1, 1), bias=False)
54 | model.model[9].m[0].cv1.bn = BatchNorm2d(18, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
55 | model.model[9].m[0].cv2.conv = Conv2d(256, 26, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
56 | model.model[9].m[0].cv2.bn = BatchNorm2d(26, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
57 | model.model[10].conv = Conv2d(512, 40, kernel_size=(1, 1), stride=(1, 1), bias=False)
58 | model.model[10].bn = BatchNorm2d(40, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
59 | model.model[13].cv1.conv = Conv2d(512, 103, kernel_size=(1, 1), stride=(1, 1), bias=False)
60 | model.model[13].cv1.bn = BatchNorm2d(103, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
61 | model.model[13].cv2.conv = Conv2d(512, 63, kernel_size=(1, 1), stride=(1, 1), bias=False)
62 | model.model[13].cv2.bn = BatchNorm2d(63, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
63 | model.model[13].cv3.conv = Conv2d(256, 131, kernel_size=(1, 1), stride=(1, 1), bias=False)
64 | model.model[13].cv3.bn = BatchNorm2d(131, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
65 | model.model[13].m[0].cv1.conv = Conv2d(128, 100, kernel_size=(1, 1), stride=(1, 1), bias=False)
66 | model.model[13].m[0].cv1.bn = BatchNorm2d(100, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
67 | model.model[13].m[0].cv2.conv = Conv2d(128, 112, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
68 | model.model[13].m[0].cv2.bn = BatchNorm2d(112, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
69 | model.model[14].conv = Conv2d(256, 93, kernel_size=(1, 1), stride=(1, 1), bias=False)
70 | model.model[14].bn = BatchNorm2d(93, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
71 | model.model[17].cv1.conv = Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
72 | model.model[17].cv1.bn = BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
73 | model.model[17].cv2.conv = Conv2d(256, 44, kernel_size=(1, 1), stride=(1, 1), bias=False)
74 | model.model[17].cv2.bn = BatchNorm2d(44, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
75 | model.model[17].cv3.conv = Conv2d(128, 105, kernel_size=(1, 1), stride=(1, 1), bias=False)
76 | model.model[17].cv3.bn = BatchNorm2d(105, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
77 | model.model[17].m[0].cv1.conv = Conv2d(64, 58, kernel_size=(1, 1), stride=(1, 1), bias=False)
78 | model.model[17].m[0].cv1.bn = BatchNorm2d(58, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
79 | model.model[17].m[0].cv2.conv = Conv2d(64, 59, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
80 | model.model[17].m[0].cv2.bn = BatchNorm2d(59, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
81 | model.model[18].conv = Conv2d(128, 56, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
82 | model.model[18].bn = BatchNorm2d(56, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
83 | model.model[20].cv1.conv = Conv2d(256, 69, kernel_size=(1, 1), stride=(1, 1), bias=False)
84 | model.model[20].cv1.bn = BatchNorm2d(69, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
85 | model.model[20].cv2.conv = Conv2d(256, 47, kernel_size=(1, 1), stride=(1, 1), bias=False)
86 | model.model[20].cv2.bn = BatchNorm2d(47, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
87 | model.model[20].cv3.conv = Conv2d(256, 160, kernel_size=(1, 1), stride=(1, 1), bias=False)
88 | model.model[20].cv3.bn = BatchNorm2d(160, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
89 | model.model[20].m[0].cv1.conv = Conv2d(128, 69, kernel_size=(1, 1), stride=(1, 1), bias=False)
90 | model.model[20].m[0].cv1.bn = BatchNorm2d(69, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
91 | model.model[20].m[0].cv2.conv = Conv2d(128, 87, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
92 | model.model[20].m[0].cv2.bn = BatchNorm2d(87, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
93 | model.model[21].conv = Conv2d(256, 88, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
94 | model.model[21].bn = BatchNorm2d(88, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
95 | model.model[23].cv1.conv = Conv2d(512, 40, kernel_size=(1, 1), stride=(1, 1), bias=False)
96 | model.model[23].cv1.bn = BatchNorm2d(40, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
97 | model.model[23].cv2.conv = Conv2d(512, 53, kernel_size=(1, 1), stride=(1, 1), bias=False)
98 | model.model[23].cv2.bn = BatchNorm2d(53, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
99 | model.model[23].cv3.conv = Conv2d(512, 146, kernel_size=(1, 1), stride=(1, 1), bias=False)
100 | model.model[23].cv3.bn = BatchNorm2d(146, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
101 | model.model[23].m[0].cv1.conv = Conv2d(256, 35, kernel_size=(1, 1), stride=(1, 1), bias=False)
102 | model.model[23].m[0].cv1.bn = BatchNorm2d(35, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
103 | model.model[23].m[0].cv2.conv = Conv2d(256, 48, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
104 | model.model[23].m[0].cv2.bn = BatchNorm2d(48, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
105 |
--------------------------------------------------------------------------------
/modelparse.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 | from torch.utils.tensorboard import SummaryWriter
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, save_one_box
14 | from utils.plots import colors, plot_one_box
15 | from utils.torch_utils import select_device, load_classifier, time_synchronized
16 | import torch.nn as nn
17 |
18 | tb_writer = SummaryWriter()
19 |
20 | def detect(opt):
21 | source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
22 | save_img = not opt.nosave and not source.endswith('.txt') # save inference images
23 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
24 | ('rtsp://', 'rtmp://', 'http://', 'https://'))
25 |
26 | # Directories
27 | save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
28 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
29 |
30 | # Initialize
31 | set_logging()
32 | device = select_device(opt.device)
33 | half = device.type != 'cpu' # half precision only supported on CUDA
34 |
35 | # Load model
36 | print("weights:",weights)
37 | model = attempt_load(weights, map_location=device) # load FP32 model
38 | stride = int(model.stride.max()) # model stride
39 | imgsz = check_img_size(imgsz, s=stride) # check img_size
40 | names = model.module.names if hasattr(model, 'module') else model.names # get class names
41 | if half:
42 | model.half() # to FP16
43 |
44 | # Second-stage classifier
45 | classify = False
46 | if classify:
47 | modelc = load_classifier(name='resnet101', n=2) # initialize
48 | modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
49 |
50 | # Set Dataloader
51 | vid_path, vid_writer = None, None
52 | if webcam:
53 | view_img = check_imshow()
54 | cudnn.benchmark = True # set True to speed up constant image size inference
55 | dataset = LoadStreams(source, img_size=imgsz, stride=stride)
56 | else:
57 | dataset = LoadImages(source, img_size=imgsz, stride=stride)
58 |
59 | # Run inference
60 | if device.type != 'cpu':
61 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
62 | t0 = time.time()
63 | # =============== show bn weights ===================== #
64 | module_list = []
65 | for i,layer in model.named_modules():
66 | if isinstance(layer,nn.BatchNorm2d):
67 | bnw = layer.state_dict()['weight']
68 | module_list.append(bnw)
69 | # bnw = bnw.sort()
70 | # print(f"{i} : {bnw} : ")
71 | size_list = [idx.data.shape[0] for idx in module_list]
72 |
73 | bn_weights = torch.zeros(sum(size_list))
74 | index = 0
75 | for idx, size in enumerate(size_list):
76 | bn_weights[index:(index + size)] = module_list[idx].data.abs().clone()
77 | index += size
78 |
79 | print("bn_weights:",bn_weights.sort())
80 | tb_writer.add_histogram('bn_weights/hist', bn_weights.numpy(), 1, bins='doane')
81 |
82 | for path, img, im0s, vid_cap in dataset:
83 | img = torch.from_numpy(img).to(device)
84 | img = img.half() if half else img.float() # uint8 to fp16/32
85 | img /= 255.0 # 0 - 255 to 0.0 - 1.0
86 | if img.ndimension() == 3:
87 | img = img.unsqueeze(0)
88 |
89 | # Inference
90 | t1 = time_synchronized()
91 | pred = model(img, augment=opt.augment)[0]
92 |
93 | # Apply NMS
94 | pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
95 | t2 = time_synchronized()
96 |
97 | # Apply Classifier
98 | if classify:
99 | pred = apply_classifier(pred, modelc, img, im0s)
100 |
101 | # Process detections
102 | for i, det in enumerate(pred): # detections per image
103 | if webcam: # batch_size >= 1
104 | p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
105 | else:
106 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
107 |
108 | p = Path(p) # to Path
109 | save_path = str(save_dir / p.name) # img.jpg
110 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
111 | s += '%gx%g ' % img.shape[2:] # print string
112 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
113 | if len(det):
114 | # Rescale boxes from img_size to im0 size
115 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
116 |
117 | # Print results
118 | for c in det[:, -1].unique():
119 | n = (det[:, -1] == c).sum() # detections per class
120 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
121 |
122 | # Write results
123 | for *xyxy, conf, cls in reversed(det):
124 | if save_txt: # Write to file
125 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
126 | line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
127 | with open(txt_path + '.txt', 'a') as f:
128 | f.write(('%g ' * len(line)).rstrip() % line + '\n')
129 |
130 | if save_img or opt.save_crop or view_img: # Add bbox to image
131 | c = int(cls) # integer class
132 | label = None if opt.hide_labels else (names[c] if opt.hide_conf else f'{names[c]} {conf:.2f}')
133 |
134 | plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=opt.line_thickness)
135 | if opt.save_crop:
136 | save_one_box(xyxy, im0s, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
137 |
138 | # Print time (inference + NMS)
139 | print(f'{s}Done. ({t2 - t1:.3f}s)')
140 |
141 | # Stream results
142 | if view_img:
143 | cv2.imshow(str(p), im0)
144 | cv2.waitKey(1) # 1 millisecond
145 |
146 | # Save results (image with detections)
147 | if save_img:
148 | if dataset.mode == 'image':
149 | cv2.imwrite(save_path, im0)
150 | else: # 'video' or 'stream'
151 | if vid_path != save_path: # new video
152 | vid_path = save_path
153 | if isinstance(vid_writer, cv2.VideoWriter):
154 | vid_writer.release() # release previous video writer
155 | if vid_cap: # video
156 | fps = vid_cap.get(cv2.CAP_PROP_FPS)
157 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
158 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
159 | else: # stream
160 | fps, w, h = 30, im0.shape[1], im0.shape[0]
161 | save_path += '.mp4'
162 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
163 | vid_writer.write(im0)
164 |
165 | if save_txt or save_img:
166 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
167 | print(f"Results saved to {save_dir}{s}")
168 |
169 | print(f'Done. ({time.time() - t0:.3f}s)')
170 |
171 |
172 | if __name__ == '__main__':
173 | parser = argparse.ArgumentParser()
174 | parser.add_argument('--weights', nargs='+', type=str, default='/home/kong/yolov5/runs/train/exp78/weights/last.pt', help='model.pt path(s)')
175 | parser.add_argument('--source', type=str, default='/home/kong/yolov5/data/test', help='source') # file/folder, 0 for webcam
176 | parser.add_argument('--img-size', type=int, default=320, help='inference size (pixels)')
177 | parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
178 | parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
179 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
180 | parser.add_argument('--view-img', action='store_true', help='display results')
181 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
182 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
183 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
184 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
185 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
186 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
187 | parser.add_argument('--augment', action='store_true', help='augmented inference')
188 | parser.add_argument('--update', action='store_true', help='update all models')
189 | parser.add_argument('--project', default='runs/detect', help='save results to project/name')
190 | parser.add_argument('--name', default='exp', help='save results to project/name')
191 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
192 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
193 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
194 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
195 | opt = parser.parse_args()
196 | print(opt)
197 | # check_requirements(exclude=('tensorboard', 'pycocotools', 'thop'))
198 |
199 | with torch.no_grad():
200 | if opt.update: # update all models (to fix SourceChangeWarning)
201 | for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
202 | detect(opt=opt)
203 | strip_optimizer(opt.weights)
204 | else:
205 | detect(opt=opt)
206 |
--------------------------------------------------------------------------------
/models/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/models/__init__.py
--------------------------------------------------------------------------------
/models/experimental.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 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, inplace=True):
114 | from models.yolo import Detect, Model
115 |
116 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
117 | model = Ensemble()
118 | for w in weights if isinstance(weights, list) else [weights]:
119 | attempt_download(w)
120 | ckpt = torch.load(w, map_location=map_location) # load
121 | # print("ckpt:",ckpt['model'])
122 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().eval()) # FP32 model
123 | # model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
124 |
125 | # Compatibility updates
126 | for m in model.modules():
127 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
128 | m.inplace = inplace # pytorch 1.7.0 compatibility
129 | elif type(m) is Conv:
130 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
131 |
132 | if len(model) == 1:
133 | return model[-1] # return model
134 | else:
135 | print('Ensemble created with %s\n' % weights)
136 | for k in ['names', 'stride']:
137 | setattr(model, k, getattr(model[-1], k))
138 | return model # return ensemble
139 |
--------------------------------------------------------------------------------
/models/export.py:
--------------------------------------------------------------------------------
1 | """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
2 |
3 | Usage:
4 | $ export PYTHONPATH="$PWD" && python models/export.py --weights yolov5s.pt --img 640 --batch 1
5 | """
6 |
7 | import argparse
8 | import sys
9 | import time
10 | from pathlib import Path
11 |
12 | sys.path.append(Path(__file__).parent.parent.absolute().__str__()) # to run '$ python *.py' files in subdirectories
13 |
14 | import torch
15 | import torch.nn as nn
16 | from torch.utils.mobile_optimizer import optimize_for_mobile
17 |
18 | import models
19 | from models.experimental import attempt_load
20 | from utils.activations import Hardswish, SiLU
21 | from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging
22 | from utils.torch_utils import select_device
23 |
24 | if __name__ == '__main__':
25 | parser = argparse.ArgumentParser()
26 | parser.add_argument('--weights', type=str, default='/home/kong/yolov5/runs/train/exp181/weights/last.pt', help='weights path')
27 | parser.add_argument('--img-size', nargs='+', type=int, default=[416, 416], help='image size') # height, width
28 | parser.add_argument('--batch-size', type=int, default=1, help='batch size')
29 | parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
30 | parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
31 | parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
32 | parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only
33 | parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
34 | opt = parser.parse_args()
35 | opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
36 | print(opt)
37 | set_logging()
38 | t = time.time()
39 |
40 | # Load PyTorch model
41 | device = select_device(opt.device)
42 | model = attempt_load(opt.weights, map_location=device) # load FP32 model
43 | labels = model.names
44 |
45 | # Checks
46 | gs = int(max(model.stride)) # grid size (max stride)
47 | opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
48 | assert not (opt.device.lower() == "cpu" and opt.half), '--half only compatible with GPU export, i.e. use --device 0'
49 |
50 | # Input
51 | img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
52 |
53 | # Update model
54 | if opt.half:
55 | img, model = img.half(), model.half() # to FP16
56 | for k, m in model.named_modules():
57 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
58 | if isinstance(m, models.common.Conv): # assign export-friendly activations
59 | if isinstance(m.act, nn.Hardswish):
60 | m.act = Hardswish()
61 | elif isinstance(m.act, nn.SiLU):
62 | m.act = SiLU()
63 | elif isinstance(m, models.yolo.Detect):
64 | m.inplace = opt.inplace
65 | m.onnx_dynamic = opt.dynamic
66 | # m.forward = m.forward_export # assign forward (optional)
67 |
68 | for _ in range(2):
69 | y = model(img) # dry runs
70 | print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
71 |
72 | # TorchScript export -----------------------------------------------------------------------------------------------
73 | prefix = colorstr('TorchScript:')
74 | try:
75 | print(f'\n{prefix} starting export with torch {torch.__version__}...')
76 | f = opt.weights.replace('.pt', '.torchscript.pt') # filename
77 | ts = torch.jit.trace(model, img, strict=False)
78 | optimize_for_mobile(ts).save(f) # https://pytorch.org/tutorials/recipes/script_optimized.html
79 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
80 | except Exception as e:
81 | print(f'{prefix} export failure: {e}')
82 |
83 | # ONNX export ------------------------------------------------------------------------------------------------------
84 | prefix = colorstr('ONNX:')
85 | try:
86 | import onnx
87 |
88 | print(f'{prefix} starting export with onnx {onnx.__version__}...')
89 | f = opt.weights.replace('.pt', '.onnx') # filename
90 | torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
91 | dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
92 | 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
93 |
94 | # Checks
95 | model_onnx = onnx.load(f) # load onnx model
96 | onnx.checker.check_model(model_onnx) # check onnx model
97 | # print(onnx.helper.printable_graph(model_onnx.graph)) # print
98 |
99 | # Simplify
100 | if opt.simplify:
101 | try:
102 | check_requirements(['onnx-simplifier'])
103 | import onnxsim
104 |
105 | print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
106 | model_onnx, check = onnxsim.simplify(model_onnx,
107 | dynamic_input_shape=opt.dynamic,
108 | input_shapes={'images': list(img.shape)} if opt.dynamic else None)
109 | assert check, 'assert check failed'
110 | onnx.save(model_onnx, f)
111 | except Exception as e:
112 | print(f'{prefix} simplifier failure: {e}')
113 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
114 | except Exception as e:
115 | print(f'{prefix} export failure: {e}')
116 |
117 | # CoreML export ----------------------------------------------------------------------------------------------------
118 | prefix = colorstr('CoreML:')
119 | try:
120 | import coremltools as ct
121 |
122 | print(f'{prefix} starting export with coremltools {ct.__version__}...')
123 | # convert model from torchscript and apply pixel scaling as per detect.py
124 | model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
125 | f = opt.weights.replace('.pt', '.mlmodel') # filename
126 | model.save(f)
127 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
128 | except Exception as e:
129 | print(f'{prefix} export failure: {e}')
130 |
131 | # Finish
132 | print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')
133 |
--------------------------------------------------------------------------------
/models/hub/anchors.yaml:
--------------------------------------------------------------------------------
1 | # Default YOLOv5 anchors for COCO data
2 |
3 |
4 | # P5 -------------------------------------------------------------------------------------------------------------------
5 | # P5-640:
6 | anchors_p5_640:
7 | - [ 10,13, 16,30, 33,23 ] # P3/8
8 | - [ 30,61, 62,45, 59,119 ] # P4/16
9 | - [ 116,90, 156,198, 373,326 ] # P5/32
10 |
11 |
12 | # P6 -------------------------------------------------------------------------------------------------------------------
13 | # P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387
14 | anchors_p6_640:
15 | - [ 9,11, 21,19, 17,41 ] # P3/8
16 | - [ 43,32, 39,70, 86,64 ] # P4/16
17 | - [ 65,131, 134,130, 120,265 ] # P5/32
18 | - [ 282,180, 247,354, 512,387 ] # P6/64
19 |
20 | # P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792
21 | anchors_p6_1280:
22 | - [ 19,27, 44,40, 38,94 ] # P3/8
23 | - [ 96,68, 86,152, 180,137 ] # P4/16
24 | - [ 140,301, 303,264, 238,542 ] # P5/32
25 | - [ 436,615, 739,380, 925,792 ] # P6/64
26 |
27 | # P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187
28 | anchors_p6_1920:
29 | - [ 28,41, 67,59, 57,141 ] # P3/8
30 | - [ 144,103, 129,227, 270,205 ] # P4/16
31 | - [ 209,452, 455,396, 358,812 ] # P5/32
32 | - [ 653,922, 1109,570, 1387,1187 ] # P6/64
33 |
34 |
35 | # P7 -------------------------------------------------------------------------------------------------------------------
36 | # P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372
37 | anchors_p7_640:
38 | - [ 11,11, 13,30, 29,20 ] # P3/8
39 | - [ 30,46, 61,38, 39,92 ] # P4/16
40 | - [ 78,80, 146,66, 79,163 ] # P5/32
41 | - [ 149,150, 321,143, 157,303 ] # P6/64
42 | - [ 257,402, 359,290, 524,372 ] # P7/128
43 |
44 | # P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818
45 | anchors_p7_1280:
46 | - [ 19,22, 54,36, 32,77 ] # P3/8
47 | - [ 70,83, 138,71, 75,173 ] # P4/16
48 | - [ 165,159, 148,334, 375,151 ] # P5/32
49 | - [ 334,317, 251,626, 499,474 ] # P6/64
50 | - [ 750,326, 534,814, 1079,818 ] # P7/128
51 |
52 | # P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227
53 | anchors_p7_1920:
54 | - [ 29,34, 81,55, 47,115 ] # P3/8
55 | - [ 105,124, 207,107, 113,259 ] # P4/16
56 | - [ 247,238, 222,500, 563,227 ] # P5/32
57 | - [ 501,476, 376,939, 749,711 ] # P6/64
58 | - [ 1126,489, 801,1222, 1618,1227 ] # P7/128
59 |
--------------------------------------------------------------------------------
/models/hub/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 |
--------------------------------------------------------------------------------
/models/hub/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/hub/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 | [-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 |
--------------------------------------------------------------------------------
/models/hub/yolov5-fpn.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 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, Bottleneck, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, BottleneckCSP, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, BottleneckCSP, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 6, BottleneckCSP, [1024]], # 9
25 | ]
26 |
27 | # YOLOv5 FPN head
28 | head:
29 | [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large)
30 |
31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium)
35 |
36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
38 | [-1, 1, Conv, [256, 1, 1]],
39 | [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small)
40 |
41 | [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
42 | ]
43 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p2.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: 3
8 |
9 | # YOLOv5 backbone
10 | backbone:
11 | # [from, number, module, args]
12 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
13 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14 | [ -1, 3, C3, [ 128 ] ],
15 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16 | [ -1, 9, C3, [ 256 ] ],
17 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18 | [ -1, 9, C3, [ 512 ] ],
19 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32
20 | [ -1, 1, SPP, [ 1024, [ 5, 9, 13 ] ] ],
21 | [ -1, 3, C3, [ 1024, False ] ], # 9
22 | ]
23 |
24 | # YOLOv5 head
25 | head:
26 | [ [ -1, 1, Conv, [ 512, 1, 1 ] ],
27 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
28 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
29 | [ -1, 3, C3, [ 512, False ] ], # 13
30 |
31 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
32 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
33 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
34 | [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small)
35 |
36 | [ -1, 1, Conv, [ 128, 1, 1 ] ],
37 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
38 | [ [ -1, 2 ], 1, Concat, [ 1 ] ], # cat backbone P2
39 | [ -1, 1, C3, [ 128, False ] ], # 21 (P2/4-xsmall)
40 |
41 | [ -1, 1, Conv, [ 128, 3, 2 ] ],
42 | [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P3
43 | [ -1, 3, C3, [ 256, False ] ], # 24 (P3/8-small)
44 |
45 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
46 | [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4
47 | [ -1, 3, C3, [ 512, False ] ], # 27 (P4/16-medium)
48 |
49 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
50 | [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat head P5
51 | [ -1, 3, C3, [ 1024, False ] ], # 30 (P5/32-large)
52 |
53 | [ [ 24, 27, 30 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5)
54 | ]
55 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p6.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: 3
8 |
9 | # YOLOv5 backbone
10 | backbone:
11 | # [from, number, module, args]
12 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
13 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14 | [ -1, 3, C3, [ 128 ] ],
15 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16 | [ -1, 9, C3, [ 256 ] ],
17 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18 | [ -1, 9, C3, [ 512 ] ],
19 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
20 | [ -1, 3, C3, [ 768 ] ],
21 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
22 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
23 | [ -1, 3, C3, [ 1024, False ] ], # 11
24 | ]
25 |
26 | # YOLOv5 head
27 | head:
28 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
29 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
30 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
31 | [ -1, 3, C3, [ 768, False ] ], # 15
32 |
33 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
34 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
35 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
36 | [ -1, 3, C3, [ 512, False ] ], # 19
37 |
38 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
39 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
40 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
41 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
42 |
43 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
44 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
45 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
46 |
47 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
48 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
49 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
50 |
51 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
52 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
53 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P5/64-xlarge)
54 |
55 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
56 | ]
57 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p7.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: 3
8 |
9 | # YOLOv5 backbone
10 | backbone:
11 | # [from, number, module, args]
12 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
13 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
14 | [ -1, 3, C3, [ 128 ] ],
15 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
16 | [ -1, 9, C3, [ 256 ] ],
17 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
18 | [ -1, 9, C3, [ 512 ] ],
19 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
20 | [ -1, 3, C3, [ 768 ] ],
21 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
22 | [ -1, 3, C3, [ 1024 ] ],
23 | [ -1, 1, Conv, [ 1280, 3, 2 ] ], # 11-P7/128
24 | [ -1, 1, SPP, [ 1280, [ 3, 5 ] ] ],
25 | [ -1, 3, C3, [ 1280, False ] ], # 13
26 | ]
27 |
28 | # YOLOv5 head
29 | head:
30 | [ [ -1, 1, Conv, [ 1024, 1, 1 ] ],
31 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
32 | [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat backbone P6
33 | [ -1, 3, C3, [ 1024, False ] ], # 17
34 |
35 | [ -1, 1, Conv, [ 768, 1, 1 ] ],
36 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
37 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
38 | [ -1, 3, C3, [ 768, False ] ], # 21
39 |
40 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
41 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
42 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
43 | [ -1, 3, C3, [ 512, False ] ], # 25
44 |
45 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
46 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
47 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
48 | [ -1, 3, C3, [ 256, False ] ], # 29 (P3/8-small)
49 |
50 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
51 | [ [ -1, 26 ], 1, Concat, [ 1 ] ], # cat head P4
52 | [ -1, 3, C3, [ 512, False ] ], # 32 (P4/16-medium)
53 |
54 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
55 | [ [ -1, 22 ], 1, Concat, [ 1 ] ], # cat head P5
56 | [ -1, 3, C3, [ 768, False ] ], # 35 (P5/32-large)
57 |
58 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
59 | [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P6
60 | [ -1, 3, C3, [ 1024, False ] ], # 38 (P6/64-xlarge)
61 |
62 | [ -1, 1, Conv, [ 1024, 3, 2 ] ],
63 | [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P7
64 | [ -1, 3, C3, [ 1280, False ] ], # 41 (P7/128-xxlarge)
65 |
66 | [ [ 29, 32, 35, 38, 41 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6, P7)
67 | ]
68 |
--------------------------------------------------------------------------------
/models/hub/yolov5-panet.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 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, BottleneckCSP, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, BottleneckCSP, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, BottleneckCSP, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, BottleneckCSP, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 PANet head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, BottleneckCSP, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/hub/yolov5l6.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 | - [ 19,27, 44,40, 38,94 ] # P3/8
9 | - [ 96,68, 86,152, 180,137 ] # P4/16
10 | - [ 140,301, 303,264, 238,542 ] # P5/32
11 | - [ 436,615, 739,380, 925,792 ] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 | [ -1, 3, C3, [ 128 ] ],
19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 | [ -1, 9, C3, [ 256 ] ],
21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 | [ -1, 9, C3, [ 512 ] ],
23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 | [ -1, 3, C3, [ 768 ] ],
25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 | [ -1, 3, C3, [ 1024, False ] ], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 | [ -1, 3, C3, [ 768, False ] ], # 15
36 |
37 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 | [ -1, 3, C3, [ 512, False ] ], # 19
41 |
42 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 |
47 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 |
51 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 |
55 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 |
59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/hub/yolov5m6.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.67 # model depth multiple
4 | width_multiple: 0.75 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [ 19,27, 44,40, 38,94 ] # P3/8
9 | - [ 96,68, 86,152, 180,137 ] # P4/16
10 | - [ 140,301, 303,264, 238,542 ] # P5/32
11 | - [ 436,615, 739,380, 925,792 ] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 | [ -1, 3, C3, [ 128 ] ],
19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 | [ -1, 9, C3, [ 256 ] ],
21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 | [ -1, 9, C3, [ 512 ] ],
23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 | [ -1, 3, C3, [ 768 ] ],
25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 | [ -1, 3, C3, [ 1024, False ] ], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 | [ -1, 3, C3, [ 768, False ] ], # 15
36 |
37 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 | [ -1, 3, C3, [ 512, False ] ], # 19
41 |
42 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 |
47 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 |
51 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 |
55 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 |
59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/hub/yolov5s-transformer.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # 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 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3TR, [1024, False]], # 9 <-------- C3TR() Transformer module
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/hub/yolov5s6.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [ 19,27, 44,40, 38,94 ] # P3/8
9 | - [ 96,68, 86,152, 180,137 ] # P4/16
10 | - [ 140,301, 303,264, 238,542 ] # P5/32
11 | - [ 436,615, 739,380, 925,792 ] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 | [ -1, 3, C3, [ 128 ] ],
19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 | [ -1, 9, C3, [ 256 ] ],
21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 | [ -1, 9, C3, [ 512 ] ],
23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 | [ -1, 3, C3, [ 768 ] ],
25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 | [ -1, 3, C3, [ 1024, False ] ], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 | [ -1, 3, C3, [ 768, False ] ], # 15
36 |
37 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 | [ -1, 3, C3, [ 512, False ] ], # 19
41 |
42 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 |
47 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 |
51 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 |
55 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 |
59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/hub/yolov5x6.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.33 # model depth multiple
4 | width_multiple: 1.25 # layer channel multiple
5 |
6 | # anchors
7 | anchors:
8 | - [ 19,27, 44,40, 38,94 ] # P3/8
9 | - [ 96,68, 86,152, 180,137 ] # P4/16
10 | - [ 140,301, 303,264, 238,542 ] # P5/32
11 | - [ 436,615, 739,380, 925,792 ] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2
17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4
18 | [ -1, 3, C3, [ 128 ] ],
19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8
20 | [ -1, 9, C3, [ 256 ] ],
21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16
22 | [ -1, 9, C3, [ 512 ] ],
23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32
24 | [ -1, 3, C3, [ 768 ] ],
25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64
26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],
27 | [ -1, 3, C3, [ 1024, False ] ], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ],
33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5
35 | [ -1, 3, C3, [ 768, False ] ], # 15
36 |
37 | [ -1, 1, Conv, [ 512, 1, 1 ] ],
38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4
40 | [ -1, 3, C3, [ 512, False ] ], # 19
41 |
42 | [ -1, 1, Conv, [ 256, 1, 1 ] ],
43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],
44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3
45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small)
46 |
47 | [ -1, 1, Conv, [ 256, 3, 2 ] ],
48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4
49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium)
50 |
51 | [ -1, 1, Conv, [ 512, 3, 2 ] ],
52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5
53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large)
54 |
55 | [ -1, 1, Conv, [ 768, 3, 2 ] ],
56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6
57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge)
58 |
59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/pruned_common.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 pruned 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 torch.cuda import amp
13 | from models.common import Conv
14 |
15 |
16 | class BottleneckPruned(nn.Module):
17 | # Pruned bottleneck
18 | def __init__(self, cv1in, cv1out, cv2out, shortcut=True, g=1): # ch_in, ch_out, shortcut, groups, expansion
19 | super(BottleneckPruned, self).__init__()
20 | self.cv1 = Conv(cv1in, cv1out, 1, 1)
21 | self.cv2 = Conv(cv1out, cv2out, 3, 1, g=g)
22 | self.add = shortcut and cv1in == cv2out
23 |
24 | def forward(self, x):
25 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
26 |
27 |
28 | class C3Pruned(nn.Module):
29 | # CSP Bottleneck with 3 convolutions
30 | def __init__(self, cv1in, cv1out, cv2out, cv3out, bottle_args, n=1, shortcut=True, g=1): # ch_in, ch_out, number, shortcut, groups, expansion
31 | super(C3Pruned, self).__init__()
32 | cv3in = bottle_args[-1][-1]
33 | self.cv1 = Conv(cv1in, cv1out, 1, 1)
34 | self.cv2 = Conv(cv1in, cv2out, 1, 1)
35 | self.cv3 = Conv(cv3in+cv2out, cv3out, 1)
36 | self.m = nn.Sequential(*[BottleneckPruned(*bottle_args[k], shortcut, g) for k in range(n)])
37 |
38 | def forward(self, x):
39 | return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
40 |
41 |
42 | class C3PrunedNoRes(nn.Module):
43 | # CSP Bottleneck with 3 convolutions
44 | def __init__(self, cv1in, cv1out, cv2out, cv3out): # ch_in, ch_out
45 | super(C3PrunedNoRes, self).__init__()
46 | self.cv1 = Conv(cv1in, cv1out, 1, 1)
47 | self.cv2 = Conv(cv1in, cv2out, 1, 1)
48 | self.cv3 = Conv(cv1out+cv2out, cv3out, 1)
49 |
50 | def forward(self, x):
51 | return self.cv3(torch.cat((self.cv1(x), self.cv2(x)), dim=1))
52 |
53 | class SPPPruned(nn.Module):
54 | # Spatial pyramid pooling layer used in YOLOv3-SPP
55 | def __init__(self, cv1in, cv1out, cv2out, k=(5, 9, 13)):
56 | super(SPPPruned, self).__init__()
57 | self.cv1 = Conv(cv1in, cv1out, 1, 1)
58 | self.cv2 = Conv(cv1out * (len(k) + 1), cv2out, 1, 1)
59 | self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
60 |
61 | def forward(self, x):
62 | x = self.cv1(x)
63 | return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
64 |
65 |
66 |
--------------------------------------------------------------------------------
/models/yolov5l.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 22 # 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 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/yolov5m.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.67 # model depth multiple
4 | width_multiple: 0.75 # 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 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/yolov5s.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # 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 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/yolov5slite.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 22 # number of classes
3 | depth_multiple: 0.25 # model depth multiple
4 | width_multiple: 0.25 # 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 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 7, 9]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/yolov5sprune.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # 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 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [0:[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | 1:[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | 2:[-1, 3, C3, [128]],
18 | 3:[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | 4:[-1, 9, C3, [256]],
20 | 5:[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | 6:[-1, 9, C3, [512]],
22 | 7:[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | 8:[-1, 1, SPP, [1024, [5, 9, 13]]],
24 | 9:[-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [10:[-1, 1, Conv, [512, 1, 1]],
30 | 11:[-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | 12:[[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | 13:[-1, 3, C3, [512, False]], # 13
33 |
34 | 14:[-1, 1, Conv, [256, 1, 1]],
35 | 15:[-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | 16:[[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | 17:[-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | 18:[-1, 1, Conv, [256, 3, 2]],
40 | 19:[[-1, 14], 1, Concat, [1]], # cat head P4
41 | 20:[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | 21:[-1, 1, Conv, [512, 3, 2]],
44 | 22:[[-1, 10], 1, Concat, [1]], # cat head P5
45 | 23:[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | 24:[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/yolov5x.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.33 # model depth multiple
4 | width_multiple: 1.25 # 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 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/prune_utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time : 2021/5/24 下午4:36
3 | # @Author : midaskong
4 | # @File : prune_utils.py
5 | # @Description:
6 |
7 | import torch
8 | from copy import deepcopy
9 | import numpy as np
10 | import torch.nn.functional as F
11 |
12 |
13 | def gather_bn_weights(module_list):
14 | prune_idx = list(range(len(module_list)))
15 | size_list = [idx.weight.data.shape[0] for idx in module_list.values()]
16 | bn_weights = torch.zeros(sum(size_list))
17 | index = 0
18 | for i, idx in enumerate(module_list.values()):
19 | size = size_list[i]
20 | bn_weights[index:(index + size)] = idx.weight.data.abs().clone()
21 | index += size
22 | return bn_weights
23 |
24 | def gather_conv_weights(module_list):
25 | prune_idx = list(range(len(module_list)))
26 | size_list = [idx.weight.data.shape[0] for idx in module_list.values()]
27 |
28 | conv_weights = torch.zeros(sum(size_list))
29 | index = 0
30 | for i, idx in enumerate(module_list.values()):
31 | size = size_list[i]
32 | conv_weights[index:(index + size)] = idx.weight.data.abs().sum(dim=1).sum(dim=1).sum(dim=1).clone()
33 | index += size
34 | return conv_weights
35 |
36 |
37 | def obtain_bn_mask(bn_module, thre):
38 |
39 | thre = thre.cuda()
40 | mask = bn_module.weight.data.abs().ge(thre).float()
41 |
42 | return mask
43 |
44 |
45 | def obtain_conv_mask(conv_module, thre):
46 | thre = thre.cuda()
47 | mask = conv_module.weight.data.abs().sum(dim=1).sum(dim=1).sum(dim=1).ge(thre).float()
48 | return mask
49 |
50 | def uodate_pruned_yolov5_cfg(model, maskbndict):
51 | # save pruned yolov5 model in yaml format:
52 | # model:
53 | # model to be pruned
54 | # maskbndict:
55 | # key : module name
56 | # value : bn layer mask index
57 | return
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install -r requirements.txt
2 |
3 | # base ----------------------------------------
4 | matplotlib>=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 |
--------------------------------------------------------------------------------
/showbn.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, save_one_box
14 | from utils.plots import colors, plot_one_box
15 | from utils.torch_utils import select_device, load_classifier, time_synchronized
16 |
17 |
18 | def detect(opt):
19 | source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
20 | save_img = not opt.nosave and not source.endswith('.txt') # save inference images
21 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
22 | ('rtsp://', 'rtmp://', 'http://', 'https://'))
23 |
24 | # Directories
25 | save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
26 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
27 |
28 | # Initialize
29 | set_logging()
30 | device = select_device(opt.device)
31 | half = device.type != 'cpu' # half precision only supported on CUDA
32 |
33 | # Load model
34 | model = attempt_load(weights, map_location=device) # load FP32 model
35 | stride = int(model.stride.max()) # model stride
36 | imgsz = check_img_size(imgsz, s=stride) # check img_size
37 | names = model.module.names if hasattr(model, 'module') else model.names # get class names
38 |
39 | # Run inference
40 | if device.type != 'cpu':
41 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
42 | t0 = time.time()
43 | print(model)
44 | for i,layer in enumerate(model.state_dict().keys()):
45 | print(f"{i} : {layer} : {model.state_dict()[layer].size()}")
46 |
47 |
48 | if __name__ == '__main__':
49 | parser = argparse.ArgumentParser()
50 | parser.add_argument('--weights', nargs='+', type=str, default='/home/kong/yolov5/yolov5s.pt', help='model.pt path(s)')
51 | parser.add_argument('--source', type=str, default='/home/kong/yolov5/data/test', help='source') # file/folder, 0 for webcam
52 | parser.add_argument('--img-size', type=int, default=416, help='inference size (pixels)')
53 | parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
54 | parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
55 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
56 | parser.add_argument('--view-img', action='store_true', help='display results')
57 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
58 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
59 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
60 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
61 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
62 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
63 | parser.add_argument('--augment', action='store_true', help='augmented inference')
64 | parser.add_argument('--update', action='store_true', help='update all models')
65 | parser.add_argument('--project', default='runs/detect', help='save results to project/name')
66 | parser.add_argument('--name', default='exp', help='save results to project/name')
67 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
68 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
69 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
70 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
71 | opt = parser.parse_args()
72 | print(opt)
73 | check_requirements(exclude=('tensorboard', 'pycocotools', 'thop'))
74 |
75 | with torch.no_grad():
76 | if opt.update: # update all models (to fix SourceChangeWarning)
77 | for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
78 | detect(opt=opt)
79 | strip_optimizer(opt.weights)
80 | else:
81 | detect(opt=opt)
82 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/utils/__init__.py
--------------------------------------------------------------------------------
/utils/activations.py:
--------------------------------------------------------------------------------
1 | # Activation functions
2 |
3 | import torch
4 | import torch.nn as nn
5 | import torch.nn.functional as F
6 |
7 |
8 | # SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
9 | class SiLU(nn.Module): # export-friendly version of nn.SiLU()
10 | @staticmethod
11 | def forward(x):
12 | return x * torch.sigmoid(x)
13 |
14 |
15 | class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
16 | @staticmethod
17 | def forward(x):
18 | # return x * F.hardsigmoid(x) # for torchscript and CoreML
19 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
20 |
21 |
22 | # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
23 | class Mish(nn.Module):
24 | @staticmethod
25 | def forward(x):
26 | return x * F.softplus(x).tanh()
27 |
28 |
29 | class MemoryEfficientMish(nn.Module):
30 | class F(torch.autograd.Function):
31 | @staticmethod
32 | def forward(ctx, x):
33 | ctx.save_for_backward(x)
34 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
35 |
36 | @staticmethod
37 | def backward(ctx, grad_output):
38 | x = ctx.saved_tensors[0]
39 | sx = torch.sigmoid(x)
40 | fx = F.softplus(x).tanh()
41 | return grad_output * (fx + x * sx * (1 - fx * fx))
42 |
43 | def forward(self, x):
44 | return self.F.apply(x)
45 |
46 |
47 | # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
48 | class FReLU(nn.Module):
49 | def __init__(self, c1, k=3): # ch_in, kernel
50 | super().__init__()
51 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
52 | self.bn = nn.BatchNorm2d(c1)
53 |
54 | def forward(self, x):
55 | return torch.max(x, self.bn(self.conv(x)))
56 |
57 |
58 | # ACON https://arxiv.org/pdf/2009.04759.pdf ----------------------------------------------------------------------------
59 | class AconC(nn.Module):
60 | r""" ACON activation (activate or not).
61 | AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
62 | according to "Activate or Not: Learning Customized Activation" .
63 | """
64 |
65 | def __init__(self, c1):
66 | super().__init__()
67 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
68 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
69 | self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
70 |
71 | def forward(self, x):
72 | dpx = (self.p1 - self.p2) * x
73 | return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
74 |
75 |
76 | class MetaAconC(nn.Module):
77 | r""" ACON activation (activate or not).
78 | MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
79 | according to "Activate or Not: Learning Customized Activation" .
80 | """
81 |
82 | def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
83 | super().__init__()
84 | c2 = max(r, c1 // r)
85 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
86 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
87 | self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
88 | self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
89 | # self.bn1 = nn.BatchNorm2d(c2)
90 | # self.bn2 = nn.BatchNorm2d(c1)
91 |
92 | def forward(self, x):
93 | y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
94 | # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
95 | # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
96 | beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
97 | dpx = (self.p1 - self.p2) * x
98 | return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
99 |
--------------------------------------------------------------------------------
/utils/autoanchor.py:
--------------------------------------------------------------------------------
1 | # Auto-anchor utils
2 |
3 | import numpy as np
4 | import torch
5 | import yaml
6 | from tqdm import tqdm
7 |
8 | from utils.general import colorstr
9 |
10 |
11 | def check_anchor_order(m):
12 | # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
13 | a = m.anchor_grid.prod(-1).view(-1) # anchor area
14 | da = a[-1] - a[0] # delta a
15 | ds = m.stride[-1] - m.stride[0] # delta s
16 | if da.sign() != ds.sign(): # same order
17 | print('Reversing anchor order')
18 | m.anchors[:] = m.anchors.flip(0)
19 | m.anchor_grid[:] = m.anchor_grid.flip(0)
20 |
21 |
22 | def check_anchors(dataset, model, thr=4.0, imgsz=640):
23 | # Check anchor fit to data, recompute if necessary
24 | prefix = colorstr('autoanchor: ')
25 | print(f'\n{prefix}Analyzing anchors... ', end='')
26 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
27 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
28 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
29 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
30 |
31 | def metric(k): # compute metric
32 | r = wh[:, None] / k[None]
33 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
34 | best = x.max(1)[0] # best_x
35 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
36 | bpr = (best > 1. / thr).float().mean() # best possible recall
37 | return bpr, aat
38 |
39 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
40 | bpr, aat = metric(anchors)
41 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
42 | if bpr < 0.98: # threshold to recompute
43 | print('. Attempting to improve anchors, please wait...')
44 | na = m.anchor_grid.numel() // 2 # number of anchors
45 | try:
46 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
47 | except Exception as e:
48 | print(f'{prefix}ERROR: {e}')
49 | new_bpr = metric(anchors)[0]
50 | if new_bpr > bpr: # replace anchors
51 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
52 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
53 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
54 | check_anchor_order(m)
55 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
56 | else:
57 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
58 | print('') # newline
59 |
60 |
61 | def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
62 | """ Creates kmeans-evolved anchors from training dataset
63 |
64 | Arguments:
65 | path: path to dataset *.yaml, or a loaded dataset
66 | n: number of anchors
67 | img_size: image size used for training
68 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
69 | gen: generations to evolve anchors using genetic algorithm
70 | verbose: print all results
71 |
72 | Return:
73 | k: kmeans evolved anchors
74 |
75 | Usage:
76 | from utils.autoanchor import *; _ = kmean_anchors()
77 | """
78 | from scipy.cluster.vq import kmeans
79 |
80 | thr = 1. / thr
81 | prefix = colorstr('autoanchor: ')
82 |
83 | def metric(k, wh): # compute metrics
84 | r = wh[:, None] / k[None]
85 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
86 | # x = wh_iou(wh, torch.tensor(k)) # iou metric
87 | return x, x.max(1)[0] # x, best_x
88 |
89 | def anchor_fitness(k): # mutation fitness
90 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
91 | return (best * (best > thr).float()).mean() # fitness
92 |
93 | def print_results(k):
94 | k = k[np.argsort(k.prod(1))] # sort small to large
95 | x, best = metric(k, wh0)
96 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
97 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
98 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
99 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
100 | for i, x in enumerate(k):
101 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
102 | return k
103 |
104 | if isinstance(path, str): # *.yaml file
105 | with open(path) as f:
106 | data_dict = yaml.safe_load(f) # model dict
107 | from utils.datasets import LoadImagesAndLabels
108 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
109 | else:
110 | dataset = path # dataset
111 |
112 | # Get label wh
113 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
114 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
115 |
116 | # Filter
117 | i = (wh0 < 3.0).any(1).sum()
118 | if i:
119 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
120 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
121 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
122 |
123 | # Kmeans calculation
124 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
125 | s = wh.std(0) # sigmas for whitening
126 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
127 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
128 | k *= s
129 | wh = torch.tensor(wh, dtype=torch.float32) # filtered
130 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
131 | k = print_results(k)
132 |
133 | # Plot
134 | # k, d = [None] * 20, [None] * 20
135 | # for i in tqdm(range(1, 21)):
136 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
137 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
138 | # ax = ax.ravel()
139 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
140 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
141 | # ax[0].hist(wh[wh[:, 0]<100, 0],400)
142 | # ax[1].hist(wh[wh[:, 1]<100, 1],400)
143 | # fig.savefig('wh.png', dpi=200)
144 |
145 | # Evolve
146 | npr = np.random
147 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
148 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar
149 | for _ in pbar:
150 | v = np.ones(sh)
151 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
152 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
153 | kg = (k.copy() * v).clip(min=2.0)
154 | fg = anchor_fitness(kg)
155 | if fg > f:
156 | f, k = fg, kg.copy()
157 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
158 | if verbose:
159 | print_results(k)
160 |
161 | return print_results(k)
162 |
--------------------------------------------------------------------------------
/utils/aws/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/utils/aws/__init__.py
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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.safe_load(f)
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 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/README.md:
--------------------------------------------------------------------------------
1 | # Flask REST API
2 | [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API created using Flask to expose the `yolov5s` model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/).
3 |
4 | ## Requirements
5 |
6 | [Flask](https://palletsprojects.com/p/flask/) is required. Install with:
7 | ```shell
8 | $ pip install Flask
9 | ```
10 |
11 | ## Run
12 |
13 | After Flask installation run:
14 |
15 | ```shell
16 | $ python3 restapi.py --port 5000
17 | ```
18 |
19 | Then use [curl](https://curl.se/) to perform a request:
20 |
21 | ```shell
22 | $ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'`
23 | ```
24 |
25 | The model inference results are returned:
26 |
27 | ```shell
28 | [{'class': 0,
29 | 'confidence': 0.8197850585,
30 | 'name': 'person',
31 | 'xmax': 1159.1403808594,
32 | 'xmin': 750.912902832,
33 | 'ymax': 711.2583007812,
34 | 'ymin': 44.0350036621},
35 | {'class': 0,
36 | 'confidence': 0.5667674541,
37 | 'name': 'person',
38 | 'xmax': 1065.5523681641,
39 | 'xmin': 116.0448303223,
40 | 'ymax': 713.8904418945,
41 | 'ymin': 198.4603881836},
42 | {'class': 27,
43 | 'confidence': 0.5661227107,
44 | 'name': 'tie',
45 | 'xmax': 516.7975463867,
46 | 'xmin': 416.6880187988,
47 | 'ymax': 717.0524902344,
48 | 'ymin': 429.2020568848}]
49 | ```
50 |
51 | An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given in `example_request.py`
52 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/example_request.py:
--------------------------------------------------------------------------------
1 | """Perform test request"""
2 | import pprint
3 |
4 | import requests
5 |
6 | DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s"
7 | TEST_IMAGE = "zidane.jpg"
8 |
9 | image_data = open(TEST_IMAGE, "rb").read()
10 |
11 | response = requests.post(DETECTION_URL, files={"image": image_data}).json()
12 |
13 | pprint.pprint(response)
14 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/restapi.py:
--------------------------------------------------------------------------------
1 | """
2 | Run a rest API exposing the yolov5s object detection model
3 | """
4 | import argparse
5 | import io
6 |
7 | import torch
8 | from PIL import Image
9 | from flask import Flask, request
10 |
11 | app = Flask(__name__)
12 |
13 | DETECTION_URL = "/v1/object-detection/yolov5s"
14 |
15 |
16 | @app.route(DETECTION_URL, methods=["POST"])
17 | def predict():
18 | if not request.method == "POST":
19 | return
20 |
21 | if request.files.get("image"):
22 | image_file = request.files["image"]
23 | image_bytes = image_file.read()
24 |
25 | img = Image.open(io.BytesIO(image_bytes))
26 |
27 | results = model(img, size=640) # reduce size=320 for faster inference
28 | return results.pandas().xyxy[0].to_json(orient="records")
29 |
30 |
31 | if __name__ == "__main__":
32 | parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model")
33 | parser.add_argument("--port", default=5000, type=int, help="port number")
34 | args = parser.parse_args()
35 |
36 | model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache
37 | app.run(host="0.0.0.0", port=args.port) # debug=True causes Restarting with stat
38 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/utils/google_app_engine/app.yaml:
--------------------------------------------------------------------------------
1 | runtime: custom
2 | env: flex
3 |
4 | service: yolov5app
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
--------------------------------------------------------------------------------
/utils/google_utils.py:
--------------------------------------------------------------------------------
1 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries
2 |
3 | import os
4 | import platform
5 | import subprocess
6 | import time
7 | from pathlib import Path
8 |
9 | import requests
10 | import torch
11 |
12 |
13 | def gsutil_getsize(url=''):
14 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
15 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
16 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes
17 |
18 |
19 | def attempt_download(file, repo='ultralytics/yolov5'):
20 | # Attempt file download if does not exist
21 | file = Path(str(file).strip().replace("'", ''))
22 |
23 | if not file.exists():
24 | file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
25 | try:
26 | response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
27 | assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
28 | tag = response['tag_name'] # i.e. 'v1.0'
29 | except: # fallback plan
30 | assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',
31 | 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
32 | try:
33 | tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
34 | except:
35 | tag = 'v5.0' # current release
36 |
37 | name = file.name
38 | if name in assets:
39 | msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'
40 | redundant = False # second download option
41 | try: # GitHub
42 | url = f'https://github.com/{repo}/releases/download/{tag}/{name}'
43 | print(f'Downloading {url} to {file}...')
44 | torch.hub.download_url_to_file(url, file)
45 | assert file.exists() and file.stat().st_size > 1E6 # check
46 | except Exception as e: # GCP
47 | print(f'Download error: {e}')
48 | assert redundant, 'No secondary mirror'
49 | url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'
50 | print(f'Downloading {url} to {file}...')
51 | os.system(f"curl -L '{url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
52 | finally:
53 | if not file.exists() or file.stat().st_size < 1E6: # check
54 | file.unlink(missing_ok=True) # remove partial downloads
55 | print(f'ERROR: Download failure: {msg}')
56 | print('')
57 | return
58 |
59 |
60 | def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
61 | # Downloads a file from Google Drive. from yolov5.utils.google_utils import *; gdrive_download()
62 | t = time.time()
63 | file = Path(file)
64 | cookie = Path('cookie') # gdrive cookie
65 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
66 | file.unlink(missing_ok=True) # remove existing file
67 | cookie.unlink(missing_ok=True) # remove existing cookie
68 |
69 | # Attempt file download
70 | out = "NUL" if platform.system() == "Windows" else "/dev/null"
71 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
72 | if os.path.exists('cookie'): # large file
73 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
74 | else: # small file
75 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
76 | r = os.system(s) # execute, capture return
77 | cookie.unlink(missing_ok=True) # remove existing cookie
78 |
79 | # Error check
80 | if r != 0:
81 | file.unlink(missing_ok=True) # remove partial
82 | print('Download error ') # raise Exception('Download error')
83 | return r
84 |
85 | # Unzip if archive
86 | if file.suffix == '.zip':
87 | print('unzipping... ', end='')
88 | os.system(f'unzip -q {file}') # unzip
89 | file.unlink() # remove zip to free space
90 |
91 | print(f'Done ({time.time() - t:.1f}s)')
92 | return r
93 |
94 |
95 | def get_token(cookie="./cookie"):
96 | with open(cookie) as f:
97 | for line in f:
98 | if "download" in line:
99 | return line.split()[-1]
100 | return ""
101 |
102 | # def upload_blob(bucket_name, source_file_name, destination_blob_name):
103 | # # Uploads a file to a bucket
104 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
105 | #
106 | # storage_client = storage.Client()
107 | # bucket = storage_client.get_bucket(bucket_name)
108 | # blob = bucket.blob(destination_blob_name)
109 | #
110 | # blob.upload_from_filename(source_file_name)
111 | #
112 | # print('File {} uploaded to {}.'.format(
113 | # source_file_name,
114 | # destination_blob_name))
115 | #
116 | #
117 | # def download_blob(bucket_name, source_blob_name, destination_file_name):
118 | # # Uploads a blob from a bucket
119 | # storage_client = storage.Client()
120 | # bucket = storage_client.get_bucket(bucket_name)
121 | # blob = bucket.blob(source_blob_name)
122 | #
123 | # blob.download_to_filename(destination_file_name)
124 | #
125 | # print('Blob {} downloaded to {}.'.format(
126 | # source_blob_name,
127 | # destination_file_name))
128 |
--------------------------------------------------------------------------------
/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), j, k, l, m))
196 | t = t.repeat((5, 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 |
--------------------------------------------------------------------------------
/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, 0.1, 0.9] # 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[detection_classes[m1[j]], gc] += 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/wandb_logging/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/midasklr/yolov5prune/8a0eff3edd2225ef9e894c72f1a9d978de37b042/utils/wandb_logging/__init__.py
--------------------------------------------------------------------------------
/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.safe_load(f) # 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 |
--------------------------------------------------------------------------------
/weights/download_weights.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Download latest models from https://github.com/ultralytics/yolov5/releases
3 | # Usage:
4 | # $ bash weights/download_weights.sh
5 |
6 | python - <