Commit cf1ed55a authored by suily's avatar suily
Browse files

Initial commit

parents
Pipeline #3338 canceled with stages
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
# YOLOv5_L
## 项目简介
YOLOv5 是一种目标检测算法,采用单阶段(one-stage)的方法,基于轻量级的卷积神经网络结构,通过引入不同尺度的特征融合和特征金字塔结构来实现高效准确的目标检测。
---
## 环境部署
### 1. 拉取镜像
```bash
docker pull image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.4.1-ubuntu22.04-dtk25.04.1-py3.10
```
### 2. 创建容器
```bash
docker run -it \
--network=host \
--hostname=localhost \
--name=yolov5 \
-v /opt/hyhal:/opt/hyhal:ro \
-v $PWD:/workspace \
--ipc=host \
--device=/dev/kfd \
--device=/dev/mkfd \
--device=/dev/dri \
--shm-size=512G \
--privileged \
--group-add video \
--cap-add=SYS_PTRACE \
-u root \
--security-opt seccomp=unconfined \
image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.4.1-ubuntu22.04-dtk25.04.1-py3.10 \
/bin/bash
```
---
## 测试步骤
### 1. 拉取代码
```bash
git clone http://developer.sourcefind.cn/codes/bw-bestperf/yolov5_l.git
cd yolov5_l
```
### 2. 安装依赖
```bash
pip install -r requirements.txt -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
cp Arial.ttf /root/.config/Ultralytics/Arial.ttf
```
### 3. 下载模型
下载所需模型:
```bash
wget https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l.pt
```
### 4. 下载数据集
数据集地址:https://www.modelscope.cn/datasets/PAI/COCO2017/
数据集目录结构如下:
```bash
coco2017
├── images
│ ├── train2017
│ ├── val2017
│ ├── test2017
├── labels
│ ├── train2017
│ ├── val2017
├── annotations
│ ├── instances_val2017.json
├── test-dev2017.txt
├── train2017.txt
├── val2017.txt
├── ...
```
修改测试配置中的数据集路径
```bash
vim data/coco.yaml # 修改 path: /path/coco2017/
```
---
## 测试代码示例(单卡测试)
单卡训练
```bash
HIP_VISIBLE_DEVICES=0 python train.py --data data/coco.yaml --epochs 5 --weights yolov5l.pt --batch-size 64 --img 640
```
---
## 配置选项说明
| 参数 | 说明 | 默认值 / 示例 |
| -------------------- | ------------------------------ | ---------------------------------------- |
| `--data` | 指定数据集的配置文件 | `data/coco.yaml` |
| `--epochs` | 训练轮次 | `5` |
| `--weights` | 指定加载的预训练权重 | `yolov5l.pt` |
| `--batch-size` | 每一个batch送入训练的图像数量 | `64` |
| `--img` | 输入图像的分辨率 | `640` |
---
## 贡献指南
欢迎对 YOLOv5_L 项目进行贡献!请遵循以下步骤:
1. Fork 本仓库,并新建分支进行功能开发或问题修复。
2. 提交规范的 commit 信息,描述清晰。
3. 提交 Pull Request,简述修改内容及目的。
4. 遵守项目代码规范和测试标准。
5. 参与代码评审,积极沟通改进方案。
---
## 许可证
本项目遵循 MIT 许可证,详见 [LICENSE](./LICENSE) 文件。
---
感谢您的关注与支持!如有问题,欢迎提交 Issue 或联系维护团队。
<div align="center">
<p>
<a align="center" href="https://ultralytics.com/yolov5" target="_blank">
<img width="850" src="https://raw.githubusercontent.com/ultralytics/assets/master/yolov5/v70/splash.png"></a>
</p>
English | [简体中文](.github/README_cn.md)
<br>
<div>
<a href="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml"><img src="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg" alt="YOLOv5 CI"></a>
<a href="https://zenodo.org/badge/latestdoi/264818686"><img src="https://zenodo.org/badge/264818686.svg" alt="YOLOv5 Citation"></a>
<a href="https://hub.docker.com/r/ultralytics/yolov5"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker" alt="Docker Pulls"></a>
<br>
<a href="https://bit.ly/yolov5-paperspace-notebook"><img src="https://assets.paperspace.io/img/gradient-badge.svg" alt="Run on Gradient"></a>
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
<a href="https://www.kaggle.com/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
</div>
<br>
<p>
YOLOv5 🚀 is the world's most loved vision AI, representing <a href="https://ultralytics.com">Ultralytics</a>
open-source research into future vision AI methods, incorporating lessons learned and best practices evolved over thousands of hours of research and development.
<br><br>
To request a commercial license please complete the form at <a href="https://ultralytics.com/license">Ultralytics Licensing</a>.
<br><br>
</p>
<div align="center">
<a href="https://github.com/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-github.png" width="2%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
<a href="https://www.linkedin.com/company/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-linkedin.png" width="2%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
<a href="https://twitter.com/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-twitter.png" width="2%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
<a href="https://www.producthunt.com/@glenn_jocher" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-producthunt.png" width="2%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
<a href="https://youtube.com/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-youtube.png" width="2%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
<a href="https://www.facebook.com/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-facebook.png" width="2%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
<a href="https://www.instagram.com/ultralytics/" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-instagram.png" width="2%" alt="" /></a>
</div>
</div>
## <div align="center">Segmentation ⭐ NEW</div>
<div align="center">
<a align="center" href="https://ultralytics.com/yolov5" target="_blank">
<img width="800" src="https://user-images.githubusercontent.com/26833433/203348073-9b85607b-03e2-48e1-a6ba-fe1c1c31749c.png"></a>
</div>
Our new YOLOv5 [release v7.0](https://github.com/ultralytics/yolov5/releases/v7.0) instance segmentation models are the fastest and most accurate in the world, beating all current [SOTA benchmarks](https://paperswithcode.com/sota/real-time-instance-segmentation-on-mscoco). We've made them super simple to train, validate and deploy. See full details in our [Release Notes](https://github.com/ultralytics/yolov5/releases/v7.0) and visit our [YOLOv5 Segmentation Colab Notebook](https://github.com/ultralytics/yolov5/blob/master/segment/tutorial.ipynb) for quickstart tutorials.
<details>
<summary>Segmentation Checkpoints</summary>
<br>
We trained YOLOv5 segmentations models on COCO for 300 epochs at image size 640 using A100 GPUs. We exported all models to ONNX FP32 for CPU speed tests and to TensorRT FP16 for GPU speed tests. We ran all speed tests on Google [Colab Pro](https://colab.research.google.com/signup) notebooks for easy reproducibility.
| Model | size<br><sup>(pixels) | mAP<sup>box<br>50-95 | mAP<sup>mask<br>50-95 | Train time<br><sup>300 epochs<br>A100 (hours) | Speed<br><sup>ONNX CPU<br>(ms) | Speed<br><sup>TRT A100<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>@640 (B) |
|----------------------------------------------------------------------------------------------------|-----------------------|----------------------|-----------------------|-----------------------------------------------|--------------------------------|--------------------------------|--------------------|------------------------|
| [YOLOv5n-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5n-seg.pt) | 640 | 27.6 | 23.4 | 80:17 | **62.7** | **1.2** | **2.0** | **7.1** |
| [YOLOv5s-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s-seg.pt) | 640 | 37.6 | 31.7 | 88:16 | 173.3 | 1.4 | 7.6 | 26.4 |
| [YOLOv5m-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5m-seg.pt) | 640 | 45.0 | 37.1 | 108:36 | 427.0 | 2.2 | 22.0 | 70.8 |
| [YOLOv5l-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5l-seg.pt) | 640 | 49.0 | 39.9 | 66:43 (2x) | 857.4 | 2.9 | 47.9 | 147.7 |
| [YOLOv5x-seg](https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5x-seg.pt) | 640 | **50.7** | **41.4** | 62:56 (3x) | 1579.2 | 4.5 | 88.8 | 265.7 |
- All checkpoints are trained to 300 epochs with SGD optimizer with `lr0=0.01` and `weight_decay=5e-5` at image size 640 and all default settings.<br>Runs logged to https://wandb.ai/glenn-jocher/YOLOv5_v70_official
- **Accuracy** values are for single-model single-scale on COCO dataset.<br>Reproduce by `python segment/val.py --data coco.yaml --weights yolov5s-seg.pt`
- **Speed** averaged over 100 inference images using a [Colab Pro](https://colab.research.google.com/signup) A100 High-RAM instance. Values indicate inference speed only (NMS adds about 1ms per image). <br>Reproduce by `python segment/val.py --data coco.yaml --weights yolov5s-seg.pt --batch 1`
- **Export** to ONNX at FP32 and TensorRT at FP16 done with `export.py`. <br>Reproduce by `python export.py --weights yolov5s-seg.pt --include engine --device 0 --half`
</details>
<details>
<summary>Segmentation Usage Examples &nbsp;<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/segment/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a></summary>
### Train
YOLOv5 segmentation training supports auto-download COCO128-seg segmentation dataset with `--data coco128-seg.yaml` argument and manual download of COCO-segments dataset with `bash data/scripts/get_coco.sh --train --val --segments` and then `python train.py --data coco.yaml`.
```bash
# Single-GPU
python segment/train.py --model yolov5s-seg.pt --data coco128-seg.yaml --epochs 5 --img 640
# Multi-GPU DDP
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 segment/train.py --model yolov5s-seg.pt --data coco128-seg.yaml --epochs 5 --img 640 --device 0,1,2,3
```
### Val
Validate YOLOv5m-seg accuracy on ImageNet-1k dataset:
```bash
bash data/scripts/get_coco.sh --val --segments # download COCO val segments split (780MB, 5000 images)
python segment/val.py --weights yolov5s-seg.pt --data coco.yaml --img 640 # validate
```
### Predict
Use pretrained YOLOv5m-seg.pt to predict bus.jpg:
```bash
python segment/predict.py --weights yolov5m-seg.pt --data data/images/bus.jpg
```
```python
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5m-seg.pt') # load from PyTorch Hub (WARNING: inference not yet supported)
```
![zidane](https://user-images.githubusercontent.com/26833433/203113421-decef4c4-183d-4a0a-a6c2-6435b33bc5d3.jpg) | ![bus](https://user-images.githubusercontent.com/26833433/203113416-11fe0025-69f7-4874-a0a6-65d0bfe2999a.jpg)
--- |---
### Export
Export YOLOv5s-seg model to ONNX and TensorRT:
```bash
python export.py --weights yolov5s-seg.pt --include onnx engine --img 640 --device 0
```
</details>
## <div align="center">Documentation</div>
See the [YOLOv5 Docs](https://docs.ultralytics.com) for full documentation on training, testing and deployment. See below for quickstart examples.
<details open>
<summary>Install</summary>
Clone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a
[**Python>=3.7.0**](https://www.python.org/) environment, including
[**PyTorch>=1.7**](https://pytorch.org/get-started/locally/).
```bash
git clone https://github.com/ultralytics/yolov5 # clone
cd yolov5
pip install -r requirements.txt # install
```
</details>
<details>
<summary>Inference</summary>
YOLOv5 [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) inference. [Models](https://github.com/ultralytics/yolov5/tree/master/models) download automatically from the latest
YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).
```python
import torch
# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5n - yolov5x6, custom
# Images
img = 'https://ultralytics.com/images/zidane.jpg' # or file, Path, PIL, OpenCV, numpy, list
# Inference
results = model(img)
# Results
results.print() # or .show(), .save(), .crop(), .pandas(), etc.
```
</details>
<details>
<summary>Inference with detect.py</summary>
`detect.py` runs inference on a variety of sources, downloading [models](https://github.com/ultralytics/yolov5/tree/master/models) automatically from
the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.
```bash
python detect.py --source 0 # webcam
img.jpg # image
vid.mp4 # video
screen # screenshot
path/ # directory
'path/*.jpg' # glob
'https://youtu.be/Zgi9g1ksQHc' # YouTube
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
```
</details>
<details>
<summary>Training</summary>
The commands below reproduce YOLOv5 [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh)
results. [Models](https://github.com/ultralytics/yolov5/tree/master/models)
and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest
YOLOv5 [release](https://github.com/ultralytics/yolov5/releases). Training times for YOLOv5n/s/m/l/x are
1/2/4/6/8 days on a V100 GPU ([Multi-GPU](https://github.com/ultralytics/yolov5/issues/475) times faster). Use the
largest `--batch-size` possible, or pass `--batch-size -1` for
YOLOv5 [AutoBatch](https://github.com/ultralytics/yolov5/pull/5092). Batch sizes shown for V100-16GB.
```bash
python train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5n.yaml --batch-size 128
yolov5s 64
yolov5m 40
yolov5l 24
yolov5x 16
```
<img width="800" src="https://user-images.githubusercontent.com/26833433/90222759-949d8800-ddc1-11ea-9fa1-1c97eed2b963.png">
</details>
<details open>
<summary>Tutorials</summary>
- [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data)  🚀 RECOMMENDED
- [Tips for Best Training Results](https://github.com/ultralytics/yolov5/wiki/Tips-for-Best-Training-Results)  ☘️
RECOMMENDED
- [Multi-GPU Training](https://github.com/ultralytics/yolov5/issues/475)
- [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) 🌟 NEW
- [TFLite, ONNX, CoreML, TensorRT Export](https://github.com/ultralytics/yolov5/issues/251) 🚀
- [NVIDIA Jetson Nano Deployment](https://github.com/ultralytics/yolov5/issues/9627) 🌟 NEW
- [Test-Time Augmentation (TTA)](https://github.com/ultralytics/yolov5/issues/303)
- [Model Ensembling](https://github.com/ultralytics/yolov5/issues/318)
- [Model Pruning/Sparsity](https://github.com/ultralytics/yolov5/issues/304)
- [Hyperparameter Evolution](https://github.com/ultralytics/yolov5/issues/607)
- [Transfer Learning with Frozen Layers](https://github.com/ultralytics/yolov5/issues/1314)
- [Architecture Summary](https://github.com/ultralytics/yolov5/issues/6998) 🌟 NEW
- [Roboflow for Datasets, Labeling, and Active Learning](https://github.com/ultralytics/yolov5/issues/4975)  🌟 NEW
- [ClearML Logging](https://github.com/ultralytics/yolov5/tree/master/utils/loggers/clearml) 🌟 NEW
- [Deci Platform](https://github.com/ultralytics/yolov5/wiki/Deci-Platform) 🌟 NEW
- [Comet Logging](https://github.com/ultralytics/yolov5/tree/master/utils/loggers/comet) 🌟 NEW
</details>
## <div align="center">Integrations</div>
<br>
<a align="center" href="https://bit.ly/ultralytics_hub" target="_blank">
<img width="100%" src="https://github.com/ultralytics/assets/raw/master/im/integrations-loop.png"></a>
<br>
<br>
<div align="center">
<a href="https://roboflow.com/?ref=ultralytics">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-roboflow.png" width="10%" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="15%" height="0" alt="" />
<a href="https://cutt.ly/yolov5-readme-clearml">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-clearml.png" width="10%" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="15%" height="0" alt="" />
<a href="https://bit.ly/yolov5-readme-comet">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-comet.png" width="10%" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="15%" height="0" alt="" />
<a href="https://bit.ly/yolov5-deci-platform">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-deci.png" width="10%" /></a>
</div>
|Roboflow|ClearML ⭐ NEW|Comet ⭐ NEW|Deci ⭐ NEW|
|:-:|:-:|:-:|:-:|
|Label and export your custom datasets directly to YOLOv5 for training with [Roboflow](https://roboflow.com/?ref=ultralytics)|Automatically track, visualize and even remotely train YOLOv5 using [ClearML](https://cutt.ly/yolov5-readme-clearml) (open-source!)|Free forever, [Comet](https://bit.ly/yolov5-readme-comet) lets you save YOLOv5 models, resume training, and interactively visualise and debug predictions|Automatically compile and quantize YOLOv5 for better inference performance in one click at [Deci](https://bit.ly/yolov5-deci-platform)|
## <div align="center">Ultralytics HUB</div>
[Ultralytics HUB](https://bit.ly/ultralytics_hub) is our ⭐ **NEW** no-code solution to visualize datasets, train YOLOv5 🚀 models, and deploy to the real world in a seamless experience. Get started for **Free** now!
<a align="center" href="https://bit.ly/ultralytics_hub" target="_blank">
<img width="100%" src="https://github.com/ultralytics/assets/raw/master/im/ultralytics-hub.png"></a>
## <div align="center">Why YOLOv5</div>
YOLOv5 has been designed to be super easy to get started and simple to learn. We prioritize real-world results.
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040763-93c22a27-347c-4e3c-847a-8094621d3f4e.png"></p>
<details>
<summary>YOLOv5-P5 640 Figure</summary>
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040757-ce0934a3-06a6-43dc-a979-2edbbd69ea0e.png"></p>
</details>
<details>
<summary>Figure Notes</summary>
- **COCO AP val** denotes mAP@0.5:0.95 metric measured on the 5000-image [COCO val2017](http://cocodataset.org) dataset over various inference sizes from 256 to 1536.
- **GPU Speed** measures average inference time per image on [COCO val2017](http://cocodataset.org) dataset using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) V100 instance at batch-size 32.
- **EfficientDet** data from [google/automl](https://github.com/google/automl) at batch size 8.
- **Reproduce** by `python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt`
</details>
### Pretrained Checkpoints
| Model | size<br><sup>(pixels) | mAP<sup>val<br>50-95 | mAP<sup>val<br>50 | Speed<br><sup>CPU b1<br>(ms) | Speed<br><sup>V100 b1<br>(ms) | Speed<br><sup>V100 b32<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>@640 (B) |
|------------------------------------------------------------------------------------------------------|-----------------------|----------------------|-------------------|------------------------------|-------------------------------|--------------------------------|--------------------|------------------------|
| [YOLOv5n](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5n.pt) | 640 | 28.0 | 45.7 | **45** | **6.3** | **0.6** | **1.9** | **4.5** |
| [YOLOv5s](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5s.pt) | 640 | 37.4 | 56.8 | 98 | 6.4 | 0.9 | 7.2 | 16.5 |
| [YOLOv5m](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5m.pt) | 640 | 45.4 | 64.1 | 224 | 8.2 | 1.7 | 21.2 | 49.0 |
| [YOLOv5l](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5l.pt) | 640 | 49.0 | 67.3 | 430 | 10.1 | 2.7 | 46.5 | 109.1 |
| [YOLOv5x](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5x.pt) | 640 | 50.7 | 68.9 | 766 | 12.1 | 4.8 | 86.7 | 205.7 |
| | | | | | | | | |
| [YOLOv5n6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5n6.pt) | 1280 | 36.0 | 54.4 | 153 | 8.1 | 2.1 | 3.2 | 4.6 |
| [YOLOv5s6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5s6.pt) | 1280 | 44.8 | 63.7 | 385 | 8.2 | 3.6 | 12.6 | 16.8 |
| [YOLOv5m6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5m6.pt) | 1280 | 51.3 | 69.3 | 887 | 11.1 | 6.8 | 35.7 | 50.0 |
| [YOLOv5l6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5l6.pt) | 1280 | 53.7 | 71.3 | 1784 | 15.8 | 10.5 | 76.8 | 111.4 |
| [YOLOv5x6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5x6.pt)<br>+ [TTA][TTA] | 1280<br>1536 | 55.0<br>**55.8** | 72.7<br>**72.7** | 3136<br>- | 26.2<br>- | 19.4<br>- | 140.7<br>- | 209.8<br>- |
<details>
<summary>Table Notes</summary>
- All checkpoints are trained to 300 epochs with default settings. Nano and Small models use [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml) hyps, all others use [hyp.scratch-high.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-high.yaml).
- **mAP<sup>val</sup>** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.<br>Reproduce by `python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
- **Speed** averaged over COCO val images using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) instance. NMS times (~1 ms/img) not included.<br>Reproduce by `python val.py --data coco.yaml --img 640 --task speed --batch 1`
- **TTA** [Test Time Augmentation](https://github.com/ultralytics/yolov5/issues/303) includes reflection and scale augmentations.<br>Reproduce by `python val.py --data coco.yaml --img 1536 --iou 0.7 --augment`
</details>
## <div align="center">Classification ⭐ NEW</div>
YOLOv5 [release v6.2](https://github.com/ultralytics/yolov5/releases) brings support for classification model training, validation and deployment! See full details in our [Release Notes](https://github.com/ultralytics/yolov5/releases/v6.2) and visit our [YOLOv5 Classification Colab Notebook](https://github.com/ultralytics/yolov5/blob/master/classify/tutorial.ipynb) for quickstart tutorials.
<details>
<summary>Classification Checkpoints</summary>
<br>
We trained YOLOv5-cls classification models on ImageNet for 90 epochs using a 4xA100 instance, and we trained ResNet and EfficientNet models alongside with the same default training settings to compare. We exported all models to ONNX FP32 for CPU speed tests and to TensorRT FP16 for GPU speed tests. We ran all speed tests on Google [Colab Pro](https://colab.research.google.com/signup) for easy reproducibility.
| Model | size<br><sup>(pixels) | acc<br><sup>top1 | acc<br><sup>top5 | Training<br><sup>90 epochs<br>4xA100 (hours) | Speed<br><sup>ONNX CPU<br>(ms) | Speed<br><sup>TensorRT V100<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>@224 (B) |
|----------------------------------------------------------------------------------------------------|-----------------------|------------------|------------------|----------------------------------------------|--------------------------------|-------------------------------------|--------------------|------------------------|
| [YOLOv5n-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5n-cls.pt) | 224 | 64.6 | 85.4 | 7:59 | **3.3** | **0.5** | **2.5** | **0.5** |
| [YOLOv5s-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5s-cls.pt) | 224 | 71.5 | 90.2 | 8:09 | 6.6 | 0.6 | 5.4 | 1.4 |
| [YOLOv5m-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5m-cls.pt) | 224 | 75.9 | 92.9 | 10:06 | 15.5 | 0.9 | 12.9 | 3.9 |
| [YOLOv5l-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5l-cls.pt) | 224 | 78.0 | 94.0 | 11:56 | 26.9 | 1.4 | 26.5 | 8.5 |
| [YOLOv5x-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5x-cls.pt) | 224 | **79.0** | **94.4** | 15:04 | 54.3 | 1.8 | 48.1 | 15.9 |
| |
| [ResNet18](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet18.pt) | 224 | 70.3 | 89.5 | **6:47** | 11.2 | 0.5 | 11.7 | 3.7 |
| [ResNet34](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet34.pt) | 224 | 73.9 | 91.8 | 8:33 | 20.6 | 0.9 | 21.8 | 7.4 |
| [ResNet50](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet50.pt) | 224 | 76.8 | 93.4 | 11:10 | 23.4 | 1.0 | 25.6 | 8.5 |
| [ResNet101](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet101.pt) | 224 | 78.5 | 94.3 | 17:10 | 42.1 | 1.9 | 44.5 | 15.9 |
| |
| [EfficientNet_b0](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b0.pt) | 224 | 75.1 | 92.4 | 13:03 | 12.5 | 1.3 | 5.3 | 1.0 |
| [EfficientNet_b1](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b1.pt) | 224 | 76.4 | 93.2 | 17:04 | 14.9 | 1.6 | 7.8 | 1.5 |
| [EfficientNet_b2](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b2.pt) | 224 | 76.6 | 93.4 | 17:10 | 15.9 | 1.6 | 9.1 | 1.7 |
| [EfficientNet_b3](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b3.pt) | 224 | 77.7 | 94.0 | 19:19 | 18.9 | 1.9 | 12.2 | 2.4 |
<details>
<summary>Table Notes (click to expand)</summary>
- All checkpoints are trained to 90 epochs with SGD optimizer with `lr0=0.001` and `weight_decay=5e-5` at image size 224 and all default settings.<br>Runs logged to https://wandb.ai/glenn-jocher/YOLOv5-Classifier-v6-2
- **Accuracy** values are for single-model single-scale on [ImageNet-1k](https://www.image-net.org/index.php) dataset.<br>Reproduce by `python classify/val.py --data ../datasets/imagenet --img 224`
- **Speed** averaged over 100 inference images using a Google [Colab Pro](https://colab.research.google.com/signup) V100 High-RAM instance.<br>Reproduce by `python classify/val.py --data ../datasets/imagenet --img 224 --batch 1`
- **Export** to ONNX at FP32 and TensorRT at FP16 done with `export.py`. <br>Reproduce by `python export.py --weights yolov5s-cls.pt --include engine onnx --imgsz 224`
</details>
</details>
<details>
<summary>Classification Usage Examples &nbsp;<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/classify/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a></summary>
### Train
YOLOv5 classification training supports auto-download of MNIST, Fashion-MNIST, CIFAR10, CIFAR100, Imagenette, Imagewoof, and ImageNet datasets with the `--data` argument. To start training on MNIST for example use `--data mnist`.
```bash
# Single-GPU
python classify/train.py --model yolov5s-cls.pt --data cifar100 --epochs 5 --img 224 --batch 128
# Multi-GPU DDP
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 classify/train.py --model yolov5s-cls.pt --data imagenet --epochs 5 --img 224 --device 0,1,2,3
```
### Val
Validate YOLOv5m-cls accuracy on ImageNet-1k dataset:
```bash
bash data/scripts/get_imagenet.sh --val # download ImageNet val split (6.3G, 50000 images)
python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224 # validate
```
### Predict
Use pretrained YOLOv5s-cls.pt to predict bus.jpg:
```bash
python classify/predict.py --weights yolov5s-cls.pt --data data/images/bus.jpg
```
```python
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s-cls.pt') # load from PyTorch Hub
```
### Export
Export a group of trained YOLOv5s-cls, ResNet and EfficientNet models to ONNX and TensorRT:
```bash
python export.py --weights yolov5s-cls.pt resnet50.pt efficientnet_b0.pt --include onnx engine --img 224
```
</details>
## <div align="center">Environments</div>
Get started in seconds with our verified environments. Click each icon below for details.
<div align="center">
<a href="https://bit.ly/yolov5-paperspace-notebook">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-gradient.png" width="10%" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="5%" alt="" />
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-colab-small.png" width="10%" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="5%" alt="" />
<a href="https://www.kaggle.com/ultralytics/yolov5">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-kaggle-small.png" width="10%" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="5%" alt="" />
<a href="https://hub.docker.com/r/ultralytics/yolov5">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-docker-small.png" width="10%" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="5%" alt="" />
<a href="https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-aws-small.png" width="10%" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="5%" alt="" />
<a href="https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart">
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-gcp-small.png" width="10%" /></a>
</div>
## <div align="center">Contribute</div>
We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible. Please see our [Contributing Guide](CONTRIBUTING.md) to get started, and fill out the [YOLOv5 Survey](https://ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) to send us feedback on your experiences. Thank you to all our contributors!
<!-- SVG image from https://opencollective.com/ultralytics/contributors.svg?width=990 -->
<a href="https://github.com/ultralytics/yolov5/graphs/contributors"><img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/image-contributors-1280.png" /></a>
## <div align="center">Contact</div>
For YOLOv5 bugs and feature requests please visit [GitHub Issues](https://github.com/ultralytics/yolov5/issues). For professional support please [Contact Us](https://ultralytics.com/contact). To request a commercial license please complete the form at [Ultralytics Licensing](https://ultralytics.com/license).
<br>
<div align="center">
<a href="https://github.com/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-github.png" width="3%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
<a href="https://www.linkedin.com/company/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-linkedin.png" width="3%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
<a href="https://twitter.com/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-twitter.png" width="3%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
<a href="https://www.producthunt.com/@glenn_jocher" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-producthunt.png" width="3%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
<a href="https://youtube.com/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-youtube.png" width="3%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
<a href="https://www.facebook.com/ultralytics" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-facebook.png" width="3%" alt="" /></a>
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
<a href="https://www.instagram.com/ultralytics/" style="text-decoration:none;">
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-instagram.png" width="3%" alt="" /></a>
</div>
[assets]: https://github.com/ultralytics/yolov5/releases
[tta]: https://github.com/ultralytics/yolov5/issues/303
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Run YOLOv5 benchmarks on all supported export formats
Format | `export.py --include` | Model
--- | --- | ---
PyTorch | - | yolov5s.pt
TorchScript | `torchscript` | yolov5s.torchscript
ONNX | `onnx` | yolov5s.onnx
OpenVINO | `openvino` | yolov5s_openvino_model/
TensorRT | `engine` | yolov5s.engine
CoreML | `coreml` | yolov5s.mlmodel
TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
TensorFlow GraphDef | `pb` | yolov5s.pb
TensorFlow Lite | `tflite` | yolov5s.tflite
TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
TensorFlow.js | `tfjs` | yolov5s_web_model/
Requirements:
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
$ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
Usage:
$ python benchmarks.py --weights yolov5s.pt --img 640
"""
import argparse
import platform
import sys
import time
from pathlib import Path
import pandas as pd
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
# ROOT = ROOT.relative_to(Path.cwd()) # relative
import export
from models.experimental import attempt_load
from models.yolo import SegmentationModel
from segment.val import run as val_seg
from utils import notebook_init
from utils.general import LOGGER, check_yaml, file_size, print_args
from utils.torch_utils import select_device
from val import run as val_det
def run(
weights=ROOT / 'yolov5s.pt', # weights path
imgsz=640, # inference size (pixels)
batch_size=1, # batch size
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
half=False, # use FP16 half-precision inference
test=False, # test exports only
pt_only=False, # test PyTorch only
hard_fail=False, # throw error on benchmark failure
):
y, t = [], time.time()
device = select_device(device)
model_type = type(attempt_load(weights, fuse=False)) # DetectionModel, SegmentationModel, etc.
for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
try:
assert i not in (9, 10), 'inference not supported' # Edge TPU and TF.js are unsupported
assert i != 5 or platform.system() == 'Darwin', 'inference only supported on macOS>=10.13' # CoreML
if 'cpu' in device.type:
assert cpu, 'inference not supported on CPU'
if 'cuda' in device.type:
assert gpu, 'inference not supported on GPU'
# Export
if f == '-':
w = weights # PyTorch format
else:
w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # all others
assert suffix in str(w), 'export failed'
# Validate
if model_type == SegmentationModel:
result = val_seg(data, w, batch_size, imgsz, plots=False, device=device, task='speed', half=half)
metric = result[0][7] # (box(p, r, map50, map), mask(p, r, map50, map), *loss(box, obj, cls))
else: # DetectionModel:
result = val_det(data, w, batch_size, imgsz, plots=False, device=device, task='speed', half=half)
metric = result[0][3] # (p, r, map50, map, *loss(box, obj, cls))
speed = result[2][1] # times (preprocess, inference, postprocess)
y.append([name, round(file_size(w), 1), round(metric, 4), round(speed, 2)]) # MB, mAP, t_inference
except Exception as e:
if hard_fail:
assert type(e) is AssertionError, f'Benchmark --hard-fail for {name}: {e}'
LOGGER.warning(f'WARNING ⚠️ Benchmark failure for {name}: {e}')
y.append([name, None, None, None]) # mAP, t_inference
if pt_only and i == 0:
break # break after PyTorch
# Print results
LOGGER.info('\n')
parse_opt()
notebook_init() # print system info
c = ['Format', 'Size (MB)', 'mAP50-95', 'Inference time (ms)'] if map else ['Format', 'Export', '', '']
py = pd.DataFrame(y, columns=c)
LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)')
LOGGER.info(str(py if map else py.iloc[:, :2]))
if hard_fail and isinstance(hard_fail, str):
metrics = py['mAP50-95'].array # values to compare to floor
floor = eval(hard_fail) # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
assert all(x > floor for x in metrics if pd.notna(x)), f'HARD FAIL: mAP50-95 < floor {floor}'
return py
def test(
weights=ROOT / 'yolov5s.pt', # weights path
imgsz=640, # inference size (pixels)
batch_size=1, # batch size
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
half=False, # use FP16 half-precision inference
test=False, # test exports only
pt_only=False, # test PyTorch only
hard_fail=False, # throw error on benchmark failure
):
y, t = [], time.time()
device = select_device(device)
for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
try:
w = weights if f == '-' else \
export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # weights
assert suffix in str(w), 'export failed'
y.append([name, True])
except Exception:
y.append([name, False]) # mAP, t_inference
# Print results
LOGGER.info('\n')
parse_opt()
notebook_init() # print system info
py = pd.DataFrame(y, columns=['Format', 'Export'])
LOGGER.info(f'\nExports complete ({time.time() - t:.2f}s)')
LOGGER.info(str(py))
return py
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
parser.add_argument('--test', action='store_true', help='test exports only')
parser.add_argument('--pt-only', action='store_true', help='test PyTorch only')
parser.add_argument('--hard-fail', nargs='?', const=True, default=False, help='Exception on error or < min metric')
opt = parser.parse_args()
opt.data = check_yaml(opt.data) # check YAML
print_args(vars(opt))
return opt
def main(opt):
test(**vars(opt)) if opt.test else run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt)
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Run YOLOv5 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
Usage - sources:
$ python classify/predict.py --weights yolov5s-cls.pt --source 0 # webcam
img.jpg # image
vid.mp4 # video
screen # screenshot
path/ # directory
'path/*.jpg' # glob
'https://youtu.be/Zgi9g1ksQHc' # YouTube
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
Usage - formats:
$ python classify/predict.py --weights yolov5s-cls.pt # PyTorch
yolov5s-cls.torchscript # TorchScript
yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
yolov5s-cls_openvino_model # OpenVINO
yolov5s-cls.engine # TensorRT
yolov5s-cls.mlmodel # CoreML (macOS-only)
yolov5s-cls_saved_model # TensorFlow SavedModel
yolov5s-cls.pb # TensorFlow GraphDef
yolov5s-cls.tflite # TensorFlow Lite
yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
yolov5s-cls_paddle_model # PaddlePaddle
"""
import argparse
import os
import platform
import sys
from pathlib import Path
import torch
import torch.nn.functional as F
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from models.common import DetectMultiBackend
from utils.augmentations import classify_transforms
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
increment_path, print_args, strip_optimizer)
from utils.plots import Annotator
from utils.torch_utils import select_device, smart_inference_mode
@smart_inference_mode()
def run(
weights=ROOT / 'yolov5s-cls.pt', # model.pt path(s)
source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam)
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
imgsz=(224, 224), # inference size (height, width)
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
view_img=False, # show results
save_txt=False, # save results to *.txt
nosave=False, # do not save images/videos
augment=False, # augmented inference
visualize=False, # visualize features
update=False, # update all models
project=ROOT / 'runs/predict-cls', # save results to project/name
name='exp', # save results to project/name
exist_ok=False, # existing project/name ok, do not increment
half=False, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
vid_stride=1, # video frame-rate stride
):
source = str(source)
save_img = not nosave and not source.endswith('.txt') # save inference images
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
screenshot = source.lower().startswith('screen')
if is_url and is_file:
source = check_file(source) # download
# Directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
# Load model
device = select_device(device)
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
stride, names, pt = model.stride, model.names, model.pt
imgsz = check_img_size(imgsz, s=stride) # check image size
# Dataloader
bs = 1 # batch_size
if webcam:
view_img = check_imshow(warn=True)
dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
bs = len(dataset)
elif screenshot:
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
else:
dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
vid_path, vid_writer = [None] * bs, [None] * bs
# Run inference
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
for path, im, im0s, vid_cap, s in dataset:
with dt[0]:
im = torch.Tensor(im).to(model.device)
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
if len(im.shape) == 3:
im = im[None] # expand for batch dim
# Inference
with dt[1]:
results = model(im)
# Post-process
with dt[2]:
pred = F.softmax(results, dim=1) # probabilities
# Process predictions
for i, prob in enumerate(pred): # per image
seen += 1
if webcam: # batch_size >= 1
p, im0, frame = path[i], im0s[i].copy(), dataset.count
s += f'{i}: '
else:
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
p = Path(p) # to Path
save_path = str(save_dir / p.name) # im.jpg
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
s += '%gx%g ' % im.shape[2:] # print string
annotator = Annotator(im0, example=str(names), pil=True)
# Print results
top5i = prob.argsort(0, descending=True)[:5].tolist() # top 5 indices
s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "
# Write results
text = '\n'.join(f'{prob[j]:.2f} {names[j]}' for j in top5i)
if save_img or view_img: # Add bbox to image
annotator.text((32, 32), text, txt_color=(255, 255, 255))
if save_txt: # Write to file
with open(f'{txt_path}.txt', 'a') as f:
f.write(text + '\n')
# Stream results
im0 = annotator.result()
if view_img:
if platform.system() == 'Linux' and p not in windows:
windows.append(p)
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond
# Save results (image with detections)
if save_img:
if dataset.mode == 'image':
cv2.imwrite(save_path, im0)
else: # 'video' or 'stream'
if vid_path[i] != save_path: # new video
vid_path[i] = save_path
if isinstance(vid_writer[i], cv2.VideoWriter):
vid_writer[i].release() # release previous video writer
if vid_cap: # video
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
else: # stream
fps, w, h = 30, im0.shape[1], im0.shape[0]
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
vid_writer[i].write(im0)
# Print time (inference-only)
LOGGER.info(f"{s}{dt[1].dt * 1E3:.1f}ms")
# Print results
t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
if save_txt or save_img:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
if update:
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model path(s)')
parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[224], help='inference size h,w')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--view-img', action='store_true', help='show results')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--visualize', action='store_true', help='visualize features')
parser.add_argument('--update', action='store_true', help='update all models')
parser.add_argument('--project', default=ROOT / 'runs/predict-cls', help='save results to project/name')
parser.add_argument('--name', default='exp', help='save results to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
opt = parser.parse_args()
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
print_args(vars(opt))
return opt
def main(opt):
check_requirements(exclude=('tensorboard', 'thop'))
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt)
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Train a YOLOv5 classifier model on a classification dataset
Usage - Single-GPU training:
$ python classify/train.py --model yolov5s-cls.pt --data imagenette160 --epochs 5 --img 224
Usage - Multi-GPU DDP training:
$ python -m torch.distributed.run --nproc_per_node 4 --master_port 1 classify/train.py --model yolov5s-cls.pt --data imagenet --epochs 5 --img 224 --device 0,1,2,3
Datasets: --data mnist, fashion-mnist, cifar10, cifar100, imagenette, imagewoof, imagenet, or 'path/to/data'
YOLOv5-cls models: --model yolov5n-cls.pt, yolov5s-cls.pt, yolov5m-cls.pt, yolov5l-cls.pt, yolov5x-cls.pt
Torchvision models: --model resnet50, efficientnet_b0, etc. See https://pytorch.org/vision/stable/models.html
"""
import argparse
import os
import subprocess
import sys
import time
from copy import deepcopy
from datetime import datetime
from pathlib import Path
import torch
import torch.distributed as dist
import torch.hub as hub
import torch.optim.lr_scheduler as lr_scheduler
import torchvision
from torch.cuda import amp
from tqdm import tqdm
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from classify import val as validate
from models.experimental import attempt_load
from models.yolo import ClassificationModel, DetectionModel
from utils.dataloaders import create_classification_dataloader
from utils.general import (DATASETS_DIR, LOGGER, TQDM_BAR_FORMAT, WorkingDirectory, check_git_info, check_git_status,
check_requirements, colorstr, download, increment_path, init_seeds, print_args, yaml_save)
from utils.loggers import GenericLogger
from utils.plots import imshow_cls
from utils.torch_utils import (ModelEMA, model_info, reshape_classifier_output, select_device, smart_DDP,
smart_optimizer, smartCrossEntropyLoss, torch_distributed_zero_first)
LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
RANK = int(os.getenv('RANK', -1))
WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
GIT_INFO = check_git_info()
def train(opt, device):
init_seeds(opt.seed + 1 + RANK, deterministic=True)
save_dir, data, bs, epochs, nw, imgsz, pretrained = \
opt.save_dir, Path(opt.data), opt.batch_size, opt.epochs, min(os.cpu_count() - 1, opt.workers), \
opt.imgsz, str(opt.pretrained).lower() == 'true'
cuda = device.type != 'cpu'
# Directories
wdir = save_dir / 'weights'
wdir.mkdir(parents=True, exist_ok=True) # make dir
last, best = wdir / 'last.pt', wdir / 'best.pt'
# Save run settings
yaml_save(save_dir / 'opt.yaml', vars(opt))
# Logger
logger = GenericLogger(opt=opt, console_logger=LOGGER) if RANK in {-1, 0} else None
# Download Dataset
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
data_dir = data if data.is_dir() else (DATASETS_DIR / data)
if not data_dir.is_dir():
LOGGER.info(f'\nDataset not found ⚠️, missing path {data_dir}, attempting download...')
t = time.time()
if str(data) == 'imagenet':
subprocess.run(f"bash {ROOT / 'data/scripts/get_imagenet.sh'}", shell=True, check=True)
else:
url = f'https://github.com/ultralytics/yolov5/releases/download/v1.0/{data}.zip'
download(url, dir=data_dir.parent)
s = f"Dataset download success ✅ ({time.time() - t:.1f}s), saved to {colorstr('bold', data_dir)}\n"
LOGGER.info(s)
# Dataloaders
nc = len([x for x in (data_dir / 'train').glob('*') if x.is_dir()]) # number of classes
trainloader = create_classification_dataloader(path=data_dir / 'train',
imgsz=imgsz,
batch_size=bs // WORLD_SIZE,
augment=True,
cache=opt.cache,
rank=LOCAL_RANK,
workers=nw)
test_dir = data_dir / 'test' if (data_dir / 'test').exists() else data_dir / 'val' # data/test or data/val
if RANK in {-1, 0}:
testloader = create_classification_dataloader(path=test_dir,
imgsz=imgsz,
batch_size=bs // WORLD_SIZE * 2,
augment=False,
cache=opt.cache,
rank=-1,
workers=nw)
# Model
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
if Path(opt.model).is_file() or opt.model.endswith('.pt'):
model = attempt_load(opt.model, device='cpu', fuse=False)
elif opt.model in torchvision.models.__dict__: # TorchVision models i.e. resnet50, efficientnet_b0
model = torchvision.models.__dict__[opt.model](weights='IMAGENET1K_V1' if pretrained else None)
else:
m = hub.list('ultralytics/yolov5') # + hub.list('pytorch/vision') # models
raise ModuleNotFoundError(f'--model {opt.model} not found. Available models are: \n' + '\n'.join(m))
if isinstance(model, DetectionModel):
LOGGER.warning("WARNING ⚠️ pass YOLOv5 classifier model with '-cls' suffix, i.e. '--model yolov5s-cls.pt'")
model = ClassificationModel(model=model, nc=nc, cutoff=opt.cutoff or 10) # convert to classification model
reshape_classifier_output(model, nc) # update class count
for m in model.modules():
if not pretrained and hasattr(m, 'reset_parameters'):
m.reset_parameters()
if isinstance(m, torch.nn.Dropout) and opt.dropout is not None:
m.p = opt.dropout # set dropout
for p in model.parameters():
p.requires_grad = True # for training
model = model.to(device)
# Info
if RANK in {-1, 0}:
model.names = trainloader.dataset.classes # attach class names
model.transforms = testloader.dataset.torch_transforms # attach inference transforms
model_info(model)
if opt.verbose:
LOGGER.info(model)
images, labels = next(iter(trainloader))
file = imshow_cls(images[:25], labels[:25], names=model.names, f=save_dir / 'train_images.jpg')
logger.log_images(file, name='Train Examples')
logger.log_graph(model, imgsz) # log model
# Optimizer
optimizer = smart_optimizer(model, opt.optimizer, opt.lr0, momentum=0.9, decay=opt.decay)
# Scheduler
lrf = 0.01 # final lr (fraction of lr0)
# lf = lambda x: ((1 + math.cos(x * math.pi / epochs)) / 2) * (1 - lrf) + lrf # cosine
lf = lambda x: (1 - x / epochs) * (1 - lrf) + lrf # linear
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
# scheduler = lr_scheduler.OneCycleLR(optimizer, max_lr=lr0, total_steps=epochs, pct_start=0.1,
# final_div_factor=1 / 25 / lrf)
# EMA
ema = ModelEMA(model) if RANK in {-1, 0} else None
# DDP mode
if cuda and RANK != -1:
model = smart_DDP(model)
# Train
t0 = time.time()
criterion = smartCrossEntropyLoss(label_smoothing=opt.label_smoothing) # loss function
best_fitness = 0.0
scaler = amp.GradScaler(enabled=cuda)
val = test_dir.stem # 'val' or 'test'
LOGGER.info(f'Image sizes {imgsz} train, {imgsz} test\n'
f'Using {nw * WORLD_SIZE} dataloader workers\n'
f"Logging results to {colorstr('bold', save_dir)}\n"
f'Starting {opt.model} training on {data} dataset with {nc} classes for {epochs} epochs...\n\n'
f"{'Epoch':>10}{'GPU_mem':>10}{'train_loss':>12}{f'{val}_loss':>12}{'top1_acc':>12}{'top5_acc':>12}")
for epoch in range(epochs): # loop over the dataset multiple times
tloss, vloss, fitness = 0.0, 0.0, 0.0 # train loss, val loss, fitness
model.train()
if RANK != -1:
trainloader.sampler.set_epoch(epoch)
pbar = enumerate(trainloader)
if RANK in {-1, 0}:
pbar = tqdm(enumerate(trainloader), total=len(trainloader), bar_format=TQDM_BAR_FORMAT)
for i, (images, labels) in pbar: # progress bar
images, labels = images.to(device, non_blocking=True), labels.to(device)
# Forward
with amp.autocast(enabled=cuda): # stability issues when enabled
loss = criterion(model(images), labels)
# Backward
scaler.scale(loss).backward()
# Optimize
scaler.unscale_(optimizer) # unscale gradients
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad()
if ema:
ema.update(model)
if RANK in {-1, 0}:
# Print
tloss = (tloss * i + loss.item()) / (i + 1) # update mean losses
mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
pbar.desc = f"{f'{epoch + 1}/{epochs}':>10}{mem:>10}{tloss:>12.3g}" + ' ' * 36
# Test
if i == len(pbar) - 1: # last batch
top1, top5, vloss = validate.run(model=ema.ema,
dataloader=testloader,
criterion=criterion,
pbar=pbar) # test accuracy, loss
fitness = top1 # define fitness as top1 accuracy
# Scheduler
scheduler.step()
# Log metrics
if RANK in {-1, 0}:
# Best fitness
if fitness > best_fitness:
best_fitness = fitness
# Log
metrics = {
"train/loss": tloss,
f"{val}/loss": vloss,
"metrics/accuracy_top1": top1,
"metrics/accuracy_top5": top5,
"lr/0": optimizer.param_groups[0]['lr']} # learning rate
logger.log_metrics(metrics, epoch)
# Save model
final_epoch = epoch + 1 == epochs
if (not opt.nosave) or final_epoch:
ckpt = {
'epoch': epoch,
'best_fitness': best_fitness,
'model': deepcopy(ema.ema).half(), # deepcopy(de_parallel(model)).half(),
'ema': None, # deepcopy(ema.ema).half(),
'updates': ema.updates,
'optimizer': None, # optimizer.state_dict(),
'opt': vars(opt),
'git': GIT_INFO, # {remote, branch, commit} if a git repo
'date': datetime.now().isoformat()}
# Save last, best and delete
torch.save(ckpt, last)
if best_fitness == fitness:
torch.save(ckpt, best)
del ckpt
# Train complete
if RANK in {-1, 0} and final_epoch:
LOGGER.info(f'\nTraining complete ({(time.time() - t0) / 3600:.3f} hours)'
f"\nResults saved to {colorstr('bold', save_dir)}"
f"\nPredict: python classify/predict.py --weights {best} --source im.jpg"
f"\nValidate: python classify/val.py --weights {best} --data {data_dir}"
f"\nExport: python export.py --weights {best} --include onnx"
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{best}')"
f"\nVisualize: https://netron.app\n")
# Plot examples
images, labels = (x[:25] for x in next(iter(testloader))) # first 25 images and labels
pred = torch.max(ema.ema(images.to(device)), 1)[1]
file = imshow_cls(images, labels, pred, model.names, verbose=False, f=save_dir / 'test_images.jpg')
# Log results
meta = {"epochs": epochs, "top1_acc": best_fitness, "date": datetime.now().isoformat()}
logger.log_images(file, name='Test Examples (true-predicted)', epoch=epoch)
logger.log_model(best, epochs, metadata=meta)
def parse_opt(known=False):
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default='yolov5s-cls.pt', help='initial weights path')
parser.add_argument('--data', type=str, default='imagenette160', help='cifar10, cifar100, mnist, imagenet, ...')
parser.add_argument('--epochs', type=int, default=10, help='total training epochs')
parser.add_argument('--batch-size', type=int, default=64, help='total batch size for all GPUs')
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=224, help='train, val image size (pixels)')
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
parser.add_argument('--project', default=ROOT / 'runs/train-cls', help='save to project/name')
parser.add_argument('--name', default='exp', help='save to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
parser.add_argument('--pretrained', nargs='?', const=True, default=True, help='start from i.e. --pretrained False')
parser.add_argument('--optimizer', choices=['SGD', 'Adam', 'AdamW', 'RMSProp'], default='Adam', help='optimizer')
parser.add_argument('--lr0', type=float, default=0.001, help='initial learning rate')
parser.add_argument('--decay', type=float, default=5e-5, help='weight decay')
parser.add_argument('--label-smoothing', type=float, default=0.1, help='Label smoothing epsilon')
parser.add_argument('--cutoff', type=int, default=None, help='Model layer cutoff index for Classify() head')
parser.add_argument('--dropout', type=float, default=None, help='Dropout (fraction)')
parser.add_argument('--verbose', action='store_true', help='Verbose mode')
parser.add_argument('--seed', type=int, default=0, help='Global training seed')
parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')
return parser.parse_known_args()[0] if known else parser.parse_args()
def main(opt):
# Checks
if RANK in {-1, 0}:
print_args(vars(opt))
check_git_status()
check_requirements()
# DDP mode
device = select_device(opt.device, batch_size=opt.batch_size)
if LOCAL_RANK != -1:
assert opt.batch_size != -1, 'AutoBatch is coming soon for classification, please pass a valid --batch-size'
assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE'
assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
torch.cuda.set_device(LOCAL_RANK)
device = torch.device('cuda', LOCAL_RANK)
dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
# Parameters
opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
# Train
train(opt, device)
def run(**kwargs):
# Usage: from yolov5 import classify; classify.train.run(data=mnist, imgsz=320, model='yolov5m')
opt = parse_opt(True)
for k, v in kwargs.items():
setattr(opt, k, v)
main(opt)
return opt
if __name__ == "__main__":
opt = parse_opt()
main(opt)
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "t6MPjfT5NrKQ"
},
"source": [
"<div align=\"center\">\n",
"\n",
" <a href=\"https://ultralytics.com/yolov5\" target=\"_blank\">\n",
" <img width=\"1024\", src=\"https://raw.githubusercontent.com/ultralytics/assets/master/yolov5/v70/splash.png\"></a>\n",
"\n",
"\n",
"<br>\n",
" <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a>\n",
" <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/classify/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
" <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n",
"<br>\n",
"\n",
"This <a href=\"https://github.com/ultralytics/yolov5\">YOLOv5</a> 🚀 notebook by <a href=\"https://ultralytics.com\">Ultralytics</a> presents simple train, validate and predict examples to help start your AI adventure.<br>See <a href=\"https://github.com/ultralytics/yolov5/issues/new/choose\">GitHub</a> for community support or <a href=\"https://ultralytics.com/contact\">contact us</a> for professional support.\n",
"\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7mGmQbAO5pQb"
},
"source": [
"# Setup\n",
"\n",
"Clone GitHub [repository](https://github.com/ultralytics/yolov5), install [dependencies](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) and check PyTorch and GPU."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "wbvMlHd_QwMG",
"outputId": "43b2e1b5-78d9-4e1d-8530-ee9779bba160"
},
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"YOLOv5 🚀 v6.2-258-g7fc7ed7 Python-3.7.15 torch-1.12.1+cu113 CUDA:0 (Tesla T4, 15110MiB)\n"
]
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"Setup complete ✅ (2 CPUs, 12.7 GB RAM, 22.6/78.2 GB disk)\n"
]
}
],
"source": [
"!git clone https://github.com/ultralytics/yolov5 # clone\n",
"%cd yolov5\n",
"%pip install -qr requirements.txt # install\n",
"\n",
"import torch\n",
"import utils\n",
"display = utils.notebook_init() # checks"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4JnkELT0cIJg"
},
"source": [
"# 1. Predict\n",
"\n",
"`classify/predict.py` runs YOLOv5 Classifcation 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/predict-cls`. Example inference sources are:\n",
"\n",
"```shell\n",
"python classify/predict.py --source 0 # webcam\n",
" img.jpg # image \n",
" vid.mp4 # video\n",
" screen # screenshot\n",
" path/ # directory\n",
" 'path/*.jpg' # glob\n",
" 'https://youtu.be/Zgi9g1ksQHc' # YouTube\n",
" 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "zR9ZbuQCH7FX",
"outputId": "1b610787-7cf7-4c33-aac2-aa50fbb84a94"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\u001b[34m\u001b[1mclassify/predict: \u001b[0mweights=['yolov5s-cls.pt'], source=data/images, data=data/coco128.yaml, imgsz=[224, 224], device=, view_img=False, save_txt=True, nosave=False, augment=False, visualize=False, update=False, project=runs/predict-cls, name=exp, exist_ok=False, half=False, dnn=False, vid_stride=1\n",
"YOLOv5 🚀 v6.2-258-g7fc7ed7 Python-3.7.15 torch-1.12.1+cu113 CUDA:0 (Tesla T4, 15110MiB)\n",
"\n",
"Downloading https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5s-cls.pt to yolov5s-cls.pt...\n",
"100% 10.5M/10.5M [00:03<00:00, 2.94MB/s]\n",
"\n",
"Fusing layers... \n",
"Model summary: 117 layers, 5447688 parameters, 0 gradients, 11.4 GFLOPs\n",
"image 1/2 /content/yolov5/data/images/bus.jpg: 224x224 minibus 0.39, police van 0.24, amphibious vehicle 0.05, recreational vehicle 0.04, trolleybus 0.03, 3.9ms\n",
"image 2/2 /content/yolov5/data/images/zidane.jpg: 224x224 suit 0.38, bow tie 0.19, bridegroom 0.18, rugby ball 0.04, stage 0.02, 4.1ms\n",
"Speed: 0.3ms pre-process, 4.0ms inference, 1.5ms NMS per image at shape (1, 3, 224, 224)\n",
"Results saved to \u001b[1mruns/predict-cls/exp\u001b[0m\n"
]
}
],
"source": [
"!python classify/predict.py --weights yolov5s-cls.pt --img 224 --source data/images\n",
"# display.Image(filename='runs/predict-cls/exp/zidane.jpg', width=600)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hkAzDWJ7cWTr"
},
"source": [
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n",
"<img align=\"left\" src=\"https://user-images.githubusercontent.com/26833433/202808393-50deb439-ae1b-4246-a685-7560c9b37211.jpg\" width=\"600\">"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0eq1SMWl6Sfn"
},
"source": [
"# 2. Validate\n",
"Validate a model's accuracy on the [Imagenet](https://image-net.org/) dataset's `val` or `test` splits. Models are downloaded automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases). To show results by class use the `--verbose` flag."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "WQPtK1QYVaD_",
"outputId": "92de5f34-cf41-49e7-b679-41db94e995ac"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"--2022-11-18 21:48:38-- https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_val.tar\n",
"Resolving image-net.org (image-net.org)... 171.64.68.16\n",
"Connecting to image-net.org (image-net.org)|171.64.68.16|:443... connected.\n",
"HTTP request sent, awaiting response... 200 OK\n",
"Length: 6744924160 (6.3G) [application/x-tar]\n",
"Saving to: ‘ILSVRC2012_img_val.tar’\n",
"\n",
"ILSVRC2012_img_val. 100%[===================>] 6.28G 7.15MB/s in 11m 13s \n",
"\n",
"2022-11-18 21:59:52 (9.55 MB/s) - ‘ILSVRC2012_img_val.tar’ saved [6744924160/6744924160]\n",
"\n"
]
}
],
"source": [
"# Download Imagenet val (6.3G, 50000 images)\n",
"!bash data/scripts/get_imagenet.sh --val"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "X58w8JLpMnjH",
"outputId": "9961ad87-d639-4489-b578-0a0578fefaab"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\u001b[34m\u001b[1mclassify/val: \u001b[0mdata=../datasets/imagenet, weights=['yolov5s-cls.pt'], batch_size=128, imgsz=224, device=, workers=8, verbose=True, project=runs/val-cls, name=exp, exist_ok=False, half=True, dnn=False\n",
"YOLOv5 🚀 v6.2-258-g7fc7ed7 Python-3.7.15 torch-1.12.1+cu113 CUDA:0 (Tesla T4, 15110MiB)\n",
"\n",
"Fusing layers... \n",
"Model summary: 117 layers, 5447688 parameters, 0 gradients, 11.4 GFLOPs\n",
"validating: 100% 391/391 [04:48<00:00, 1.35it/s]\n",
" Class Images top1_acc top5_acc\n",
" all 50000 0.715 0.902\n",
" tench 50 0.94 0.98\n",
" goldfish 50 0.88 0.92\n",
" great white shark 50 0.78 0.96\n",
" tiger shark 50 0.68 0.96\n",
" hammerhead shark 50 0.82 0.92\n",
" electric ray 50 0.76 0.9\n",
" stingray 50 0.7 0.9\n",
" cock 50 0.78 0.92\n",
" hen 50 0.84 0.96\n",
" ostrich 50 0.98 1\n",
" brambling 50 0.9 0.96\n",
" goldfinch 50 0.92 0.98\n",
" house finch 50 0.88 0.96\n",
" junco 50 0.94 0.98\n",
" indigo bunting 50 0.86 0.88\n",
" American robin 50 0.9 0.96\n",
" bulbul 50 0.84 0.96\n",
" jay 50 0.9 0.96\n",
" magpie 50 0.84 0.96\n",
" chickadee 50 0.9 1\n",
" American dipper 50 0.82 0.92\n",
" kite 50 0.76 0.94\n",
" bald eagle 50 0.92 1\n",
" vulture 50 0.96 1\n",
" great grey owl 50 0.94 0.98\n",
" fire salamander 50 0.96 0.98\n",
" smooth newt 50 0.58 0.94\n",
" newt 50 0.74 0.9\n",
" spotted salamander 50 0.86 0.94\n",
" axolotl 50 0.86 0.96\n",
" American bullfrog 50 0.78 0.92\n",
" tree frog 50 0.84 0.96\n",
" tailed frog 50 0.48 0.8\n",
" loggerhead sea turtle 50 0.68 0.94\n",
" leatherback sea turtle 50 0.5 0.8\n",
" mud turtle 50 0.64 0.84\n",
" terrapin 50 0.52 0.98\n",
" box turtle 50 0.84 0.98\n",
" banded gecko 50 0.7 0.88\n",
" green iguana 50 0.76 0.94\n",
" Carolina anole 50 0.58 0.96\n",
"desert grassland whiptail lizard 50 0.82 0.94\n",
" agama 50 0.74 0.92\n",
" frilled-necked lizard 50 0.84 0.86\n",
" alligator lizard 50 0.58 0.78\n",
" Gila monster 50 0.72 0.8\n",
" European green lizard 50 0.42 0.9\n",
" chameleon 50 0.76 0.84\n",
" Komodo dragon 50 0.86 0.96\n",
" Nile crocodile 50 0.7 0.84\n",
" American alligator 50 0.76 0.96\n",
" triceratops 50 0.9 0.94\n",
" worm snake 50 0.76 0.88\n",
" ring-necked snake 50 0.8 0.92\n",
" eastern hog-nosed snake 50 0.58 0.88\n",
" smooth green snake 50 0.6 0.94\n",
" kingsnake 50 0.82 0.9\n",
" garter snake 50 0.88 0.94\n",
" water snake 50 0.7 0.94\n",
" vine snake 50 0.66 0.76\n",
" night snake 50 0.34 0.82\n",
" boa constrictor 50 0.8 0.96\n",
" African rock python 50 0.48 0.76\n",
" Indian cobra 50 0.82 0.94\n",
" green mamba 50 0.54 0.86\n",
" sea snake 50 0.62 0.9\n",
" Saharan horned viper 50 0.56 0.86\n",
"eastern diamondback rattlesnake 50 0.6 0.86\n",
" sidewinder 50 0.28 0.86\n",
" trilobite 50 0.98 0.98\n",
" harvestman 50 0.86 0.94\n",
" scorpion 50 0.86 0.94\n",
" yellow garden spider 50 0.92 0.96\n",
" barn spider 50 0.38 0.98\n",
" European garden spider 50 0.62 0.98\n",
" southern black widow 50 0.88 0.94\n",
" tarantula 50 0.94 1\n",
" wolf spider 50 0.82 0.92\n",
" tick 50 0.74 0.84\n",
" centipede 50 0.68 0.82\n",
" black grouse 50 0.88 0.98\n",
" ptarmigan 50 0.78 0.94\n",
" ruffed grouse 50 0.88 1\n",
" prairie grouse 50 0.92 1\n",
" peacock 50 0.88 0.9\n",
" quail 50 0.9 0.94\n",
" partridge 50 0.74 0.96\n",
" grey parrot 50 0.9 0.96\n",
" macaw 50 0.88 0.98\n",
"sulphur-crested cockatoo 50 0.86 0.92\n",
" lorikeet 50 0.96 1\n",
" coucal 50 0.82 0.88\n",
" bee eater 50 0.96 0.98\n",
" hornbill 50 0.9 0.96\n",
" hummingbird 50 0.88 0.96\n",
" jacamar 50 0.92 0.94\n",
" toucan 50 0.84 0.94\n",
" duck 50 0.76 0.94\n",
" red-breasted merganser 50 0.86 0.96\n",
" goose 50 0.74 0.96\n",
" black swan 50 0.94 0.98\n",
" tusker 50 0.54 0.92\n",
" echidna 50 0.98 1\n",
" platypus 50 0.72 0.84\n",
" wallaby 50 0.78 0.88\n",
" koala 50 0.84 0.92\n",
" wombat 50 0.78 0.84\n",
" jellyfish 50 0.88 0.96\n",
" sea anemone 50 0.72 0.9\n",
" brain coral 50 0.88 0.96\n",
" flatworm 50 0.8 0.98\n",
" nematode 50 0.86 0.9\n",
" conch 50 0.74 0.88\n",
" snail 50 0.78 0.88\n",
" slug 50 0.74 0.82\n",
" sea slug 50 0.88 0.98\n",
" chiton 50 0.88 0.98\n",
" chambered nautilus 50 0.88 0.92\n",
" Dungeness crab 50 0.78 0.94\n",
" rock crab 50 0.68 0.86\n",
" fiddler crab 50 0.64 0.86\n",
" red king crab 50 0.76 0.96\n",
" American lobster 50 0.78 0.96\n",
" spiny lobster 50 0.74 0.88\n",
" crayfish 50 0.56 0.86\n",
" hermit crab 50 0.78 0.96\n",
" isopod 50 0.66 0.78\n",
" white stork 50 0.88 0.96\n",
" black stork 50 0.84 0.98\n",
" spoonbill 50 0.96 1\n",
" flamingo 50 0.94 1\n",
" little blue heron 50 0.92 0.98\n",
" great egret 50 0.9 0.96\n",
" bittern 50 0.86 0.94\n",
" crane (bird) 50 0.62 0.9\n",
" limpkin 50 0.98 1\n",
" common gallinule 50 0.92 0.96\n",
" American coot 50 0.9 0.98\n",
" bustard 50 0.92 0.96\n",
" ruddy turnstone 50 0.94 1\n",
" dunlin 50 0.86 0.94\n",
" common redshank 50 0.9 0.96\n",
" dowitcher 50 0.84 0.96\n",
" oystercatcher 50 0.86 0.94\n",
" pelican 50 0.92 0.96\n",
" king penguin 50 0.88 0.96\n",
" albatross 50 0.9 1\n",
" grey whale 50 0.84 0.92\n",
" killer whale 50 0.92 1\n",
" dugong 50 0.84 0.96\n",
" sea lion 50 0.82 0.92\n",
" Chihuahua 50 0.66 0.84\n",
" Japanese Chin 50 0.72 0.98\n",
" Maltese 50 0.76 0.94\n",
" Pekingese 50 0.84 0.94\n",
" Shih Tzu 50 0.74 0.96\n",
" King Charles Spaniel 50 0.88 0.98\n",
" Papillon 50 0.86 0.94\n",
" toy terrier 50 0.48 0.94\n",
" Rhodesian Ridgeback 50 0.76 0.98\n",
" Afghan Hound 50 0.84 1\n",
" Basset Hound 50 0.8 0.92\n",
" Beagle 50 0.82 0.96\n",
" Bloodhound 50 0.48 0.72\n",
" Bluetick Coonhound 50 0.86 0.94\n",
" Black and Tan Coonhound 50 0.54 0.8\n",
"Treeing Walker Coonhound 50 0.66 0.98\n",
" English foxhound 50 0.32 0.84\n",
" Redbone Coonhound 50 0.62 0.94\n",
" borzoi 50 0.92 1\n",
" Irish Wolfhound 50 0.48 0.88\n",
" Italian Greyhound 50 0.76 0.98\n",
" Whippet 50 0.74 0.92\n",
" Ibizan Hound 50 0.6 0.86\n",
" Norwegian Elkhound 50 0.88 0.98\n",
" Otterhound 50 0.62 0.9\n",
" Saluki 50 0.72 0.92\n",
" Scottish Deerhound 50 0.86 0.98\n",
" Weimaraner 50 0.88 0.94\n",
"Staffordshire Bull Terrier 50 0.66 0.98\n",
"American Staffordshire Terrier 50 0.64 0.92\n",
" Bedlington Terrier 50 0.9 0.92\n",
" Border Terrier 50 0.86 0.92\n",
" Kerry Blue Terrier 50 0.78 0.98\n",
" Irish Terrier 50 0.7 0.96\n",
" Norfolk Terrier 50 0.68 0.9\n",
" Norwich Terrier 50 0.72 1\n",
" Yorkshire Terrier 50 0.66 0.9\n",
" Wire Fox Terrier 50 0.64 0.98\n",
" Lakeland Terrier 50 0.74 0.92\n",
" Sealyham Terrier 50 0.76 0.9\n",
" Airedale Terrier 50 0.82 0.92\n",
" Cairn Terrier 50 0.76 0.9\n",
" Australian Terrier 50 0.48 0.84\n",
" Dandie Dinmont Terrier 50 0.82 0.92\n",
" Boston Terrier 50 0.92 1\n",
" Miniature Schnauzer 50 0.68 0.9\n",
" Giant Schnauzer 50 0.72 0.98\n",
" Standard Schnauzer 50 0.74 1\n",
" Scottish Terrier 50 0.76 0.96\n",
" Tibetan Terrier 50 0.48 1\n",
"Australian Silky Terrier 50 0.66 0.96\n",
"Soft-coated Wheaten Terrier 50 0.74 0.96\n",
"West Highland White Terrier 50 0.88 0.96\n",
" Lhasa Apso 50 0.68 0.96\n",
" Flat-Coated Retriever 50 0.72 0.94\n",
" Curly-coated Retriever 50 0.82 0.94\n",
" Golden Retriever 50 0.86 0.94\n",
" Labrador Retriever 50 0.82 0.94\n",
"Chesapeake Bay Retriever 50 0.76 0.96\n",
"German Shorthaired Pointer 50 0.8 0.96\n",
" Vizsla 50 0.68 0.96\n",
" English Setter 50 0.7 1\n",
" Irish Setter 50 0.8 0.9\n",
" Gordon Setter 50 0.84 0.92\n",
" Brittany 50 0.84 0.96\n",
" Clumber Spaniel 50 0.92 0.96\n",
"English Springer Spaniel 50 0.88 1\n",
" Welsh Springer Spaniel 50 0.92 1\n",
" Cocker Spaniels 50 0.7 0.94\n",
" Sussex Spaniel 50 0.72 0.92\n",
" Irish Water Spaniel 50 0.88 0.98\n",
" Kuvasz 50 0.66 0.9\n",
" Schipperke 50 0.9 0.98\n",
" Groenendael 50 0.8 0.94\n",
" Malinois 50 0.86 0.98\n",
" Briard 50 0.52 0.8\n",
" Australian Kelpie 50 0.6 0.88\n",
" Komondor 50 0.88 0.94\n",
" Old English Sheepdog 50 0.94 0.98\n",
" Shetland Sheepdog 50 0.74 0.9\n",
" collie 50 0.6 0.96\n",
" Border Collie 50 0.74 0.96\n",
" Bouvier des Flandres 50 0.78 0.94\n",
" Rottweiler 50 0.88 0.96\n",
" German Shepherd Dog 50 0.8 0.98\n",
" Dobermann 50 0.68 0.96\n",
" Miniature Pinscher 50 0.76 0.88\n",
"Greater Swiss Mountain Dog 50 0.68 0.94\n",
" Bernese Mountain Dog 50 0.96 1\n",
" Appenzeller Sennenhund 50 0.22 1\n",
" Entlebucher Sennenhund 50 0.64 0.98\n",
" Boxer 50 0.7 0.92\n",
" Bullmastiff 50 0.78 0.98\n",
" Tibetan Mastiff 50 0.88 0.96\n",
" French Bulldog 50 0.84 0.94\n",
" Great Dane 50 0.54 0.9\n",
" St. Bernard 50 0.92 1\n",
" husky 50 0.46 0.98\n",
" Alaskan Malamute 50 0.76 0.96\n",
" Siberian Husky 50 0.46 0.98\n",
" Dalmatian 50 0.94 0.98\n",
" Affenpinscher 50 0.78 0.9\n",
" Basenji 50 0.92 0.94\n",
" pug 50 0.94 0.98\n",
" Leonberger 50 1 1\n",
" Newfoundland 50 0.78 0.96\n",
" Pyrenean Mountain Dog 50 0.78 0.96\n",
" Samoyed 50 0.96 1\n",
" Pomeranian 50 0.98 1\n",
" Chow Chow 50 0.9 0.96\n",
" Keeshond 50 0.88 0.94\n",
" Griffon Bruxellois 50 0.84 0.98\n",
" Pembroke Welsh Corgi 50 0.82 0.94\n",
" Cardigan Welsh Corgi 50 0.66 0.98\n",
" Toy Poodle 50 0.52 0.88\n",
" Miniature Poodle 50 0.52 0.92\n",
" Standard Poodle 50 0.8 1\n",
" Mexican hairless dog 50 0.88 0.98\n",
" grey wolf 50 0.82 0.92\n",
" Alaskan tundra wolf 50 0.78 0.98\n",
" red wolf 50 0.48 0.9\n",
" coyote 50 0.64 0.86\n",
" dingo 50 0.76 0.88\n",
" dhole 50 0.9 0.98\n",
" African wild dog 50 0.98 1\n",
" hyena 50 0.88 0.96\n",
" red fox 50 0.54 0.92\n",
" kit fox 50 0.72 0.98\n",
" Arctic fox 50 0.94 1\n",
" grey fox 50 0.7 0.94\n",
" tabby cat 50 0.54 0.92\n",
" tiger cat 50 0.22 0.94\n",
" Persian cat 50 0.9 0.98\n",
" Siamese cat 50 0.96 1\n",
" Egyptian Mau 50 0.54 0.8\n",
" cougar 50 0.9 1\n",
" lynx 50 0.72 0.88\n",
" leopard 50 0.78 0.98\n",
" snow leopard 50 0.9 0.98\n",
" jaguar 50 0.7 0.94\n",
" lion 50 0.9 0.98\n",
" tiger 50 0.92 0.98\n",
" cheetah 50 0.94 0.98\n",
" brown bear 50 0.94 0.98\n",
" American black bear 50 0.8 1\n",
" polar bear 50 0.84 0.96\n",
" sloth bear 50 0.72 0.92\n",
" mongoose 50 0.7 0.92\n",
" meerkat 50 0.82 0.92\n",
" tiger beetle 50 0.92 0.94\n",
" ladybug 50 0.86 0.94\n",
" ground beetle 50 0.64 0.94\n",
" longhorn beetle 50 0.62 0.88\n",
" leaf beetle 50 0.64 0.98\n",
" dung beetle 50 0.86 0.98\n",
" rhinoceros beetle 50 0.86 0.94\n",
" weevil 50 0.9 1\n",
" fly 50 0.78 0.94\n",
" bee 50 0.68 0.94\n",
" ant 50 0.68 0.78\n",
" grasshopper 50 0.5 0.92\n",
" cricket 50 0.64 0.92\n",
" stick insect 50 0.64 0.92\n",
" cockroach 50 0.72 0.8\n",
" mantis 50 0.64 0.86\n",
" cicada 50 0.9 0.96\n",
" leafhopper 50 0.88 0.94\n",
" lacewing 50 0.78 0.92\n",
" dragonfly 50 0.82 0.98\n",
" damselfly 50 0.82 1\n",
" red admiral 50 0.94 0.96\n",
" ringlet 50 0.86 0.98\n",
" monarch butterfly 50 0.9 0.92\n",
" small white 50 0.9 1\n",
" sulphur butterfly 50 0.92 1\n",
"gossamer-winged butterfly 50 0.88 1\n",
" starfish 50 0.88 0.92\n",
" sea urchin 50 0.84 0.94\n",
" sea cucumber 50 0.66 0.84\n",
" cottontail rabbit 50 0.72 0.94\n",
" hare 50 0.84 0.96\n",
" Angora rabbit 50 0.94 0.98\n",
" hamster 50 0.96 1\n",
" porcupine 50 0.88 0.98\n",
" fox squirrel 50 0.76 0.94\n",
" marmot 50 0.92 0.96\n",
" beaver 50 0.78 0.94\n",
" guinea pig 50 0.78 0.94\n",
" common sorrel 50 0.96 0.98\n",
" zebra 50 0.94 0.96\n",
" pig 50 0.5 0.76\n",
" wild boar 50 0.84 0.96\n",
" warthog 50 0.84 0.96\n",
" hippopotamus 50 0.88 0.96\n",
" ox 50 0.48 0.94\n",
" water buffalo 50 0.78 0.94\n",
" bison 50 0.88 0.96\n",
" ram 50 0.58 0.92\n",
" bighorn sheep 50 0.66 1\n",
" Alpine ibex 50 0.92 0.98\n",
" hartebeest 50 0.94 1\n",
" impala 50 0.82 0.96\n",
" gazelle 50 0.7 0.96\n",
" dromedary 50 0.9 1\n",
" llama 50 0.82 0.94\n",
" weasel 50 0.44 0.92\n",
" mink 50 0.78 0.96\n",
" European polecat 50 0.46 0.9\n",
" black-footed ferret 50 0.68 0.96\n",
" otter 50 0.66 0.88\n",
" skunk 50 0.96 0.96\n",
" badger 50 0.86 0.92\n",
" armadillo 50 0.88 0.9\n",
" three-toed sloth 50 0.96 1\n",
" orangutan 50 0.78 0.92\n",
" gorilla 50 0.82 0.94\n",
" chimpanzee 50 0.84 0.94\n",
" gibbon 50 0.76 0.86\n",
" siamang 50 0.68 0.94\n",
" guenon 50 0.8 0.94\n",
" patas monkey 50 0.62 0.82\n",
" baboon 50 0.9 0.98\n",
" macaque 50 0.8 0.86\n",
" langur 50 0.6 0.82\n",
" black-and-white colobus 50 0.86 0.9\n",
" proboscis monkey 50 1 1\n",
" marmoset 50 0.74 0.98\n",
" white-headed capuchin 50 0.72 0.9\n",
" howler monkey 50 0.86 0.94\n",
" titi 50 0.5 0.9\n",
"Geoffroy's spider monkey 50 0.42 0.8\n",
" common squirrel monkey 50 0.76 0.92\n",
" ring-tailed lemur 50 0.72 0.94\n",
" indri 50 0.9 0.96\n",
" Asian elephant 50 0.58 0.92\n",
" African bush elephant 50 0.7 0.98\n",
" red panda 50 0.94 0.94\n",
" giant panda 50 0.94 0.98\n",
" snoek 50 0.74 0.9\n",
" eel 50 0.6 0.84\n",
" coho salmon 50 0.84 0.96\n",
" rock beauty 50 0.88 0.98\n",
" clownfish 50 0.78 0.98\n",
" sturgeon 50 0.68 0.94\n",
" garfish 50 0.62 0.8\n",
" lionfish 50 0.96 0.96\n",
" pufferfish 50 0.88 0.96\n",
" abacus 50 0.74 0.88\n",
" abaya 50 0.84 0.92\n",
" academic gown 50 0.42 0.86\n",
" accordion 50 0.8 0.9\n",
" acoustic guitar 50 0.5 0.76\n",
" aircraft carrier 50 0.8 0.96\n",
" airliner 50 0.92 1\n",
" airship 50 0.76 0.82\n",
" altar 50 0.64 0.98\n",
" ambulance 50 0.88 0.98\n",
" amphibious vehicle 50 0.64 0.94\n",
" analog clock 50 0.52 0.92\n",
" apiary 50 0.82 0.96\n",
" apron 50 0.7 0.84\n",
" waste container 50 0.4 0.8\n",
" assault rifle 50 0.42 0.84\n",
" backpack 50 0.34 0.64\n",
" bakery 50 0.4 0.68\n",
" balance beam 50 0.8 0.98\n",
" balloon 50 0.86 0.96\n",
" ballpoint pen 50 0.52 0.96\n",
" Band-Aid 50 0.7 0.9\n",
" banjo 50 0.84 1\n",
" baluster 50 0.68 0.94\n",
" barbell 50 0.56 0.9\n",
" barber chair 50 0.7 0.92\n",
" barbershop 50 0.54 0.86\n",
" barn 50 0.96 0.96\n",
" barometer 50 0.84 0.98\n",
" barrel 50 0.56 0.88\n",
" wheelbarrow 50 0.66 0.88\n",
" baseball 50 0.74 0.98\n",
" basketball 50 0.88 0.98\n",
" bassinet 50 0.66 0.92\n",
" bassoon 50 0.74 0.98\n",
" swimming cap 50 0.62 0.88\n",
" bath towel 50 0.54 0.78\n",
" bathtub 50 0.4 0.88\n",
" station wagon 50 0.66 0.84\n",
" lighthouse 50 0.78 0.94\n",
" beaker 50 0.52 0.68\n",
" military cap 50 0.84 0.96\n",
" beer bottle 50 0.66 0.88\n",
" beer glass 50 0.6 0.84\n",
" bell-cot 50 0.56 0.96\n",
" bib 50 0.58 0.82\n",
" tandem bicycle 50 0.86 0.96\n",
" bikini 50 0.56 0.88\n",
" ring binder 50 0.64 0.84\n",
" binoculars 50 0.54 0.78\n",
" birdhouse 50 0.86 0.94\n",
" boathouse 50 0.74 0.92\n",
" bobsleigh 50 0.92 0.96\n",
" bolo tie 50 0.8 0.94\n",
" poke bonnet 50 0.64 0.86\n",
" bookcase 50 0.66 0.92\n",
" bookstore 50 0.62 0.88\n",
" bottle cap 50 0.58 0.7\n",
" bow 50 0.72 0.86\n",
" bow tie 50 0.7 0.9\n",
" brass 50 0.92 0.96\n",
" bra 50 0.5 0.7\n",
" breakwater 50 0.62 0.86\n",
" breastplate 50 0.4 0.9\n",
" broom 50 0.6 0.86\n",
" bucket 50 0.66 0.8\n",
" buckle 50 0.5 0.68\n",
" bulletproof vest 50 0.5 0.78\n",
" high-speed train 50 0.94 0.96\n",
" butcher shop 50 0.74 0.94\n",
" taxicab 50 0.64 0.86\n",
" cauldron 50 0.44 0.66\n",
" candle 50 0.48 0.74\n",
" cannon 50 0.88 0.94\n",
" canoe 50 0.94 1\n",
" can opener 50 0.66 0.86\n",
" cardigan 50 0.68 0.8\n",
" car mirror 50 0.94 0.96\n",
" carousel 50 0.94 0.98\n",
" tool kit 50 0.56 0.78\n",
" carton 50 0.42 0.7\n",
" car wheel 50 0.38 0.74\n",
"automated teller machine 50 0.76 0.94\n",
" cassette 50 0.52 0.8\n",
" cassette player 50 0.28 0.9\n",
" castle 50 0.78 0.88\n",
" catamaran 50 0.78 1\n",
" CD player 50 0.52 0.82\n",
" cello 50 0.82 1\n",
" mobile phone 50 0.68 0.86\n",
" chain 50 0.38 0.66\n",
" chain-link fence 50 0.7 0.84\n",
" chain mail 50 0.64 0.9\n",
" chainsaw 50 0.84 0.92\n",
" chest 50 0.68 0.92\n",
" chiffonier 50 0.26 0.64\n",
" chime 50 0.62 0.84\n",
" china cabinet 50 0.82 0.96\n",
" Christmas stocking 50 0.92 0.94\n",
" church 50 0.62 0.9\n",
" movie theater 50 0.58 0.88\n",
" cleaver 50 0.32 0.62\n",
" cliff dwelling 50 0.88 1\n",
" cloak 50 0.32 0.64\n",
" clogs 50 0.58 0.88\n",
" cocktail shaker 50 0.62 0.7\n",
" coffee mug 50 0.44 0.72\n",
" coffeemaker 50 0.64 0.92\n",
" coil 50 0.66 0.84\n",
" combination lock 50 0.64 0.84\n",
" computer keyboard 50 0.7 0.82\n",
" confectionery store 50 0.54 0.86\n",
" container ship 50 0.82 0.98\n",
" convertible 50 0.78 0.98\n",
" corkscrew 50 0.82 0.92\n",
" cornet 50 0.46 0.88\n",
" cowboy boot 50 0.64 0.8\n",
" cowboy hat 50 0.64 0.82\n",
" cradle 50 0.38 0.8\n",
" crane (machine) 50 0.78 0.94\n",
" crash helmet 50 0.92 0.96\n",
" crate 50 0.52 0.82\n",
" infant bed 50 0.74 1\n",
" Crock Pot 50 0.78 0.9\n",
" croquet ball 50 0.9 0.96\n",
" crutch 50 0.46 0.7\n",
" cuirass 50 0.54 0.86\n",
" dam 50 0.74 0.92\n",
" desk 50 0.6 0.86\n",
" desktop computer 50 0.54 0.94\n",
" rotary dial telephone 50 0.88 0.94\n",
" diaper 50 0.68 0.84\n",
" digital clock 50 0.54 0.76\n",
" digital watch 50 0.58 0.86\n",
" dining table 50 0.76 0.9\n",
" dishcloth 50 0.94 1\n",
" dishwasher 50 0.44 0.78\n",
" disc brake 50 0.98 1\n",
" dock 50 0.54 0.94\n",
" dog sled 50 0.84 1\n",
" dome 50 0.72 0.92\n",
" doormat 50 0.56 0.82\n",
" drilling rig 50 0.84 0.96\n",
" drum 50 0.38 0.68\n",
" drumstick 50 0.56 0.72\n",
" dumbbell 50 0.62 0.9\n",
" Dutch oven 50 0.7 0.84\n",
" electric fan 50 0.82 0.86\n",
" electric guitar 50 0.62 0.84\n",
" electric locomotive 50 0.92 0.98\n",
" entertainment center 50 0.9 0.98\n",
" envelope 50 0.44 0.86\n",
" espresso machine 50 0.72 0.94\n",
" face powder 50 0.7 0.92\n",
" feather boa 50 0.7 0.84\n",
" filing cabinet 50 0.88 0.98\n",
" fireboat 50 0.94 0.98\n",
" fire engine 50 0.84 0.9\n",
" fire screen sheet 50 0.62 0.76\n",
" flagpole 50 0.74 0.88\n",
" flute 50 0.36 0.72\n",
" folding chair 50 0.62 0.84\n",
" football helmet 50 0.86 0.94\n",
" forklift 50 0.8 0.92\n",
" fountain 50 0.84 0.94\n",
" fountain pen 50 0.76 0.92\n",
" four-poster bed 50 0.78 0.94\n",
" freight car 50 0.96 1\n",
" French horn 50 0.76 0.92\n",
" frying pan 50 0.36 0.78\n",
" fur coat 50 0.84 0.96\n",
" garbage truck 50 0.9 0.98\n",
" gas mask 50 0.84 0.92\n",
" gas pump 50 0.9 0.98\n",
" goblet 50 0.68 0.82\n",
" go-kart 50 0.9 1\n",
" golf ball 50 0.84 0.9\n",
" golf cart 50 0.78 0.86\n",
" gondola 50 0.98 0.98\n",
" gong 50 0.74 0.92\n",
" gown 50 0.62 0.96\n",
" grand piano 50 0.7 0.96\n",
" greenhouse 50 0.8 0.98\n",
" grille 50 0.72 0.9\n",
" grocery store 50 0.66 0.94\n",
" guillotine 50 0.86 0.92\n",
" barrette 50 0.52 0.66\n",
" hair spray 50 0.5 0.74\n",
" half-track 50 0.78 0.9\n",
" hammer 50 0.56 0.76\n",
" hamper 50 0.64 0.84\n",
" hair dryer 50 0.56 0.74\n",
" hand-held computer 50 0.42 0.86\n",
" handkerchief 50 0.78 0.94\n",
" hard disk drive 50 0.76 0.84\n",
" harmonica 50 0.7 0.88\n",
" harp 50 0.88 0.96\n",
" harvester 50 0.78 1\n",
" hatchet 50 0.54 0.74\n",
" holster 50 0.66 0.84\n",
" home theater 50 0.64 0.94\n",
" honeycomb 50 0.56 0.88\n",
" hook 50 0.3 0.6\n",
" hoop skirt 50 0.64 0.86\n",
" horizontal bar 50 0.68 0.98\n",
" horse-drawn vehicle 50 0.88 0.94\n",
" hourglass 50 0.88 0.96\n",
" iPod 50 0.76 0.94\n",
" clothes iron 50 0.82 0.88\n",
" jack-o'-lantern 50 0.98 0.98\n",
" jeans 50 0.68 0.84\n",
" jeep 50 0.72 0.9\n",
" T-shirt 50 0.72 0.96\n",
" jigsaw puzzle 50 0.84 0.94\n",
" pulled rickshaw 50 0.86 0.94\n",
" joystick 50 0.8 0.9\n",
" kimono 50 0.84 0.96\n",
" knee pad 50 0.62 0.88\n",
" knot 50 0.66 0.8\n",
" lab coat 50 0.8 0.96\n",
" ladle 50 0.36 0.64\n",
" lampshade 50 0.48 0.84\n",
" laptop computer 50 0.26 0.88\n",
" lawn mower 50 0.78 0.96\n",
" lens cap 50 0.46 0.72\n",
" paper knife 50 0.26 0.5\n",
" library 50 0.54 0.9\n",
" lifeboat 50 0.92 0.98\n",
" lighter 50 0.56 0.78\n",
" limousine 50 0.76 0.92\n",
" ocean liner 50 0.88 0.94\n",
" lipstick 50 0.74 0.9\n",
" slip-on shoe 50 0.74 0.92\n",
" lotion 50 0.5 0.86\n",
" speaker 50 0.52 0.68\n",
" loupe 50 0.32 0.52\n",
" sawmill 50 0.72 0.9\n",
" magnetic compass 50 0.52 0.82\n",
" mail bag 50 0.68 0.92\n",
" mailbox 50 0.82 0.92\n",
" tights 50 0.22 0.94\n",
" tank suit 50 0.24 0.9\n",
" manhole cover 50 0.96 0.98\n",
" maraca 50 0.74 0.9\n",
" marimba 50 0.84 0.94\n",
" mask 50 0.44 0.82\n",
" match 50 0.66 0.9\n",
" maypole 50 0.96 1\n",
" maze 50 0.8 0.96\n",
" measuring cup 50 0.54 0.76\n",
" medicine chest 50 0.6 0.84\n",
" megalith 50 0.8 0.92\n",
" microphone 50 0.52 0.7\n",
" microwave oven 50 0.48 0.72\n",
" military uniform 50 0.62 0.84\n",
" milk can 50 0.68 0.82\n",
" minibus 50 0.7 1\n",
" miniskirt 50 0.46 0.76\n",
" minivan 50 0.38 0.8\n",
" missile 50 0.4 0.84\n",
" mitten 50 0.76 0.88\n",
" mixing bowl 50 0.8 0.92\n",
" mobile home 50 0.54 0.78\n",
" Model T 50 0.92 0.96\n",
" modem 50 0.58 0.86\n",
" monastery 50 0.44 0.9\n",
" monitor 50 0.4 0.86\n",
" moped 50 0.56 0.94\n",
" mortar 50 0.68 0.94\n",
" square academic cap 50 0.5 0.84\n",
" mosque 50 0.9 1\n",
" mosquito net 50 0.9 0.98\n",
" scooter 50 0.9 0.98\n",
" mountain bike 50 0.78 0.96\n",
" tent 50 0.88 0.96\n",
" computer mouse 50 0.42 0.82\n",
" mousetrap 50 0.76 0.88\n",
" moving van 50 0.4 0.72\n",
" muzzle 50 0.5 0.72\n",
" nail 50 0.68 0.74\n",
" neck brace 50 0.56 0.68\n",
" necklace 50 0.86 1\n",
" nipple 50 0.7 0.88\n",
" notebook computer 50 0.34 0.84\n",
" obelisk 50 0.8 0.92\n",
" oboe 50 0.6 0.84\n",
" ocarina 50 0.8 0.86\n",
" odometer 50 0.96 1\n",
" oil filter 50 0.58 0.82\n",
" organ 50 0.82 0.9\n",
" oscilloscope 50 0.9 0.96\n",
" overskirt 50 0.2 0.7\n",
" bullock cart 50 0.7 0.94\n",
" oxygen mask 50 0.46 0.84\n",
" packet 50 0.5 0.78\n",
" paddle 50 0.56 0.94\n",
" paddle wheel 50 0.86 0.96\n",
" padlock 50 0.74 0.78\n",
" paintbrush 50 0.62 0.8\n",
" pajamas 50 0.56 0.92\n",
" palace 50 0.64 0.96\n",
" pan flute 50 0.84 0.86\n",
" paper towel 50 0.66 0.84\n",
" parachute 50 0.92 0.94\n",
" parallel bars 50 0.62 0.96\n",
" park bench 50 0.74 0.9\n",
" parking meter 50 0.84 0.92\n",
" passenger car 50 0.5 0.82\n",
" patio 50 0.58 0.84\n",
" payphone 50 0.74 0.92\n",
" pedestal 50 0.52 0.9\n",
" pencil case 50 0.64 0.92\n",
" pencil sharpener 50 0.52 0.78\n",
" perfume 50 0.7 0.9\n",
" Petri dish 50 0.6 0.8\n",
" photocopier 50 0.88 0.98\n",
" plectrum 50 0.7 0.84\n",
" Pickelhaube 50 0.72 0.86\n",
" picket fence 50 0.84 0.94\n",
" pickup truck 50 0.64 0.92\n",
" pier 50 0.52 0.82\n",
" piggy bank 50 0.82 0.94\n",
" pill bottle 50 0.76 0.86\n",
" pillow 50 0.76 0.9\n",
" ping-pong ball 50 0.84 0.88\n",
" pinwheel 50 0.76 0.88\n",
" pirate ship 50 0.76 0.94\n",
" pitcher 50 0.46 0.84\n",
" hand plane 50 0.84 0.94\n",
" planetarium 50 0.88 0.98\n",
" plastic bag 50 0.36 0.62\n",
" plate rack 50 0.52 0.78\n",
" plow 50 0.78 0.88\n",
" plunger 50 0.42 0.7\n",
" Polaroid camera 50 0.84 0.92\n",
" pole 50 0.38 0.74\n",
" police van 50 0.76 0.94\n",
" poncho 50 0.58 0.86\n",
" billiard table 50 0.8 0.88\n",
" soda bottle 50 0.56 0.94\n",
" pot 50 0.78 0.92\n",
" potter's wheel 50 0.9 0.94\n",
" power drill 50 0.42 0.72\n",
" prayer rug 50 0.7 0.86\n",
" printer 50 0.54 0.86\n",
" prison 50 0.7 0.9\n",
" projectile 50 0.28 0.9\n",
" projector 50 0.62 0.84\n",
" hockey puck 50 0.92 0.96\n",
" punching bag 50 0.6 0.68\n",
" purse 50 0.42 0.78\n",
" quill 50 0.68 0.84\n",
" quilt 50 0.64 0.9\n",
" race car 50 0.72 0.92\n",
" racket 50 0.72 0.9\n",
" radiator 50 0.66 0.76\n",
" radio 50 0.64 0.92\n",
" radio telescope 50 0.9 0.96\n",
" rain barrel 50 0.8 0.98\n",
" recreational vehicle 50 0.84 0.94\n",
" reel 50 0.72 0.82\n",
" reflex camera 50 0.72 0.92\n",
" refrigerator 50 0.7 0.9\n",
" remote control 50 0.7 0.88\n",
" restaurant 50 0.5 0.66\n",
" revolver 50 0.82 1\n",
" rifle 50 0.38 0.7\n",
" rocking chair 50 0.62 0.84\n",
" rotisserie 50 0.88 0.92\n",
" eraser 50 0.54 0.76\n",
" rugby ball 50 0.86 0.94\n",
" ruler 50 0.68 0.86\n",
" running shoe 50 0.78 0.94\n",
" safe 50 0.82 0.92\n",
" safety pin 50 0.4 0.62\n",
" salt shaker 50 0.66 0.9\n",
" sandal 50 0.66 0.86\n",
" sarong 50 0.64 0.86\n",
" saxophone 50 0.66 0.88\n",
" scabbard 50 0.76 0.92\n",
" weighing scale 50 0.58 0.78\n",
" school bus 50 0.92 1\n",
" schooner 50 0.84 1\n",
" scoreboard 50 0.9 0.96\n",
" CRT screen 50 0.14 0.7\n",
" screw 50 0.9 0.98\n",
" screwdriver 50 0.3 0.58\n",
" seat belt 50 0.88 0.94\n",
" sewing machine 50 0.76 0.9\n",
" shield 50 0.56 0.82\n",
" shoe store 50 0.78 0.96\n",
" shoji 50 0.8 0.92\n",
" shopping basket 50 0.52 0.88\n",
" shopping cart 50 0.76 0.92\n",
" shovel 50 0.62 0.84\n",
" shower cap 50 0.7 0.84\n",
" shower curtain 50 0.64 0.82\n",
" ski 50 0.74 0.92\n",
" ski mask 50 0.72 0.88\n",
" sleeping bag 50 0.68 0.8\n",
" slide rule 50 0.72 0.88\n",
" sliding door 50 0.44 0.78\n",
" slot machine 50 0.94 0.98\n",
" snorkel 50 0.86 0.98\n",
" snowmobile 50 0.88 1\n",
" snowplow 50 0.84 0.98\n",
" soap dispenser 50 0.56 0.86\n",
" soccer ball 50 0.86 0.96\n",
" sock 50 0.62 0.76\n",
" solar thermal collector 50 0.72 0.96\n",
" sombrero 50 0.6 0.84\n",
" soup bowl 50 0.56 0.94\n",
" space bar 50 0.34 0.88\n",
" space heater 50 0.52 0.74\n",
" space shuttle 50 0.82 0.96\n",
" spatula 50 0.3 0.6\n",
" motorboat 50 0.86 1\n",
" spider web 50 0.7 0.9\n",
" spindle 50 0.86 0.98\n",
" sports car 50 0.6 0.94\n",
" spotlight 50 0.26 0.6\n",
" stage 50 0.68 0.86\n",
" steam locomotive 50 0.94 1\n",
" through arch bridge 50 0.84 0.96\n",
" steel drum 50 0.82 0.9\n",
" stethoscope 50 0.6 0.82\n",
" scarf 50 0.5 0.92\n",
" stone wall 50 0.76 0.9\n",
" stopwatch 50 0.58 0.9\n",
" stove 50 0.46 0.74\n",
" strainer 50 0.64 0.84\n",
" tram 50 0.88 0.96\n",
" stretcher 50 0.6 0.8\n",
" couch 50 0.8 0.96\n",
" stupa 50 0.88 0.88\n",
" submarine 50 0.72 0.92\n",
" suit 50 0.4 0.78\n",
" sundial 50 0.58 0.74\n",
" sunglass 50 0.14 0.58\n",
" sunglasses 50 0.28 0.58\n",
" sunscreen 50 0.32 0.7\n",
" suspension bridge 50 0.6 0.94\n",
" mop 50 0.74 0.92\n",
" sweatshirt 50 0.28 0.66\n",
" swimsuit 50 0.52 0.82\n",
" swing 50 0.76 0.84\n",
" switch 50 0.56 0.76\n",
" syringe 50 0.62 0.82\n",
" table lamp 50 0.6 0.88\n",
" tank 50 0.8 0.96\n",
" tape player 50 0.46 0.76\n",
" teapot 50 0.84 1\n",
" teddy bear 50 0.82 0.94\n",
" television 50 0.6 0.9\n",
" tennis ball 50 0.7 0.94\n",
" thatched roof 50 0.88 0.9\n",
" front curtain 50 0.8 0.92\n",
" thimble 50 0.6 0.8\n",
" threshing machine 50 0.56 0.88\n",
" throne 50 0.72 0.82\n",
" tile roof 50 0.72 0.94\n",
" toaster 50 0.66 0.84\n",
" tobacco shop 50 0.42 0.7\n",
" toilet seat 50 0.62 0.88\n",
" torch 50 0.64 0.84\n",
" totem pole 50 0.92 0.98\n",
" tow truck 50 0.62 0.88\n",
" toy store 50 0.6 0.94\n",
" tractor 50 0.76 0.98\n",
" semi-trailer truck 50 0.78 0.92\n",
" tray 50 0.46 0.64\n",
" trench coat 50 0.54 0.72\n",
" tricycle 50 0.72 0.94\n",
" trimaran 50 0.7 0.98\n",
" tripod 50 0.58 0.86\n",
" triumphal arch 50 0.92 0.98\n",
" trolleybus 50 0.9 1\n",
" trombone 50 0.54 0.88\n",
" tub 50 0.24 0.82\n",
" turnstile 50 0.84 0.94\n",
" typewriter keyboard 50 0.68 0.98\n",
" umbrella 50 0.52 0.7\n",
" unicycle 50 0.74 0.96\n",
" upright piano 50 0.76 0.9\n",
" vacuum cleaner 50 0.62 0.9\n",
" vase 50 0.5 0.78\n",
" vault 50 0.76 0.92\n",
" velvet 50 0.2 0.42\n",
" vending machine 50 0.9 1\n",
" vestment 50 0.54 0.82\n",
" viaduct 50 0.78 0.86\n",
" violin 50 0.68 0.78\n",
" volleyball 50 0.86 1\n",
" waffle iron 50 0.72 0.88\n",
" wall clock 50 0.54 0.88\n",
" wallet 50 0.52 0.9\n",
" wardrobe 50 0.68 0.88\n",
" military aircraft 50 0.9 0.98\n",
" sink 50 0.72 0.96\n",
" washing machine 50 0.78 0.94\n",
" water bottle 50 0.54 0.74\n",
" water jug 50 0.22 0.74\n",
" water tower 50 0.9 0.96\n",
" whiskey jug 50 0.64 0.74\n",
" whistle 50 0.72 0.84\n",
" wig 50 0.84 0.9\n",
" window screen 50 0.68 0.8\n",
" window shade 50 0.52 0.76\n",
" Windsor tie 50 0.22 0.66\n",
" wine bottle 50 0.42 0.82\n",
" wing 50 0.54 0.96\n",
" wok 50 0.46 0.82\n",
" wooden spoon 50 0.58 0.8\n",
" wool 50 0.32 0.82\n",
" split-rail fence 50 0.74 0.9\n",
" shipwreck 50 0.84 0.96\n",
" yawl 50 0.78 0.96\n",
" yurt 50 0.84 1\n",
" website 50 0.98 1\n",
" comic book 50 0.62 0.9\n",
" crossword 50 0.84 0.88\n",
" traffic sign 50 0.78 0.9\n",
" traffic light 50 0.8 0.94\n",
" dust jacket 50 0.72 0.94\n",
" menu 50 0.82 0.96\n",
" plate 50 0.44 0.88\n",
" guacamole 50 0.8 0.92\n",
" consomme 50 0.54 0.88\n",
" hot pot 50 0.86 0.98\n",
" trifle 50 0.92 0.98\n",
" ice cream 50 0.68 0.94\n",
" ice pop 50 0.62 0.84\n",
" baguette 50 0.62 0.88\n",
" bagel 50 0.64 0.92\n",
" pretzel 50 0.72 0.88\n",
" cheeseburger 50 0.9 1\n",
" hot dog 50 0.74 0.94\n",
" mashed potato 50 0.74 0.9\n",
" cabbage 50 0.84 0.96\n",
" broccoli 50 0.9 0.96\n",
" cauliflower 50 0.82 1\n",
" zucchini 50 0.74 0.9\n",
" spaghetti squash 50 0.8 0.96\n",
" acorn squash 50 0.82 0.96\n",
" butternut squash 50 0.7 0.94\n",
" cucumber 50 0.6 0.96\n",
" artichoke 50 0.84 0.94\n",
" bell pepper 50 0.84 0.98\n",
" cardoon 50 0.88 0.94\n",
" mushroom 50 0.38 0.92\n",
" Granny Smith 50 0.9 0.96\n",
" strawberry 50 0.6 0.88\n",
" orange 50 0.7 0.92\n",
" lemon 50 0.78 0.98\n",
" fig 50 0.82 0.96\n",
" pineapple 50 0.86 0.96\n",
" banana 50 0.84 0.96\n",
" jackfruit 50 0.9 0.98\n",
" custard apple 50 0.86 0.96\n",
" pomegranate 50 0.82 0.98\n",
" hay 50 0.8 0.92\n",
" carbonara 50 0.88 0.94\n",
" chocolate syrup 50 0.46 0.84\n",
" dough 50 0.4 0.6\n",
" meatloaf 50 0.58 0.84\n",
" pizza 50 0.84 0.96\n",
" pot pie 50 0.68 0.9\n",
" burrito 50 0.8 0.98\n",
" red wine 50 0.54 0.82\n",
" espresso 50 0.64 0.88\n",
" cup 50 0.38 0.7\n",
" eggnog 50 0.38 0.7\n",
" alp 50 0.54 0.88\n",
" bubble 50 0.8 0.96\n",
" cliff 50 0.64 1\n",
" coral reef 50 0.72 0.96\n",
" geyser 50 0.94 1\n",
" lakeshore 50 0.54 0.88\n",
" promontory 50 0.58 0.94\n",
" shoal 50 0.6 0.96\n",
" seashore 50 0.44 0.78\n",
" valley 50 0.72 0.94\n",
" volcano 50 0.78 0.96\n",
" baseball player 50 0.72 0.94\n",
" bridegroom 50 0.72 0.88\n",
" scuba diver 50 0.8 1\n",
" rapeseed 50 0.94 0.98\n",
" daisy 50 0.96 0.98\n",
" yellow lady's slipper 50 1 1\n",
" corn 50 0.4 0.88\n",
" acorn 50 0.92 0.98\n",
" rose hip 50 0.92 0.98\n",
" horse chestnut seed 50 0.94 0.98\n",
" coral fungus 50 0.96 0.96\n",
" agaric 50 0.82 0.94\n",
" gyromitra 50 0.98 1\n",
" stinkhorn mushroom 50 0.8 0.94\n",
" earth star 50 0.98 1\n",
" hen-of-the-woods 50 0.8 0.96\n",
" bolete 50 0.74 0.94\n",
" ear 50 0.48 0.94\n",
" toilet paper 50 0.36 0.68\n",
"Speed: 0.1ms pre-process, 0.3ms inference, 0.0ms post-process per image at shape (1, 3, 224, 224)\n",
"Results saved to \u001b[1mruns/val-cls/exp\u001b[0m\n"
]
}
],
"source": [
"# Validate YOLOv5s on Imagenet val\n",
"!python classify/val.py --weights yolov5s-cls.pt --data ../datasets/imagenet --img 224 --half"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ZY2VXXXu74w5"
},
"source": [
"# 3. Train\n",
"\n",
"<p align=\"\"><a href=\"https://roboflow.com/?ref=ultralytics\"><img width=\"1000\" src=\"https://github.com/ultralytics/assets/raw/master/im/integrations-loop.png\"/></a></p>\n",
"Close the active learning loop by sampling images from your inference conditions with the `roboflow` pip package\n",
"<br><br>\n",
"\n",
"Train a YOLOv5s Classification model on the [Imagenette](https://image-net.org/) dataset with `--data imagenet`, starting from pretrained `--pretrained yolov5s-cls.pt`.\n",
"\n",
"- **Pretrained [Models](https://github.com/ultralytics/yolov5/tree/master/models)** are downloaded\n",
"automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases)\n",
"- **Training Results** are saved to `runs/train-cls/` with incrementing run directories, i.e. `runs/train-cls/exp2`, `runs/train-cls/exp3` etc.\n",
"<br><br>\n",
"\n",
"A **Mosaic Dataloader** is used for training which combines 4 images into 1 mosaic.\n",
"\n",
"## Train on Custom Data with Roboflow 🌟 NEW\n",
"\n",
"[Roboflow](https://roboflow.com/?ref=ultralytics) enables you to easily **organize, label, and prepare** a high quality dataset with your own custom data. Roboflow also makes it easy to establish an active learning pipeline, collaborate with your team on dataset improvement, and integrate directly into your model building workflow with the `roboflow` pip package.\n",
"\n",
"- Custom Training Example: [https://blog.roboflow.com/train-yolov5-classification-custom-data/](https://blog.roboflow.com/train-yolov5-classification-custom-data/?ref=ultralytics)\n",
"- Custom Training Notebook: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1KZiKUAjtARHAfZCXbJRv14-pOnIsBLPV?usp=sharing)\n",
"<br>\n",
"\n",
"<p align=\"\"><a href=\"https://roboflow.com/?ref=ultralytics\"><img width=\"480\" src=\"https://user-images.githubusercontent.com/26833433/202802162-92e60571-ab58-4409-948d-b31fddcd3c6f.png\"/></a></p>Label images lightning fast (including with model-assisted labeling)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "i3oKtE4g-aNn"
},
"outputs": [],
"source": [
"#@title Select YOLOv5 🚀 logger {run: 'auto'}\n",
"logger = 'TensorBoard' #@param ['TensorBoard', 'Comet', 'ClearML']\n",
"\n",
"if logger == 'TensorBoard':\n",
" %load_ext tensorboard\n",
" %tensorboard --logdir runs/train\n",
"elif logger == 'Comet':\n",
" %pip install -q comet_ml\n",
" import comet_ml; comet_ml.init()\n",
"elif logger == 'ClearML':\n",
" import clearml; clearml.browser_login()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "1NcFxRcFdJ_O",
"outputId": "638c55b1-dc45-4eee-cabc-4921dc61faf5"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\u001b[34m\u001b[1mclassify/train: \u001b[0mmodel=yolov5s-cls.pt, data=imagenette160, epochs=3, batch_size=16, imgsz=224, nosave=False, cache=ram, device=, workers=8, project=runs/train-cls, name=exp, exist_ok=False, pretrained=True, optimizer=Adam, lr0=0.001, decay=5e-05, label_smoothing=0.1, cutoff=None, dropout=None, verbose=False, seed=0, local_rank=-1\n",
"\u001b[34m\u001b[1mgithub: \u001b[0mup to date with https://github.com/ultralytics/yolov5 ✅\n",
"YOLOv5 🚀 v6.2-258-g7fc7ed7 Python-3.7.15 torch-1.12.1+cu113 CUDA:0 (Tesla T4, 15110MiB)\n",
"\n",
"\u001b[34m\u001b[1mTensorBoard: \u001b[0mStart with 'tensorboard --logdir runs/train-cls', view at http://localhost:6006/\n",
"\n",
"Dataset not found ⚠️, missing path /content/datasets/imagenette160, attempting download...\n",
"Downloading https://github.com/ultralytics/yolov5/releases/download/v1.0/imagenette160.zip to /content/datasets/imagenette160.zip...\n",
"100% 103M/103M [00:09<00:00, 11.1MB/s]\n",
"Unzipping /content/datasets/imagenette160.zip...\n",
"Dataset download success ✅ (13.2s), saved to \u001b[1m/content/datasets/imagenette160\u001b[0m\n",
"\n",
"\u001b[34m\u001b[1malbumentations: \u001b[0mRandomResizedCrop(p=1.0, height=224, width=224, scale=(0.08, 1.0), ratio=(0.75, 1.3333333333333333), interpolation=1), HorizontalFlip(p=0.5), ColorJitter(p=0.5, brightness=[0.6, 1.4], contrast=[0.6, 1.4], saturation=[0.6, 1.4], hue=[0, 0]), Normalize(p=1.0, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0), ToTensorV2(always_apply=True, p=1.0, transpose_mask=False)\n",
"Model summary: 149 layers, 4185290 parameters, 4185290 gradients, 10.5 GFLOPs\n",
"\u001b[34m\u001b[1moptimizer:\u001b[0m Adam(lr=0.001) with parameter groups 32 weight(decay=0.0), 33 weight(decay=5e-05), 33 bias\n",
"Image sizes 224 train, 224 test\n",
"Using 1 dataloader workers\n",
"Logging results to \u001b[1mruns/train-cls/exp\u001b[0m\n",
"Starting yolov5s-cls.pt training on imagenette160 dataset with 10 classes for 3 epochs...\n",
"\n",
" Epoch GPU_mem train_loss val_loss top1_acc top5_acc\n",
" 1/3 0.348G 1.31 1.09 0.794 0.979: 100% 592/592 [01:02<00:00, 9.47it/s]\n",
" 2/3 0.415G 1.09 0.852 0.883 0.99: 100% 592/592 [00:59<00:00, 10.00it/s]\n",
" 3/3 0.415G 0.954 0.776 0.907 0.994: 100% 592/592 [00:59<00:00, 9.89it/s]\n",
"\n",
"Training complete (0.051 hours)\n",
"Results saved to \u001b[1mruns/train-cls/exp\u001b[0m\n",
"Predict: python classify/predict.py --weights runs/train-cls/exp/weights/best.pt --source im.jpg\n",
"Validate: python classify/val.py --weights runs/train-cls/exp/weights/best.pt --data /content/datasets/imagenette160\n",
"Export: python export.py --weights runs/train-cls/exp/weights/best.pt --include onnx\n",
"PyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', 'runs/train-cls/exp/weights/best.pt')\n",
"Visualize: https://netron.app\n",
"\n"
]
}
],
"source": [
"# Train YOLOv5s Classification on Imagenette160 for 3 epochs\n",
"!python classify/train.py --img 224 --batch 16 --epochs 3 --data imagenette160 --model yolov5s-cls.pt --cache"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "15glLzbQx5u0"
},
"source": [
"# 4. Visualize"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nWOsI5wJR1o3"
},
"source": [
"## Comet Logging and Visualization 🌟 NEW\n",
"[Comet](https://bit.ly/yolov5-readme-comet) is now fully integrated with YOLOv5. Track and visualize model metrics in real time, save your hyperparameters, datasets, and model checkpoints, and visualize your model predictions with [Comet Custom Panels](https://bit.ly/yolov5-colab-comet-panels)! Comet makes sure you never lose track of your work and makes it easy to share results and collaborate across teams of all sizes! \n",
"\n",
"Getting started is easy:\n",
"```shell\n",
"pip install comet_ml # 1. install\n",
"export COMET_API_KEY=<Your API Key> # 2. paste API key\n",
"python train.py --img 640 --epochs 3 --data coco128.yaml --weights yolov5s.pt # 3. train\n",
"```\n",
"\n",
"To learn more about all of the supported Comet features for this integration, check out the [Comet Tutorial](https://github.com/ultralytics/yolov5/tree/master/utils/loggers/comet). If you'd like to learn more about Comet, head over to our [documentation](https://bit.ly/yolov5-colab-comet-docs). Get started by trying out the Comet Colab Notebook:\n",
"[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1RG0WOQyxlDlo5Km8GogJpIEJlg_5lyYO?usp=sharing)\n",
"\n",
"<img width=\"1920\" alt=\"yolo-ui\" src=\"https://user-images.githubusercontent.com/26833433/202851203-164e94e1-2238-46dd-91f8-de020e9d6b41.png\">"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Lay2WsTjNJzP"
},
"source": [
"## ClearML Logging and Automation 🌟 NEW\n",
"\n",
"[ClearML](https://cutt.ly/yolov5-notebook-clearml) is completely integrated into YOLOv5 to track your experimentation, manage dataset versions and even remotely execute training runs. To enable ClearML (check cells above):\n",
"\n",
"- `pip install clearml`\n",
"- run `clearml-init` to connect to a ClearML server (**deploy your own [open-source server](https://github.com/allegroai/clearml-server)**, or use our [free hosted server](https://cutt.ly/yolov5-notebook-clearml))\n",
"\n",
"You'll get all the great expected features from an experiment manager: live updates, model upload, experiment comparison etc. but ClearML also tracks uncommitted changes and installed packages for example. Thanks to that ClearML Tasks (which is what we call experiments) are also reproducible on different machines! With only 1 extra line, we can schedule a YOLOv5 training task on a queue to be executed by any number of ClearML Agents (workers).\n",
"\n",
"You can use ClearML Data to version your dataset and then pass it to YOLOv5 simply using its unique ID. This will help you keep track of your data without adding extra hassle. Explore the [ClearML Tutorial](https://github.com/ultralytics/yolov5/tree/master/utils/loggers/clearml) for details!\n",
"\n",
"<a href=\"https://cutt.ly/yolov5-notebook-clearml\">\n",
"<img alt=\"ClearML Experiment Management UI\" src=\"https://github.com/thepycoder/clearml_screenshots/raw/main/scalars.jpg\" width=\"1280\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-WPvRbS5Swl6"
},
"source": [
"## Local Logging\n",
"\n",
"Training results are automatically logged with [Tensorboard](https://www.tensorflow.org/tensorboard) and [CSV](https://github.com/ultralytics/yolov5/pull/4148) loggers to `runs/train`, with a new experiment directory created for each new training as `runs/train/exp2`, `runs/train/exp3`, etc.\n",
"\n",
"This directory contains train and val statistics, mosaics, labels, predictions and augmentated mosaics, as well as metrics and charts including precision-recall (PR) curves and confusion matrices. \n",
"\n",
"<img alt=\"Local logging results\" src=\"https://user-images.githubusercontent.com/26833433/183222430-e1abd1b7-782c-4cde-b04d-ad52926bf818.jpg\" width=\"1280\"/>\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Zelyeqbyt3GD"
},
"source": [
"# Environments\n",
"\n",
"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):\n",
"\n",
"- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n",
"- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)\n",
"- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart)\n",
"- **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6Qu7Iesl0p54"
},
"source": [
"# Status\n",
"\n",
"![YOLOv5 CI](https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg)\n",
"\n",
"If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), testing ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on macOS, Windows, and Ubuntu every 24 hours and on every commit.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "IEijrePND_2I"
},
"source": [
"# Appendix\n",
"\n",
"Additional content below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "GMusP4OAxFu6"
},
"outputs": [],
"source": [
"# YOLOv5 PyTorch HUB Inference (DetectionModels only)\n",
"import torch\n",
"\n",
"model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # yolov5n - yolov5x6 or custom\n",
"im = 'https://ultralytics.com/images/zidane.jpg' # file, Path, PIL.Image, OpenCV, nparray, list\n",
"results = model(im) # inference\n",
"results.print() # or .show(), .save(), .crop(), .pandas(), etc."
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"name": "YOLOv5 Classification Tutorial",
"provenance": [],
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Validate a trained YOLOv5 classification model on a classification dataset
Usage:
$ bash data/scripts/get_imagenet.sh --val # download ImageNet val split (6.3G, 50000 images)
$ python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224 # validate ImageNet
Usage - formats:
$ python classify/val.py --weights yolov5s-cls.pt # PyTorch
yolov5s-cls.torchscript # TorchScript
yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
yolov5s-cls_openvino_model # OpenVINO
yolov5s-cls.engine # TensorRT
yolov5s-cls.mlmodel # CoreML (macOS-only)
yolov5s-cls_saved_model # TensorFlow SavedModel
yolov5s-cls.pb # TensorFlow GraphDef
yolov5s-cls.tflite # TensorFlow Lite
yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
yolov5s-cls_paddle_model # PaddlePaddle
"""
import argparse
import os
import sys
from pathlib import Path
import torch
from tqdm import tqdm
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from models.common import DetectMultiBackend
from utils.dataloaders import create_classification_dataloader
from utils.general import (LOGGER, TQDM_BAR_FORMAT, Profile, check_img_size, check_requirements, colorstr,
increment_path, print_args)
from utils.torch_utils import select_device, smart_inference_mode
@smart_inference_mode()
def run(
data=ROOT / '../datasets/mnist', # dataset dir
weights=ROOT / 'yolov5s-cls.pt', # model.pt path(s)
batch_size=128, # batch size
imgsz=224, # inference size (pixels)
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
workers=8, # max dataloader workers (per RANK in DDP mode)
verbose=False, # verbose output
project=ROOT / 'runs/val-cls', # save to project/name
name='exp', # save to project/name
exist_ok=False, # existing project/name ok, do not increment
half=False, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
model=None,
dataloader=None,
criterion=None,
pbar=None,
):
# Initialize/load model and set device
training = model is not None
if training: # called by train.py
device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
half &= device.type != 'cpu' # half precision only supported on CUDA
model.half() if half else model.float()
else: # called directly
device = select_device(device, batch_size=batch_size)
# Directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
save_dir.mkdir(parents=True, exist_ok=True) # make dir
# Load model
model = DetectMultiBackend(weights, device=device, dnn=dnn, fp16=half)
stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
imgsz = check_img_size(imgsz, s=stride) # check image size
half = model.fp16 # FP16 supported on limited backends with CUDA
if engine:
batch_size = model.batch_size
else:
device = model.device
if not (pt or jit):
batch_size = 1 # export.py models default to batch-size 1
LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models')
# Dataloader
data = Path(data)
test_dir = data / 'test' if (data / 'test').exists() else data / 'val' # data/test or data/val
dataloader = create_classification_dataloader(path=test_dir,
imgsz=imgsz,
batch_size=batch_size,
augment=False,
rank=-1,
workers=workers)
model.eval()
pred, targets, loss, dt = [], [], 0, (Profile(), Profile(), Profile())
n = len(dataloader) # number of batches
action = 'validating' if dataloader.dataset.root.stem == 'val' else 'testing'
desc = f"{pbar.desc[:-36]}{action:>36}" if pbar else f"{action}"
bar = tqdm(dataloader, desc, n, not training, bar_format=TQDM_BAR_FORMAT, position=0)
with torch.cuda.amp.autocast(enabled=device.type != 'cpu'):
for images, labels in bar:
with dt[0]:
images, labels = images.to(device, non_blocking=True), labels.to(device)
with dt[1]:
y = model(images)
with dt[2]:
pred.append(y.argsort(1, descending=True)[:, :5])
targets.append(labels)
if criterion:
loss += criterion(y, labels)
loss /= n
pred, targets = torch.cat(pred), torch.cat(targets)
correct = (targets[:, None] == pred).float()
acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
top1, top5 = acc.mean(0).tolist()
if pbar:
pbar.desc = f"{pbar.desc[:-36]}{loss:>12.3g}{top1:>12.3g}{top5:>12.3g}"
if verbose: # all classes
LOGGER.info(f"{'Class':>24}{'Images':>12}{'top1_acc':>12}{'top5_acc':>12}")
LOGGER.info(f"{'all':>24}{targets.shape[0]:>12}{top1:>12.3g}{top5:>12.3g}")
for i, c in model.names.items():
aci = acc[targets == i]
top1i, top5i = aci.mean(0).tolist()
LOGGER.info(f"{c:>24}{aci.shape[0]:>12}{top1i:>12.3g}{top5i:>12.3g}")
# Print results
t = tuple(x.t / len(dataloader.dataset.samples) * 1E3 for x in dt) # speeds per image
shape = (1, 3, imgsz, imgsz)
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms post-process per image at shape {shape}' % t)
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
return top1, top5, loss
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--data', type=str, default=ROOT / '../datasets/mnist', help='dataset path')
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model.pt path(s)')
parser.add_argument('--batch-size', type=int, default=128, help='batch size')
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=224, help='inference size (pixels)')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
parser.add_argument('--verbose', nargs='?', const=True, default=True, help='verbose output')
parser.add_argument('--project', default=ROOT / 'runs/val-cls', help='save to project/name')
parser.add_argument('--name', default='exp', help='save to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
opt = parser.parse_args()
print_args(vars(opt))
return opt
def main(opt):
check_requirements(exclude=('tensorboard', 'thop'))
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt)
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ by Argo AI
# Example usage: python train.py --data Argoverse.yaml
# parent
# ├── yolov5
# └── datasets
# └── Argoverse ← downloads here (31.3 GB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/Argoverse # dataset root dir
train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images
val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images
test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview
# Classes
names:
0: person
1: bicycle
2: car
3: motorcycle
4: bus
5: truck
6: traffic_light
7: stop_sign
# Download script/URL (optional) ---------------------------------------------------------------------------------------
download: |
import json
from tqdm import tqdm
from utils.general import download, Path
def argoverse2yolo(set):
labels = {}
a = json.load(open(set, "rb"))
for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."):
img_id = annot['image_id']
img_name = a['images'][img_id]['name']
img_label_name = f'{img_name[:-3]}txt'
cls = annot['category_id'] # instance class id
x_center, y_center, width, height = annot['bbox']
x_center = (x_center + width / 2) / 1920.0 # offset and scale
y_center = (y_center + height / 2) / 1200.0 # offset and scale
width /= 1920.0 # scale
height /= 1200.0 # scale
img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']]
if not img_dir.exists():
img_dir.mkdir(parents=True, exist_ok=True)
k = str(img_dir / img_label_name)
if k not in labels:
labels[k] = []
labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n")
for k in labels:
with open(k, "w") as f:
f.writelines(labels[k])
# Download
dir = Path(yaml['path']) # dataset root dir
urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip']
download(urls, dir=dir, delete=False)
# Convert
annotations_dir = 'Argoverse-HD/annotations/'
(dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images'
for d in "train.json", "val.json":
argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# Global Wheat 2020 dataset http://www.global-wheat.com/ by University of Saskatchewan
# Example usage: python train.py --data GlobalWheat2020.yaml
# parent
# ├── yolov5
# └── datasets
# └── GlobalWheat2020 ← downloads here (7.0 GB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/GlobalWheat2020 # dataset root dir
train: # train images (relative to 'path') 3422 images
- images/arvalis_1
- images/arvalis_2
- images/arvalis_3
- images/ethz_1
- images/rres_1
- images/inrae_1
- images/usask_1
val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)
- images/ethz_1
test: # test images (optional) 1276 images
- images/utokyo_1
- images/utokyo_2
- images/nau_1
- images/uq_1
# Classes
names:
0: wheat_head
# Download script/URL (optional) ---------------------------------------------------------------------------------------
download: |
from utils.general import download, Path
# Download
dir = Path(yaml['path']) # dataset root dir
urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']
download(urls, dir=dir)
# Make Directories
for p in 'annotations', 'images', 'labels':
(dir / p).mkdir(parents=True, exist_ok=True)
# Move
for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
(dir / p).rename(dir / 'images' / p) # move to /images
f = (dir / p).with_suffix('.json') # json file
if f.exists():
f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# ImageNet-1k dataset https://www.image-net.org/index.php by Stanford University
# Simplified class names from https://github.com/anishathalye/imagenet-simple-labels
# Example usage: python classify/train.py --data imagenet
# parent
# ├── yolov5
# └── datasets
# └── imagenet ← downloads here (144 GB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/imagenet # dataset root dir
train: train # train images (relative to 'path') 1281167 images
val: val # val images (relative to 'path') 50000 images
test: # test images (optional)
# Classes
names:
0: tench
1: goldfish
2: great white shark
3: tiger shark
4: hammerhead shark
5: electric ray
6: stingray
7: cock
8: hen
9: ostrich
10: brambling
11: goldfinch
12: house finch
13: junco
14: indigo bunting
15: American robin
16: bulbul
17: jay
18: magpie
19: chickadee
20: American dipper
21: kite
22: bald eagle
23: vulture
24: great grey owl
25: fire salamander
26: smooth newt
27: newt
28: spotted salamander
29: axolotl
30: American bullfrog
31: tree frog
32: tailed frog
33: loggerhead sea turtle
34: leatherback sea turtle
35: mud turtle
36: terrapin
37: box turtle
38: banded gecko
39: green iguana
40: Carolina anole
41: desert grassland whiptail lizard
42: agama
43: frilled-necked lizard
44: alligator lizard
45: Gila monster
46: European green lizard
47: chameleon
48: Komodo dragon
49: Nile crocodile
50: American alligator
51: triceratops
52: worm snake
53: ring-necked snake
54: eastern hog-nosed snake
55: smooth green snake
56: kingsnake
57: garter snake
58: water snake
59: vine snake
60: night snake
61: boa constrictor
62: African rock python
63: Indian cobra
64: green mamba
65: sea snake
66: Saharan horned viper
67: eastern diamondback rattlesnake
68: sidewinder
69: trilobite
70: harvestman
71: scorpion
72: yellow garden spider
73: barn spider
74: European garden spider
75: southern black widow
76: tarantula
77: wolf spider
78: tick
79: centipede
80: black grouse
81: ptarmigan
82: ruffed grouse
83: prairie grouse
84: peacock
85: quail
86: partridge
87: grey parrot
88: macaw
89: sulphur-crested cockatoo
90: lorikeet
91: coucal
92: bee eater
93: hornbill
94: hummingbird
95: jacamar
96: toucan
97: duck
98: red-breasted merganser
99: goose
100: black swan
101: tusker
102: echidna
103: platypus
104: wallaby
105: koala
106: wombat
107: jellyfish
108: sea anemone
109: brain coral
110: flatworm
111: nematode
112: conch
113: snail
114: slug
115: sea slug
116: chiton
117: chambered nautilus
118: Dungeness crab
119: rock crab
120: fiddler crab
121: red king crab
122: American lobster
123: spiny lobster
124: crayfish
125: hermit crab
126: isopod
127: white stork
128: black stork
129: spoonbill
130: flamingo
131: little blue heron
132: great egret
133: bittern
134: crane (bird)
135: limpkin
136: common gallinule
137: American coot
138: bustard
139: ruddy turnstone
140: dunlin
141: common redshank
142: dowitcher
143: oystercatcher
144: pelican
145: king penguin
146: albatross
147: grey whale
148: killer whale
149: dugong
150: sea lion
151: Chihuahua
152: Japanese Chin
153: Maltese
154: Pekingese
155: Shih Tzu
156: King Charles Spaniel
157: Papillon
158: toy terrier
159: Rhodesian Ridgeback
160: Afghan Hound
161: Basset Hound
162: Beagle
163: Bloodhound
164: Bluetick Coonhound
165: Black and Tan Coonhound
166: Treeing Walker Coonhound
167: English foxhound
168: Redbone Coonhound
169: borzoi
170: Irish Wolfhound
171: Italian Greyhound
172: Whippet
173: Ibizan Hound
174: Norwegian Elkhound
175: Otterhound
176: Saluki
177: Scottish Deerhound
178: Weimaraner
179: Staffordshire Bull Terrier
180: American Staffordshire Terrier
181: Bedlington Terrier
182: Border Terrier
183: Kerry Blue Terrier
184: Irish Terrier
185: Norfolk Terrier
186: Norwich Terrier
187: Yorkshire Terrier
188: Wire Fox Terrier
189: Lakeland Terrier
190: Sealyham Terrier
191: Airedale Terrier
192: Cairn Terrier
193: Australian Terrier
194: Dandie Dinmont Terrier
195: Boston Terrier
196: Miniature Schnauzer
197: Giant Schnauzer
198: Standard Schnauzer
199: Scottish Terrier
200: Tibetan Terrier
201: Australian Silky Terrier
202: Soft-coated Wheaten Terrier
203: West Highland White Terrier
204: Lhasa Apso
205: Flat-Coated Retriever
206: Curly-coated Retriever
207: Golden Retriever
208: Labrador Retriever
209: Chesapeake Bay Retriever
210: German Shorthaired Pointer
211: Vizsla
212: English Setter
213: Irish Setter
214: Gordon Setter
215: Brittany
216: Clumber Spaniel
217: English Springer Spaniel
218: Welsh Springer Spaniel
219: Cocker Spaniels
220: Sussex Spaniel
221: Irish Water Spaniel
222: Kuvasz
223: Schipperke
224: Groenendael
225: Malinois
226: Briard
227: Australian Kelpie
228: Komondor
229: Old English Sheepdog
230: Shetland Sheepdog
231: collie
232: Border Collie
233: Bouvier des Flandres
234: Rottweiler
235: German Shepherd Dog
236: Dobermann
237: Miniature Pinscher
238: Greater Swiss Mountain Dog
239: Bernese Mountain Dog
240: Appenzeller Sennenhund
241: Entlebucher Sennenhund
242: Boxer
243: Bullmastiff
244: Tibetan Mastiff
245: French Bulldog
246: Great Dane
247: St. Bernard
248: husky
249: Alaskan Malamute
250: Siberian Husky
251: Dalmatian
252: Affenpinscher
253: Basenji
254: pug
255: Leonberger
256: Newfoundland
257: Pyrenean Mountain Dog
258: Samoyed
259: Pomeranian
260: Chow Chow
261: Keeshond
262: Griffon Bruxellois
263: Pembroke Welsh Corgi
264: Cardigan Welsh Corgi
265: Toy Poodle
266: Miniature Poodle
267: Standard Poodle
268: Mexican hairless dog
269: grey wolf
270: Alaskan tundra wolf
271: red wolf
272: coyote
273: dingo
274: dhole
275: African wild dog
276: hyena
277: red fox
278: kit fox
279: Arctic fox
280: grey fox
281: tabby cat
282: tiger cat
283: Persian cat
284: Siamese cat
285: Egyptian Mau
286: cougar
287: lynx
288: leopard
289: snow leopard
290: jaguar
291: lion
292: tiger
293: cheetah
294: brown bear
295: American black bear
296: polar bear
297: sloth bear
298: mongoose
299: meerkat
300: tiger beetle
301: ladybug
302: ground beetle
303: longhorn beetle
304: leaf beetle
305: dung beetle
306: rhinoceros beetle
307: weevil
308: fly
309: bee
310: ant
311: grasshopper
312: cricket
313: stick insect
314: cockroach
315: mantis
316: cicada
317: leafhopper
318: lacewing
319: dragonfly
320: damselfly
321: red admiral
322: ringlet
323: monarch butterfly
324: small white
325: sulphur butterfly
326: gossamer-winged butterfly
327: starfish
328: sea urchin
329: sea cucumber
330: cottontail rabbit
331: hare
332: Angora rabbit
333: hamster
334: porcupine
335: fox squirrel
336: marmot
337: beaver
338: guinea pig
339: common sorrel
340: zebra
341: pig
342: wild boar
343: warthog
344: hippopotamus
345: ox
346: water buffalo
347: bison
348: ram
349: bighorn sheep
350: Alpine ibex
351: hartebeest
352: impala
353: gazelle
354: dromedary
355: llama
356: weasel
357: mink
358: European polecat
359: black-footed ferret
360: otter
361: skunk
362: badger
363: armadillo
364: three-toed sloth
365: orangutan
366: gorilla
367: chimpanzee
368: gibbon
369: siamang
370: guenon
371: patas monkey
372: baboon
373: macaque
374: langur
375: black-and-white colobus
376: proboscis monkey
377: marmoset
378: white-headed capuchin
379: howler monkey
380: titi
381: Geoffroy's spider monkey
382: common squirrel monkey
383: ring-tailed lemur
384: indri
385: Asian elephant
386: African bush elephant
387: red panda
388: giant panda
389: snoek
390: eel
391: coho salmon
392: rock beauty
393: clownfish
394: sturgeon
395: garfish
396: lionfish
397: pufferfish
398: abacus
399: abaya
400: academic gown
401: accordion
402: acoustic guitar
403: aircraft carrier
404: airliner
405: airship
406: altar
407: ambulance
408: amphibious vehicle
409: analog clock
410: apiary
411: apron
412: waste container
413: assault rifle
414: backpack
415: bakery
416: balance beam
417: balloon
418: ballpoint pen
419: Band-Aid
420: banjo
421: baluster
422: barbell
423: barber chair
424: barbershop
425: barn
426: barometer
427: barrel
428: wheelbarrow
429: baseball
430: basketball
431: bassinet
432: bassoon
433: swimming cap
434: bath towel
435: bathtub
436: station wagon
437: lighthouse
438: beaker
439: military cap
440: beer bottle
441: beer glass
442: bell-cot
443: bib
444: tandem bicycle
445: bikini
446: ring binder
447: binoculars
448: birdhouse
449: boathouse
450: bobsleigh
451: bolo tie
452: poke bonnet
453: bookcase
454: bookstore
455: bottle cap
456: bow
457: bow tie
458: brass
459: bra
460: breakwater
461: breastplate
462: broom
463: bucket
464: buckle
465: bulletproof vest
466: high-speed train
467: butcher shop
468: taxicab
469: cauldron
470: candle
471: cannon
472: canoe
473: can opener
474: cardigan
475: car mirror
476: carousel
477: tool kit
478: carton
479: car wheel
480: automated teller machine
481: cassette
482: cassette player
483: castle
484: catamaran
485: CD player
486: cello
487: mobile phone
488: chain
489: chain-link fence
490: chain mail
491: chainsaw
492: chest
493: chiffonier
494: chime
495: china cabinet
496: Christmas stocking
497: church
498: movie theater
499: cleaver
500: cliff dwelling
501: cloak
502: clogs
503: cocktail shaker
504: coffee mug
505: coffeemaker
506: coil
507: combination lock
508: computer keyboard
509: confectionery store
510: container ship
511: convertible
512: corkscrew
513: cornet
514: cowboy boot
515: cowboy hat
516: cradle
517: crane (machine)
518: crash helmet
519: crate
520: infant bed
521: Crock Pot
522: croquet ball
523: crutch
524: cuirass
525: dam
526: desk
527: desktop computer
528: rotary dial telephone
529: diaper
530: digital clock
531: digital watch
532: dining table
533: dishcloth
534: dishwasher
535: disc brake
536: dock
537: dog sled
538: dome
539: doormat
540: drilling rig
541: drum
542: drumstick
543: dumbbell
544: Dutch oven
545: electric fan
546: electric guitar
547: electric locomotive
548: entertainment center
549: envelope
550: espresso machine
551: face powder
552: feather boa
553: filing cabinet
554: fireboat
555: fire engine
556: fire screen sheet
557: flagpole
558: flute
559: folding chair
560: football helmet
561: forklift
562: fountain
563: fountain pen
564: four-poster bed
565: freight car
566: French horn
567: frying pan
568: fur coat
569: garbage truck
570: gas mask
571: gas pump
572: goblet
573: go-kart
574: golf ball
575: golf cart
576: gondola
577: gong
578: gown
579: grand piano
580: greenhouse
581: grille
582: grocery store
583: guillotine
584: barrette
585: hair spray
586: half-track
587: hammer
588: hamper
589: hair dryer
590: hand-held computer
591: handkerchief
592: hard disk drive
593: harmonica
594: harp
595: harvester
596: hatchet
597: holster
598: home theater
599: honeycomb
600: hook
601: hoop skirt
602: horizontal bar
603: horse-drawn vehicle
604: hourglass
605: iPod
606: clothes iron
607: jack-o'-lantern
608: jeans
609: jeep
610: T-shirt
611: jigsaw puzzle
612: pulled rickshaw
613: joystick
614: kimono
615: knee pad
616: knot
617: lab coat
618: ladle
619: lampshade
620: laptop computer
621: lawn mower
622: lens cap
623: paper knife
624: library
625: lifeboat
626: lighter
627: limousine
628: ocean liner
629: lipstick
630: slip-on shoe
631: lotion
632: speaker
633: loupe
634: sawmill
635: magnetic compass
636: mail bag
637: mailbox
638: tights
639: tank suit
640: manhole cover
641: maraca
642: marimba
643: mask
644: match
645: maypole
646: maze
647: measuring cup
648: medicine chest
649: megalith
650: microphone
651: microwave oven
652: military uniform
653: milk can
654: minibus
655: miniskirt
656: minivan
657: missile
658: mitten
659: mixing bowl
660: mobile home
661: Model T
662: modem
663: monastery
664: monitor
665: moped
666: mortar
667: square academic cap
668: mosque
669: mosquito net
670: scooter
671: mountain bike
672: tent
673: computer mouse
674: mousetrap
675: moving van
676: muzzle
677: nail
678: neck brace
679: necklace
680: nipple
681: notebook computer
682: obelisk
683: oboe
684: ocarina
685: odometer
686: oil filter
687: organ
688: oscilloscope
689: overskirt
690: bullock cart
691: oxygen mask
692: packet
693: paddle
694: paddle wheel
695: padlock
696: paintbrush
697: pajamas
698: palace
699: pan flute
700: paper towel
701: parachute
702: parallel bars
703: park bench
704: parking meter
705: passenger car
706: patio
707: payphone
708: pedestal
709: pencil case
710: pencil sharpener
711: perfume
712: Petri dish
713: photocopier
714: plectrum
715: Pickelhaube
716: picket fence
717: pickup truck
718: pier
719: piggy bank
720: pill bottle
721: pillow
722: ping-pong ball
723: pinwheel
724: pirate ship
725: pitcher
726: hand plane
727: planetarium
728: plastic bag
729: plate rack
730: plow
731: plunger
732: Polaroid camera
733: pole
734: police van
735: poncho
736: billiard table
737: soda bottle
738: pot
739: potter's wheel
740: power drill
741: prayer rug
742: printer
743: prison
744: projectile
745: projector
746: hockey puck
747: punching bag
748: purse
749: quill
750: quilt
751: race car
752: racket
753: radiator
754: radio
755: radio telescope
756: rain barrel
757: recreational vehicle
758: reel
759: reflex camera
760: refrigerator
761: remote control
762: restaurant
763: revolver
764: rifle
765: rocking chair
766: rotisserie
767: eraser
768: rugby ball
769: ruler
770: running shoe
771: safe
772: safety pin
773: salt shaker
774: sandal
775: sarong
776: saxophone
777: scabbard
778: weighing scale
779: school bus
780: schooner
781: scoreboard
782: CRT screen
783: screw
784: screwdriver
785: seat belt
786: sewing machine
787: shield
788: shoe store
789: shoji
790: shopping basket
791: shopping cart
792: shovel
793: shower cap
794: shower curtain
795: ski
796: ski mask
797: sleeping bag
798: slide rule
799: sliding door
800: slot machine
801: snorkel
802: snowmobile
803: snowplow
804: soap dispenser
805: soccer ball
806: sock
807: solar thermal collector
808: sombrero
809: soup bowl
810: space bar
811: space heater
812: space shuttle
813: spatula
814: motorboat
815: spider web
816: spindle
817: sports car
818: spotlight
819: stage
820: steam locomotive
821: through arch bridge
822: steel drum
823: stethoscope
824: scarf
825: stone wall
826: stopwatch
827: stove
828: strainer
829: tram
830: stretcher
831: couch
832: stupa
833: submarine
834: suit
835: sundial
836: sunglass
837: sunglasses
838: sunscreen
839: suspension bridge
840: mop
841: sweatshirt
842: swimsuit
843: swing
844: switch
845: syringe
846: table lamp
847: tank
848: tape player
849: teapot
850: teddy bear
851: television
852: tennis ball
853: thatched roof
854: front curtain
855: thimble
856: threshing machine
857: throne
858: tile roof
859: toaster
860: tobacco shop
861: toilet seat
862: torch
863: totem pole
864: tow truck
865: toy store
866: tractor
867: semi-trailer truck
868: tray
869: trench coat
870: tricycle
871: trimaran
872: tripod
873: triumphal arch
874: trolleybus
875: trombone
876: tub
877: turnstile
878: typewriter keyboard
879: umbrella
880: unicycle
881: upright piano
882: vacuum cleaner
883: vase
884: vault
885: velvet
886: vending machine
887: vestment
888: viaduct
889: violin
890: volleyball
891: waffle iron
892: wall clock
893: wallet
894: wardrobe
895: military aircraft
896: sink
897: washing machine
898: water bottle
899: water jug
900: water tower
901: whiskey jug
902: whistle
903: wig
904: window screen
905: window shade
906: Windsor tie
907: wine bottle
908: wing
909: wok
910: wooden spoon
911: wool
912: split-rail fence
913: shipwreck
914: yawl
915: yurt
916: website
917: comic book
918: crossword
919: traffic sign
920: traffic light
921: dust jacket
922: menu
923: plate
924: guacamole
925: consomme
926: hot pot
927: trifle
928: ice cream
929: ice pop
930: baguette
931: bagel
932: pretzel
933: cheeseburger
934: hot dog
935: mashed potato
936: cabbage
937: broccoli
938: cauliflower
939: zucchini
940: spaghetti squash
941: acorn squash
942: butternut squash
943: cucumber
944: artichoke
945: bell pepper
946: cardoon
947: mushroom
948: Granny Smith
949: strawberry
950: orange
951: lemon
952: fig
953: pineapple
954: banana
955: jackfruit
956: custard apple
957: pomegranate
958: hay
959: carbonara
960: chocolate syrup
961: dough
962: meatloaf
963: pizza
964: pot pie
965: burrito
966: red wine
967: espresso
968: cup
969: eggnog
970: alp
971: bubble
972: cliff
973: coral reef
974: geyser
975: lakeshore
976: promontory
977: shoal
978: seashore
979: valley
980: volcano
981: baseball player
982: bridegroom
983: scuba diver
984: rapeseed
985: daisy
986: yellow lady's slipper
987: corn
988: acorn
989: rose hip
990: horse chestnut seed
991: coral fungus
992: agaric
993: gyromitra
994: stinkhorn mushroom
995: earth star
996: hen-of-the-woods
997: bolete
998: ear
999: toilet paper
# Download script/URL (optional)
download: data/scripts/get_imagenet.sh
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# Objects365 dataset https://www.objects365.org/ by Megvii
# Example usage: python train.py --data Objects365.yaml
# parent
# ├── yolov5
# └── datasets
# └── Objects365 ← downloads here (712 GB = 367G data + 345G zips)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/Objects365 # dataset root dir
train: images/train # train images (relative to 'path') 1742289 images
val: images/val # val images (relative to 'path') 80000 images
test: # test images (optional)
# Classes
names:
0: Person
1: Sneakers
2: Chair
3: Other Shoes
4: Hat
5: Car
6: Lamp
7: Glasses
8: Bottle
9: Desk
10: Cup
11: Street Lights
12: Cabinet/shelf
13: Handbag/Satchel
14: Bracelet
15: Plate
16: Picture/Frame
17: Helmet
18: Book
19: Gloves
20: Storage box
21: Boat
22: Leather Shoes
23: Flower
24: Bench
25: Potted Plant
26: Bowl/Basin
27: Flag
28: Pillow
29: Boots
30: Vase
31: Microphone
32: Necklace
33: Ring
34: SUV
35: Wine Glass
36: Belt
37: Monitor/TV
38: Backpack
39: Umbrella
40: Traffic Light
41: Speaker
42: Watch
43: Tie
44: Trash bin Can
45: Slippers
46: Bicycle
47: Stool
48: Barrel/bucket
49: Van
50: Couch
51: Sandals
52: Basket
53: Drum
54: Pen/Pencil
55: Bus
56: Wild Bird
57: High Heels
58: Motorcycle
59: Guitar
60: Carpet
61: Cell Phone
62: Bread
63: Camera
64: Canned
65: Truck
66: Traffic cone
67: Cymbal
68: Lifesaver
69: Towel
70: Stuffed Toy
71: Candle
72: Sailboat
73: Laptop
74: Awning
75: Bed
76: Faucet
77: Tent
78: Horse
79: Mirror
80: Power outlet
81: Sink
82: Apple
83: Air Conditioner
84: Knife
85: Hockey Stick
86: Paddle
87: Pickup Truck
88: Fork
89: Traffic Sign
90: Balloon
91: Tripod
92: Dog
93: Spoon
94: Clock
95: Pot
96: Cow
97: Cake
98: Dinning Table
99: Sheep
100: Hanger
101: Blackboard/Whiteboard
102: Napkin
103: Other Fish
104: Orange/Tangerine
105: Toiletry
106: Keyboard
107: Tomato
108: Lantern
109: Machinery Vehicle
110: Fan
111: Green Vegetables
112: Banana
113: Baseball Glove
114: Airplane
115: Mouse
116: Train
117: Pumpkin
118: Soccer
119: Skiboard
120: Luggage
121: Nightstand
122: Tea pot
123: Telephone
124: Trolley
125: Head Phone
126: Sports Car
127: Stop Sign
128: Dessert
129: Scooter
130: Stroller
131: Crane
132: Remote
133: Refrigerator
134: Oven
135: Lemon
136: Duck
137: Baseball Bat
138: Surveillance Camera
139: Cat
140: Jug
141: Broccoli
142: Piano
143: Pizza
144: Elephant
145: Skateboard
146: Surfboard
147: Gun
148: Skating and Skiing shoes
149: Gas stove
150: Donut
151: Bow Tie
152: Carrot
153: Toilet
154: Kite
155: Strawberry
156: Other Balls
157: Shovel
158: Pepper
159: Computer Box
160: Toilet Paper
161: Cleaning Products
162: Chopsticks
163: Microwave
164: Pigeon
165: Baseball
166: Cutting/chopping Board
167: Coffee Table
168: Side Table
169: Scissors
170: Marker
171: Pie
172: Ladder
173: Snowboard
174: Cookies
175: Radiator
176: Fire Hydrant
177: Basketball
178: Zebra
179: Grape
180: Giraffe
181: Potato
182: Sausage
183: Tricycle
184: Violin
185: Egg
186: Fire Extinguisher
187: Candy
188: Fire Truck
189: Billiards
190: Converter
191: Bathtub
192: Wheelchair
193: Golf Club
194: Briefcase
195: Cucumber
196: Cigar/Cigarette
197: Paint Brush
198: Pear
199: Heavy Truck
200: Hamburger
201: Extractor
202: Extension Cord
203: Tong
204: Tennis Racket
205: Folder
206: American Football
207: earphone
208: Mask
209: Kettle
210: Tennis
211: Ship
212: Swing
213: Coffee Machine
214: Slide
215: Carriage
216: Onion
217: Green beans
218: Projector
219: Frisbee
220: Washing Machine/Drying Machine
221: Chicken
222: Printer
223: Watermelon
224: Saxophone
225: Tissue
226: Toothbrush
227: Ice cream
228: Hot-air balloon
229: Cello
230: French Fries
231: Scale
232: Trophy
233: Cabbage
234: Hot dog
235: Blender
236: Peach
237: Rice
238: Wallet/Purse
239: Volleyball
240: Deer
241: Goose
242: Tape
243: Tablet
244: Cosmetics
245: Trumpet
246: Pineapple
247: Golf Ball
248: Ambulance
249: Parking meter
250: Mango
251: Key
252: Hurdle
253: Fishing Rod
254: Medal
255: Flute
256: Brush
257: Penguin
258: Megaphone
259: Corn
260: Lettuce
261: Garlic
262: Swan
263: Helicopter
264: Green Onion
265: Sandwich
266: Nuts
267: Speed Limit Sign
268: Induction Cooker
269: Broom
270: Trombone
271: Plum
272: Rickshaw
273: Goldfish
274: Kiwi fruit
275: Router/modem
276: Poker Card
277: Toaster
278: Shrimp
279: Sushi
280: Cheese
281: Notepaper
282: Cherry
283: Pliers
284: CD
285: Pasta
286: Hammer
287: Cue
288: Avocado
289: Hamimelon
290: Flask
291: Mushroom
292: Screwdriver
293: Soap
294: Recorder
295: Bear
296: Eggplant
297: Board Eraser
298: Coconut
299: Tape Measure/Ruler
300: Pig
301: Showerhead
302: Globe
303: Chips
304: Steak
305: Crosswalk Sign
306: Stapler
307: Camel
308: Formula 1
309: Pomegranate
310: Dishwasher
311: Crab
312: Hoverboard
313: Meat ball
314: Rice Cooker
315: Tuba
316: Calculator
317: Papaya
318: Antelope
319: Parrot
320: Seal
321: Butterfly
322: Dumbbell
323: Donkey
324: Lion
325: Urinal
326: Dolphin
327: Electric Drill
328: Hair Dryer
329: Egg tart
330: Jellyfish
331: Treadmill
332: Lighter
333: Grapefruit
334: Game board
335: Mop
336: Radish
337: Baozi
338: Target
339: French
340: Spring Rolls
341: Monkey
342: Rabbit
343: Pencil Case
344: Yak
345: Red Cabbage
346: Binoculars
347: Asparagus
348: Barbell
349: Scallop
350: Noddles
351: Comb
352: Dumpling
353: Oyster
354: Table Tennis paddle
355: Cosmetics Brush/Eyeliner Pencil
356: Chainsaw
357: Eraser
358: Lobster
359: Durian
360: Okra
361: Lipstick
362: Cosmetics Mirror
363: Curling
364: Table Tennis
# Download script/URL (optional) ---------------------------------------------------------------------------------------
download: |
from tqdm import tqdm
from utils.general import Path, check_requirements, download, np, xyxy2xywhn
check_requirements(('pycocotools>=2.0',))
from pycocotools.coco import COCO
# Make Directories
dir = Path(yaml['path']) # dataset root dir
for p in 'images', 'labels':
(dir / p).mkdir(parents=True, exist_ok=True)
for q in 'train', 'val':
(dir / p / q).mkdir(parents=True, exist_ok=True)
# Train, Val Splits
for split, patches in [('train', 50 + 1), ('val', 43 + 1)]:
print(f"Processing {split} in {patches} patches ...")
images, labels = dir / 'images' / split, dir / 'labels' / split
# Download
url = f"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/"
if split == 'train':
download([f'{url}zhiyuan_objv2_{split}.tar.gz'], dir=dir, delete=False) # annotations json
download([f'{url}patch{i}.tar.gz' for i in range(patches)], dir=images, curl=True, delete=False, threads=8)
elif split == 'val':
download([f'{url}zhiyuan_objv2_{split}.json'], dir=dir, delete=False) # annotations json
download([f'{url}images/v1/patch{i}.tar.gz' for i in range(15 + 1)], dir=images, curl=True, delete=False, threads=8)
download([f'{url}images/v2/patch{i}.tar.gz' for i in range(16, patches)], dir=images, curl=True, delete=False, threads=8)
# Move
for f in tqdm(images.rglob('*.jpg'), desc=f'Moving {split} images'):
f.rename(images / f.name) # move to /images/{split}
# Labels
coco = COCO(dir / f'zhiyuan_objv2_{split}.json')
names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
for cid, cat in enumerate(names):
catIds = coco.getCatIds(catNms=[cat])
imgIds = coco.getImgIds(catIds=catIds)
for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):
width, height = im["width"], im["height"]
path = Path(im["file_name"]) # image filename
try:
with open(labels / path.with_suffix('.txt').name, 'a') as file:
annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None)
for a in coco.loadAnns(annIds):
x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner)
xyxy = np.array([x, y, x + w, y + h])[None] # pixels(1,4)
x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0] # normalized and clipped
file.write(f"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\n")
except Exception as e:
print(e)
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail
# Example usage: python train.py --data SKU-110K.yaml
# parent
# ├── yolov5
# └── datasets
# └── SKU-110K ← downloads here (13.6 GB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/SKU-110K # dataset root dir
train: train.txt # train images (relative to 'path') 8219 images
val: val.txt # val images (relative to 'path') 588 images
test: test.txt # test images (optional) 2936 images
# Classes
names:
0: object
# Download script/URL (optional) ---------------------------------------------------------------------------------------
download: |
import shutil
from tqdm import tqdm
from utils.general import np, pd, Path, download, xyxy2xywh
# Download
dir = Path(yaml['path']) # dataset root dir
parent = Path(dir.parent) # download dir
urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz']
download(urls, dir=parent, delete=False)
# Rename directories
if dir.exists():
shutil.rmtree(dir)
(parent / 'SKU110K_fixed').rename(dir) # rename dir
(dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir
# Convert labels
names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names
for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv':
x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations
images, unique_images = x[:, 0], np.unique(x[:, 0])
with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f:
f.writelines(f'./images/{s}\n' for s in unique_images)
for im in tqdm(unique_images, desc=f'Converting {dir / d}'):
cls = 0 # single-class dataset
with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f:
for r in x[images == im]:
w, h = r[6], r[7] # image width, height
xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance
f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford
# Example usage: python train.py --data VOC.yaml
# parent
# ├── yolov5
# └── datasets
# └── VOC ← downloads here (2.8 GB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/VOC
train: # train images (relative to 'path') 16551 images
- images/train2012
- images/train2007
- images/val2012
- images/val2007
val: # val images (relative to 'path') 4952 images
- images/test2007
test: # test images (optional)
- images/test2007
# Classes
names:
0: aeroplane
1: bicycle
2: bird
3: boat
4: bottle
5: bus
6: car
7: cat
8: chair
9: cow
10: diningtable
11: dog
12: horse
13: motorbike
14: person
15: pottedplant
16: sheep
17: sofa
18: train
19: tvmonitor
# Download script/URL (optional) ---------------------------------------------------------------------------------------
download: |
import xml.etree.ElementTree as ET
from tqdm import tqdm
from utils.general import download, Path
def convert_label(path, lb_path, year, image_id):
def convert_box(size, box):
dw, dh = 1. / size[0], 1. / size[1]
x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]
return x * dw, y * dh, w * dw, h * dh
in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')
out_file = open(lb_path, 'w')
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
names = list(yaml['names'].values()) # names list
for obj in root.iter('object'):
cls = obj.find('name').text
if cls in names and int(obj.find('difficult').text) != 1:
xmlbox = obj.find('bndbox')
bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])
cls_id = names.index(cls) # class id
out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n')
# Download
dir = Path(yaml['path']) # dataset root dir
url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
urls = [f'{url}VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images
f'{url}VOCtest_06-Nov-2007.zip', # 438MB, 4953 images
f'{url}VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images
download(urls, dir=dir / 'images', delete=False, curl=True, threads=3)
# Convert
path = dir / 'images/VOCdevkit'
for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'):
imgs_path = dir / 'images' / f'{image_set}{year}'
lbs_path = dir / 'labels' / f'{image_set}{year}'
imgs_path.mkdir(exist_ok=True, parents=True)
lbs_path.mkdir(exist_ok=True, parents=True)
with open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt') as f:
image_ids = f.read().strip().split()
for id in tqdm(image_ids, desc=f'{image_set}{year}'):
f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path
lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path
f.rename(imgs_path / f.name) # move image
convert_label(path, lb_path, year, id) # convert labels to YOLO format
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University
# Example usage: python train.py --data VisDrone.yaml
# parent
# ├── yolov5
# └── datasets
# └── VisDrone ← downloads here (2.3 GB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/VisDrone # dataset root dir
train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images
val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images
test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images
# Classes
names:
0: pedestrian
1: people
2: bicycle
3: car
4: van
5: truck
6: tricycle
7: awning-tricycle
8: bus
9: motor
# Download script/URL (optional) ---------------------------------------------------------------------------------------
download: |
from utils.general import download, os, Path
def visdrone2yolo(dir):
from PIL import Image
from tqdm import tqdm
def convert_box(size, box):
# Convert VisDrone box to YOLO xywh box
dw = 1. / size[0]
dh = 1. / size[1]
return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
(dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
for f in pbar:
img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
lines = []
with open(f, 'r') as file: # read annotation.txt
for row in [x.split(',') for x in file.read().strip().splitlines()]:
if row[4] == '0': # VisDrone 'ignored regions' class 0
continue
cls = int(row[5]) - 1
box = convert_box(img_size, tuple(map(int, row[:4])))
lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl:
fl.writelines(lines) # write label.txt
# Download
dir = Path(yaml['path']) # dataset root dir
urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']
download(urls, dir=dir, curl=True, threads=4)
# Convert
for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# COCO 2017 dataset http://cocodataset.org by Microsoft
# Example usage: python train.py --data coco.yaml
# parent
# ├── yolov5
# └── datasets
# └── coco ← downloads here (20.1 GB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: /home/DL_DATA/coco2017/ # dataset root dir
train: train2017.txt # train images (relative to 'path') 118287 images
val: val2017.txt # val images (relative to 'path') 5000 images
#test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
# Classes
names:
0: person
1: bicycle
2: car
3: motorcycle
4: airplane
5: bus
6: train
7: truck
8: boat
9: traffic light
10: fire hydrant
11: stop sign
12: parking meter
13: bench
14: bird
15: cat
16: dog
17: horse
18: sheep
19: cow
20: elephant
21: bear
22: zebra
23: giraffe
24: backpack
25: umbrella
26: handbag
27: tie
28: suitcase
29: frisbee
30: skis
31: snowboard
32: sports ball
33: kite
34: baseball bat
35: baseball glove
36: skateboard
37: surfboard
38: tennis racket
39: bottle
40: wine glass
41: cup
42: fork
43: knife
44: spoon
45: bowl
46: banana
47: apple
48: sandwich
49: orange
50: broccoli
51: carrot
52: hot dog
53: pizza
54: donut
55: cake
56: chair
57: couch
58: potted plant
59: bed
60: dining table
61: toilet
62: tv
63: laptop
64: mouse
65: remote
66: keyboard
67: cell phone
68: microwave
69: oven
70: toaster
71: sink
72: refrigerator
73: book
74: clock
75: vase
76: scissors
77: teddy bear
78: hair drier
79: toothbrush
# Download script/URL (optional)
download: |
from utils.general import download, Path
# Download labels
segments = False # segment or box labels
dir = Path(yaml['path']) # dataset root dir
url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels
download(urls, dir=dir.parent)
# Download data
urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images
'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images
'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional)
download(urls, dir=dir / 'images', threads=3)
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# COCO128-seg dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics
# Example usage: python train.py --data coco128.yaml
# parent
# ├── yolov5
# └── datasets
# └── coco128-seg ← downloads here (7 MB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/coco128-seg # dataset root dir
train: images/train2017 # train images (relative to 'path') 128 images
val: images/train2017 # val images (relative to 'path') 128 images
test: # test images (optional)
# Classes
names:
0: person
1: bicycle
2: car
3: motorcycle
4: airplane
5: bus
6: train
7: truck
8: boat
9: traffic light
10: fire hydrant
11: stop sign
12: parking meter
13: bench
14: bird
15: cat
16: dog
17: horse
18: sheep
19: cow
20: elephant
21: bear
22: zebra
23: giraffe
24: backpack
25: umbrella
26: handbag
27: tie
28: suitcase
29: frisbee
30: skis
31: snowboard
32: sports ball
33: kite
34: baseball bat
35: baseball glove
36: skateboard
37: surfboard
38: tennis racket
39: bottle
40: wine glass
41: cup
42: fork
43: knife
44: spoon
45: bowl
46: banana
47: apple
48: sandwich
49: orange
50: broccoli
51: carrot
52: hot dog
53: pizza
54: donut
55: cake
56: chair
57: couch
58: potted plant
59: bed
60: dining table
61: toilet
62: tv
63: laptop
64: mouse
65: remote
66: keyboard
67: cell phone
68: microwave
69: oven
70: toaster
71: sink
72: refrigerator
73: book
74: clock
75: vase
76: scissors
77: teddy bear
78: hair drier
79: toothbrush
# Download script/URL (optional)
download: https://ultralytics.com/assets/coco128-seg.zip
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics
# Example usage: python train.py --data coco128.yaml
# parent
# ├── yolov5
# └── datasets
# └── coco128 ← downloads here (7 MB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
path: ../datasets/coco128 # dataset root dir
train: images/train2017 # train images (relative to 'path') 128 images
val: images/train2017 # val images (relative to 'path') 128 images
test: # test images (optional)
# Classes
names:
0: person
1: bicycle
2: car
3: motorcycle
4: airplane
5: bus
6: train
7: truck
8: boat
9: traffic light
10: fire hydrant
11: stop sign
12: parking meter
13: bench
14: bird
15: cat
16: dog
17: horse
18: sheep
19: cow
20: elephant
21: bear
22: zebra
23: giraffe
24: backpack
25: umbrella
26: handbag
27: tie
28: suitcase
29: frisbee
30: skis
31: snowboard
32: sports ball
33: kite
34: baseball bat
35: baseball glove
36: skateboard
37: surfboard
38: tennis racket
39: bottle
40: wine glass
41: cup
42: fork
43: knife
44: spoon
45: bowl
46: banana
47: apple
48: sandwich
49: orange
50: broccoli
51: carrot
52: hot dog
53: pizza
54: donut
55: cake
56: chair
57: couch
58: potted plant
59: bed
60: dining table
61: toilet
62: tv
63: laptop
64: mouse
65: remote
66: keyboard
67: cell phone
68: microwave
69: oven
70: toaster
71: sink
72: refrigerator
73: book
74: clock
75: vase
76: scissors
77: teddy bear
78: hair drier
79: toothbrush
# Download script/URL (optional)
download: https://ultralytics.com/assets/coco128.zip
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# Hyperparameters for Objects365 training
# python train.py --weights yolov5m.pt --data Objects365.yaml --evolve
# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials
lr0: 0.00258
lrf: 0.17
momentum: 0.779
weight_decay: 0.00058
warmup_epochs: 1.33
warmup_momentum: 0.86
warmup_bias_lr: 0.0711
box: 0.0539
cls: 0.299
cls_pw: 0.825
obj: 0.632
obj_pw: 1.0
iou_t: 0.2
anchor_t: 3.44
anchors: 3.2
fl_gamma: 0.0
hsv_h: 0.0188
hsv_s: 0.704
hsv_v: 0.36
degrees: 0.0
translate: 0.0902
scale: 0.491
shear: 0.0
perspective: 0.0
flipud: 0.0
fliplr: 0.5
mosaic: 1.0
mixup: 0.0
copy_paste: 0.0
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
# Hyperparameters for VOC training
# python train.py --batch 128 --weights yolov5m6.pt --data VOC.yaml --epochs 50 --img 512 --hyp hyp.scratch-med.yaml --evolve
# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials
# YOLOv5 Hyperparameter Evolution Results
# Best generation: 467
# Last generation: 996
# metrics/precision, metrics/recall, metrics/mAP_0.5, metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss
# 0.87729, 0.85125, 0.91286, 0.72664, 0.0076739, 0.0042529, 0.0013865
lr0: 0.00334
lrf: 0.15135
momentum: 0.74832
weight_decay: 0.00025
warmup_epochs: 3.3835
warmup_momentum: 0.59462
warmup_bias_lr: 0.18657
box: 0.02
cls: 0.21638
cls_pw: 0.5
obj: 0.51728
obj_pw: 0.67198
iou_t: 0.2
anchor_t: 3.3744
fl_gamma: 0.0
hsv_h: 0.01041
hsv_s: 0.54703
hsv_v: 0.27739
degrees: 0.0
translate: 0.04591
scale: 0.75544
shear: 0.0
perspective: 0.0
flipud: 0.0
fliplr: 0.5
mosaic: 0.85834
mixup: 0.04266
copy_paste: 0.0
anchors: 3.412
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment