├── LICENSE
├── README.md
├── baseline.yaml
├── common.py
├── main.py
├── mixup_layer.py
└── subcluster_adacos.py
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # sub-cluster-AdaCos
2 | Accompanying code for the paper "Sub-Cluster AdaCos: Learning Representations for Anomalous Sound Detection" (http://wilkinghoff.com/publications/ijcnn21_sub-cluster.pdf).
3 |
4 | You will need all datasets from task 2 "Unsupervised Detection of Anomalous Sounds for Machine Condition Monitoring" of the DCASE challenge 2020 (http://dcase.community/challenge2020/task-unsupervised-detection-of-anomalous-sounds) as well as Tensorflow 2.
5 |
6 | When finding this code helpful, or reusing parts of it, a citation would be appreciated:
7 |
8 | @inproceedings{wilkinghoff2021sub,
9 | title={Sub-Cluster {A}da{C}os: Learning Representations for Anomalous Sound Detection},
10 | author={Wilkinghoff, Kevin},
11 | booktitle={International Joint Conference on Neural Networks (IJCNN)},
12 | year={2021},
13 | publisher={IEEE}
14 | }
15 |
--------------------------------------------------------------------------------
/baseline.yaml:
--------------------------------------------------------------------------------
1 | dev_directory : ./dev_data
2 | eval_directory : ./eval_data
3 | all_data_directory: ./all_data
4 | model_directory: ./model
5 | result_directory: ./result
6 | result_file: result.csv
7 |
8 | max_fpr : 0.1
9 |
10 | feature:
11 | n_mels: 128
12 | frames : 5
13 | n_fft: 1024
14 | hop_length: 512
15 | power: 2.0
16 |
17 |
18 | fit:
19 | compile:
20 | optimizer : adam
21 | loss : mean_squared_error
22 | epochs : 100
23 | batch_size : 512
24 | shuffle : True
25 | validation_split : 0.1
26 | verbose : 1
27 |
--------------------------------------------------------------------------------
/common.py:
--------------------------------------------------------------------------------
1 | """
2 | @file common.py
3 | @brief Commonly used script
4 | @author Toshiki Nakamura, Yuki Nikaido, and Yohei Kawaguchi (Hitachi Ltd.)
5 | Copyright (C) 2020 Hitachi, Ltd. All right reserved.
6 | """
7 |
8 | ########################################################################
9 | # import python-library
10 | ########################################################################
11 | # default
12 | import glob
13 | import argparse
14 | import sys
15 | import os
16 |
17 | # additional
18 | import numpy
19 | import librosa
20 | import librosa.core
21 | import librosa.feature
22 | import yaml
23 |
24 | ########################################################################
25 |
26 |
27 | ########################################################################
28 | # setup STD I/O
29 | ########################################################################
30 | """
31 | Standard output is logged in "baseline.log".
32 | """
33 | import logging
34 |
35 | logging.basicConfig(level=logging.DEBUG, filename="baseline.log")
36 | logger = logging.getLogger(' ')
37 | handler = logging.StreamHandler()
38 | formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
39 | handler.setFormatter(formatter)
40 | logger.addHandler(handler)
41 |
42 |
43 | ########################################################################
44 |
45 |
46 | ########################################################################
47 | # version
48 | ########################################################################
49 | __versions__ = "1.0.0"
50 | ########################################################################
51 |
52 |
53 | ########################################################################
54 | # argparse
55 | ########################################################################
56 | def command_line_chk():
57 | parser = argparse.ArgumentParser(description='Without option argument, it will not run properly.')
58 | parser.add_argument('-v', '--version', action='store_true', help="show application version")
59 | parser.add_argument('-e', '--eval', action='store_true', help="run mode Evaluation")
60 | parser.add_argument('-d', '--dev', action='store_true', help="run mode Development")
61 | parser.add_argument('-a', '--all', action='store_true', help="run mode All_Data")
62 | args = parser.parse_args()
63 | if args.version:
64 | print("===============================")
65 | print("DCASE 2020 task 2 baseline\nversion {}".format(__versions__))
66 | print("===============================\n")
67 | if args.eval ^ args.dev ^ args.all:
68 | if args.dev:
69 | flag = True
70 | elif args.all:
71 | flag = 2
72 | else:
73 | flag = False
74 | else:
75 | flag = None
76 | print("incorrect argument")
77 | print("please set option argument '--dev' or '--eval'")
78 | return flag
79 | ########################################################################
80 |
81 |
82 | ########################################################################
83 | # load parameter.yaml
84 | ########################################################################
85 | def yaml_load():
86 | with open("baseline.yaml") as stream:
87 | param = yaml.safe_load(stream)
88 | return param
89 |
90 | ########################################################################
91 |
92 |
93 | ########################################################################
94 | # file I/O
95 | ########################################################################
96 | # wav file Input
97 | def file_load(wav_name, mono=False):
98 | """
99 | load .wav file.
100 |
101 | wav_name : str
102 | target .wav file
103 | sampling_rate : int
104 | audio file sampling_rate
105 | mono : boolean
106 | When load a multi channels file and this param True, the returned data will be merged for mono data
107 |
108 | return : numpy.array( float )
109 | """
110 | try:
111 | return librosa.load(wav_name, sr=None, mono=mono)
112 | except:
113 | logger.error("file_broken or not exists!! : {}".format(wav_name))
114 |
115 |
116 | ########################################################################
117 |
118 |
119 | ########################################################################
120 | # feature extractor
121 | ########################################################################
122 | def file_to_vector_array(file_name,
123 | n_mels=64,
124 | frames=5,
125 | n_fft=1024,
126 | hop_length=512,
127 | power=2.0):
128 | """
129 | convert file_name to a vector array.
130 |
131 | file_name : str
132 | target .wav file
133 |
134 | return : numpy.array( numpy.array( float ) )
135 | vector array
136 | * dataset.shape = (dataset_size, feature_vector_length)
137 | """
138 | # 01 calculate the number of dimensions
139 | dims = n_mels * frames
140 |
141 | # 02 generate melspectrogram using librosa
142 | y, sr = file_load(file_name)
143 | mel_spectrogram = librosa.feature.melspectrogram(y=y,
144 | sr=sr,
145 | n_fft=n_fft,
146 | hop_length=hop_length,
147 | n_mels=n_mels,
148 | power=power)
149 |
150 | # 03 convert melspectrogram to log mel energy
151 | log_mel_spectrogram = 20.0 / power * numpy.log10(mel_spectrogram + sys.float_info.epsilon)
152 |
153 | # 04 calculate total vector size
154 | vector_array_size = len(log_mel_spectrogram[0, :]) - frames + 1
155 |
156 | # 05 skip too short clips
157 | if vector_array_size < 1:
158 | return numpy.empty((0, dims))
159 |
160 | # 06 generate feature vectors by concatenating multiframes
161 | vector_array = numpy.zeros((vector_array_size, dims))
162 | for t in range(frames):
163 | vector_array[:, n_mels * t: n_mels * (t + 1)] = log_mel_spectrogram[:, t: t + vector_array_size].T
164 |
165 | return vector_array
166 |
167 |
168 | # load dataset
169 | def select_dirs(param, mode):
170 | """
171 | param : dict
172 | baseline.yaml data
173 |
174 | return :
175 | if active type the development :
176 | dirs : list [ str ]
177 | load base directory list of dev_data
178 | if active type the evaluation :
179 | dirs : list [ str ]
180 | load base directory list of eval_data
181 | """
182 | if mode == 1:
183 | logger.info("load_directory <- development")
184 | dir_path = os.path.abspath("{base}/*".format(base=param["dev_directory"]))
185 | dirs = sorted(glob.glob(dir_path))
186 | elif mode == 2:
187 | logger.info("load_directory <- development + evaluation")
188 | dir_path = os.path.abspath("{base}/*".format(base=param["all_data_directory"]))
189 | dirs = sorted(glob.glob(dir_path))
190 | else:
191 | logger.info("load_directory <- evaluation")
192 | dir_path = os.path.abspath("{base}/*".format(base=param["eval_directory"]))
193 | dirs = sorted(glob.glob(dir_path))
194 | return dirs
195 |
196 | ########################################################################
197 |
198 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 | import keras
4 | import os
5 | import soundfile as sf
6 | import tensorflow as tf
7 | import librosa
8 | from sklearn.metrics import roc_auc_score, roc_curve
9 | from sklearn.utils import class_weight
10 | import common as com
11 | from tqdm import tqdm
12 | from sklearn.preprocessing import LabelEncoder
13 | from mixup_layer import MixupLayer
14 | from subcluster_adacos import SCAdaCos
15 | from sklearn.mixture import GaussianMixture
16 |
17 |
18 | def mixupLoss(y_true, y_pred):
19 | return tf.keras.losses.categorical_crossentropy(y_true=y_pred[:, :, 1], y_pred=y_pred[:, :, 0])
20 |
21 |
22 | def length_norm(mat):
23 | norm_mat = []
24 | for line in mat:
25 | temp = line/np.math.sqrt(sum(np.power(line, 2)))
26 | norm_mat.append(temp)
27 | norm_mat = np.array(norm_mat)
28 | return norm_mat
29 |
30 |
31 | class LogMelExtractor(object):
32 | """
33 | Original source code (before changes): https://github.com/qiuqiangkong/dcase2019_task1
34 | """
35 | def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, fmax):
36 | """Log mel feature extractor.
37 |
38 | Args:
39 | sample_rate: int
40 | window_size: int
41 | hop_size: int
42 | mel_bins: int
43 | fmin: int, minimum frequency of mel filter banks
44 | fmax: int, maximum frequency of mel filter banks
45 | """
46 |
47 | self.window_size = window_size
48 | self.hop_size = hop_size
49 | self.window_func = np.hanning(window_size)
50 |
51 | self.melW = librosa.filters.mel(
52 | sr=sample_rate,
53 | n_fft=window_size,
54 | n_mels=mel_bins,
55 | fmin=fmin,
56 | fmax=fmax).T
57 |
58 | def transform(self, audio):
59 | """Extract feature of a singlechannel audio file.
60 |
61 | Args:
62 | audio: (samples,)
63 |
64 | Returns:
65 | feature: (frames_num, freq_bins)
66 | """
67 |
68 | window_size = self.window_size
69 | hop_size = self.hop_size
70 | window_func = self.window_func
71 |
72 | # Compute short-time Fourier transform
73 | stft_matrix = librosa.core.stft(
74 | y=audio,
75 | n_fft=window_size,
76 | hop_length=hop_size,
77 | window=window_func,
78 | center=True,
79 | dtype=np.complex64,
80 | pad_mode='reflect').T
81 | '''(N, n_fft // 2 + 1)'''
82 |
83 | # Mel spectrogram
84 | mel_spectrogram = np.dot(np.abs(stft_matrix) ** 2, self.melW)
85 |
86 | # Log mel spectrogram
87 | logmel_spectrogram = librosa.core.power_to_db(
88 | mel_spectrogram, ref=1.0, amin=1e-10,
89 | top_db=None)
90 |
91 | logmel_spectrogram = logmel_spectrogram.astype(np.float32).transpose()
92 | return logmel_spectrogram
93 |
94 |
95 | def model_cnn(emb_size, num_classes, time_dim, min_val, n_subclusters):
96 | data_input = tf.keras.layers.Input(shape=(time_dim, emb_size, 1), dtype='float32')
97 | label_input = tf.keras.layers.Input(shape=(num_classes), dtype='float32')
98 | y = label_input
99 | x = data_input
100 | l2_weight_decay = tf.keras.regularizers.l2(1e-5)
101 | x, y = MixupLayer(prob=1)([x, y])
102 |
103 | # first block
104 | x = tf.keras.layers.Conv2D(16, 7, strides=2, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(x)
105 | x = tf.keras.layers.LeakyReLU(alpha=0.1)(x)
106 | x = tf.keras.layers.BatchNormalization()(x)
107 | x = tf.keras.layers.MaxPooling2D(3, strides=2)(x)
108 |
109 | # second block
110 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(x)
111 | xr = tf.keras.layers.Conv2D(16, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
112 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(xr)
113 | xr = tf.keras.layers.BatchNormalization()(xr)
114 | xr = tf.keras.layers.Conv2D(16, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
115 | x = tf.keras.layers.Add()([x, xr])
116 | x = tf.keras.layers.BatchNormalization()(x)
117 |
118 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(x)
119 | xr = tf.keras.layers.Conv2D(16, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
120 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(xr)
121 | xr = tf.keras.layers.BatchNormalization()(xr)
122 | xr = tf.keras.layers.Conv2D(16, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
123 | x = tf.keras.layers.Add()([x, xr])
124 | x = tf.keras.layers.BatchNormalization()(x)
125 |
126 | # third block
127 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(x)
128 | xr = tf.keras.layers.Conv2D(32, 3, strides=(2, 2), activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
129 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(xr)
130 | xr = tf.keras.layers.BatchNormalization()(xr)
131 | xr = tf.keras.layers.Conv2D(32, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
132 | x = tf.keras.layers.MaxPooling2D((2, 2), padding='same')(x)
133 | x = tf.keras.layers.Conv2D(kernel_size=1, filters=32, strides=1, padding="same", kernel_regularizer=l2_weight_decay)(x)
134 | x = tf.keras.layers.Add()([x, xr])
135 | x = tf.keras.layers.BatchNormalization()(x)
136 |
137 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(x)
138 | xr = tf.keras.layers.Conv2D(32, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
139 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(xr)
140 | xr = tf.keras.layers.BatchNormalization()(xr)
141 | xr = tf.keras.layers.Conv2D(32, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
142 | x = tf.keras.layers.Add()([x, xr])
143 | x = tf.keras.layers.BatchNormalization()(x)
144 |
145 | # fourth block
146 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(x)
147 | xr = tf.keras.layers.Conv2D(64, 3, strides=(2, 2), activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
148 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(xr)
149 | xr = tf.keras.layers.BatchNormalization()(xr)
150 | xr = tf.keras.layers.Conv2D(64, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
151 | x = tf.keras.layers.MaxPooling2D((2, 2), padding='same')(x)
152 | x = tf.keras.layers.Conv2D(kernel_size=1, filters=64, strides=1, padding="same", kernel_regularizer=l2_weight_decay)(x)
153 | x = tf.keras.layers.Add()([x, xr])
154 | x = tf.keras.layers.BatchNormalization()(x)
155 |
156 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(x)
157 | xr = tf.keras.layers.Conv2D(64, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
158 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(xr)
159 | xr = tf.keras.layers.BatchNormalization()(xr)
160 | xr = tf.keras.layers.Conv2D(64, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
161 | x = tf.keras.layers.Add()([x, xr])
162 | x = tf.keras.layers.BatchNormalization()(x)
163 |
164 | # fifth block
165 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(x)
166 | xr = tf.keras.layers.Conv2D(128, 3, strides=(2, 2), activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
167 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(xr)
168 | xr = tf.keras.layers.BatchNormalization()(xr)
169 | xr = tf.keras.layers.Conv2D(128, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
170 | x = tf.keras.layers.MaxPooling2D((2, 2), padding='same')(x)
171 | x = tf.keras.layers.Conv2D(kernel_size=1, filters=128, strides=1, padding="same", kernel_regularizer=l2_weight_decay)(x)
172 | x = tf.keras.layers.Add()([x, xr])
173 | x = tf.keras.layers.BatchNormalization()(x)
174 |
175 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(x)
176 | xr = tf.keras.layers.Conv2D(128, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
177 | xr = tf.keras.layers.LeakyReLU(alpha=0.1)(xr)
178 | xr = tf.keras.layers.BatchNormalization()(xr)
179 | xr = tf.keras.layers.Conv2D(128, 3, activation='linear', padding='same', kernel_regularizer=l2_weight_decay)(xr)
180 | x = tf.keras.layers.Add()([x, xr])
181 | x = tf.keras.layers.BatchNormalization()(x)
182 |
183 | # get embeddings and classify
184 | x = tf.keras.layers.MaxPooling2D((10, 1), padding='same')(x)
185 | x = tf.keras.layers.Flatten(name='flat')(x)
186 | x = tf.keras.layers.Dense(128, kernel_regularizer=l2_weight_decay, name='emb')(x)
187 | output = SCAdaCos(n_classes=num_classes, n_subclusters=n_subclusters)([x, y, label_input])
188 | loss_output = tf.keras.layers.Lambda(lambda x: tf.stack(x, axis=-1))([output, y])
189 |
190 | return data_input, label_input, loss_output
191 |
192 |
193 | ########################################################################################################################
194 | # Load data and compute embeddings
195 | ########################################################################################################################
196 | # emb_size = 6144
197 | n_log_mel = 128
198 | target_sr = 16000
199 | param = com.yaml_load()
200 | extractor = LogMelExtractor(target_sr, 1024, 512, mel_bins=n_log_mel, fmin=0, fmax=target_sr/2)
201 |
202 | # load train data
203 | print('Loading train data')
204 | categories = os.listdir("./dev_data")
205 |
206 | if os.path.isfile(str(n_log_mel) + '_train_log_mel.npy'):
207 | train_log_mel = np.load(str(n_log_mel) + '_train_log_mel.npy')
208 | train_ids = np.load('train_ids.npy')
209 | train_files = np.load('train_files.npy')
210 | else:
211 | train_log_mel = []
212 | train_ids = []
213 | train_files = []
214 | dicts = ['./dev_data/', './eval_data/']
215 | #dicts = ['./eval_data/']
216 | #dicts = ['./dev_data/']
217 | eps=1e-12
218 | for label, category in enumerate(categories):
219 | print(category)
220 | for dict in dicts:
221 | for count, file in tqdm(enumerate(os.listdir(dict + category + "/train")), total=len(os.listdir(dict + category + "/train"))):
222 | file_path = dict + category + "/train/" + file
223 | wav, fs = sf.read(file_path)
224 | wav = librosa.core.to_mono(wav.transpose()).transpose()
225 | # extract log_mels
226 | log_mel = extractor.transform(wav).transpose()
227 | if log_mel.shape[0] > 313:
228 | log_mel = log_mel[log_mel.shape[0]-313:, :]
229 | train_log_mel.append(log_mel)
230 | train_ids.append(category + '_' + file.split('_')[-2])
231 | train_files.append(file_path)
232 | # reshape arrays and store
233 | train_ids = np.array(train_ids)
234 | train_files = np.array(train_files)
235 | train_log_mel = np.expand_dims(np.array(train_log_mel, dtype=np.float32), axis=-1)
236 | np.save('train_ids.npy', train_ids)
237 | np.save('train_files.npy', train_files)
238 | np.save(str(n_log_mel) + '_train_log_mel.npy', train_log_mel)
239 |
240 | # load evaluation data
241 | print('Loading evaluation data')
242 | if os.path.isfile(str(n_log_mel) + '_eval_log_mel.npy'):
243 | eval_log_mel = np.load(str(n_log_mel) + '_eval_log_mel.npy')
244 | eval_ids = np.load('eval_ids.npy')
245 | eval_normal = np.load('eval_normal.npy')
246 | eval_files = np.load('eval_files.npy')
247 | else:
248 | eval_log_mel = []
249 | eval_ids = []
250 | eval_normal = []
251 | eval_files = []
252 | eps=1e-12
253 | for label, category in enumerate(categories):
254 | print(category)
255 | for count, file in tqdm(enumerate(os.listdir("./dev_data/" + category + "/test")), total=len(os.listdir("./dev_data/" + category + "/test"))):
256 | file_path = "./dev_data/" + category + "/test/" + file
257 | wav, fs = sf.read(file_path)
258 | wav = librosa.core.to_mono(wav.transpose()).transpose()
259 | # extract log_mels
260 | log_mel = extractor.transform(wav).transpose()
261 | if log_mel.shape[0] > 313:
262 | log_mel = log_mel[log_mel.shape[0]-313:, :]
263 | eval_log_mel.append(log_mel)
264 | eval_ids.append(category + '_' + file.split('_')[-2])
265 | eval_normal.append(file.split('_')[0] == 'normal')
266 | eval_files.append(file_path)
267 | # reshape arrays and store
268 | eval_ids = np.array(eval_ids)
269 | eval_normal = np.array(eval_normal)
270 | eval_files = np.array(eval_files)
271 | eval_log_mel = np.expand_dims(np.array(eval_log_mel, dtype=np.float32), axis=-1)
272 | np.save('eval_ids.npy', eval_ids)
273 | np.save('eval_normal.npy', eval_normal)
274 | np.save('eval_files.npy', eval_files)
275 | np.save(str(n_log_mel) + '_eval_log_mel.npy', eval_log_mel)
276 |
277 | # load test data
278 | print('Loading test data')
279 | if os.path.isfile(str(n_log_mel) + '_test_log_mel.npy'):
280 | test_log_mel = np.load(str(n_log_mel) + '_test_log_mel.npy')
281 | test_ids = np.load('test_ids.npy')
282 | test_files = np.load('test_files.npy')
283 | else:
284 | test_log_mel = []
285 | test_ids = []
286 | test_files = []
287 | eps = 1e-12
288 | for label, category in enumerate(categories):
289 | print(category)
290 | for count, file in tqdm(enumerate(os.listdir("./eval_data/" + category + "/test")), total=len(os.listdir("./eval_data/" + category + "/test"))):
291 | file_path = "./eval_data/" + category + "/test/" + file
292 | wav, fs = sf.read(file_path)
293 | wav = librosa.core.to_mono(wav.transpose()).transpose()
294 | # extract log_mels
295 | log_mel = extractor.transform(wav).transpose()
296 | if log_mel.shape[0] > 313:
297 | log_mel = log_mel[log_mel.shape[0]-313:, :]
298 | test_log_mel.append(log_mel)
299 | test_ids.append(category + '_' + file.split('_')[-2])
300 | test_files.append(file_path)
301 | # reshape arrays and store
302 | test_ids = np.array(test_ids)
303 | test_files = np.array(test_files)
304 | test_log_mel = np.expand_dims(np.array(test_log_mel, dtype=np.float32), axis=-1)
305 | np.save('test_ids.npy', test_ids)
306 | np.save('test_files.npy', test_files)
307 | np.save(str(n_log_mel) + '_test_log_mel.npy', test_log_mel)
308 |
309 | # encode ids as labels
310 | le = LabelEncoder()
311 | train_labels = le.fit_transform(train_ids)
312 | eval_labels = le.transform(eval_ids)
313 | test_labels = le.transform(test_ids)
314 |
315 | # distinguish between normal and anomalous samples
316 | unknown_log_mel = eval_log_mel[~eval_normal]
317 | unknown_labels = eval_labels[~eval_normal]
318 | unknown_files = eval_files[~eval_normal]
319 | unknown_ids = eval_ids[~eval_normal]
320 | eval_log_mel = eval_log_mel[eval_normal]
321 | eval_labels = eval_labels[eval_normal]
322 | eval_files = eval_files[eval_normal]
323 | eval_ids = eval_ids[eval_normal]
324 |
325 | # set up dict to convert machine type into a vector indicating all ids that belong to that type
326 | type_dict = {'ToyCar': np.array([1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
327 | 'ToyConveyor': np.array([0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
328 | 'fan': np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
329 | 'pump': np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
330 | 'slider': np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0]),
331 | 'valve': np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1])}
332 | type_dict_s = {'ToyCar': np.array([1,0,0,0,0,0]),
333 | 'ToyConveyor': np.array([0,1,0,0,0,0]),
334 | 'fan': np.array([0,0,1,0,0,0]),
335 | 'pump': np.array([0,0,0,1,0,0]),
336 | 'slider': np.array([0,0,0,0,1,0]),
337 | 'valve': np.array([0,0,0,0,0,1])}
338 |
339 | type_labels_train = np.array([type_dict[train_id.split('_')[0]] for train_id in train_ids])
340 | type_labels_eval = np.array([type_dict[eval_id.split('_')[0]] for eval_id in eval_ids])
341 | type_labels_unknown = np.array([type_dict[unknown_id.split('_')[0]] for unknown_id in unknown_ids])
342 | type_labels_train_s = np.array([type_dict_s[train_id.split('_')[0]] for train_id in train_ids])
343 | type_labels_eval_s = np.array([type_dict_s[eval_id.split('_')[0]] for eval_id in eval_ids])
344 | type_labels_unknown_s = np.array([type_dict_s[unknown_id.split('_')[0]] for unknown_id in unknown_ids])
345 |
346 | ########################################################################################################################
347 | # Preprocessing
348 | ########################################################################################################################
349 |
350 | # feature normalization
351 | print('Normalizing data')
352 | eps = 1e-12
353 | mean_log_mel = np.expand_dims(np.repeat(np.expand_dims(np.mean(train_log_mel.reshape(train_log_mel.shape[0]*train_log_mel.shape[1], train_log_mel.shape[2], 1), axis=0), axis=0),
354 | repeats=train_log_mel.shape[1], axis=0), axis=0)
355 | std_log_mel = np.expand_dims(np.repeat(np.expand_dims(np.std(train_log_mel.reshape(train_log_mel.shape[0]*train_log_mel.shape[1], train_log_mel.shape[2], 1), axis=0), axis=0),
356 | repeats=train_log_mel.shape[1], axis=0), axis=0)
357 | train_log_mel = (train_log_mel-mean_log_mel)/(std_log_mel+eps)
358 | eval_log_mel = (eval_log_mel-mean_log_mel)/(std_log_mel+eps)
359 | unknown_log_mel = (unknown_log_mel-mean_log_mel)/(std_log_mel+eps)
360 | test_log_mel = (test_log_mel-mean_log_mel)/(std_log_mel+eps)
361 |
362 | ########################################################################################################################
363 | # train cnn
364 | ########################################################################################################################
365 | batch_size = 64
366 | batch_size_test = 64
367 | epochs = 100
368 | aeons = 4
369 | alpha = 1
370 |
371 | # predicting with GMMs
372 | pred_eval = np.zeros((eval_log_mel.shape[0], np.unique(train_labels).shape[0], 3))
373 | pred_unknown = np.zeros((unknown_log_mel.shape[0], np.unique(train_labels).shape[0], 3))
374 | pred_test = np.zeros((test_log_mel.shape[0], np.unique(train_labels).shape[0], 3))
375 | pred_train = np.zeros((train_log_mel.shape[0], np.unique(train_labels).shape[0], 3))
376 | for n_subclusters in 2**np.arange(7):
377 | y_train_cat = keras.utils.np_utils.to_categorical(train_labels, num_classes=len(np.unique(train_labels)))
378 | y_eval_cat = keras.utils.np_utils.to_categorical(eval_labels, num_classes=len(np.unique(train_labels)))
379 | y_unknown_cat = keras.utils.np_utils.to_categorical(unknown_labels, num_classes=len(np.unique(train_labels)))
380 |
381 | # compile model
382 | data_input, label_input, loss_output = model_cnn(emb_size=train_log_mel.shape[2],
383 | num_classes=len(np.unique(train_labels)),
384 | time_dim=train_log_mel.shape[1], min_val=np.min(train_log_mel), n_subclusters=n_subclusters)
385 | model = tf.keras.Model(inputs=[data_input, label_input], outputs=[loss_output])
386 | model.compile(loss=[mixupLoss], optimizer=tf.keras.optimizers.Adam())
387 | print(model.summary())
388 | callbacks = [
389 | tf.keras.callbacks.TensorBoard(log_dir=os.path.join("logs"), histogram_freq=0, write_graph=True,
390 | write_images=False)
391 | ]
392 |
393 | for k in np.arange(aeons):
394 | print('subclusters: ' + str(n_subclusters))
395 | print('aeon: ' + str(k))
396 | # fit model
397 | weight_path = './models/wts_log_mel_' + str(k + 1) + 'k_' + str(n_log_mel) + '_' + str(n_subclusters) + '.h5'
398 | if not os.path.isfile(weight_path):
399 | class_weights = class_weight.compute_class_weight('balanced', np.unique(train_labels), train_labels)
400 | class_weights = {i: class_weights[i] for i in range(class_weights.shape[0])}
401 | model.fit([train_log_mel, y_train_cat], y_train_cat, verbose=1,
402 | batch_size= batch_size, epochs=epochs, callbacks=callbacks,
403 | validation_data=([eval_log_mel, y_eval_cat], y_eval_cat), class_weight=class_weights)
404 | model.save(weight_path)
405 | else:
406 | model = tf.keras.models.load_model(weight_path,
407 | custom_objects={'MixupLayer': MixupLayer, 'mixupLoss': mixupLoss, 'SCAdaCos': SCAdaCos})
408 |
409 | emb_model = tf.keras.Model(model.input, model.get_layer('emb').output)
410 | eval_embs = emb_model.predict([eval_log_mel, y_eval_cat], batch_size=batch_size)
411 | train_embs = emb_model.predict([train_log_mel, y_train_cat], batch_size=batch_size)
412 | unknown_embs = emb_model.predict([unknown_log_mel, np.zeros((unknown_log_mel.shape[0], len(np.unique(train_labels))))], batch_size=batch_size)
413 | test_embs = emb_model.predict([test_log_mel, np.zeros((test_log_mel.shape[0], len(np.unique(train_labels))))], batch_size=batch_size)
414 |
415 | # length normalization
416 | print('normalizing lengths')
417 | x_train_ln = length_norm(train_embs)
418 | x_eval_ln = length_norm(eval_embs)
419 | x_test_ln = length_norm(test_embs)
420 | x_unknown_ln = length_norm(unknown_embs)
421 |
422 | model_means = model.layers[-2].get_weights()[0].transpose()
423 | model_means_ln = length_norm(model_means)
424 |
425 | x_train_ln = np.concatenate([x_train_ln, np.mean(train_log_mel, axis=1)[:, :, 0], np.max(train_log_mel, axis=1)[:, :, 0]], axis=-1)
426 | x_eval_ln = np.concatenate([x_eval_ln, np.mean(eval_log_mel, axis=1)[:, :, 0], np.max(eval_log_mel, axis=1)[:, :, 0]], axis=-1)
427 | x_test_ln = np.concatenate([x_test_ln, np.mean(test_log_mel, axis=1)[:, :, 0], np.max(test_log_mel, axis=1)[:, :, 0]], axis=-1)
428 | x_unknown_ln = np.concatenate([x_unknown_ln, np.mean(unknown_log_mel, axis=1)[:, :, 0], np.max(unknown_log_mel, axis=1)[:, :, 0]], axis=-1)
429 | for j, lab in tqdm(enumerate(np.unique(train_labels)), total=len(np.unique(train_labels))):
430 | clf1 = GaussianMixture(n_components=n_subclusters, covariance_type='full', reg_covar=1e-3, means_init=model_means_ln[j * n_subclusters:(j + 1) * n_subclusters]).fit(
431 | x_train_ln[train_labels == lab, :train_embs.shape[1]])
432 | clf2 = GaussianMixture(n_components=1, covariance_type='full', reg_covar=1e-3).fit(
433 | x_train_ln[train_labels == lab, train_embs.shape[1]:train_embs.shape[1] + train_log_mel.shape[2]])
434 | clf3 = GaussianMixture(n_components=1, covariance_type='full', reg_covar=1e-3).fit(
435 | x_train_ln[train_labels == lab, train_embs.shape[1] + train_log_mel.shape[2]:])
436 |
437 | pred_eval[:, j, 0] += -np.max(clf1._estimate_log_prob(x_eval_ln[:, :eval_embs.shape[1]]), axis=-1)
438 | pred_eval[:, j, 1] += -clf2.score_samples(
439 | x_eval_ln[:, eval_embs.shape[1]:eval_embs.shape[1] + eval_log_mel.shape[2]])
440 | pred_eval[:, j, 2] += -clf3.score_samples(x_eval_ln[:, eval_embs.shape[1] + eval_log_mel.shape[2]:])
441 |
442 | pred_unknown[:, j, 0] += -np.max(clf1._estimate_log_prob(x_unknown_ln[:, :unknown_embs.shape[1]]), axis=-1)
443 | pred_unknown[:, j, 1] += -clf2.score_samples(
444 | x_unknown_ln[:, unknown_embs.shape[1]:unknown_embs.shape[1] + unknown_log_mel.shape[2]])
445 | pred_unknown[:, j, 2] += -clf3.score_samples(
446 | x_unknown_ln[:, unknown_embs.shape[1] + unknown_log_mel.shape[2]:])
447 |
448 | pred_test[:, j, 0] += -np.max(clf1._estimate_log_prob(x_test_ln[:, :test_embs.shape[1]]), axis=-1)
449 | pred_test[:, j, 1] += -clf2.score_samples(
450 | x_test_ln[:, test_embs.shape[1]:test_embs.shape[1] + test_log_mel.shape[2]])
451 | pred_test[:, j, 2] += -clf3.score_samples(x_test_ln[:, test_embs.shape[1] + test_log_mel.shape[2]:])
452 |
453 | # use mean for machine type ToyConveyor
454 | pred_eval_final = pred_eval[:, :, 0]
455 | pred_unknown_final = pred_unknown[:, :, 0]
456 | pred_test_final = pred_test[:, :, 0]
457 | for lab in np.unique(train_labels):
458 | if le.inverse_transform([lab])[0].split('_')[0] == 'ToyConveyor':
459 | pred_eval_final[:, lab] = pred_eval[:, lab, 1]
460 | pred_unknown_final[:, lab] = pred_unknown[:, lab, 1]
461 | pred_test_final[:, lab] = pred_test[:, lab, 1]
462 |
463 | # output performance
464 | print('performance on evaluation set')
465 | y_pred_eval = np.argmin(pred_eval_final, axis=1)
466 | y_pred_unknown = np.argmin(pred_unknown_final, axis=1)
467 | print('####################')
468 | print('closed-set performance by machine id:')
469 | print('evaluation files: ' + str(np.mean(y_pred_eval == eval_labels)))
470 | print('unknown files: ' + str(np.mean(y_pred_unknown == unknown_labels)))
471 | print('all files: ' + str(
472 | np.mean(np.hstack([y_pred_unknown, y_pred_eval]) == np.hstack([unknown_labels, eval_labels]))))
473 | print('####################')
474 | type_labels_eval1 = np.array([eval_id.split('_')[0] for eval_id in eval_ids])
475 | type_labels_unknown1 = np.array([unknown_id.split('_')[0] for unknown_id in unknown_ids])
476 | type_pred_eval1 = np.array([pred_id.split('_')[0] for pred_id in le.inverse_transform(y_pred_eval)])
477 | type_pred_unknown1 = np.array([pred_id.split('_')[0] for pred_id in le.inverse_transform(y_pred_unknown)])
478 | print('closed-set performance by machine type:')
479 | print('evaluation files: ' + str(np.mean(type_pred_eval1 == type_labels_eval1)))
480 | print('unknown files: ' + str(np.mean(type_pred_unknown1 == type_labels_unknown1)))
481 | print('all files: ' + str(np.mean(
482 | np.hstack([type_pred_unknown1, type_pred_eval1]) == np.hstack([type_labels_unknown1, type_labels_eval1]))))
483 | print('####################')
484 | print('closed-set performance on test data')
485 | y_pred_test = np.argmin(pred_test_final, axis=1)
486 | type_labels_test1 = np.array([test_id.split('_')[0] for test_id in test_ids])
487 | type_pred_test1 = np.array([pred_id.split('_')[0] for pred_id in le.inverse_transform(y_pred_test)])
488 | print('for machine id: ' + str(np.mean(y_pred_test == test_labels)))
489 | print('for machine type: ' + str(np.mean(type_pred_test1 == type_labels_test1)))
490 | print('####################')
491 | aucs = []
492 | p_aucs = []
493 | for j, cat in enumerate(np.unique(eval_ids)):
494 | y_pred = np.concatenate([pred_eval_final[eval_labels == le.transform([cat]), le.transform([cat])],
495 | pred_unknown_final[unknown_labels == le.transform([cat]), le.transform([cat])]],
496 | axis=0)
497 | y_true = np.concatenate([np.zeros(np.sum(eval_labels == le.transform([cat]))),
498 | np.ones(np.sum(unknown_labels == le.transform([cat])))], axis=0)
499 | auc = roc_auc_score(y_true, y_pred)
500 | aucs.append(auc)
501 | p_auc = roc_auc_score(y_true, y_pred, max_fpr=param["max_fpr"])
502 | p_aucs.append(p_auc)
503 | print('AUC for category ' + str(cat) + ': ' + str(auc * 100))
504 | print('pAUC for category ' + str(cat) + ': ' + str(p_auc * 100))
505 | print('####################')
506 | aucs = np.array(aucs)
507 | p_aucs = np.array(p_aucs)
508 | for cat in categories:
509 | mean_auc = np.mean(aucs[np.array([eval_id.split('_')[0] for eval_id in np.unique(eval_ids)]) == cat])
510 | print('mean AUC for category ' + str(cat) + ': ' + str(mean_auc * 100))
511 | mean_p_auc = np.mean(p_aucs[np.array([eval_id.split('_')[0] for eval_id in np.unique(eval_ids)]) == cat])
512 | print('mean pAUC for category ' + str(cat) + ': ' + str(mean_p_auc * 100))
513 | print('####################')
514 | for cat in categories:
515 | mean_auc = np.mean(aucs[np.array([eval_id.split('_')[0] for eval_id in np.unique(eval_ids)]) == cat])
516 | mean_p_auc = np.mean(p_aucs[np.array([eval_id.split('_')[0] for eval_id in np.unique(eval_ids)]) == cat])
517 | print('mean of AUC and pAUC for category ' + str(cat) + ': ' + str((mean_p_auc + mean_auc) * 50))
518 | print('####################')
519 | mean_auc = np.mean(aucs)
520 | print('mean AUC: ' + str(mean_auc * 100))
521 | mean_p_auc = np.mean(p_aucs)
522 | print('mean pAUC: ' + str(mean_p_auc * 100))
523 |
524 | # create challenge submission files
525 | print('creating submission files')
526 | for j, cat in enumerate(np.unique(test_ids)):
527 | file_idx = test_labels == le.transform([cat])
528 | results = pd.DataFrame()
529 | results['output1'], results['output2'] = [[f.split('/')[-1] for f in test_files[file_idx]],
530 | [str(s) for s in pred_test_final[file_idx, le.transform([cat])]]]
531 | results.to_csv('teams/mfcc_emb/anomaly_score_' + cat.split('_')[0] + '_id_' + cat.split('_')[-1] + '.csv',
532 | encoding='utf-8', index=False, header=False)
533 | print('####################')
534 | print('>>>> finished! <<<<<')
535 | print('####################')
536 |
--------------------------------------------------------------------------------
/mixup_layer.py:
--------------------------------------------------------------------------------
1 | from tensorflow.keras import backend as K
2 | from tensorflow.keras import layers
3 | import tensorflow as tf
4 | import tensorflow_probability as tfp
5 |
6 | class MixupLayer(layers.Layer):
7 | def __init__(self, prob, alpha=1, **kwargs):
8 | super(MixupLayer, self).__init__(**kwargs)
9 | self.prob = prob
10 | self.alpha = alpha
11 |
12 | def build(self, input_shape):
13 | self.built = True
14 |
15 | def call(self, inputs, training=None):
16 | # get mixup weights
17 | if self.alpha == 1:
18 | #dist = tfp.distributions.Beta(0.5, 0.5)
19 | #l = dist.sample([tf.shape(inputs[0])[0]])
20 | l = tf.random.uniform(shape=[tf.shape(inputs[0])[0]])
21 | X_l = tf.reshape(l, [-1]+[1]*(len(inputs[0].shape)-1))
22 | y_l = tf.reshape(l, [-1]+[1]*(len(inputs[1].shape)-1))
23 |
24 | # mixup data
25 | X1 = inputs[0]
26 | X2 = tf.reverse(inputs[0], axis=[0])
27 | X = X1 * X_l + X2 * (1 - X_l)
28 |
29 | # mixup labels
30 | y1 = inputs[1]
31 | y2 = tf.reverse(inputs[1], axis=[0])
32 | y = y1 * y_l + y2 * (1 - y_l)
33 |
34 | # apply mixup or not
35 | dec = tf.dtypes.cast(tf.random.uniform(shape=[tf.shape(inputs[0])[0]]) < self.prob, tf.dtypes.float32)
36 | dec1 = tf.reshape(dec, [-1] + [1] * (len(inputs[0].shape) - 1))
37 | out1 = dec1 * X + (1 - dec1) * inputs[0]
38 | dec2 = tf.reshape(dec, [-1] + [1] * (len(inputs[1].shape) - 1))
39 | out2 = dec2 * y + (1 - dec2) * inputs[1]
40 | outputs = [out1, out2]
41 |
42 | # pick output corresponding to training phase
43 | return K.in_train_phase(outputs, inputs, training=training)
44 |
45 | def get_config(self):
46 | config = {
47 | 'prob': self.prob,
48 | 'alpha': self.alpha
49 | }
50 | base_config = super(MixupLayer, self).get_config()
51 | return dict(list(base_config.items()) + list(config.items()))
52 |
53 |
--------------------------------------------------------------------------------
/subcluster_adacos.py:
--------------------------------------------------------------------------------
1 | import math
2 | import tensorflow as tf
3 | import tensorflow_probability as tfp
4 | from tensorflow.keras import backend as K
5 |
6 |
7 | class SCAdaCos(tf.keras.layers.Layer):
8 | def __init__(self, n_classes=10, n_subclusters=1, regularizer=None, **kwargs):
9 | super(SCAdaCos, self).__init__(**kwargs)
10 | self.n_classes = n_classes
11 | self.n_subclusters = n_subclusters
12 | self.s_init = math.sqrt(2) * math.log(n_classes*n_subclusters - 1)
13 | self.regularizer = tf.keras.regularizers.get(regularizer)
14 |
15 | def build(self, input_shape):
16 | super(SCAdaCos, self).build(input_shape[0])
17 | self.W = self.add_weight(name='W_AdaCos' + str(self.n_classes) + '_' + str(self.n_subclusters),
18 | shape=(input_shape[0][-1], self.n_classes*self.n_subclusters),
19 | initializer='glorot_uniform',
20 | trainable=True,
21 | regularizer=self.regularizer)
22 | self.s = self.add_weight(name='s' + str(self.n_classes) + '_' + str(self.n_subclusters),
23 | shape=(),
24 | initializer=tf.keras.initializers.Constant(self.s_init),
25 | trainable=False,
26 | aggregation=tf.VariableAggregation.MEAN)
27 |
28 | def call(self, inputs, training=None):
29 | x, y1, y2 = inputs
30 | y1_orig = y1
31 | y1 = tf.repeat(y1, repeats=self.n_subclusters, axis=-1)
32 | y2 = tf.repeat(y2, repeats=self.n_subclusters, axis=-1)
33 | # normalize feature
34 | x = tf.nn.l2_normalize(x, axis=1)
35 | # normalize weights
36 | W = tf.nn.l2_normalize(self.W, axis=0)
37 | # dot product
38 | logits = x @ W # same as cos theta
39 | theta = tf.acos(K.clip(logits, -1.0 + K.epsilon(), 1.0 - K.epsilon()))
40 |
41 | if training:
42 | max_s_logits = tf.reduce_max(self.s * logits)
43 | B_avg = tf.exp(self.s*logits-max_s_logits)
44 | B_avg = tf.reduce_mean(tf.reduce_sum(B_avg, axis=1))
45 | theta_class = tf.reduce_sum(y1 * theta, axis=1) * tf.math.count_nonzero(y1_orig, axis=1, dtype=tf.dtypes.float32) # take mix-upped angle of mix-upped classes
46 | theta_med = tfp.stats.percentile(theta_class, q=50) # computes median
47 | self.s.assign(
48 | (max_s_logits + tf.math.log(B_avg)) /
49 | tf.math.cos(tf.minimum(math.pi / 4, theta_med)) + K.epsilon())
50 | logits *= self.s
51 | out = tf.keras.activations.softmax(logits)
52 | out = tf.reshape(out, (-1, self.n_classes, self.n_subclusters))
53 | out = tf.math.reduce_sum(out, axis=2)
54 | return out
55 |
56 | def compute_output_shape(self, input_shape):
57 | return (None, self.n_classes)
58 |
59 | def get_config(self):
60 | config = {
61 | 'n_classes': self.n_classes,
62 | 'regularizer': self.regularizer,
63 | 'n_subclusters': self.n_subclusters
64 | }
65 | base_config = super(SCAdaCos, self).get_config()
66 | return dict(list(base_config.items()) + list(config.items()))
--------------------------------------------------------------------------------