├── Dockerfile
├── LICENSE
├── README.md
├── Socail_Distance_Mapping.ipynb
├── data
├── coco.yaml
├── coco128.yaml
├── hyp.finetune.yaml
├── hyp.scratch.yaml
├── images
│ ├── bus.jpg
│ └── zidane.jpg
├── scripts
│ ├── get_coco.sh
│ └── get_voc.sh
└── voc.yaml
├── detect.py
├── hubconf.py
├── inference
└── people1.mp4
├── requirements.txt
├── test.py
├── train.py
├── tutorial.ipynb
└── utils
├── activations.py
├── autoanchor.py
├── datasets.py
├── general.py
├── google_app_engine
├── Dockerfile
├── additional_requirements.txt
└── app.yaml
├── google_utils.py
├── loss.py
├── metrics.py
├── plots.py
├── torch_utils.py
└── utils.py
/Dockerfile:
--------------------------------------------------------------------------------
1 | # Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch
2 | FROM nvcr.io/nvidia/pytorch:20.10-py3
3 |
4 | # Install dependencies
5 | RUN pip install --upgrade pip
6 | # COPY requirements.txt .
7 | # RUN pip install -r requirements.txt
8 | RUN pip install gsutil
9 |
10 | # Create working directory
11 | RUN mkdir -p /usr/src/app
12 | WORKDIR /usr/src/app
13 |
14 | # Copy contents
15 | COPY . /usr/src/app
16 |
17 | # Copy weights
18 | #RUN python3 -c "from models import *; \
19 | #attempt_download('weights/yolov5s.pt'); \
20 | #attempt_download('weights/yolov5m.pt'); \
21 | #attempt_download('weights/yolov5l.pt')"
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 -a -q --filter ancestor=ultralytics/yolov5:latest)
41 |
42 | # Bash into running container
43 | # sudo docker container exec -it ba65811811ab bash
44 |
45 | # Bash into stopped container
46 | # sudo docker commit 092b16b25c5b usr/resume && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco --entrypoint=sh usr/resume
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 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |  
4 |
5 | 
6 |
7 | This repository represents Ultralytics open-source research into future object detection methods, and incorporates our lessons learned and best practices evolved over training thousands of models on custom client datasets with our previous YOLO repository https://github.com/ultralytics/yolov3. **All code and models are under active development, and are subject to modification or deletion without notice.** Use at your own risk.
8 |
9 |
** GPU Speed measures end-to-end time per image averaged over 5000 COCO val2017 images using a V100 GPU with batch size 32, and includes image preprocessing, PyTorch FP16 inference, postprocessing and NMS. EfficientDet data from [google/automl](https://github.com/google/automl) at batch size 8.
10 |
11 | - **August 13, 2020**: [v3.0 release](https://github.com/ultralytics/yolov5/releases/tag/v3.0): nn.Hardswish() activations, data autodownload, native AMP.
12 | - **July 23, 2020**: [v2.0 release](https://github.com/ultralytics/yolov5/releases/tag/v2.0): improved model definition, training and mAP.
13 | - **June 22, 2020**: [PANet](https://arxiv.org/abs/1803.01534) updates: new heads, reduced parameters, improved speed and mAP [364fcfd](https://github.com/ultralytics/yolov5/commit/364fcfd7dba53f46edd4f04c037a039c0a287972).
14 | - **June 19, 2020**: [FP16](https://pytorch.org/docs/stable/nn.html#torch.nn.Module.half) as new default for smaller checkpoints and faster inference [d4c6674](https://github.com/ultralytics/yolov5/commit/d4c6674c98e19df4c40e33a777610a18d1961145).
15 | - **June 9, 2020**: [CSP](https://github.com/WongKinYiu/CrossStagePartialNetworks) updates: improved speed, size, and accuracy (credit to @WongKinYiu for CSP).
16 | - **May 27, 2020**: Public release. YOLOv5 models are SOTA among all known YOLO implementations.
17 |
18 |
19 | ## Pretrained Checkpoints
20 |
21 | | Model | APval | APtest | AP50 | SpeedGPU | FPSGPU || params | FLOPS |
22 | |---------- |------ |------ |------ | -------- | ------| ------ |------ | :------: |
23 | | [YOLOv5s](https://github.com/ultralytics/yolov5/releases) | 37.0 | 37.0 | 56.2 | **2.4ms** | **416** || 7.5M | 13.2B
24 | | [YOLOv5m](https://github.com/ultralytics/yolov5/releases) | 44.3 | 44.3 | 63.2 | 3.4ms | 294 || 21.8M | 39.4B
25 | | [YOLOv5l](https://github.com/ultralytics/yolov5/releases) | 47.7 | 47.7 | 66.5 | 4.4ms | 227 || 47.8M | 88.1B
26 | | [YOLOv5x](https://github.com/ultralytics/yolov5/releases) | **49.2** | **49.2** | **67.7** | 6.9ms | 145 || 89.0M | 166.4B
27 | | | | | | | || |
28 | | [YOLOv5x](https://github.com/ultralytics/yolov5/releases) + TTA|**50.8**| **50.8** | **68.9** | 25.5ms | 39 || 89.0M | 354.3B
29 | | | | | | | || |
30 | | [YOLOv3-SPP](https://github.com/ultralytics/yolov5/releases) | 45.6 | 45.5 | 65.2 | 4.5ms | 222 || 63.0M | 118.0B
31 |
32 | ** APtest denotes COCO [test-dev2017](http://cocodataset.org/#upload) server results, all other AP results denote val2017 accuracy.
33 | ** All AP numbers are for single-model single-scale without ensemble or TTA. **Reproduce mAP** by `python test.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
34 | ** SpeedGPU averaged over 5000 COCO val2017 images using a GCP [n1-standard-16](https://cloud.google.com/compute/docs/machine-types#n1_standard_machine_types) V100 instance, and includes image preprocessing, FP16 inference, postprocessing and NMS. NMS is 1-2ms/img. **Reproduce speed** by `python test.py --data coco.yaml --img 640 --conf 0.25 --iou 0.45`
35 | ** All checkpoints are trained to 300 epochs with default settings and hyperparameters (no autoaugmentation).
36 | ** Test Time Augmentation ([TTA](https://github.com/ultralytics/yolov5/issues/303)) runs at 3 image sizes. **Reproduce TTA** by `python test.py --data coco.yaml --img 832 --iou 0.65 --augment`
37 |
38 | ## Requirements
39 |
40 | Python 3.8 or later with all [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) dependencies installed, including `torch>=1.7`. To install run:
41 | ```bash
42 | $ pip install -r requirements.txt
43 | ```
44 |
45 |
46 | ## Tutorials
47 |
48 | * [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) 🚀 RECOMMENDED
49 | * [Weights & Biases Logging](https://github.com/ultralytics/yolov5/issues/1289) 🌟 NEW
50 | * [Multi-GPU Training](https://github.com/ultralytics/yolov5/issues/475)
51 | * [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) ⭐ NEW
52 | * [ONNX and TorchScript Export](https://github.com/ultralytics/yolov5/issues/251)
53 | * [Test-Time Augmentation (TTA)](https://github.com/ultralytics/yolov5/issues/303)
54 | * [Model Ensembling](https://github.com/ultralytics/yolov5/issues/318)
55 | * [Model Pruning/Sparsity](https://github.com/ultralytics/yolov5/issues/304)
56 | * [Hyperparameter Evolution](https://github.com/ultralytics/yolov5/issues/607)
57 | * [Transfer Learning with Frozen Layers](https://github.com/ultralytics/yolov5/issues/1314) ⭐ NEW
58 | * [TensorRT Deployment](https://github.com/wang-xinyu/tensorrtx)
59 |
60 |
61 | ## Environments
62 |
63 | YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):
64 |
65 | - **Google Colab Notebook** with free GPU:
66 | - **Kaggle Notebook** with free GPU: [https://www.kaggle.com/ultralytics/yolov5](https://www.kaggle.com/ultralytics/yolov5)
67 | - **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)
68 | - **Docker Image** https://hub.docker.com/r/ultralytics/yolov5. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) 
69 |
70 |
71 | ## Inference
72 |
73 | detect.py runs inference on a variety of sources, downloading models automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.
74 | ```bash
75 | $ python detect.py --source 0 # webcam
76 | file.jpg # image
77 | file.mp4 # video
78 | path/ # directory
79 | path/*.jpg # glob
80 | rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa # rtsp stream
81 | rtmp://192.168.1.105/live/test # rtmp stream
82 | http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8 # http stream
83 | ```
84 |
85 | To run inference on example images in `data/images`:
86 | ```bash
87 | $ python detect.py --source data/images --weights yolov5s.pt --conf 0.25
88 |
89 | Namespace(agnostic_nms=False, augment=False, classes=None, conf_thres=0.25, device='', img_size=640, iou_thres=0.45, save_conf=False, save_dir='runs/detect', save_txt=False, source='data/images/', update=False, view_img=False, weights=['yolov5s.pt'])
90 | Using torch 1.7.0+cu101 CUDA:0 (Tesla V100-SXM2-16GB, 16130MB)
91 |
92 | Downloading https://github.com/ultralytics/yolov5/releases/download/v3.1/yolov5s.pt to yolov5s.pt... 100%|██████████████| 14.5M/14.5M [00:00<00:00, 21.3MB/s]
93 |
94 | Fusing layers...
95 | Model Summary: 232 layers, 7459581 parameters, 0 gradients
96 | image 1/2 data/images/bus.jpg: 640x480 4 persons, 1 buss, 1 skateboards, Done. (0.012s)
97 | image 2/2 data/images/zidane.jpg: 384x640 2 persons, 2 ties, Done. (0.012s)
98 | Results saved to runs/detect/exp
99 | Done. (0.113s)
100 | ```
101 |
102 |
103 | ### PyTorch Hub
104 |
105 | To run **batched inference** with YOLOv5 and [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36):
106 | ```python
107 | import torch
108 | from PIL import Image
109 |
110 | # Model
111 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True).autoshape() # for PIL/cv2/np inputs and NMS
112 |
113 | # Images
114 | img1 = Image.open('zidane.jpg')
115 | img2 = Image.open('bus.jpg')
116 | imgs = [img1, img2] # batched list of images
117 |
118 | # Inference
119 | prediction = model(imgs, size=640) # includes NMS
120 | ```
121 |
122 |
123 | ## Training
124 |
125 | Download [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh) and run command below. Training times for YOLOv5s/m/l/x are 2/4/6/8 days on a single V100 (multi-GPU times faster). Use the largest `--batch-size` your GPU allows (batch sizes shown for 16 GB devices).
126 | ```bash
127 | $ python train.py --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 64
128 | yolov5m 40
129 | yolov5l 24
130 | yolov5x 16
131 | ```
132 |
133 |
134 |
135 | ## Citation
136 |
137 | [](https://zenodo.org/badge/latestdoi/264818686)
138 |
139 |
140 | ## About Us
141 |
142 | Ultralytics is a U.S.-based particle physics and AI startup with over 6 years of expertise supporting government, academic and business clients. We offer a wide range of vision AI services, spanning from simple expert advice up to delivery of fully customized, end-to-end production solutions, including:
143 | - **Cloud-based AI** systems operating on **hundreds of HD video streams in realtime.**
144 | - **Edge AI** integrated into custom iOS and Android apps for realtime **30 FPS video inference.**
145 | - **Custom data training**, hyperparameter evolution, and model exportation to any destination.
146 |
147 | For business inquiries and professional support requests please visit us at https://www.ultralytics.com.
148 |
149 |
150 | ## Contact
151 |
152 | **Issues should be raised directly in the repository.** For business inquiries or professional support requests please visit https://www.ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com.
153 |
--------------------------------------------------------------------------------
/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.load(f, Loader=yaml.FullLoader) # 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.0032
12 | lrf: 0.12
13 | momentum: 0.843
14 | weight_decay: 0.00036
15 | warmup_epochs: 2.0
16 | warmup_momentum: 0.5
17 | warmup_bias_lr: 0.05
18 | box: 0.0296
19 | cls: 0.243
20 | cls_pw: 0.631
21 | obj: 0.301
22 | obj_pw: 0.911
23 | iou_t: 0.2
24 | anchor_t: 2.91
25 | # anchors: 3.63
26 | fl_gamma: 0.0
27 | hsv_h: 0.0138
28 | hsv_s: 0.664
29 | hsv_v: 0.464
30 | degrees: 0.373
31 | translate: 0.245
32 | scale: 0.898
33 | shear: 0.602
34 | perspective: 0.0
35 | flipud: 0.00856
36 | fliplr: 0.5
37 | mosaic: 1.0
38 | mixup: 0.243
39 |
--------------------------------------------------------------------------------
/data/hyp.scratch.yaml:
--------------------------------------------------------------------------------
1 | # Hyperparameters for COCO training from scratch
2 | # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4 |
5 |
6 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7 | lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
8 | momentum: 0.937 # SGD momentum/Adam beta1
9 | weight_decay: 0.0005 # optimizer weight decay 5e-4
10 | warmup_epochs: 3.0 # warmup epochs (fractions ok)
11 | warmup_momentum: 0.8 # warmup initial momentum
12 | warmup_bias_lr: 0.1 # warmup initial bias lr
13 | box: 0.05 # box loss gain
14 | cls: 0.5 # cls loss gain
15 | cls_pw: 1.0 # cls BCELoss positive_weight
16 | obj: 1.0 # obj loss gain (scale with pixels)
17 | obj_pw: 1.0 # obj BCELoss positive_weight
18 | iou_t: 0.20 # IoU training threshold
19 | anchor_t: 4.0 # anchor-multiple threshold
20 | # anchors: 3 # anchors per output layer (0 to ignore)
21 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
22 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
23 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
24 | hsv_v: 0.4 # image HSV-Value augmentation (fraction)
25 | degrees: 0.0 # image rotation (+/- deg)
26 | translate: 0.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/Akbonline/Social-Distancing-using-YOLOv5/44b63c7593759cfb787e5b17deabc08d7e05bd03/data/images/bus.jpg
--------------------------------------------------------------------------------
/data/images/zidane.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Akbonline/Social-Distancing-using-YOLOv5/44b63c7593759cfb787e5b17deabc08d7e05bd03/data/images/zidane.jpg
--------------------------------------------------------------------------------
/data/scripts/get_coco.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # COCO 2017 dataset http://cocodataset.org
3 | # Download command: bash data/scripts/get_coco.sh
4 | # Train command: python train.py --data coco.yaml
5 | # Default dataset location is next to /yolov5:
6 | # /parent_folder
7 | # /coco
8 | # /yolov5
9 |
10 | # Download/unzip labels
11 | d='../' # unzip directory
12 | url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
13 | f='coco2017labels.zip' # 68 MB
14 | echo 'Downloading' $url$f ' ...' && curl -L $url$f -o $f && unzip -q $f -d $d && rm $f # download, unzip, remove
15 |
16 | # Download/unzip images
17 | d='../coco/images' # unzip directory
18 | url=http://images.cocodataset.org/zips/
19 | f1='train2017.zip' # 19G, 118k images
20 | f2='val2017.zip' # 1G, 5k images
21 | f3='test2017.zip' # 7G, 41k images (optional)
22 | for f in $f1 $f2; do
23 | echo 'Downloading' $url$f ' ...' && curl -L $url$f -o $f && unzip -q $f -d $d && rm $f # download, unzip, remove
24 | done
25 |
--------------------------------------------------------------------------------
/data/scripts/get_voc.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/
3 | # Download command: bash data/scripts/get_voc.sh
4 | # Train command: python train.py --data voc.yaml
5 | # Default dataset location is next to /yolov5:
6 | # /parent_folder
7 | # /VOC
8 | # /yolov5
9 |
10 | start=$(date +%s)
11 | mkdir -p ../tmp
12 | cd ../tmp/
13 |
14 | # Download/unzip images and labels
15 | d='.' # unzip directory
16 | url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
17 | f1=VOCtrainval_06-Nov-2007.zip # 446MB, 5012 images
18 | f2=VOCtest_06-Nov-2007.zip # 438MB, 4953 images
19 | f3=VOCtrainval_11-May-2012.zip # 1.95GB, 17126 images
20 | for f in $f1 $f2 $f3; do
21 | echo 'Downloading' $url$f ' ...' && curl -L $url$f -o $f && unzip -q $f -d $d && rm $f # download, unzip, remove
22 | done
23 |
24 | end=$(date +%s)
25 | runtime=$((end - start))
26 | echo "Completed in" $runtime "seconds"
27 |
28 | echo "Splitting dataset..."
29 | python3 - "$@" <train.txt
89 | cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt >train.all.txt
90 |
91 | python3 - "$@" <= 1
79 | p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
80 | else:
81 | p, s, im0 = path, '', im0s
82 |
83 | save_path = str(Path(out) / Path(p).name)
84 | s += '%gx%g ' % img.shape[2:] # print string
85 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
86 | if det is not None and len(det):
87 | # Rescale boxes from img_size to im0 size
88 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
89 |
90 | # Print results
91 | for c in det[:, -1].unique():
92 | n = (det[:, -1] == c).sum() # detections per class
93 | s += '%g %ss, ' % (n, names[int(c)]) # add to string
94 |
95 | # Write results
96 | for *xyxy, conf, cls in det:
97 | if save_txt: # Write to file
98 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
99 | with open(save_path[:save_path.rfind('.')] + '.txt', 'a') as file:
100 | file.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format
101 |
102 | if save_img or view_img: # Add bbox to image
103 | label = '%s %.2f' % (names[int(cls)], conf)
104 | if label is not None:
105 | if (label.split())[0] == 'person':
106 | people_coords.append(xyxy)
107 | # plot_one_box(xyxy, im0, line_thickness=3)
108 | plot_dots_on_people(xyxy, im0)
109 |
110 | # Plot lines connecting people
111 | distancing(people_coords, im0, dist_thres_lim=(200,250))
112 |
113 | # Print time (inference + NMS)
114 | print('%sDone. (%.3fs)' % (s, t2 - t1))
115 |
116 | # Stream results
117 | if view_img:
118 | cv2.imshow(p, im0)
119 | if cv2.waitKey(1) == ord('q'): # q to quit
120 | raise StopIteration
121 |
122 | # Save results (image with detections)
123 | if save_img:
124 | if dataset.mode == 'images':
125 | cv2.imwrite(save_path, im0)
126 | else:
127 | if vid_path != save_path: # new video
128 | vid_path = save_path
129 | if isinstance(vid_writer, cv2.VideoWriter):
130 | vid_writer.release() # release previous video writer
131 |
132 | fps = vid_cap.get(cv2.CAP_PROP_FPS)
133 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
134 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
135 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*opt.fourcc), fps, (w, h))
136 | vid_writer.write(im0)
137 |
138 | if save_txt or save_img:
139 | print('Results saved to %s' % os.getcwd() + os.sep + out)
140 | if platform == 'darwin': # MacOS
141 | os.system('open ' + save_path)
142 |
143 | print('Done. (%.3fs)' % (time.time() - t0))
144 |
145 |
146 | if __name__ == '__main__':
147 | parser = argparse.ArgumentParser()
148 | parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path')
149 | parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
150 | parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder
151 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
152 | parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold')
153 | parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS')
154 | parser.add_argument('--fourcc', type=str, default='mp4v', help='output video codec (verify ffmpeg support)')
155 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
156 | parser.add_argument('--view-img', action='store_true', help='display results')
157 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
158 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class')
159 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
160 | parser.add_argument('--augment', action='store_true', help='augmented inference')
161 | opt = parser.parse_args()
162 | opt.img_size = check_img_size(opt.img_size)
163 | print(opt)
164 |
165 | with torch.no_grad():
166 | detect()
167 |
--------------------------------------------------------------------------------
/hubconf.py:
--------------------------------------------------------------------------------
1 | """File for accessing YOLOv5 via PyTorch Hub https://pytorch.org/hub/
2 |
3 | Usage:
4 | import torch
5 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True, channels=3, classes=80)
6 | """
7 |
8 | dependencies = ['torch', 'yaml']
9 |
10 | import os
11 |
12 | import torch
13 |
14 | from models.yolo import Model
15 | from utils import google_utils
16 |
17 |
18 | def create(name, pretrained, channels, classes):
19 | """Creates a specified YOLOv5 model
20 |
21 | Arguments:
22 | name (str): name of model, i.e. 'yolov5s'
23 | pretrained (bool): load pretrained weights into the model
24 | channels (int): number of input channels
25 | classes (int): number of model classes
26 |
27 | Returns:
28 | pytorch model
29 | """
30 | config = os.path.join(os.path.dirname(__file__), 'models', '%s.yaml' % name) # model.yaml path
31 | model = Model(config, channels, classes)
32 | if pretrained:
33 | ckpt = '%s.pt' % name # checkpoint filename
34 | google_utils.attempt_download(ckpt) # download if not found locally
35 | state_dict = torch.load(ckpt, map_location=torch.device('cpu'))['model'].float().state_dict() # to FP32
36 | state_dict = {k: v for k, v in state_dict.items() if model.state_dict()[k].shape == v.shape} # filter
37 | model.load_state_dict(state_dict, strict=False) # load
38 | return model
39 |
40 |
41 | def yolov5s(pretrained=False, channels=3, classes=80):
42 | """YOLOv5-small model from https://github.com/ultralytics/yolov5
43 |
44 | Arguments:
45 | pretrained (bool): load pretrained weights into the model, default=False
46 | channels (int): number of input channels, default=3
47 | classes (int): number of model classes, default=80
48 |
49 | Returns:
50 | pytorch model
51 | """
52 | return create('yolov5s', pretrained, channels, classes)
53 |
54 |
55 | def yolov5m(pretrained=False, channels=3, classes=80):
56 | """YOLOv5-medium model from https://github.com/ultralytics/yolov5
57 |
58 | Arguments:
59 | pretrained (bool): load pretrained weights into the model, default=False
60 | channels (int): number of input channels, default=3
61 | classes (int): number of model classes, default=80
62 |
63 | Returns:
64 | pytorch model
65 | """
66 | return create('yolov5m', pretrained, channels, classes)
67 |
68 |
69 | def yolov5l(pretrained=False, channels=3, classes=80):
70 | """YOLOv5-large model from https://github.com/ultralytics/yolov5
71 |
72 | Arguments:
73 | pretrained (bool): load pretrained weights into the model, default=False
74 | channels (int): number of input channels, default=3
75 | classes (int): number of model classes, default=80
76 |
77 | Returns:
78 | pytorch model
79 | """
80 | return create('yolov5l', pretrained, channels, classes)
81 |
82 |
83 | def yolov5x(pretrained=False, channels=3, classes=80):
84 | """YOLOv5-xlarge model from https://github.com/ultralytics/yolov5
85 |
86 | Arguments:
87 | pretrained (bool): load pretrained weights into the model, default=False
88 | channels (int): number of input channels, default=3
89 | classes (int): number of model classes, default=80
90 |
91 | Returns:
92 | pytorch model
93 | """
94 | return create('yolov5x', pretrained, channels, classes)
95 |
--------------------------------------------------------------------------------
/inference/people1.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Akbonline/Social-Distancing-using-YOLOv5/44b63c7593759cfb787e5b17deabc08d7e05bd03/inference/people1.mp4
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install -r requirements.txt
2 |
3 | # base ----------------------------------------
4 | Cython
5 | matplotlib>=3.2.2
6 | numpy>=1.18.5
7 | opencv-python>=4.1.2
8 | Pillow
9 | PyYAML>=5.3
10 | scipy>=1.4.1
11 | tensorboard>=2.2
12 | torch>=1.6.0
13 | torchvision>=0.7.0
14 | tqdm>=4.41.0
15 |
16 | # logging -------------------------------------
17 | # wandb
18 |
19 | # plotting ------------------------------------
20 | seaborn
21 | pandas
22 |
23 | # export --------------------------------------
24 | # coremltools==4.0
25 | # onnx>=1.8.0
26 | # scikit-learn==0.19.2 # for coreml quantization
27 |
28 | # extras --------------------------------------
29 | # thop # FLOPS computation
30 | # pycocotools>=2.0 # COCO mAP
31 |
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import json
3 | import os
4 | from pathlib import Path
5 | from threading import Thread
6 |
7 | import numpy as np
8 | import torch
9 | import yaml
10 | from tqdm import tqdm
11 |
12 | from models.experimental import attempt_load
13 | from utils.datasets import create_dataloader
14 | from utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, \
15 | non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, set_logging, increment_path
16 | from utils.loss import compute_loss
17 | from utils.metrics import ap_per_class, ConfusionMatrix
18 | from utils.plots import plot_images, output_to_target, plot_study_txt
19 | from utils.torch_utils import select_device, time_synchronized
20 |
21 |
22 | def test(data,
23 | weights=None,
24 | batch_size=32,
25 | imgsz=640,
26 | conf_thres=0.001,
27 | iou_thres=0.6, # for NMS
28 | save_json=False,
29 | single_cls=False,
30 | augment=False,
31 | verbose=False,
32 | model=None,
33 | dataloader=None,
34 | save_dir=Path(''), # for saving images
35 | save_txt=False, # for auto-labelling
36 | save_hybrid=False, # for hybrid auto-labelling
37 | save_conf=False, # save auto-label confidences
38 | plots=True,
39 | log_imgs=0): # number of logged images
40 |
41 | # Initialize/load model and set device
42 | training = model is not None
43 | if training: # called by train.py
44 | device = next(model.parameters()).device # get model device
45 |
46 | else: # called directly
47 | set_logging()
48 | device = select_device(opt.device, batch_size=batch_size)
49 |
50 | # Directories
51 | save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
52 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
53 |
54 | # Load model
55 | model = attempt_load(weights, map_location=device) # load FP32 model
56 | imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size
57 |
58 | # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99
59 | # if device.type != 'cpu' and torch.cuda.device_count() > 1:
60 | # model = nn.DataParallel(model)
61 |
62 | # Half
63 | half = device.type != 'cpu' # half precision only supported on CUDA
64 | if half:
65 | model.half()
66 |
67 | # Configure
68 | model.eval()
69 | is_coco = data.endswith('coco.yaml') # is COCO dataset
70 | with open(data) as f:
71 | data = yaml.load(f, Loader=yaml.FullLoader) # model dict
72 | check_dataset(data) # check
73 | nc = 1 if single_cls else int(data['nc']) # number of classes
74 | iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
75 | niou = iouv.numel()
76 |
77 | # Logging
78 | log_imgs, wandb = min(log_imgs, 100), None # ceil
79 | try:
80 | import wandb # Weights & Biases
81 | except ImportError:
82 | log_imgs = 0
83 |
84 | # Dataloader
85 | if not training:
86 | img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
87 | _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
88 | path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images
89 | dataloader = create_dataloader(path, imgsz, batch_size, model.stride.max(), opt, pad=0.5, rect=True)[0]
90 |
91 | seen = 0
92 | confusion_matrix = ConfusionMatrix(nc=nc)
93 | names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)}
94 | coco91class = coco80_to_coco91_class()
95 | s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
96 | p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
97 | loss = torch.zeros(3, device=device)
98 | jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []
99 | for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
100 | img = img.to(device, non_blocking=True)
101 | img = img.half() if half else img.float() # uint8 to fp16/32
102 | img /= 255.0 # 0 - 255 to 0.0 - 1.0
103 | targets = targets.to(device)
104 | nb, _, height, width = img.shape # batch size, channels, height, width
105 |
106 | with torch.no_grad():
107 | # Run model
108 | t = time_synchronized()
109 | inf_out, train_out = model(img, augment=augment) # inference and training outputs
110 | t0 += time_synchronized() - t
111 |
112 | # Compute loss
113 | if training:
114 | loss += compute_loss([x.float() for x in train_out], targets, model)[1][:3] # box, obj, cls
115 |
116 | # Run NMS
117 | targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels
118 | lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
119 | t = time_synchronized()
120 | output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, labels=lb)
121 | t1 += time_synchronized() - t
122 |
123 | # Statistics per image
124 | for si, pred in enumerate(output):
125 | labels = targets[targets[:, 0] == si, 1:]
126 | nl = len(labels)
127 | tcls = labels[:, 0].tolist() if nl else [] # target class
128 | path = Path(paths[si])
129 | seen += 1
130 |
131 | if len(pred) == 0:
132 | if nl:
133 | stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
134 | continue
135 |
136 | # Predictions
137 | predn = pred.clone()
138 | scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred
139 |
140 | # Append to text file
141 | if save_txt:
142 | gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh
143 | for *xyxy, conf, cls in predn.tolist():
144 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
145 | line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
146 | with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f:
147 | f.write(('%g ' * len(line)).rstrip() % line + '\n')
148 |
149 | # W&B logging
150 | if plots and len(wandb_images) < log_imgs:
151 | box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
152 | "class_id": int(cls),
153 | "box_caption": "%s %.3f" % (names[cls], conf),
154 | "scores": {"class_score": conf},
155 | "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
156 | boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
157 | wandb_images.append(wandb.Image(img[si], boxes=boxes, caption=path.name))
158 |
159 | # Append to pycocotools JSON dictionary
160 | if save_json:
161 | # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
162 | image_id = int(path.stem) if path.stem.isnumeric() else path.stem
163 | box = xyxy2xywh(predn[:, :4]) # xywh
164 | box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
165 | for p, b in zip(pred.tolist(), box.tolist()):
166 | jdict.append({'image_id': image_id,
167 | 'category_id': coco91class[int(p[5])] if is_coco else int(p[5]),
168 | 'bbox': [round(x, 3) for x in b],
169 | 'score': round(p[4], 5)})
170 |
171 | # Assign all predictions as incorrect
172 | correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
173 | if nl:
174 | detected = [] # target indices
175 | tcls_tensor = labels[:, 0]
176 |
177 | # target boxes
178 | tbox = xywh2xyxy(labels[:, 1:5])
179 | scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels
180 | if plots:
181 | confusion_matrix.process_batch(pred, torch.cat((labels[:, 0:1], tbox), 1))
182 |
183 | # Per target class
184 | for cls in torch.unique(tcls_tensor):
185 | ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices
186 | pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices
187 |
188 | # Search for detections
189 | if pi.shape[0]:
190 | # Prediction to target ious
191 | ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices
192 |
193 | # Append detections
194 | detected_set = set()
195 | for j in (ious > iouv[0]).nonzero(as_tuple=False):
196 | d = ti[i[j]] # detected target
197 | if d.item() not in detected_set:
198 | detected_set.add(d.item())
199 | detected.append(d)
200 | correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
201 | if len(detected) == nl: # all targets already located in image
202 | break
203 |
204 | # Append statistics (correct, conf, pcls, tcls)
205 | stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
206 |
207 | # Plot images
208 | if plots and batch_i < 3:
209 | f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels
210 | Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start()
211 | f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions
212 | Thread(target=plot_images, args=(img, output_to_target(output), paths, f, names), daemon=True).start()
213 |
214 | # Compute statistics
215 | stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
216 | if len(stats) and stats[0].any():
217 | p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names)
218 | p, r, ap50, ap = p[:, 0], r[:, 0], ap[:, 0], ap.mean(1) # [P, R, AP@0.5, AP@0.5:0.95]
219 | mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
220 | nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
221 | else:
222 | nt = torch.zeros(1)
223 |
224 | # Print results
225 | pf = '%20s' + '%12.3g' * 6 # print format
226 | print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
227 |
228 | # Print results per class
229 | if verbose and nc > 1 and len(stats):
230 | for i, c in enumerate(ap_class):
231 | print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
232 |
233 | # Print speeds
234 | t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
235 | if not training:
236 | print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
237 |
238 | # Plots
239 | if plots:
240 | confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
241 | if wandb and wandb.run:
242 | wandb.log({"Images": wandb_images})
243 | wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))]})
244 |
245 | # Save JSON
246 | if save_json and len(jdict):
247 | w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights
248 | anno_json = '../coco/annotations/instances_val2017.json' # annotations json
249 | pred_json = str(save_dir / f"{w}_predictions.json") # predictions json
250 | print('\nEvaluating pycocotools mAP... saving %s...' % pred_json)
251 | with open(pred_json, 'w') as f:
252 | json.dump(jdict, f)
253 |
254 | try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
255 | from pycocotools.coco import COCO
256 | from pycocotools.cocoeval import COCOeval
257 |
258 | anno = COCO(anno_json) # init annotations api
259 | pred = anno.loadRes(pred_json) # init predictions api
260 | eval = COCOeval(anno, pred, 'bbox')
261 | if is_coco:
262 | eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate
263 | eval.evaluate()
264 | eval.accumulate()
265 | eval.summarize()
266 | map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5)
267 | except Exception as e:
268 | print(f'pycocotools unable to run: {e}')
269 |
270 | # Return results
271 | if not training:
272 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
273 | print(f"Results saved to {save_dir}{s}")
274 | model.float() # for training
275 | maps = np.zeros(nc) + map
276 | for i, c in enumerate(ap_class):
277 | maps[c] = ap[i]
278 | return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
279 |
280 |
281 | if __name__ == '__main__':
282 | parser = argparse.ArgumentParser(prog='test.py')
283 | parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
284 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path')
285 | parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
286 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
287 | parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
288 | parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS')
289 | parser.add_argument('--task', default='val', help="'val', 'test', 'study'")
290 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
291 | parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
292 | parser.add_argument('--augment', action='store_true', help='augmented inference')
293 | parser.add_argument('--verbose', action='store_true', help='report mAP by class')
294 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
295 | parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt')
296 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
297 | parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
298 | parser.add_argument('--project', default='runs/test', help='save to project/name')
299 | parser.add_argument('--name', default='exp', help='save to project/name')
300 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
301 | opt = parser.parse_args()
302 | opt.save_json |= opt.data.endswith('coco.yaml')
303 | opt.data = check_file(opt.data) # check file
304 | print(opt)
305 |
306 | if opt.task in ['val', 'test']: # run normally
307 | test(opt.data,
308 | opt.weights,
309 | opt.batch_size,
310 | opt.img_size,
311 | opt.conf_thres,
312 | opt.iou_thres,
313 | opt.save_json,
314 | opt.single_cls,
315 | opt.augment,
316 | opt.verbose,
317 | save_txt=opt.save_txt | opt.save_hybrid,
318 | save_hybrid=opt.save_hybrid,
319 | save_conf=opt.save_conf,
320 | )
321 |
322 | elif opt.task == 'study': # run over a range of settings and save/plot
323 | for weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
324 | f = 'study_%s_%s.txt' % (Path(opt.data).stem, Path(weights).stem) # filename to save to
325 | x = list(range(320, 800, 64)) # x axis
326 | y = [] # y axis
327 | for i in x: # img-size
328 | print('\nRunning %s point %s...' % (f, i))
329 | r, _, t = test(opt.data, weights, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json,
330 | plots=False)
331 | y.append(r + t) # results and times
332 | np.savetxt(f, y, fmt='%10.4g') # save
333 | os.system('zip -r study.zip study_*.txt')
334 | plot_study_txt(f, x) # plot
335 |
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import logging
3 | import os
4 | import random
5 | import time
6 | from pathlib import Path
7 | from threading import Thread
8 | from warnings import warn
9 |
10 | import math
11 | import numpy as np
12 | import torch.distributed as dist
13 | import torch.nn as nn
14 | import torch.nn.functional as F
15 | import torch.optim as optim
16 | import torch.optim.lr_scheduler as lr_scheduler
17 | import torch.utils.data
18 | import yaml
19 | from torch.cuda import amp
20 | from torch.nn.parallel import DistributedDataParallel as DDP
21 | from torch.utils.tensorboard import SummaryWriter
22 | from tqdm import tqdm
23 |
24 | import test # import test.py to get mAP after each epoch
25 | from models.experimental import attempt_load
26 | from models.yolo import Model
27 | from utils.autoanchor import check_anchors
28 | from utils.datasets import create_dataloader
29 | from utils.general import labels_to_class_weights, increment_path, labels_to_image_weights, init_seeds, \
30 | fitness, strip_optimizer, get_latest_run, check_dataset, check_file, check_git_status, check_img_size, \
31 | print_mutation, set_logging
32 | from utils.google_utils import attempt_download
33 | from utils.loss import compute_loss
34 | from utils.plots import plot_images, plot_labels, plot_results, plot_evolution
35 | from utils.torch_utils import ModelEMA, select_device, intersect_dicts, torch_distributed_zero_first
36 |
37 | logger = logging.getLogger(__name__)
38 |
39 | try:
40 | import wandb
41 | except ImportError:
42 | wandb = None
43 | logger.info("Install Weights & Biases for experiment logging via 'pip install wandb' (recommended)")
44 |
45 |
46 | def train(hyp, opt, device, tb_writer=None, wandb=None):
47 | logger.info(f'Hyperparameters {hyp}')
48 | save_dir, epochs, batch_size, total_batch_size, weights, rank = \
49 | Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank
50 |
51 | # Directories
52 | wdir = save_dir / 'weights'
53 | wdir.mkdir(parents=True, exist_ok=True) # make dir
54 | last = wdir / 'last.pt'
55 | best = wdir / 'best.pt'
56 | results_file = save_dir / 'results.txt'
57 |
58 | # Save run settings
59 | with open(save_dir / 'hyp.yaml', 'w') as f:
60 | yaml.dump(hyp, f, sort_keys=False)
61 | with open(save_dir / 'opt.yaml', 'w') as f:
62 | yaml.dump(vars(opt), f, sort_keys=False)
63 |
64 | # Configure
65 | plots = not opt.evolve # create plots
66 | cuda = device.type != 'cpu'
67 | init_seeds(2 + rank)
68 | with open(opt.data) as f:
69 | data_dict = yaml.load(f, Loader=yaml.FullLoader) # data dict
70 | with torch_distributed_zero_first(rank):
71 | check_dataset(data_dict) # check
72 | train_path = data_dict['train']
73 | test_path = data_dict['val']
74 | nc, names = (1, ['item']) if opt.single_cls else (int(data_dict['nc']), data_dict['names']) # number classes, names
75 | assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
76 |
77 | # Model
78 | pretrained = weights.endswith('.pt')
79 | if pretrained:
80 | with torch_distributed_zero_first(rank):
81 | attempt_download(weights) # download if not found locally
82 | ckpt = torch.load(weights, map_location=device) # load checkpoint
83 | if hyp.get('anchors'):
84 | ckpt['model'].yaml['anchors'] = round(hyp['anchors']) # force autoanchor
85 | model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc).to(device) # create
86 | exclude = ['anchor'] if opt.cfg or hyp.get('anchors') else [] # exclude keys
87 | state_dict = ckpt['model'].float().state_dict() # to FP32
88 | state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect
89 | model.load_state_dict(state_dict, strict=False) # load
90 | logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report
91 | else:
92 | model = Model(opt.cfg, ch=3, nc=nc).to(device) # create
93 |
94 | # Freeze
95 | freeze = [] # parameter names to freeze (full or partial)
96 | for k, v in model.named_parameters():
97 | v.requires_grad = True # train all layers
98 | if any(x in k for x in freeze):
99 | print('freezing %s' % k)
100 | v.requires_grad = False
101 |
102 | # Optimizer
103 | nbs = 64 # nominal batch size
104 | accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
105 | hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
106 |
107 | pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
108 | for k, v in model.named_modules():
109 | if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter):
110 | pg2.append(v.bias) # biases
111 | if isinstance(v, nn.BatchNorm2d):
112 | pg0.append(v.weight) # no decay
113 | elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter):
114 | pg1.append(v.weight) # apply decay
115 |
116 | if opt.adam:
117 | optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
118 | else:
119 | optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
120 |
121 | optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
122 | optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
123 | logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
124 | del pg0, pg1, pg2
125 |
126 | # Scheduler https://arxiv.org/pdf/1812.01187.pdf
127 | # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR
128 | lf = lambda x: ((1 + math.cos(x * math.pi / epochs)) / 2) * (1 - hyp['lrf']) + hyp['lrf'] # cosine
129 | scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
130 | # plot_lr_scheduler(optimizer, scheduler, epochs)
131 |
132 | # Logging
133 | if wandb and wandb.run is None:
134 | opt.hyp = hyp # add hyperparameters
135 | wandb_run = wandb.init(config=opt, resume="allow",
136 | project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
137 | name=save_dir.stem,
138 | id=ckpt.get('wandb_id') if 'ckpt' in locals() else None)
139 | loggers = {'wandb': wandb} # loggers dict
140 |
141 | # Resume
142 | start_epoch, best_fitness = 0, 0.0
143 | if pretrained:
144 | # Optimizer
145 | if ckpt['optimizer'] is not None:
146 | optimizer.load_state_dict(ckpt['optimizer'])
147 | best_fitness = ckpt['best_fitness']
148 |
149 | # Results
150 | if ckpt.get('training_results') is not None:
151 | with open(results_file, 'w') as file:
152 | file.write(ckpt['training_results']) # write results.txt
153 |
154 | # Epochs
155 | start_epoch = ckpt['epoch'] + 1
156 | if opt.resume:
157 | assert start_epoch > 0, '%s training to %g epochs is finished, nothing to resume.' % (weights, epochs)
158 | if epochs < start_epoch:
159 | logger.info('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
160 | (weights, ckpt['epoch'], epochs))
161 | epochs += ckpt['epoch'] # finetune additional epochs
162 |
163 | del ckpt, state_dict
164 |
165 | # Image sizes
166 | gs = int(max(model.stride)) # grid size (max stride)
167 | imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples
168 |
169 | # DP mode
170 | if cuda and rank == -1 and torch.cuda.device_count() > 1:
171 | model = torch.nn.DataParallel(model)
172 |
173 | # SyncBatchNorm
174 | if opt.sync_bn and cuda and rank != -1:
175 | model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
176 | logger.info('Using SyncBatchNorm()')
177 |
178 | # EMA
179 | ema = ModelEMA(model) if rank in [-1, 0] else None
180 |
181 | # DDP mode
182 | if cuda and rank != -1:
183 | model = DDP(model, device_ids=[opt.local_rank], output_device=opt.local_rank)
184 |
185 | # Trainloader
186 | dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt,
187 | hyp=hyp, augment=True, cache=opt.cache_images, rect=opt.rect, rank=rank,
188 | world_size=opt.world_size, workers=opt.workers,
189 | image_weights=opt.image_weights)
190 | mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class
191 | nb = len(dataloader) # number of batches
192 | assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1)
193 |
194 | # Process 0
195 | if rank in [-1, 0]:
196 | ema.updates = start_epoch * nb // accumulate # set EMA updates
197 | testloader = create_dataloader(test_path, imgsz_test, total_batch_size, gs, opt, # testloader
198 | hyp=hyp, cache=opt.cache_images and not opt.notest, rect=True,
199 | rank=-1, world_size=opt.world_size, workers=opt.workers, pad=0.5)[0]
200 |
201 | if not opt.resume:
202 | labels = np.concatenate(dataset.labels, 0)
203 | c = torch.tensor(labels[:, 0]) # classes
204 | # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency
205 | # model._initialize_biases(cf.to(device))
206 | if plots:
207 | Thread(target=plot_labels, args=(labels, save_dir, loggers), daemon=True).start()
208 | if tb_writer:
209 | tb_writer.add_histogram('classes', c, 0)
210 |
211 | # Anchors
212 | if not opt.noautoanchor:
213 | check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
214 |
215 | # Model parameters
216 | hyp['cls'] *= nc / 80. # scale coco-tuned hyp['cls'] to current dataset
217 | model.nc = nc # attach number of classes to model
218 | model.hyp = hyp # attach hyperparameters to model
219 | model.gr = 1.0 # iou loss ratio (obj_loss = 1.0 or iou)
220 | model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights
221 | model.names = names
222 |
223 | # Start training
224 | t0 = time.time()
225 | nw = max(round(hyp['warmup_epochs'] * nb), 1000) # number of warmup iterations, max(3 epochs, 1k iterations)
226 | # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
227 | maps = np.zeros(nc) # mAP per class
228 | results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
229 | scheduler.last_epoch = start_epoch - 1 # do not move
230 | scaler = amp.GradScaler(enabled=cuda)
231 | logger.info('Image sizes %g train, %g test\n'
232 | 'Using %g dataloader workers\nLogging results to %s\n'
233 | 'Starting training for %g epochs...' % (imgsz, imgsz_test, dataloader.num_workers, save_dir, epochs))
234 | for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
235 | model.train()
236 |
237 | # Update image weights (optional)
238 | if opt.image_weights:
239 | # Generate indices
240 | if rank in [-1, 0]:
241 | cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights
242 | iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
243 | dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
244 | # Broadcast if DDP
245 | if rank != -1:
246 | indices = (torch.tensor(dataset.indices) if rank == 0 else torch.zeros(dataset.n)).int()
247 | dist.broadcast(indices, 0)
248 | if rank != 0:
249 | dataset.indices = indices.cpu().numpy()
250 |
251 | # Update mosaic border
252 | # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
253 | # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
254 |
255 | mloss = torch.zeros(4, device=device) # mean losses
256 | if rank != -1:
257 | dataloader.sampler.set_epoch(epoch)
258 | pbar = enumerate(dataloader)
259 | logger.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'total', 'targets', 'img_size'))
260 | if rank in [-1, 0]:
261 | pbar = tqdm(pbar, total=nb) # progress bar
262 | optimizer.zero_grad()
263 | for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
264 | ni = i + nb * epoch # number integrated batches (since train start)
265 | imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0
266 |
267 | # Warmup
268 | if ni <= nw:
269 | xi = [0, nw] # x interp
270 | # model.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
271 | accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round())
272 | for j, x in enumerate(optimizer.param_groups):
273 | # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
274 | x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
275 | if 'momentum' in x:
276 | x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
277 |
278 | # Multi-scale
279 | if opt.multi_scale:
280 | sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
281 | sf = sz / max(imgs.shape[2:]) # scale factor
282 | if sf != 1:
283 | ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
284 | imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
285 |
286 | # Forward
287 | with amp.autocast(enabled=cuda):
288 | pred = model(imgs) # forward
289 | loss, loss_items = compute_loss(pred, targets.to(device), model) # loss scaled by batch_size
290 | if rank != -1:
291 | loss *= opt.world_size # gradient averaged between devices in DDP mode
292 |
293 | # Backward
294 | scaler.scale(loss).backward()
295 |
296 | # Optimize
297 | if ni % accumulate == 0:
298 | scaler.step(optimizer) # optimizer.step
299 | scaler.update()
300 | optimizer.zero_grad()
301 | if ema:
302 | ema.update(model)
303 |
304 | # Print
305 | if rank in [-1, 0]:
306 | mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
307 | mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
308 | s = ('%10s' * 2 + '%10.4g' * 6) % (
309 | '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1])
310 | pbar.set_description(s)
311 |
312 | # Plot
313 | if plots and ni < 3:
314 | f = save_dir / f'train_batch{ni}.jpg' # filename
315 | Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
316 | # if tb_writer:
317 | # tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch)
318 | # tb_writer.add_graph(model, imgs) # add model to tensorboard
319 | elif plots and ni == 3 and wandb:
320 | wandb.log({"Mosaics": [wandb.Image(str(x), caption=x.name) for x in save_dir.glob('train*.jpg')]})
321 |
322 | # end batch ------------------------------------------------------------------------------------------------
323 | # end epoch ----------------------------------------------------------------------------------------------------
324 |
325 | # Scheduler
326 | lr = [x['lr'] for x in optimizer.param_groups] # for tensorboard
327 | scheduler.step()
328 |
329 | # DDP process 0 or single-GPU
330 | if rank in [-1, 0]:
331 | # mAP
332 | if ema:
333 | ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride'])
334 | final_epoch = epoch + 1 == epochs
335 | if not opt.notest or final_epoch: # Calculate mAP
336 | results, maps, times = test.test(opt.data,
337 | batch_size=total_batch_size,
338 | imgsz=imgsz_test,
339 | model=ema.ema,
340 | single_cls=opt.single_cls,
341 | dataloader=testloader,
342 | save_dir=save_dir,
343 | plots=plots and final_epoch,
344 | log_imgs=opt.log_imgs if wandb else 0)
345 |
346 | # Write
347 | with open(results_file, 'a') as f:
348 | f.write(s + '%10.4g' * 7 % results + '\n') # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
349 | if len(opt.name) and opt.bucket:
350 | os.system('gsutil cp %s gs://%s/results/results%s.txt' % (results_file, opt.bucket, opt.name))
351 |
352 | # Log
353 | tags = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss
354 | 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
355 | 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss
356 | 'x/lr0', 'x/lr1', 'x/lr2'] # params
357 | for x, tag in zip(list(mloss[:-1]) + list(results) + lr, tags):
358 | if tb_writer:
359 | tb_writer.add_scalar(tag, x, epoch) # tensorboard
360 | if wandb:
361 | wandb.log({tag: x}) # W&B
362 |
363 | # Update best mAP
364 | fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
365 | if fi > best_fitness:
366 | best_fitness = fi
367 |
368 | # Save model
369 | save = (not opt.nosave) or (final_epoch and not opt.evolve)
370 | if save:
371 | with open(results_file, 'r') as f: # create checkpoint
372 | ckpt = {'epoch': epoch,
373 | 'best_fitness': best_fitness,
374 | 'training_results': f.read(),
375 | 'model': ema.ema,
376 | 'optimizer': None if final_epoch else optimizer.state_dict(),
377 | 'wandb_id': wandb_run.id if wandb else None}
378 |
379 | # Save last, best and delete
380 | torch.save(ckpt, last)
381 | if best_fitness == fi:
382 | torch.save(ckpt, best)
383 | del ckpt
384 | # end epoch ----------------------------------------------------------------------------------------------------
385 | # end training
386 |
387 | if rank in [-1, 0]:
388 | # Strip optimizers
389 | for f in [last, best]:
390 | if f.exists(): # is *.pt
391 | strip_optimizer(f) # strip optimizer
392 | os.system('gsutil cp %s gs://%s/weights' % (f, opt.bucket)) if opt.bucket else None # upload
393 |
394 | # Plots
395 | if plots:
396 | plot_results(save_dir=save_dir) # save as results.png
397 | if wandb:
398 | files = ['results.png', 'precision_recall_curve.png', 'confusion_matrix.png']
399 | wandb.log({"Results": [wandb.Image(str(save_dir / f), caption=f) for f in files
400 | if (save_dir / f).exists()]})
401 | logger.info('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
402 |
403 | # Test best.pt
404 | if opt.data.endswith('coco.yaml') and nc == 80: # if COCO
405 | results, _, _ = test.test(opt.data,
406 | batch_size=total_batch_size,
407 | imgsz=imgsz_test,
408 | model=attempt_load(best if best.exists() else last, device).half(),
409 | single_cls=opt.single_cls,
410 | dataloader=testloader,
411 | save_dir=save_dir,
412 | save_json=True, # use pycocotools
413 | plots=False)
414 |
415 | else:
416 | dist.destroy_process_group()
417 |
418 | wandb.run.finish() if wandb and wandb.run else None
419 | torch.cuda.empty_cache()
420 | return results
421 |
422 |
423 | if __name__ == '__main__':
424 | parser = argparse.ArgumentParser()
425 | parser.add_argument('--weights', type=str, default='yolov5s.pt', help='initial weights path')
426 | parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
427 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
428 | parser.add_argument('--hyp', type=str, default='data/hyp.scratch.yaml', help='hyperparameters path')
429 | parser.add_argument('--epochs', type=int, default=300)
430 | parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
431 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes')
432 | parser.add_argument('--rect', action='store_true', help='rectangular training')
433 | parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
434 | parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
435 | parser.add_argument('--notest', action='store_true', help='only test final epoch')
436 | parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
437 | parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
438 | parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
439 | parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
440 | parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
441 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
442 | parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
443 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
444 | parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer')
445 | parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
446 | parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
447 | parser.add_argument('--log-imgs', type=int, default=16, help='number of images for W&B logging, max 100')
448 | parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers')
449 | parser.add_argument('--project', default='runs/train', help='save to project/name')
450 | parser.add_argument('--name', default='exp', help='save to project/name')
451 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
452 | opt = parser.parse_args()
453 |
454 | # Set DDP variables
455 | opt.total_batch_size = opt.batch_size
456 | opt.world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1
457 | opt.global_rank = int(os.environ['RANK']) if 'RANK' in os.environ else -1
458 | set_logging(opt.global_rank)
459 | if opt.global_rank in [-1, 0]:
460 | check_git_status()
461 |
462 | # Resume
463 | if opt.resume: # resume an interrupted run
464 | ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
465 | assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
466 | with open(Path(ckpt).parent.parent / 'opt.yaml') as f:
467 | opt = argparse.Namespace(**yaml.load(f, Loader=yaml.FullLoader)) # replace
468 | opt.cfg, opt.weights, opt.resume = '', ckpt, True
469 | logger.info('Resuming training from %s' % ckpt)
470 | else:
471 | # opt.hyp = opt.hyp or ('hyp.finetune.yaml' if opt.weights else 'hyp.scratch.yaml')
472 | opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
473 | assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
474 | opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
475 | opt.name = 'evolve' if opt.evolve else opt.name
476 | opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok | opt.evolve) # increment run
477 |
478 | # DDP mode
479 | device = select_device(opt.device, batch_size=opt.batch_size)
480 | if opt.local_rank != -1:
481 | assert torch.cuda.device_count() > opt.local_rank
482 | torch.cuda.set_device(opt.local_rank)
483 | device = torch.device('cuda', opt.local_rank)
484 | dist.init_process_group(backend='nccl', init_method='env://') # distributed backend
485 | assert opt.batch_size % opt.world_size == 0, '--batch-size must be multiple of CUDA device count'
486 | opt.batch_size = opt.total_batch_size // opt.world_size
487 |
488 | # Hyperparameters
489 | with open(opt.hyp) as f:
490 | hyp = yaml.load(f, Loader=yaml.FullLoader) # load hyps
491 | if 'box' not in hyp:
492 | warn('Compatibility: %s missing "box" which was renamed from "giou" in %s' %
493 | (opt.hyp, 'https://github.com/ultralytics/yolov5/pull/1120'))
494 | hyp['box'] = hyp.pop('giou')
495 |
496 | # Train
497 | logger.info(opt)
498 | if not opt.evolve:
499 | tb_writer = None # init loggers
500 | if opt.global_rank in [-1, 0]:
501 | logger.info(f'Start Tensorboard with "tensorboard --logdir {opt.project}", view at http://localhost:6006/')
502 | tb_writer = SummaryWriter(opt.save_dir) # Tensorboard
503 | train(hyp, opt, device, tb_writer, wandb)
504 |
505 | # Evolve hyperparameters (optional)
506 | else:
507 | # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
508 | meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
509 | 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
510 | 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
511 | 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
512 | 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
513 | 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
514 | 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
515 | 'box': (1, 0.02, 0.2), # box loss gain
516 | 'cls': (1, 0.2, 4.0), # cls loss gain
517 | 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
518 | 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
519 | 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
520 | 'iou_t': (0, 0.1, 0.7), # IoU training threshold
521 | 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
522 | 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
523 | 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
524 | 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
525 | 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
526 | 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
527 | 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
528 | 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
529 | 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
530 | 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
531 | 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
532 | 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
533 | 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
534 | 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
535 | 'mixup': (1, 0.0, 1.0)} # image mixup (probability)
536 |
537 | assert opt.local_rank == -1, 'DDP mode not implemented for --evolve'
538 | opt.notest, opt.nosave = True, True # only test/save final epoch
539 | # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
540 | yaml_file = Path(opt.save_dir) / 'hyp_evolved.yaml' # save best result here
541 | if opt.bucket:
542 | os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
543 |
544 | for _ in range(300): # generations to evolve
545 | if Path('evolve.txt').exists(): # if evolve.txt exists: select best hyps and mutate
546 | # Select parent(s)
547 | parent = 'single' # parent selection method: 'single' or 'weighted'
548 | x = np.loadtxt('evolve.txt', ndmin=2)
549 | n = min(5, len(x)) # number of previous results to consider
550 | x = x[np.argsort(-fitness(x))][:n] # top n mutations
551 | w = fitness(x) - fitness(x).min() # weights
552 | if parent == 'single' or len(x) == 1:
553 | # x = x[random.randint(0, n - 1)] # random selection
554 | x = x[random.choices(range(n), weights=w)[0]] # weighted selection
555 | elif parent == 'weighted':
556 | x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
557 |
558 | # Mutate
559 | mp, s = 0.8, 0.2 # mutation probability, sigma
560 | npr = np.random
561 | npr.seed(int(time.time()))
562 | g = np.array([x[0] for x in meta.values()]) # gains 0-1
563 | ng = len(meta)
564 | v = np.ones(ng)
565 | while all(v == 1): # mutate until a change occurs (prevent duplicates)
566 | v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
567 | for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
568 | hyp[k] = float(x[i + 7] * v[i]) # mutate
569 |
570 | # Constrain to limits
571 | for k, v in meta.items():
572 | hyp[k] = max(hyp[k], v[1]) # lower limit
573 | hyp[k] = min(hyp[k], v[2]) # upper limit
574 | hyp[k] = round(hyp[k], 5) # significant digits
575 |
576 | # Train mutation
577 | results = train(hyp.copy(), opt, device, wandb=wandb)
578 |
579 | # Write mutation results
580 | print_mutation(hyp.copy(), results, yaml_file, opt.bucket)
581 |
582 | # Plot results
583 | plot_evolution(yaml_file)
584 | print(f'Hyperparameter evolution complete. Best results saved as: {yaml_file}\n'
585 | f'Command to train a new model with these hyperparameters: $ python train.py --hyp {yaml_file}')
586 |
--------------------------------------------------------------------------------
/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 | # Swish https://arxiv.org/pdf/1905.02244.pdf ---------------------------------------------------------------------------
9 | class Swish(nn.Module): #
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 | class MemoryEfficientSwish(nn.Module):
23 | class F(torch.autograd.Function):
24 | @staticmethod
25 | def forward(ctx, x):
26 | ctx.save_for_backward(x)
27 | return x * torch.sigmoid(x)
28 |
29 | @staticmethod
30 | def backward(ctx, grad_output):
31 | x = ctx.saved_tensors[0]
32 | sx = torch.sigmoid(x)
33 | return grad_output * (sx * (1 + x * (1 - sx)))
34 |
35 | def forward(self, x):
36 | return self.F.apply(x)
37 |
38 |
39 | # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
40 | class Mish(nn.Module):
41 | @staticmethod
42 | def forward(x):
43 | return x * F.softplus(x).tanh()
44 |
45 |
46 | class MemoryEfficientMish(nn.Module):
47 | class F(torch.autograd.Function):
48 | @staticmethod
49 | def forward(ctx, x):
50 | ctx.save_for_backward(x)
51 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
52 |
53 | @staticmethod
54 | def backward(ctx, grad_output):
55 | x = ctx.saved_tensors[0]
56 | sx = torch.sigmoid(x)
57 | fx = F.softplus(x).tanh()
58 | return grad_output * (fx + x * sx * (1 - fx * fx))
59 |
60 | def forward(self, x):
61 | return self.F.apply(x)
62 |
63 |
64 | # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
65 | class FReLU(nn.Module):
66 | def __init__(self, c1, k=3): # ch_in, kernel
67 | super().__init__()
68 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1)
69 | self.bn = nn.BatchNorm2d(c1)
70 |
71 | def forward(self, x):
72 | return torch.max(x, self.bn(self.conv(x)))
73 |
--------------------------------------------------------------------------------
/utils/autoanchor.py:
--------------------------------------------------------------------------------
1 | # Auto-anchor utils
2 |
3 | import numpy as np
4 | import torch
5 | import yaml
6 | from scipy.cluster.vq import kmeans
7 | from tqdm import tqdm
8 |
9 |
10 | def check_anchor_order(m):
11 | # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
12 | a = m.anchor_grid.prod(-1).view(-1) # anchor area
13 | da = a[-1] - a[0] # delta a
14 | ds = m.stride[-1] - m.stride[0] # delta s
15 | if da.sign() != ds.sign(): # same order
16 | print('Reversing anchor order')
17 | m.anchors[:] = m.anchors.flip(0)
18 | m.anchor_grid[:] = m.anchor_grid.flip(0)
19 |
20 |
21 | def check_anchors(dataset, model, thr=4.0, imgsz=640):
22 | # Check anchor fit to data, recompute if necessary
23 | print('\nAnalyzing anchors... ', end='')
24 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
25 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
26 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
27 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
28 |
29 | def metric(k): # compute metric
30 | r = wh[:, None] / k[None]
31 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
32 | best = x.max(1)[0] # best_x
33 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
34 | bpr = (best > 1. / thr).float().mean() # best possible recall
35 | return bpr, aat
36 |
37 | bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2))
38 | print('anchors/target = %.2f, Best Possible Recall (BPR) = %.4f' % (aat, bpr), end='')
39 | if bpr < 0.98: # threshold to recompute
40 | print('. Attempting to improve anchors, please wait...')
41 | na = m.anchor_grid.numel() // 2 # number of anchors
42 | new_anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
43 | new_bpr = metric(new_anchors.reshape(-1, 2))[0]
44 | if new_bpr > bpr: # replace anchors
45 | new_anchors = torch.tensor(new_anchors, device=m.anchors.device).type_as(m.anchors)
46 | m.anchor_grid[:] = new_anchors.clone().view_as(m.anchor_grid) # for inference
47 | m.anchors[:] = new_anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
48 | check_anchor_order(m)
49 | print('New anchors saved to model. Update model *.yaml to use these anchors in the future.')
50 | else:
51 | print('Original anchors better than new anchors. Proceeding with original anchors.')
52 | print('') # newline
53 |
54 |
55 | def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
56 | """ Creates kmeans-evolved anchors from training dataset
57 |
58 | Arguments:
59 | path: path to dataset *.yaml, or a loaded dataset
60 | n: number of anchors
61 | img_size: image size used for training
62 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
63 | gen: generations to evolve anchors using genetic algorithm
64 | verbose: print all results
65 |
66 | Return:
67 | k: kmeans evolved anchors
68 |
69 | Usage:
70 | from utils.autoanchor import *; _ = kmean_anchors()
71 | """
72 | thr = 1. / thr
73 |
74 | def metric(k, wh): # compute metrics
75 | r = wh[:, None] / k[None]
76 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
77 | # x = wh_iou(wh, torch.tensor(k)) # iou metric
78 | return x, x.max(1)[0] # x, best_x
79 |
80 | def anchor_fitness(k): # mutation fitness
81 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
82 | return (best * (best > thr).float()).mean() # fitness
83 |
84 | def print_results(k):
85 | k = k[np.argsort(k.prod(1))] # sort small to large
86 | x, best = metric(k, wh0)
87 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
88 | print('thr=%.2f: %.4f best possible recall, %.2f anchors past thr' % (thr, bpr, aat))
89 | print('n=%g, img_size=%s, metric_all=%.3f/%.3f-mean/best, past_thr=%.3f-mean: ' %
90 | (n, img_size, x.mean(), best.mean(), x[x > thr].mean()), end='')
91 | for i, x in enumerate(k):
92 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
93 | return k
94 |
95 | if isinstance(path, str): # *.yaml file
96 | with open(path) as f:
97 | data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict
98 | from utils.datasets import LoadImagesAndLabels
99 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
100 | else:
101 | dataset = path # dataset
102 |
103 | # Get label wh
104 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
105 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
106 |
107 | # Filter
108 | i = (wh0 < 3.0).any(1).sum()
109 | if i:
110 | print('WARNING: Extremely small objects found. '
111 | '%g of %g labels are < 3 pixels in width or height.' % (i, len(wh0)))
112 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
113 |
114 | # Kmeans calculation
115 | print('Running kmeans for %g anchors on %g points...' % (n, len(wh)))
116 | s = wh.std(0) # sigmas for whitening
117 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
118 | k *= s
119 | wh = torch.tensor(wh, dtype=torch.float32) # filtered
120 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
121 | k = print_results(k)
122 |
123 | # Plot
124 | # k, d = [None] * 20, [None] * 20
125 | # for i in tqdm(range(1, 21)):
126 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
127 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
128 | # ax = ax.ravel()
129 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
130 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
131 | # ax[0].hist(wh[wh[:, 0]<100, 0],400)
132 | # ax[1].hist(wh[wh[:, 1]<100, 1],400)
133 | # fig.savefig('wh.png', dpi=200)
134 |
135 | # Evolve
136 | npr = np.random
137 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
138 | pbar = tqdm(range(gen), desc='Evolving anchors with Genetic Algorithm') # progress bar
139 | for _ in pbar:
140 | v = np.ones(sh)
141 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
142 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
143 | kg = (k.copy() * v).clip(min=2.0)
144 | fg = anchor_fitness(kg)
145 | if fg > f:
146 | f, k = fg, kg.copy()
147 | pbar.desc = 'Evolving anchors with Genetic Algorithm: fitness = %.4f' % f
148 | if verbose:
149 | print_results(k)
150 |
151 | return print_results(k)
152 |
--------------------------------------------------------------------------------
/utils/general.py:
--------------------------------------------------------------------------------
1 | # General utils
2 |
3 | import glob
4 | import logging
5 | import os
6 | import platform
7 | import random
8 | import re
9 | import subprocess
10 | import time
11 | from pathlib import Path
12 |
13 | import cv2
14 | import math
15 | import numpy as np
16 | import torch
17 | import torchvision
18 | import yaml
19 |
20 | from utils.google_utils import gsutil_getsize
21 | from utils.metrics import fitness
22 | from utils.torch_utils import init_torch_seeds
23 |
24 | # Settings
25 | torch.set_printoptions(linewidth=320, precision=5, profile='long')
26 | np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
27 | cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
28 |
29 |
30 | def set_logging(rank=-1):
31 | logging.basicConfig(
32 | format="%(message)s",
33 | level=logging.INFO if rank in [-1, 0] else logging.WARN)
34 |
35 |
36 | def init_seeds(seed=0):
37 | random.seed(seed)
38 | np.random.seed(seed)
39 | init_torch_seeds(seed)
40 |
41 |
42 | def get_latest_run(search_dir='.'):
43 | # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
44 | last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
45 | return max(last_list, key=os.path.getctime) if last_list else ''
46 |
47 |
48 | def check_git_status():
49 | # Suggest 'git pull' if repo is out of date
50 | if platform.system() in ['Linux', 'Darwin'] and not os.path.isfile('/.dockerenv'):
51 | s = subprocess.check_output('if [ -d .git ]; then git fetch && git status -uno; fi', shell=True).decode('utf-8')
52 | if 'Your branch is behind' in s:
53 | print(s[s.find('Your branch is behind'):s.find('\n\n')] + '\n')
54 |
55 |
56 | def check_img_size(img_size, s=32):
57 | # Verify img_size is a multiple of stride s
58 | new_size = make_divisible(img_size, int(s)) # ceil gs-multiple
59 | if new_size != img_size:
60 | print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size))
61 | return new_size
62 |
63 |
64 | def check_file(file):
65 | # Search for file if not found
66 | if os.path.isfile(file) or file == '':
67 | return file
68 | else:
69 | files = glob.glob('./**/' + file, recursive=True) # find file
70 | assert len(files), 'File Not Found: %s' % file # assert file was found
71 | assert len(files) == 1, "Multiple files match '%s', specify exact path: %s" % (file, files) # assert unique
72 | return files[0] # return file
73 |
74 |
75 | def check_dataset(dict):
76 | # Download dataset if not found locally
77 | val, s = dict.get('val'), dict.get('download')
78 | if val and len(val):
79 | val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
80 | if not all(x.exists() for x in val):
81 | print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()])
82 | if s and len(s): # download script
83 | print('Downloading %s ...' % s)
84 | if s.startswith('http') and s.endswith('.zip'): # URL
85 | f = Path(s).name # filename
86 | torch.hub.download_url_to_file(s, f)
87 | r = os.system('unzip -q %s -d ../ && rm %s' % (f, f)) # unzip
88 | else: # bash script
89 | r = os.system(s)
90 | print('Dataset autodownload %s\n' % ('success' if r == 0 else 'failure')) # analyze return value
91 | else:
92 | raise Exception('Dataset not found.')
93 |
94 |
95 | def make_divisible(x, divisor):
96 | # Returns x evenly divisible by divisor
97 | return math.ceil(x / divisor) * divisor
98 |
99 |
100 | def labels_to_class_weights(labels, nc=80):
101 | # Get class weights (inverse frequency) from training labels
102 | if labels[0] is None: # no labels loaded
103 | return torch.Tensor()
104 |
105 | labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
106 | classes = labels[:, 0].astype(np.int) # labels = [class xywh]
107 | weights = np.bincount(classes, minlength=nc) # occurrences per class
108 |
109 | # Prepend gridpoint count (for uCE training)
110 | # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
111 | # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
112 |
113 | weights[weights == 0] = 1 # replace empty bins with 1
114 | weights = 1 / weights # number of targets per class
115 | weights /= weights.sum() # normalize
116 | return torch.from_numpy(weights)
117 |
118 |
119 | def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
120 | # Produces image weights based on class_weights and image contents
121 | class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels])
122 | image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
123 | # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
124 | return image_weights
125 |
126 |
127 | def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
128 | # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
129 | # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
130 | # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
131 | # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
132 | # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
133 | x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
134 | 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
135 | 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
136 | return x
137 |
138 |
139 | def xyxy2xywh(x):
140 | # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
141 | y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
142 | y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
143 | y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
144 | y[:, 2] = x[:, 2] - x[:, 0] # width
145 | y[:, 3] = x[:, 3] - x[:, 1] # height
146 | return y
147 |
148 |
149 | def xywh2xyxy(x):
150 | # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
151 | y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
152 | y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
153 | y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
154 | y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
155 | y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
156 | return y
157 |
158 |
159 | def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
160 | # Rescale coords (xyxy) from img1_shape to img0_shape
161 | if ratio_pad is None: # calculate from img0_shape
162 | gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
163 | pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
164 | else:
165 | gain = ratio_pad[0][0]
166 | pad = ratio_pad[1]
167 |
168 | coords[:, [0, 2]] -= pad[0] # x padding
169 | coords[:, [1, 3]] -= pad[1] # y padding
170 | coords[:, :4] /= gain
171 | clip_coords(coords, img0_shape)
172 | return coords
173 |
174 |
175 | def clip_coords(boxes, img_shape):
176 | # Clip bounding xyxy bounding boxes to image shape (height, width)
177 | boxes[:, 0].clamp_(0, img_shape[1]) # x1
178 | boxes[:, 1].clamp_(0, img_shape[0]) # y1
179 | boxes[:, 2].clamp_(0, img_shape[1]) # x2
180 | boxes[:, 3].clamp_(0, img_shape[0]) # y2
181 |
182 |
183 | def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-9):
184 | # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
185 | box2 = box2.T
186 |
187 | # Get the coordinates of bounding boxes
188 | if x1y1x2y2: # x1, y1, x2, y2 = box1
189 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
190 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
191 | else: # transform from xywh to xyxy
192 | b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
193 | b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
194 | b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
195 | b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
196 |
197 | # Intersection area
198 | inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
199 | (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
200 |
201 | # Union Area
202 | w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
203 | w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
204 | union = w1 * h1 + w2 * h2 - inter + eps
205 |
206 | iou = inter / union
207 | if GIoU or DIoU or CIoU:
208 | cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
209 | ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
210 | if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
211 | c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
212 | rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +
213 | (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared
214 | if DIoU:
215 | return iou - rho2 / c2 # DIoU
216 | elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
217 | v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
218 | with torch.no_grad():
219 | alpha = v / ((1 + eps) - iou + v)
220 | return iou - (rho2 / c2 + v * alpha) # CIoU
221 | else: # GIoU https://arxiv.org/pdf/1902.09630.pdf
222 | c_area = cw * ch + eps # convex area
223 | return iou - (c_area - union) / c_area # GIoU
224 | else:
225 | return iou # IoU
226 |
227 |
228 | def box_iou(box1, box2):
229 | # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
230 | """
231 | Return intersection-over-union (Jaccard index) of boxes.
232 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
233 | Arguments:
234 | box1 (Tensor[N, 4])
235 | box2 (Tensor[M, 4])
236 | Returns:
237 | iou (Tensor[N, M]): the NxM matrix containing the pairwise
238 | IoU values for every element in boxes1 and boxes2
239 | """
240 |
241 | def box_area(box):
242 | # box = 4xn
243 | return (box[2] - box[0]) * (box[3] - box[1])
244 |
245 | area1 = box_area(box1.T)
246 | area2 = box_area(box2.T)
247 |
248 | # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
249 | inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
250 | return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
251 |
252 |
253 | def wh_iou(wh1, wh2):
254 | # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
255 | wh1 = wh1[:, None] # [N,1,2]
256 | wh2 = wh2[None] # [1,M,2]
257 | inter = torch.min(wh1, wh2).prod(2) # [N,M]
258 | return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
259 |
260 |
261 | def non_max_suppression(prediction, conf_thres=0.1, iou_thres=0.6, classes=None, agnostic=False, labels=()):
262 | """Performs Non-Maximum Suppression (NMS) on inference results
263 |
264 | Returns:
265 | detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
266 | """
267 |
268 | nc = prediction.shape[2] - 5 # number of classes
269 | xc = prediction[..., 4] > conf_thres # candidates
270 |
271 | # Settings
272 | min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
273 | max_det = 300 # maximum number of detections per image
274 | time_limit = 10.0 # seconds to quit after
275 | redundant = True # require redundant detections
276 | multi_label = nc > 1 # multiple labels per box (adds 0.5ms/img)
277 | merge = False # use merge-NMS
278 |
279 | t = time.time()
280 | output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
281 | for xi, x in enumerate(prediction): # image index, image inference
282 | # Apply constraints
283 | # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
284 | x = x[xc[xi]] # confidence
285 |
286 | # Cat apriori labels if autolabelling
287 | if labels and len(labels[xi]):
288 | l = labels[xi]
289 | v = torch.zeros((len(l), nc + 5), device=x.device)
290 | v[:, :4] = l[:, 1:5] # box
291 | v[:, 4] = 1.0 # conf
292 | v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
293 | x = torch.cat((x, v), 0)
294 |
295 | # If none remain process next image
296 | if not x.shape[0]:
297 | continue
298 |
299 | # Compute conf
300 | x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
301 |
302 | # Box (center x, center y, width, height) to (x1, y1, x2, y2)
303 | box = xywh2xyxy(x[:, :4])
304 |
305 | # Detections matrix nx6 (xyxy, conf, cls)
306 | if multi_label:
307 | i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
308 | x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
309 | else: # best class only
310 | conf, j = x[:, 5:].max(1, keepdim=True)
311 | x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
312 |
313 | # Filter by class
314 | if classes:
315 | x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
316 |
317 | # Apply finite constraint
318 | # if not torch.isfinite(x).all():
319 | # x = x[torch.isfinite(x).all(1)]
320 |
321 | # If none remain process next image
322 | n = x.shape[0] # number of boxes
323 | if not n:
324 | continue
325 |
326 | # Sort by confidence
327 | # x = x[x[:, 4].argsort(descending=True)]
328 |
329 | # Batched NMS
330 | c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
331 | boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
332 | i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
333 | if i.shape[0] > max_det: # limit detections
334 | i = i[:max_det]
335 | if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
336 | # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
337 | iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
338 | weights = iou * scores[None] # box weights
339 | x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
340 | if redundant:
341 | i = i[iou.sum(1) > 1] # require redundancy
342 |
343 | output[xi] = x[i]
344 | if (time.time() - t) > time_limit:
345 | break # time limit exceeded
346 |
347 | return output
348 |
349 |
350 | def strip_optimizer(f='weights/best.pt', s=''): # from utils.general import *; strip_optimizer()
351 | # Strip optimizer from 'f' to finalize training, optionally save as 's'
352 | x = torch.load(f, map_location=torch.device('cpu'))
353 | x['optimizer'] = None
354 | x['training_results'] = None
355 | x['epoch'] = -1
356 | x['model'].half() # to FP16
357 | for p in x['model'].parameters():
358 | p.requires_grad = False
359 | torch.save(x, s or f)
360 | mb = os.path.getsize(s or f) / 1E6 # filesize
361 | print('Optimizer stripped from %s,%s %.1fMB' % (f, (' saved as %s,' % s) if s else '', mb))
362 |
363 |
364 | def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):
365 | # Print mutation results to evolve.txt (for use with train.py --evolve)
366 | a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
367 | b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
368 | c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
369 | print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
370 |
371 | if bucket:
372 | url = 'gs://%s/evolve.txt' % bucket
373 | if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0):
374 | os.system('gsutil cp %s .' % url) # download evolve.txt if larger than local
375 |
376 | with open('evolve.txt', 'a') as f: # append result
377 | f.write(c + b + '\n')
378 | x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
379 | x = x[np.argsort(-fitness(x))] # sort
380 | np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness
381 |
382 | # Save yaml
383 | for i, k in enumerate(hyp.keys()):
384 | hyp[k] = float(x[0, i + 7])
385 | with open(yaml_file, 'w') as f:
386 | results = tuple(x[0, :7])
387 | c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
388 | f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n')
389 | yaml.dump(hyp, f, sort_keys=False)
390 |
391 | if bucket:
392 | os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)) # upload
393 |
394 |
395 | def apply_classifier(x, model, img, im0):
396 | # applies a second stage classifier to yolo outputs
397 | im0 = [im0] if isinstance(im0, np.ndarray) else im0
398 | for i, d in enumerate(x): # per image
399 | if d is not None and len(d):
400 | d = d.clone()
401 |
402 | # Reshape and pad cutouts
403 | b = xyxy2xywh(d[:, :4]) # boxes
404 | b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
405 | b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
406 | d[:, :4] = xywh2xyxy(b).long()
407 |
408 | # Rescale boxes from img_size to im0 size
409 | scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
410 |
411 | # Classes
412 | pred_cls1 = d[:, 5].long()
413 | ims = []
414 | for j, a in enumerate(d): # per item
415 | cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
416 | im = cv2.resize(cutout, (224, 224)) # BGR
417 | # cv2.imwrite('test%i.jpg' % j, cutout)
418 |
419 | im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
420 | im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
421 | im /= 255.0 # 0 - 255 to 0.0 - 1.0
422 | ims.append(im)
423 |
424 | pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
425 | x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
426 |
427 | return x
428 |
429 |
430 | def increment_path(path, exist_ok=True, sep=''):
431 | # Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc.
432 | path = Path(path) # os-agnostic
433 | if (path.exists() and exist_ok) or (not path.exists()):
434 | return str(path)
435 | else:
436 | dirs = glob.glob(f"{path}{sep}*") # similar paths
437 | matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
438 | i = [int(m.groups()[0]) for m in matches if m] # indices
439 | n = max(i) + 1 if i else 2 # increment number
440 | return f"{path}{sep}{n}" # update path
441 |
--------------------------------------------------------------------------------
/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 torch
10 |
11 |
12 | def gsutil_getsize(url=''):
13 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
14 | s = subprocess.check_output('gsutil du %s' % url, shell=True).decode('utf-8')
15 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes
16 |
17 |
18 | def attempt_download(weights):
19 | # Attempt to download pretrained weights if not found locally
20 | weights = str(weights).strip().replace("'", '')
21 | file = Path(weights).name.lower()
22 |
23 | msg = weights + ' missing, try downloading from https://github.com/ultralytics/yolov5/releases/'
24 | models = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt'] # available models
25 | redundant = False # offer second download option
26 |
27 | if file in models and not os.path.isfile(weights):
28 | # Google Drive
29 | # d = {'yolov5s.pt': '1R5T6rIyy3lLwgFXNms8whc-387H0tMQO',
30 | # 'yolov5m.pt': '1vobuEExpWQVpXExsJ2w-Mbf3HJjWkQJr',
31 | # 'yolov5l.pt': '1hrlqD1Wdei7UT4OgT785BEk1JwnSvNEV',
32 | # 'yolov5x.pt': '1mM8aZJlWTxOg7BZJvNUMrTnA2AbeCVzS'}
33 | # r = gdrive_download(id=d[file], name=weights) if file in d else 1
34 | # if r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6: # check
35 | # return
36 |
37 | try: # GitHub
38 | url = 'https://github.com/ultralytics/yolov5/releases/download/v3.1/' + file
39 | print('Downloading %s to %s...' % (url, weights))
40 | torch.hub.download_url_to_file(url, weights)
41 | assert os.path.exists(weights) and os.path.getsize(weights) > 1E6 # check
42 | except Exception as e: # GCP
43 | print('Download error: %s' % e)
44 | assert redundant, 'No secondary mirror'
45 | url = 'https://storage.googleapis.com/ultralytics/yolov5/ckpt/' + file
46 | print('Downloading %s to %s...' % (url, weights))
47 | r = os.system('curl -L %s -o %s' % (url, weights)) # torch.hub.download_url_to_file(url, weights)
48 | finally:
49 | if not (os.path.exists(weights) and os.path.getsize(weights) > 1E6): # check
50 | os.remove(weights) if os.path.exists(weights) else None # remove partial downloads
51 | print('ERROR: Download failure: %s' % msg)
52 | print('')
53 | return
54 |
55 |
56 | def gdrive_download(id='1n_oKgR81BJtqk75b00eAjdv03qVCQn2f', name='coco128.zip'):
57 | # Downloads a file from Google Drive. from utils.google_utils import *; gdrive_download()
58 | t = time.time()
59 |
60 | print('Downloading https://drive.google.com/uc?export=download&id=%s as %s... ' % (id, name), end='')
61 | os.remove(name) if os.path.exists(name) else None # remove existing
62 | os.remove('cookie') if os.path.exists('cookie') else None
63 |
64 | # Attempt file download
65 | out = "NUL" if platform.system() == "Windows" else "/dev/null"
66 | os.system('curl -c ./cookie -s -L "drive.google.com/uc?export=download&id=%s" > %s ' % (id, out))
67 | if os.path.exists('cookie'): # large file
68 | s = 'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm=%s&id=%s" -o %s' % (get_token(), id, name)
69 | else: # small file
70 | s = 'curl -s -L -o %s "drive.google.com/uc?export=download&id=%s"' % (name, id)
71 | r = os.system(s) # execute, capture return
72 | os.remove('cookie') if os.path.exists('cookie') else None
73 |
74 | # Error check
75 | if r != 0:
76 | os.remove(name) if os.path.exists(name) else None # remove partial
77 | print('Download error ') # raise Exception('Download error')
78 | return r
79 |
80 | # Unzip if archive
81 | if name.endswith('.zip'):
82 | print('unzipping... ', end='')
83 | os.system('unzip -q %s' % name) # unzip
84 | os.remove(name) # remove zip to free space
85 |
86 | print('Done (%.1fs)' % (time.time() - t))
87 | return r
88 |
89 |
90 | def get_token(cookie="./cookie"):
91 | with open(cookie) as f:
92 | for line in f:
93 | if "download" in line:
94 | return line.split()[-1]
95 | return ""
96 |
97 | # def upload_blob(bucket_name, source_file_name, destination_blob_name):
98 | # # Uploads a file to a bucket
99 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
100 | #
101 | # storage_client = storage.Client()
102 | # bucket = storage_client.get_bucket(bucket_name)
103 | # blob = bucket.blob(destination_blob_name)
104 | #
105 | # blob.upload_from_filename(source_file_name)
106 | #
107 | # print('File {} uploaded to {}.'.format(
108 | # source_file_name,
109 | # destination_blob_name))
110 | #
111 | #
112 | # def download_blob(bucket_name, source_blob_name, destination_file_name):
113 | # # Uploads a blob from a bucket
114 | # storage_client = storage.Client()
115 | # bucket = storage_client.get_bucket(bucket_name)
116 | # blob = bucket.blob(source_blob_name)
117 | #
118 | # blob.download_to_filename(destination_file_name)
119 | #
120 | # print('Blob {} downloaded to {}.'.format(
121 | # source_blob_name,
122 | # destination_file_name))
123 |
--------------------------------------------------------------------------------
/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 | def compute_loss(p, targets, model): # predictions, targets, model
89 | device = targets.device
90 | lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
91 | tcls, tbox, indices, anchors = build_targets(p, targets, model) # targets
92 | h = model.hyp # hyperparameters
93 |
94 | # Define criteria
95 | BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['cls_pw']])).to(device)
96 | BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['obj_pw']])).to(device)
97 |
98 | # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
99 | cp, cn = smooth_BCE(eps=0.0)
100 |
101 | # Focal loss
102 | g = h['fl_gamma'] # focal loss gamma
103 | if g > 0:
104 | BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
105 |
106 | # Losses
107 | nt = 0 # number of targets
108 | no = len(p) # number of outputs
109 | balance = [4.0, 1.0, 0.4] if no == 3 else [4.0, 1.0, 0.4, 0.1] # P3-5 or P3-6
110 | for i, pi in enumerate(p): # layer index, layer predictions
111 | b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
112 | tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
113 |
114 | n = b.shape[0] # number of targets
115 | if n:
116 | nt += n # cumulative targets
117 | ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
118 |
119 | # Regression
120 | pxy = ps[:, :2].sigmoid() * 2. - 0.5
121 | pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
122 | pbox = torch.cat((pxy, pwh), 1).to(device) # predicted box
123 | iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
124 | lbox += (1.0 - iou).mean() # iou loss
125 |
126 | # Objectness
127 | tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
128 |
129 | # Classification
130 | if model.nc > 1: # cls loss (only if multiple classes)
131 | t = torch.full_like(ps[:, 5:], cn, device=device) # targets
132 | t[range(n), tcls[i]] = cp
133 | lcls += BCEcls(ps[:, 5:], t) # BCE
134 |
135 | # Append targets to text file
136 | # with open('targets.txt', 'a') as file:
137 | # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
138 |
139 | lobj += BCEobj(pi[..., 4], tobj) * balance[i] # obj loss
140 |
141 | s = 3 / no # output count scaling
142 | lbox *= h['box'] * s
143 | lobj *= h['obj'] * s * (1.4 if no == 4 else 1.)
144 | lcls *= h['cls'] * s
145 | bs = tobj.shape[0] # batch size
146 |
147 | loss = lbox + lobj + lcls
148 | return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
149 |
150 |
151 | def build_targets(p, targets, model):
152 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
153 | det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
154 | na, nt = det.na, targets.shape[0] # number of anchors, targets
155 | tcls, tbox, indices, anch = [], [], [], []
156 | gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
157 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
158 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
159 |
160 | g = 0.5 # bias
161 | off = torch.tensor([[0, 0],
162 | [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
163 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
164 | ], device=targets.device).float() * g # offsets
165 |
166 | for i in range(det.nl):
167 | anchors = det.anchors[i]
168 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
169 |
170 | # Match targets to anchors
171 | t = targets * gain
172 | if nt:
173 | # Matches
174 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio
175 | j = torch.max(r, 1. / r).max(2)[0] < model.hyp['anchor_t'] # compare
176 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
177 | t = t[j] # filter
178 |
179 | # Offsets
180 | gxy = t[:, 2:4] # grid xy
181 | gxi = gain[[2, 3]] - gxy # inverse
182 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T
183 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T
184 | j = torch.stack((torch.ones_like(j), j, k, l, m))
185 | t = t.repeat((5, 1, 1))[j]
186 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
187 | else:
188 | t = targets[0]
189 | offsets = 0
190 |
191 | # Define
192 | b, c = t[:, :2].long().T # image, class
193 | gxy = t[:, 2:4] # grid xy
194 | gwh = t[:, 4:6] # grid wh
195 | gij = (gxy - offsets).long()
196 | gi, gj = gij.T # grid xy indices
197 |
198 | # Append
199 | a = t[:, 6].long() # anchor indices
200 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
201 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
202 | anch.append(anchors[a]) # anchors
203 | tcls.append(c) # class
204 |
205 | return tcls, tbox, indices, anch
206 |
--------------------------------------------------------------------------------
/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='precision-recall_curve.png', 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 |
39 | # Create Precision-Recall curve and compute AP for each class
40 | px, py = np.linspace(0, 1, 1000), [] # for plotting
41 | pr_score = 0.1 # score to evaluate P and R https://github.com/ultralytics/yolov3/issues/898
42 | s = [unique_classes.shape[0], tp.shape[1]] # number class, number iou thresholds (i.e. 10 for mAP0.5...0.95)
43 | ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s)
44 | for ci, c in enumerate(unique_classes):
45 | i = pred_cls == c
46 | n_l = (target_cls == c).sum() # number of labels
47 | n_p = i.sum() # number of predictions
48 |
49 | if n_p == 0 or n_l == 0:
50 | continue
51 | else:
52 | # Accumulate FPs and TPs
53 | fpc = (1 - tp[i]).cumsum(0)
54 | tpc = tp[i].cumsum(0)
55 |
56 | # Recall
57 | recall = tpc / (n_l + 1e-16) # recall curve
58 | r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0]) # r at pr_score, negative x, xp because xp decreases
59 |
60 | # Precision
61 | precision = tpc / (tpc + fpc) # precision curve
62 | p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0]) # p at pr_score
63 |
64 | # AP from recall-precision curve
65 | for j in range(tp.shape[1]):
66 | ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
67 | if plot and (j == 0):
68 | py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
69 |
70 | # Compute F1 score (harmonic mean of precision and recall)
71 | f1 = 2 * p * r / (p + r + 1e-16)
72 |
73 | if plot:
74 | plot_pr_curve(px, py, ap, save_dir, names)
75 |
76 | return p, r, ap, f1, unique_classes.astype('int32')
77 |
78 |
79 | def compute_ap(recall, precision):
80 | """ Compute the average precision, given the recall and precision curves
81 | # Arguments
82 | recall: The recall curve (list)
83 | precision: The precision curve (list)
84 | # Returns
85 | Average precision, precision curve, recall curve
86 | """
87 |
88 | # Append sentinel values to beginning and end
89 | mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))
90 | mpre = np.concatenate(([1.], precision, [0.]))
91 |
92 | # Compute the precision envelope
93 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
94 |
95 | # Integrate area under curve
96 | method = 'interp' # methods: 'continuous', 'interp'
97 | if method == 'interp':
98 | x = np.linspace(0, 1, 101) # 101-point interp (COCO)
99 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
100 | else: # 'continuous'
101 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
102 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
103 |
104 | return ap, mpre, mrec
105 |
106 |
107 | class ConfusionMatrix:
108 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
109 | def __init__(self, nc, conf=0.25, iou_thres=0.45):
110 | self.matrix = np.zeros((nc + 1, nc + 1))
111 | self.nc = nc # number of classes
112 | self.conf = conf
113 | self.iou_thres = iou_thres
114 |
115 | def process_batch(self, detections, labels):
116 | """
117 | Return intersection-over-union (Jaccard index) of boxes.
118 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
119 | Arguments:
120 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class
121 | labels (Array[M, 5]), class, x1, y1, x2, y2
122 | Returns:
123 | None, updates confusion matrix accordingly
124 | """
125 | detections = detections[detections[:, 4] > self.conf]
126 | gt_classes = labels[:, 0].int()
127 | detection_classes = detections[:, 5].int()
128 | iou = general.box_iou(labels[:, 1:], detections[:, :4])
129 |
130 | x = torch.where(iou > self.iou_thres)
131 | if x[0].shape[0]:
132 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
133 | if x[0].shape[0] > 1:
134 | matches = matches[matches[:, 2].argsort()[::-1]]
135 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
136 | matches = matches[matches[:, 2].argsort()[::-1]]
137 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
138 | else:
139 | matches = np.zeros((0, 3))
140 |
141 | n = matches.shape[0] > 0
142 | m0, m1, _ = matches.transpose().astype(np.int16)
143 | for i, gc in enumerate(gt_classes):
144 | j = m0 == i
145 | if n and sum(j) == 1:
146 | self.matrix[gc, detection_classes[m1[j]]] += 1 # correct
147 | else:
148 | self.matrix[gc, self.nc] += 1 # background FP
149 |
150 | if n:
151 | for i, dc in enumerate(detection_classes):
152 | if not any(m1 == i):
153 | self.matrix[self.nc, dc] += 1 # background FN
154 |
155 | def matrix(self):
156 | return self.matrix
157 |
158 | def plot(self, save_dir='', names=()):
159 | try:
160 | import seaborn as sn
161 |
162 | array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize
163 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
164 |
165 | fig = plt.figure(figsize=(12, 9), tight_layout=True)
166 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
167 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
168 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
169 | xticklabels=names + ['background FN'] if labels else "auto",
170 | yticklabels=names + ['background FP'] if labels else "auto").set_facecolor((1, 1, 1))
171 | fig.axes[0].set_xlabel('True')
172 | fig.axes[0].set_ylabel('Predicted')
173 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
174 | except Exception as e:
175 | pass
176 |
177 | def print(self):
178 | for i in range(self.nc + 1):
179 | print(' '.join(map(str, self.matrix[i])))
180 |
181 |
182 | # Plots ----------------------------------------------------------------------------------------------------------------
183 |
184 | def plot_pr_curve(px, py, ap, save_dir='.', names=()):
185 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
186 | py = np.stack(py, axis=1)
187 |
188 | if 0 < len(names) < 21: # show mAP in legend if < 10 classes
189 | for i, y in enumerate(py.T):
190 | ax.plot(px, y, linewidth=1, label=f'{names[i]} %.3f' % ap[i, 0]) # plot(recall, precision)
191 | else:
192 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
193 |
194 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
195 | ax.set_xlabel('Recall')
196 | ax.set_ylabel('Precision')
197 | ax.set_xlim(0, 1)
198 | ax.set_ylim(0, 1)
199 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
200 | fig.savefig(Path(save_dir) / 'precision_recall_curve.png', dpi=250)
201 |
--------------------------------------------------------------------------------
/utils/plots.py:
--------------------------------------------------------------------------------
1 | # Plotting utils
2 |
3 | import glob
4 | import os
5 | import random
6 | from copy import copy
7 | from pathlib import Path
8 |
9 | import cv2
10 | import math
11 | import matplotlib
12 | import matplotlib.pyplot as plt
13 | import numpy as np
14 | import torch
15 | import yaml
16 | from PIL import Image, ImageDraw
17 | from scipy.signal import butter, filtfilt
18 |
19 | from utils.general import xywh2xyxy, xyxy2xywh
20 | from utils.metrics import fitness
21 |
22 | # Settings
23 | matplotlib.rc('font', **{'size': 11})
24 | matplotlib.use('Agg') # for writing to files only
25 |
26 |
27 | def color_list():
28 | # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
29 | def hex2rgb(h):
30 | return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
31 |
32 | return [hex2rgb(h) for h in plt.rcParams['axes.prop_cycle'].by_key()['color']]
33 |
34 |
35 | def hist2d(x, y, n=100):
36 | # 2d histogram used in labels.png and evolve.png
37 | xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
38 | hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
39 | xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
40 | yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
41 | return np.log(hist[xidx, yidx])
42 |
43 |
44 | def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
45 | # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
46 | def butter_lowpass(cutoff, fs, order):
47 | nyq = 0.5 * fs
48 | normal_cutoff = cutoff / nyq
49 | return butter(order, normal_cutoff, btype='low', analog=False)
50 |
51 | b, a = butter_lowpass(cutoff, fs, order=order)
52 | return filtfilt(b, a, data) # forward-backward filter
53 |
54 |
55 | def plot_one_box(x, img, color=None, label=None, line_thickness=None):
56 | # Plots one bounding box on image img
57 | tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
58 | color = color or [random.randint(0, 255) for _ in range(3)]
59 | c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
60 | cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
61 | if label:
62 | tf = max(tl - 1, 1) # font thickness
63 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
64 | c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
65 | cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
66 | cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
67 |
68 |
69 | def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
70 | # Compares the two methods for width-height anchor multiplication
71 | # https://github.com/ultralytics/yolov3/issues/168
72 | x = np.arange(-4.0, 4.0, .1)
73 | ya = np.exp(x)
74 | yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
75 |
76 | fig = plt.figure(figsize=(6, 3), tight_layout=True)
77 | plt.plot(x, ya, '.-', label='YOLOv3')
78 | plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
79 | plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
80 | plt.xlim(left=-4, right=4)
81 | plt.ylim(bottom=0, top=6)
82 | plt.xlabel('input')
83 | plt.ylabel('output')
84 | plt.grid()
85 | plt.legend()
86 | fig.savefig('comparison.png', dpi=200)
87 |
88 |
89 | def output_to_target(output):
90 | # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
91 | targets = []
92 | for i, o in enumerate(output):
93 | for *box, conf, cls in o.cpu().numpy():
94 | targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
95 | return np.array(targets)
96 |
97 |
98 | def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
99 | # Plot image grid with labels
100 |
101 | if isinstance(images, torch.Tensor):
102 | images = images.cpu().float().numpy()
103 | if isinstance(targets, torch.Tensor):
104 | targets = targets.cpu().numpy()
105 |
106 | # un-normalise
107 | if np.max(images[0]) <= 1:
108 | images *= 255
109 |
110 | tl = 3 # line thickness
111 | tf = max(tl - 1, 1) # font thickness
112 | bs, _, h, w = images.shape # batch size, _, height, width
113 | bs = min(bs, max_subplots) # limit plot images
114 | ns = np.ceil(bs ** 0.5) # number of subplots (square)
115 |
116 | # Check if we should resize
117 | scale_factor = max_size / max(h, w)
118 | if scale_factor < 1:
119 | h = math.ceil(scale_factor * h)
120 | w = math.ceil(scale_factor * w)
121 |
122 | colors = color_list() # list of colors
123 | mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
124 | for i, img in enumerate(images):
125 | if i == max_subplots: # if last batch has fewer images than we expect
126 | break
127 |
128 | block_x = int(w * (i // ns))
129 | block_y = int(h * (i % ns))
130 |
131 | img = img.transpose(1, 2, 0)
132 | if scale_factor < 1:
133 | img = cv2.resize(img, (w, h))
134 |
135 | mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
136 | if len(targets) > 0:
137 | image_targets = targets[targets[:, 0] == i]
138 | boxes = xywh2xyxy(image_targets[:, 2:6]).T
139 | classes = image_targets[:, 1].astype('int')
140 | labels = image_targets.shape[1] == 6 # labels if no conf column
141 | conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
142 |
143 | if boxes.shape[1]:
144 | if boxes.max() <= 1.01: # if normalized with tolerance 0.01
145 | boxes[[0, 2]] *= w # scale to pixels
146 | boxes[[1, 3]] *= h
147 | elif scale_factor < 1: # absolute coords need scale if image scales
148 | boxes *= scale_factor
149 | boxes[[0, 2]] += block_x
150 | boxes[[1, 3]] += block_y
151 | for j, box in enumerate(boxes.T):
152 | cls = int(classes[j])
153 | color = colors[cls % len(colors)]
154 | cls = names[cls] if names else cls
155 | if labels or conf[j] > 0.25: # 0.25 conf thresh
156 | label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
157 | plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
158 |
159 | # Draw image filename labels
160 | if paths:
161 | label = Path(paths[i]).name[:40] # trim to 40 char
162 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
163 | cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
164 | lineType=cv2.LINE_AA)
165 |
166 | # Image border
167 | cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
168 |
169 | if fname:
170 | r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
171 | mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
172 | # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
173 | Image.fromarray(mosaic).save(fname) # PIL save
174 | return mosaic
175 |
176 |
177 | def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
178 | # Plot LR simulating training for full epochs
179 | optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
180 | y = []
181 | for _ in range(epochs):
182 | scheduler.step()
183 | y.append(optimizer.param_groups[0]['lr'])
184 | plt.plot(y, '.-', label='LR')
185 | plt.xlabel('epoch')
186 | plt.ylabel('LR')
187 | plt.grid()
188 | plt.xlim(0, epochs)
189 | plt.ylim(0)
190 | plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
191 |
192 |
193 | def plot_test_txt(): # from utils.plots import *; plot_test()
194 | # Plot test.txt histograms
195 | x = np.loadtxt('test.txt', dtype=np.float32)
196 | box = xyxy2xywh(x[:, :4])
197 | cx, cy = box[:, 0], box[:, 1]
198 |
199 | fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
200 | ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
201 | ax.set_aspect('equal')
202 | plt.savefig('hist2d.png', dpi=300)
203 |
204 | fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
205 | ax[0].hist(cx, bins=600)
206 | ax[1].hist(cy, bins=600)
207 | plt.savefig('hist1d.png', dpi=200)
208 |
209 |
210 | def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
211 | # Plot targets.txt histograms
212 | x = np.loadtxt('targets.txt', dtype=np.float32).T
213 | s = ['x targets', 'y targets', 'width targets', 'height targets']
214 | fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
215 | ax = ax.ravel()
216 | for i in range(4):
217 | ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
218 | ax[i].legend()
219 | ax[i].set_title(s[i])
220 | plt.savefig('targets.jpg', dpi=200)
221 |
222 |
223 | def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
224 | # Plot study.txt generated by test.py
225 | fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
226 | ax = ax.ravel()
227 |
228 | fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
229 | for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s', 'yolov5m', 'yolov5l', 'yolov5x']]:
230 | y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
231 | x = np.arange(y.shape[1]) if x is None else np.array(x)
232 | s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
233 | for i in range(7):
234 | ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
235 | ax[i].set_title(s[i])
236 |
237 | j = y[3].argmax() + 1
238 | ax2.plot(y[6, :j], y[3, :j] * 1E2, '.-', linewidth=2, markersize=8,
239 | label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
240 |
241 | ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
242 | 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
243 |
244 | ax2.grid()
245 | ax2.set_xlim(0, 30)
246 | ax2.set_ylim(28, 50)
247 | ax2.set_yticks(np.arange(30, 55, 5))
248 | ax2.set_xlabel('GPU Speed (ms/img)')
249 | ax2.set_ylabel('COCO AP val')
250 | ax2.legend(loc='lower right')
251 | plt.savefig('test_study.png', dpi=300)
252 |
253 |
254 | def plot_labels(labels, save_dir=Path(''), loggers=None):
255 | # plot dataset labels
256 | c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
257 | nc = int(c.max() + 1) # number of classes
258 | colors = color_list()
259 |
260 | # seaborn correlogram
261 | try:
262 | import seaborn as sns
263 | import pandas as pd
264 | x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
265 | sns.pairplot(x, corner=True, diag_kind='hist', kind='scatter', markers='o',
266 | plot_kws=dict(s=3, edgecolor=None, linewidth=1, alpha=0.02),
267 | diag_kws=dict(bins=50))
268 | plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
269 | plt.close()
270 | except Exception as e:
271 | pass
272 |
273 | # matplotlib labels
274 | matplotlib.use('svg') # faster
275 | ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
276 | ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
277 | ax[0].set_xlabel('classes')
278 | ax[2].scatter(b[0], b[1], c=hist2d(b[0], b[1], 90), cmap='jet')
279 | ax[2].set_xlabel('x')
280 | ax[2].set_ylabel('y')
281 | ax[3].scatter(b[2], b[3], c=hist2d(b[2], b[3], 90), cmap='jet')
282 | ax[3].set_xlabel('width')
283 | ax[3].set_ylabel('height')
284 |
285 | # rectangles
286 | labels[:, 1:3] = 0.5 # center
287 | labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
288 | img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
289 | for cls, *box in labels[:1000]:
290 | ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot
291 | ax[1].imshow(img)
292 | ax[1].axis('off')
293 |
294 | for a in [0, 1, 2, 3]:
295 | for s in ['top', 'right', 'left', 'bottom']:
296 | ax[a].spines[s].set_visible(False)
297 |
298 | plt.savefig(save_dir / 'labels.jpg', dpi=200)
299 | matplotlib.use('Agg')
300 | plt.close()
301 |
302 | # loggers
303 | for k, v in loggers.items() or {}:
304 | if k == 'wandb' and v:
305 | v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]})
306 |
307 |
308 | def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
309 | # Plot hyperparameter evolution results in evolve.txt
310 | with open(yaml_file) as f:
311 | hyp = yaml.load(f, Loader=yaml.FullLoader)
312 | x = np.loadtxt('evolve.txt', ndmin=2)
313 | f = fitness(x)
314 | # weights = (f - f.min()) ** 2 # for weighted results
315 | plt.figure(figsize=(10, 12), tight_layout=True)
316 | matplotlib.rc('font', **{'size': 8})
317 | for i, (k, v) in enumerate(hyp.items()):
318 | y = x[:, i + 7]
319 | # mu = (y * weights).sum() / weights.sum() # best weighted result
320 | mu = y[f.argmax()] # best single result
321 | plt.subplot(6, 5, i + 1)
322 | plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
323 | plt.plot(mu, f.max(), 'k+', markersize=15)
324 | plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
325 | if i % 5 != 0:
326 | plt.yticks([])
327 | print('%15s: %.3g' % (k, mu))
328 | plt.savefig('evolve.png', dpi=200)
329 | print('\nPlot saved as evolve.png')
330 |
331 |
332 | def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
333 | # Plot training 'results*.txt', overlaying train and val losses
334 | s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
335 | t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
336 | for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
337 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
338 | n = results.shape[1] # number of rows
339 | x = range(start, min(stop, n) if stop else n)
340 | fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
341 | ax = ax.ravel()
342 | for i in range(5):
343 | for j in [i, i + 5]:
344 | y = results[j, x]
345 | ax[i].plot(x, y, marker='.', label=s[j])
346 | # y_smooth = butter_lowpass_filtfilt(y)
347 | # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
348 |
349 | ax[i].set_title(t[i])
350 | ax[i].legend()
351 | ax[i].set_ylabel(f) if i == 0 else None # add filename
352 | fig.savefig(f.replace('.txt', '.png'), dpi=200)
353 |
354 |
355 | def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
356 | # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
357 | fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
358 | ax = ax.ravel()
359 | s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
360 | 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
361 | if bucket:
362 | # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
363 | files = ['results%g.txt' % x for x in id]
364 | c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
365 | os.system(c)
366 | else:
367 | files = list(Path(save_dir).glob('results*.txt'))
368 | assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
369 | for fi, f in enumerate(files):
370 | try:
371 | results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
372 | n = results.shape[1] # number of rows
373 | x = range(start, min(stop, n) if stop else n)
374 | for i in range(10):
375 | y = results[i, x]
376 | if i in [0, 1, 2, 5, 6, 7]:
377 | y[y == 0] = np.nan # don't show zero loss values
378 | # y /= y[0] # normalize
379 | label = labels[fi] if len(labels) else f.stem
380 | ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
381 | ax[i].set_title(s[i])
382 | # if i in [5, 6, 7]: # share train and val loss y axes
383 | # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
384 | except Exception as e:
385 | print('Warning: Plotting error for %s; %s' % (f, e))
386 |
387 | ax[1].legend()
388 | fig.savefig(Path(save_dir) / 'results.png', dpi=200)
389 |
--------------------------------------------------------------------------------
/utils/torch_utils.py:
--------------------------------------------------------------------------------
1 | # PyTorch utils
2 |
3 | import logging
4 | import os
5 | import time
6 | from contextlib import contextmanager
7 | from copy import deepcopy
8 |
9 | import math
10 | import torch
11 | import torch.backends.cudnn as cudnn
12 | import torch.nn as nn
13 | import torch.nn.functional as F
14 | import torchvision
15 |
16 | logger = logging.getLogger(__name__)
17 |
18 |
19 | @contextmanager
20 | def torch_distributed_zero_first(local_rank: int):
21 | """
22 | Decorator to make all processes in distributed training wait for each local_master to do something.
23 | """
24 | if local_rank not in [-1, 0]:
25 | torch.distributed.barrier()
26 | yield
27 | if local_rank == 0:
28 | torch.distributed.barrier()
29 |
30 |
31 | def init_torch_seeds(seed=0):
32 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
33 | torch.manual_seed(seed)
34 | if seed == 0: # slower, more reproducible
35 | cudnn.deterministic = True
36 | cudnn.benchmark = False
37 | else: # faster, less reproducible
38 | cudnn.deterministic = False
39 | cudnn.benchmark = True
40 |
41 |
42 | def select_device(device='', batch_size=None):
43 | # device = 'cpu' or '0' or '0,1,2,3'
44 | cpu_request = device.lower() == 'cpu'
45 | if device and not cpu_request: # if device requested other than 'cpu'
46 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
47 | assert torch.cuda.is_available(), 'CUDA unavailable, invalid device %s requested' % device # check availablity
48 |
49 | cuda = False if cpu_request else torch.cuda.is_available()
50 | if cuda:
51 | c = 1024 ** 2 # bytes to MB
52 | ng = torch.cuda.device_count()
53 | if ng > 1 and batch_size: # check that batch_size is compatible with device_count
54 | assert batch_size % ng == 0, 'batch-size %g not multiple of GPU count %g' % (batch_size, ng)
55 | x = [torch.cuda.get_device_properties(i) for i in range(ng)]
56 | s = f'Using torch {torch.__version__} '
57 | for i in range(0, ng):
58 | if i == 1:
59 | s = ' ' * len(s)
60 | logger.info("%sCUDA:%g (%s, %dMB)" % (s, i, x[i].name, x[i].total_memory / c))
61 | else:
62 | logger.info(f'Using torch {torch.__version__} CPU')
63 |
64 | logger.info('') # skip a line
65 | return torch.device('cuda:0' if cuda else 'cpu')
66 |
67 |
68 | def time_synchronized():
69 | torch.cuda.synchronize() if torch.cuda.is_available() else None
70 | return time.time()
71 |
72 |
73 | def is_parallel(model):
74 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
75 |
76 |
77 | def intersect_dicts(da, db, exclude=()):
78 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
79 | return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
80 |
81 |
82 | def initialize_weights(model):
83 | for m in model.modules():
84 | t = type(m)
85 | if t is nn.Conv2d:
86 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
87 | elif t is nn.BatchNorm2d:
88 | m.eps = 1e-3
89 | m.momentum = 0.03
90 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
91 | m.inplace = True
92 |
93 |
94 | def find_modules(model, mclass=nn.Conv2d):
95 | # Finds layer indices matching module class 'mclass'
96 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
97 |
98 |
99 | def sparsity(model):
100 | # Return global model sparsity
101 | a, b = 0., 0.
102 | for p in model.parameters():
103 | a += p.numel()
104 | b += (p == 0).sum()
105 | return b / a
106 |
107 |
108 | def prune(model, amount=0.3):
109 | # Prune model to requested global sparsity
110 | import torch.nn.utils.prune as prune
111 | print('Pruning model... ', end='')
112 | for name, m in model.named_modules():
113 | if isinstance(m, nn.Conv2d):
114 | prune.l1_unstructured(m, name='weight', amount=amount) # prune
115 | prune.remove(m, 'weight') # make permanent
116 | print(' %.3g global sparsity' % sparsity(model))
117 |
118 |
119 | def fuse_conv_and_bn(conv, bn):
120 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
121 | fusedconv = nn.Conv2d(conv.in_channels,
122 | conv.out_channels,
123 | kernel_size=conv.kernel_size,
124 | stride=conv.stride,
125 | padding=conv.padding,
126 | groups=conv.groups,
127 | bias=True).requires_grad_(False).to(conv.weight.device)
128 |
129 | # prepare filters
130 | w_conv = conv.weight.clone().view(conv.out_channels, -1)
131 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
132 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size()))
133 |
134 | # prepare spatial bias
135 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
136 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
137 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
138 |
139 | return fusedconv
140 |
141 |
142 | def model_info(model, verbose=False, img_size=640):
143 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
144 | n_p = sum(x.numel() for x in model.parameters()) # number parameters
145 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
146 | if verbose:
147 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
148 | for i, (name, p) in enumerate(model.named_parameters()):
149 | name = name.replace('module_list.', '')
150 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
151 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
152 |
153 | try: # FLOPS
154 | from thop import profile
155 | stride = int(model.stride.max()) if hasattr(model, 'stride') else 32
156 | img = torch.zeros((1, 3, stride, stride), device=next(model.parameters()).device) # input
157 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride FLOPS
158 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
159 | fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 FLOPS
160 | except (ImportError, Exception):
161 | fs = ''
162 |
163 | logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
164 |
165 |
166 | def load_classifier(name='resnet101', n=2):
167 | # Loads a pretrained model reshaped to n-class output
168 | model = torchvision.models.__dict__[name](pretrained=True)
169 |
170 | # ResNet model properties
171 | # input_size = [3, 224, 224]
172 | # input_space = 'RGB'
173 | # input_range = [0, 1]
174 | # mean = [0.485, 0.456, 0.406]
175 | # std = [0.229, 0.224, 0.225]
176 |
177 | # Reshape output to n classes
178 | filters = model.fc.weight.shape[1]
179 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
180 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
181 | model.fc.out_features = n
182 | return model
183 |
184 |
185 | def scale_img(img, ratio=1.0, same_shape=False): # img(16,3,256,416), r=ratio
186 | # scales img(bs,3,y,x) by ratio
187 | if ratio == 1.0:
188 | return img
189 | else:
190 | h, w = img.shape[2:]
191 | s = (int(h * ratio), int(w * ratio)) # new size
192 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
193 | if not same_shape: # pad/crop img
194 | gs = 32 # (pixels) grid size
195 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
196 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
197 |
198 |
199 | def copy_attr(a, b, include=(), exclude=()):
200 | # Copy attributes from b to a, options to only include [...] and to exclude [...]
201 | for k, v in b.__dict__.items():
202 | if (len(include) and k not in include) or k.startswith('_') or k in exclude:
203 | continue
204 | else:
205 | setattr(a, k, v)
206 |
207 |
208 | class ModelEMA:
209 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
210 | Keep a moving average of everything in the model state_dict (parameters and buffers).
211 | This is intended to allow functionality like
212 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
213 | A smoothed version of the weights is necessary for some training schemes to perform well.
214 | This class is sensitive where it is initialized in the sequence of model init,
215 | GPU assignment and distributed training wrappers.
216 | """
217 |
218 | def __init__(self, model, decay=0.9999, updates=0):
219 | # Create EMA
220 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
221 | # if next(model.parameters()).device.type != 'cpu':
222 | # self.ema.half() # FP16 EMA
223 | self.updates = updates # number of EMA updates
224 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
225 | for p in self.ema.parameters():
226 | p.requires_grad_(False)
227 |
228 | def update(self, model):
229 | # Update EMA parameters
230 | with torch.no_grad():
231 | self.updates += 1
232 | d = self.decay(self.updates)
233 |
234 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
235 | for k, v in self.ema.state_dict().items():
236 | if v.dtype.is_floating_point:
237 | v *= d
238 | v += (1. - d) * msd[k].detach()
239 |
240 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
241 | # Update EMA attributes
242 | copy_attr(self.ema, model, include, exclude)
243 |
--------------------------------------------------------------------------------