├── .gitignore
├── Calculations
├── SELU_calculations.nb
└── SELU_calculations.pdf
├── HTRU2
└── README.md
├── LICENSE
├── Pytorch
├── SelfNormalizingNetworks_CNN_CIFAR10.ipynb
├── SelfNormalizingNetworks_CNN_MNIST.ipynb
└── SelfNormalizingNetworks_MLP_MNIST.ipynb
├── README.md
├── SNN-successes
└── README.md
├── TF_1_x
├── README.md
├── SelfNormalizingNetworks_CNN_CIFAR10.ipynb
├── SelfNormalizingNetworks_CNN_MNIST.ipynb
├── SelfNormalizingNetworks_MLP_MNIST.ipynb
├── environment.yml
├── getSELUparameters.ipynb
└── selu.py
├── TF_2_x
├── CIFAR10-Conv-SELU.py
├── MNIST-Conv-SELU.py
├── MNIST-MLP-SELU.py
└── README.md
├── Tox21
└── README.md
├── UCI
└── README.md
├── environment.yml
└── figure1
├── README.md
├── create_plots.ipynb
├── run.py
└── utils.py
/.gitignore:
--------------------------------------------------------------------------------
1 | */.ipynb_checkpoints/*
2 | */checkpoints/*
3 | */data_set/*
4 | */saved_models/*
5 | */logs/*
--------------------------------------------------------------------------------
/Calculations/SELU_calculations.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bioinf-jku/SNNs/b578499301fcb801f8d4135dbd7cebb246722bfc/Calculations/SELU_calculations.pdf
--------------------------------------------------------------------------------
/HTRU2/README.md:
--------------------------------------------------------------------------------
1 | ## HTRU2 data set
2 | - [download](https://archive.ics.uci.edu/ml/machine-learning-databases/00372/HTRU2.zip)
3 |
--------------------------------------------------------------------------------
/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 | # Self-Normalizing Networks
2 | Tutorials and implementations for "Self-normalizing networks"(SNNs) as suggested by Klambauer et al. ([arXiv pre-print](https://arxiv.org/pdf/1706.02515.pdf)).
3 |
4 | ## Versions
5 | - see [environment](environment.yml) file for full list of prerequisites. Tutorial implementations use Tensorflow > 2.0 (Keras) or Pytorch, but versions for Tensorflow 1.x
6 | users based on the deprecated tf.contrib module (with separate [environment](TF_1_x/environment.yml) file) are also available.
7 |
8 | #### Note for Tensorflow >= 1.4 users
9 | Tensorflow >= 1.4 already has the function [tf.nn.selu](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/nn/selu) and [tf.contrib.nn.alpha_dropout](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/contrib/nn/alpha_dropout) that implement the SELU activation function and the suggested dropout version.
10 | #### Note for Tensorflow >= 2.0 users
11 | Tensorflow 2.3 already has selu activation function when using high level framework keras, [tf.keras.activations.selu](https://www.tensorflow.org/api_docs/python/tf/keras/activations/selu).
12 | Must be combined with [tf.keras.initializers.LecunNormal](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/LecunNormal), corresponding dropout version is [tf.keras.layers.AlphaDropout](https://www.tensorflow.org/api_docs/python/tf/keras/layers/AlphaDropout).
13 | #### Note for Pytorch users
14 | Pytorch versions >= 0.2 feature [torch.nn.SELU](https://pytorch.org/docs/stable/generated/torch.nn.SELU.html#torch.nn.SELU) and [torch.nn.AlphaDropout](https://pytorch.org/docs/stable/generated/torch.nn.AlphaDropout.html#torch.nn.AlphaDropout), they must be combined with the correct initializer, namely [torch.nn.init.kaiming_normal_](https://pytorch.org/docs/stable/nn.init.html#torch.nn.init.kaiming_normal_) (parameter, mode='fan_in', nonlinearity='linear')
15 | as this is identical to lecun initialisation (mode='fan_in') with a gain of 1 (nonlinearity='linear').
16 |
17 |
18 | ## Tutorials
19 |
20 | ### Tensorflow 1.x
21 | - Multilayer Perceptron on MNIST ([notebook](TF_1_x/SelfNormalizingNetworks_MLP_MNIST.ipynb))
22 | - Convolutional Neural Network on MNIST ([notebook](TF_1_x/SelfNormalizingNetworks_CNN_MNIST.ipynb))
23 | - Convolutional Neural Network on CIFAR10 ([notebook](TF_1_x/SelfNormalizingNetworks_CNN_CIFAR10.ipynb))
24 |
25 | ### Tensorflow 2.x (Keras)
26 | - Multilayer Perceptron on MNIST ([python script](TF_2_x/MNIST-MLP-SELU.py))
27 | - Convolutional Neural Network on MNIST ([python script](TF_2_x/MNIST-Conv-SELU.py))
28 | - Convolutional Neural Network on CIFAR10 ([python script](TF_2_x/CIFAR10-Conv-SELU.py))
29 |
30 | ### Pytorch
31 |
32 | - Multilayer Perceptron on MNIST ([notebook](Pytorch/SelfNormalizingNetworks_MLP_MNIST.ipynb))
33 | - Convolutional Neural Network on MNIST ([notebook](Pytorch/SelfNormalizingNetworks_CNN_MNIST.ipynb))
34 | - Convolutional Neural Network on CIFAR10 ([notebook](Pytorch/SelfNormalizingNetworks_CNN_CIFAR10.ipynb))
35 |
36 | ## Further material
37 |
38 | ### Design novel SELU functions (Tensorflow 1.x)
39 | - How to obtain the SELU parameters alpha and lambda for arbitrary fixed points ([notebook](TF_1_x/getSELUparameters.ipynb))
40 |
41 | ### Basic python functions to implement SNNs (Tensorflow 1.x)
42 | are provided as code chunks here: [selu.py](TF_1_x/selu.py)
43 |
44 | ### Notebooks and code to produce Figure 1 (Tensorflow 1.x)
45 | are provided here: [Figure1](figure1/), builds on top of the [biutils](https://github.com/untom/biutils) package.
46 |
47 | ### Calculations and numeric checks of the theorems (Mathematica)
48 | are provided as mathematica notebooks here:
49 |
50 | - [Mathematica notebook](Calculations/SELU_calculations.nb)
51 | - [Mathematica PDF](Calculations/SELU_calculations.pdf)
52 |
53 | ### UCI, Tox21 and HTRU2 data sets
54 |
55 | - [UCI](http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz)
56 | - [Tox21](http://bioinf.jku.at/research/DeepTox/tox21.zip)
57 | - [HTRU2](https://archive.ics.uci.edu/ml/machine-learning-databases/00372/HTRU2.zip)
58 |
--------------------------------------------------------------------------------
/SNN-successes/README.md:
--------------------------------------------------------------------------------
1 | # Models and architectures built on Self-Normalizing Networks
2 |
3 | ## GANs
4 | - [THINKING LIKE A MACHINE - GENERATING VISUAL RATIONALES WITH WASSERSTEIN GANS](https://pdfs.semanticscholar.org/dd4c/23a21b1199f34e5003e26d2171d02ba12d45.pdf): Both discriminator and generator trained without batch normalization.
5 | - [Deformable Deep Convolutional Generative Adversarial Network in Microwave Based Hand Gesture Recognition System](https://arxiv.org/abs/1711.01968):
6 | The rate between SELU and SELU+BN proves that SELU itself has the convergence quality of BN.
7 |
8 | ## Convolutional neural networks
9 | - [Effectiveness of Self Normalizing Neural Networks for Text Classification](https://arxiv.org/abs/1905.01338): Applied properties of SNN to CNN to give rise to new arechitecture SCNN (Self normalizaing CNN) which performed better than CNN in text classification.
10 | - [Solving internal covariate shift in deep learning with linked neurons](https://arxiv.org/abs/1712.02609): Show that ultra-deep CNNs without batch normalization can only be trained SELUs (except with the suggested method described by the authors).
11 | - [DCASE 2017 ACOUSTIC SCENE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK IN TIME SERIES](http://www.cs.tut.fi/sgn/arg/dcase2017/documents/challenge_technical_reports/DCASE2017_Biho_116.pdf): Deep CNN trained without batch normalization.
12 | - [Point-wise Convolutional Neural Network](https://arxiv.org/abs/1712.05245): Training with SELU converges faster than training with ReLU; improved accuracy with SELU.
13 | - [Over the Air Deep Learning Based Radio Signal Classification](https://arxiv.org/abs/1712.04578): Slight performance improvement over ReLU.
14 | - [Convolutional neural networks for structured omics: OmicsCNN and the OmicsConv layer](https://arxiv.org/abs/1710.05918): Deep CNN trained without batch normalization.
15 | - [Searching for Activation Functions](https://arxiv.org/abs/1710.05941): ResNet architectures trained with SELUs probably together with batch normalization.
16 | - [EddyNet: A Deep Neural Network For Pixel-Wise Classification of Oceanic Eddies](https://arxiv.org/abs/1711.03954): Fast CNN training with SELUs. ReLU with BN better at final performance but skip connections not handled appropriately.
17 | - [SMILES2Vec: An Interpretable General-Purpose Deep Neural Network for Predicting Chemical Properties](https://arxiv.org/abs/1712.02034): 20-layer ResNet trained with SELUs.
18 | - [Sentiment Analysis of Tweets in Malayalam Using Long Short-Term Memory Units and Convolutional Neural Nets](https://link.springer.com/chapter/10.1007/978-3-319-71928-3_31)
19 | - [RETUYT in TASS 2017: Sentiment Analysis for Spanish Tweets using SVM and CNN](https://arxiv.org/abs/1710.06393)
20 |
21 |
22 | ## FNNs are finally deep
23 | - [Predicting Adolescent Suicide Attempts with Neural Networks](https://arxiv.org/abs/1711.10057): The use of the SELU activation renders batch normalization
24 | unnecessary.
25 | - [Improving Palliative Care with Deep Learning](https://arxiv.org/abs/1711.06402): An 18-layer neural network with SELUs performed best.
26 | - [An Iterative Closest Points Approach to Neural Generative Models](https://arxiv.org/abs/1711.06562)
27 | - [Retrieval of Surface Ozone from UV-MFRSR Irradiances using Deep Learning](http://uvb.nrel.colostate.edu/UVB/publications/AGU-Retrieval-Surface-Ozone-Deep-Learning.pdf): 6-10 layer networks perform best.
28 |
29 |
30 | ## Reinforcement Learning
31 | - [Automated Cloud Provisioning on AWS using Deep Reinforcement Learning](https://arxiv.org/abs/1709.04305): Deep CNN architecture trained with SELUs.
32 | - [Learning to Run with Actor-Critic Ensemble](https://arxiv.org/abs/1712.08987): Second best method (actor-critic ensemble) at the NIPS2017 "Learning to Run" competition. They have
33 | tried several activation functions and found that the activation function of Scaled Exponential Linear Units (SELU) are superior to ReLU, Leaky ReLU, Tanh and Sigmoid.
34 |
35 | ## Autoencoders
36 | - [Replacement AutoEncoder: A Privacy-Preserving Algorithm for Sensory Data Analysis](https://arxiv.org/abs/1710.06564): Deep autoencoder trained with SELUs.
37 | - [Application of generative autoencoder in de novo molecular design](https://arxiv.org/abs/1711.07839): Faster convergence with SELUs.
38 |
39 | ## Recurrent Neural Networks
40 | - [Sentiment extraction from Consumer-generated noisy short texts](http://sentic.net/sentire2017meisheri.pdf): SNNs used in FC layers.
41 |
42 |
43 |
--------------------------------------------------------------------------------
/TF_1_x/README.md:
--------------------------------------------------------------------------------
1 | Tensorflow 1.15 version if you happen to work on Tensorflow versions < 2.
2 | Full list of prerequisites is to be found in [environment](environment.yml) file.
--------------------------------------------------------------------------------
/TF_1_x/SelfNormalizingNetworks_CNN_MNIST.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "collapsed": false
7 | },
8 | "source": [
9 | "# Tutorial on self-normalizing networks on the MNIST data set: convolutional neural networks\n",
10 | "\n",
11 | "*Author:* Guenter Klambauer, 2017\n",
12 | "\n",
13 | "Derived from: [Aymeric Damien](https://github.com/aymericdamien/TensorFlow-Examples/) "
14 | ]
15 | },
16 | {
17 | "cell_type": "code",
18 | "execution_count": 1,
19 | "metadata": {
20 | "collapsed": false
21 | },
22 | "outputs": [
23 | {
24 | "name": "stdout",
25 | "output_type": "stream",
26 | "text": [
27 | "WARNING:tensorflow:From :17: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
28 | "Instructions for updating:\n",
29 | "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
30 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
31 | "Instructions for updating:\n",
32 | "Please write your own downloading logic.\n",
33 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
34 | "Instructions for updating:\n",
35 | "Please use tf.data to implement this functionality.\n",
36 | "Extracting /tmp/data/train-images-idx3-ubyte.gz\n",
37 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
38 | "Instructions for updating:\n",
39 | "Please use tf.data to implement this functionality.\n",
40 | "Extracting /tmp/data/train-labels-idx1-ubyte.gz\n",
41 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
42 | "Instructions for updating:\n",
43 | "Please use tf.one_hot on tensors.\n",
44 | "Extracting /tmp/data/t10k-images-idx3-ubyte.gz\n",
45 | "Extracting /tmp/data/t10k-labels-idx1-ubyte.gz\n",
46 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
47 | "Instructions for updating:\n",
48 | "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
49 | "1.15.0\n"
50 | ]
51 | }
52 | ],
53 | "source": [
54 | "import tensorflow as tf\n",
55 | "import numpy as np\n",
56 | "\n",
57 | "import numbers\n",
58 | "from tensorflow.python.framework import ops\n",
59 | "from tensorflow.python.framework import tensor_shape\n",
60 | "from tensorflow.python.framework import tensor_util\n",
61 | "from tensorflow.python.ops import math_ops\n",
62 | "from tensorflow.python.ops import random_ops\n",
63 | "from tensorflow.python.ops import array_ops\n",
64 | "from tensorflow.python.layers import utils\n",
65 | "\n",
66 | "from sklearn.preprocessing import StandardScaler\n",
67 | "\n",
68 | "# Import MNIST data\n",
69 | "from tensorflow.examples.tutorials.mnist import input_data\n",
70 | "mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n",
71 | "\n",
72 | "print(tf.__version__)"
73 | ]
74 | },
75 | {
76 | "cell_type": "markdown",
77 | "metadata": {},
78 | "source": [
79 | "### (1) Definition of scaled exponential linear units (SELUs)"
80 | ]
81 | },
82 | {
83 | "cell_type": "code",
84 | "execution_count": 2,
85 | "metadata": {
86 | "collapsed": true
87 | },
88 | "outputs": [],
89 | "source": [
90 | "def selu(x):\n",
91 | " with ops.name_scope('elu') as scope:\n",
92 | " alpha = 1.6732632423543772848170429916717\n",
93 | " scale = 1.0507009873554804934193349852946\n",
94 | " return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))"
95 | ]
96 | },
97 | {
98 | "cell_type": "markdown",
99 | "metadata": {},
100 | "source": [
101 | "### (2) Definition of dropout variant for SNNs\n"
102 | ]
103 | },
104 | {
105 | "cell_type": "code",
106 | "execution_count": 3,
107 | "metadata": {
108 | "collapsed": true
109 | },
110 | "outputs": [],
111 | "source": [
112 | "def dropout_selu(x, rate, alpha= -1.7580993408473766, fixedPointMean=0.0, fixedPointVar=1.0, \n",
113 | " noise_shape=None, seed=None, name=None, training=False):\n",
114 | " \"\"\"Dropout to a value with rescaling.\"\"\"\n",
115 | "\n",
116 | " def dropout_selu_impl(x, rate, alpha, noise_shape, seed, name):\n",
117 | " keep_prob = 1.0 - rate\n",
118 | " x = ops.convert_to_tensor(x, name=\"x\")\n",
119 | " if isinstance(keep_prob, numbers.Real) and not 0 < keep_prob <= 1:\n",
120 | " raise ValueError(\"keep_prob must be a scalar tensor or a float in the \"\n",
121 | " \"range (0, 1], got %g\" % keep_prob)\n",
122 | " keep_prob = ops.convert_to_tensor(keep_prob, dtype=x.dtype, name=\"keep_prob\")\n",
123 | " keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())\n",
124 | "\n",
125 | " alpha = ops.convert_to_tensor(alpha, dtype=x.dtype, name=\"alpha\")\n",
126 | " keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())\n",
127 | "\n",
128 | " if tensor_util.constant_value(keep_prob) == 1:\n",
129 | " return x\n",
130 | "\n",
131 | " noise_shape = noise_shape if noise_shape is not None else array_ops.shape(x)\n",
132 | " random_tensor = keep_prob\n",
133 | " random_tensor += random_ops.random_uniform(noise_shape, seed=seed, dtype=x.dtype)\n",
134 | " binary_tensor = math_ops.floor(random_tensor)\n",
135 | " ret = x * binary_tensor + alpha * (1-binary_tensor)\n",
136 | "\n",
137 | " a = tf.sqrt(fixedPointVar / (keep_prob *((1-keep_prob) * tf.pow(alpha-fixedPointMean,2) + fixedPointVar)))\n",
138 | "\n",
139 | " b = fixedPointMean - a * (keep_prob * fixedPointMean + (1 - keep_prob) * alpha)\n",
140 | " ret = a * ret + b\n",
141 | " ret.set_shape(x.get_shape())\n",
142 | " return ret\n",
143 | "\n",
144 | " with ops.name_scope(name, \"dropout\", [x]) as name:\n",
145 | " return utils.smart_cond(training,\n",
146 | " lambda: dropout_selu_impl(x, rate, alpha, noise_shape, seed, name),\n",
147 | " lambda: array_ops.identity(x))\n"
148 | ]
149 | },
150 | {
151 | "cell_type": "markdown",
152 | "metadata": {},
153 | "source": [
154 | "### (3) Scale input to zero mean and unit variance"
155 | ]
156 | },
157 | {
158 | "cell_type": "code",
159 | "execution_count": 4,
160 | "metadata": {
161 | "collapsed": false
162 | },
163 | "outputs": [],
164 | "source": [
165 | "scaler = StandardScaler().fit(mnist.train.images)"
166 | ]
167 | },
168 | {
169 | "cell_type": "code",
170 | "execution_count": 5,
171 | "metadata": {
172 | "collapsed": true
173 | },
174 | "outputs": [],
175 | "source": [
176 | "# Parameters\n",
177 | "learning_rate = 0.025\n",
178 | "training_iters = 50\n",
179 | "batch_size = 128\n",
180 | "display_step = 1\n",
181 | "\n",
182 | "# Network Parameters\n",
183 | "n_input = 784 # MNIST data input (img shape: 28*28)\n",
184 | "n_classes = 10 # MNIST total classes (0-9 digits)\n",
185 | "keep_prob_ReLU = 0.5 # Dropout, probability to keep units\n",
186 | "dropout_prob_SNN = 0.05 # Dropout, probability to dropout units\n",
187 | "\n",
188 | "# tf Graph input\n",
189 | "x = tf.placeholder(tf.float32, [None, n_input])\n",
190 | "y = tf.placeholder(tf.float32, [None, n_classes])\n",
191 | "keep_prob = tf.placeholder(tf.float32) #dropout (keep probability for ReLU)\n",
192 | "dropout_prob = tf.placeholder(tf.float32) #dropout (dropout probability for SNN)\n",
193 | "is_training = tf.placeholder(tf.bool)"
194 | ]
195 | },
196 | {
197 | "cell_type": "code",
198 | "execution_count": 6,
199 | "metadata": {
200 | "collapsed": true
201 | },
202 | "outputs": [],
203 | "source": [
204 | "# Create some wrappers for simplicity\n",
205 | "def conv2d(x, W, b, strides=1):\n",
206 | " # Conv2D wrapper, with bias and relu activation\n",
207 | " x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n",
208 | " x = tf.nn.bias_add(x, b)\n",
209 | " return tf.nn.relu(x)\n",
210 | "\n",
211 | "def conv2d_SNN(x, W, b, strides=1):\n",
212 | " # Conv2D wrapper, with bias and relu activation\n",
213 | " x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n",
214 | " x = tf.nn.bias_add(x, b)\n",
215 | " return selu(x)\n",
216 | "\n",
217 | "def maxpool2d(x, k=2):\n",
218 | " # MaxPool2D wrapper\n",
219 | " return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],\n",
220 | " padding='SAME')"
221 | ]
222 | },
223 | {
224 | "cell_type": "code",
225 | "execution_count": 7,
226 | "metadata": {
227 | "collapsed": true
228 | },
229 | "outputs": [],
230 | "source": [
231 | "# Create model\n",
232 | "def conv_net_ReLU(x, weights, biases, keep_prob):\n",
233 | " # Reshape input picture\n",
234 | " x = tf.reshape(x, shape=[-1, 28, 28, 1])\n",
235 | "\n",
236 | " # Convolution Layer\n",
237 | " conv1 = conv2d(x, weights['wc1'], biases['bc1'])\n",
238 | " # Max Pooling (down-sampling)\n",
239 | " conv1 = maxpool2d(conv1, k=2)\n",
240 | "\n",
241 | " # Convolution Layer\n",
242 | " conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])\n",
243 | " # Max Pooling (down-sampling)\n",
244 | " conv2 = maxpool2d(conv2, k=2)\n",
245 | "\n",
246 | " # Fully connected layer\n",
247 | " # Reshape conv2 output to fit fully connected layer input\n",
248 | " fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])\n",
249 | " fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n",
250 | " fc1 = tf.nn.relu(fc1)\n",
251 | " \n",
252 | " # Apply Dropout\n",
253 | " fc1 = tf.nn.dropout(fc1, keep_prob)\n",
254 | "\n",
255 | " # Output, class prediction\n",
256 | " out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n",
257 | " return out"
258 | ]
259 | },
260 | {
261 | "cell_type": "code",
262 | "execution_count": 8,
263 | "metadata": {
264 | "collapsed": true
265 | },
266 | "outputs": [],
267 | "source": [
268 | "# Create model\n",
269 | "def conv_net_SNN(x, weights, biases, dropout_prob, is_training):\n",
270 | " # Reshape input picture\n",
271 | " x = tf.reshape(x, shape=[-1, 28, 28, 1])\n",
272 | "\n",
273 | " # Convolution Layer\n",
274 | " conv1 = conv2d_SNN(x, weights['wc1'], biases['bc1'],)\n",
275 | " # Max Pooling (down-sampling)\n",
276 | " conv1 = maxpool2d(conv1, k=2)\n",
277 | "\n",
278 | " # Convolution Layer\n",
279 | " conv2 = conv2d_SNN(conv1, weights['wc2'], biases['bc2'])\n",
280 | " # Max Pooling (down-sampling)\n",
281 | " conv2 = maxpool2d(conv2, k=2)\n",
282 | "\n",
283 | " # Fully connected layer\n",
284 | " # Reshape conv2 output to fit fully connected layer input\n",
285 | " fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])\n",
286 | " fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n",
287 | " fc1 = selu(fc1)\n",
288 | " \n",
289 | " # Apply Dropout\n",
290 | " fc1 = dropout_selu(fc1, dropout_prob,training=is_training)\n",
291 | "\n",
292 | " # Output, class prediction\n",
293 | " out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n",
294 | " return out"
295 | ]
296 | },
297 | {
298 | "cell_type": "code",
299 | "execution_count": 9,
300 | "metadata": {
301 | "collapsed": true
302 | },
303 | "outputs": [],
304 | "source": [
305 | "# RELU: Store layers weight & bias\n",
306 | "## Improved with MSRA initialization\n",
307 | "\n",
308 | "weights = {\n",
309 | " # 5x5 conv, 1 input, 32 outputs\n",
310 | " 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32],stddev=np.sqrt(2/25)) ),\n",
311 | " # 5x5 conv, 32 inputs, 64 outputs\n",
312 | " 'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64],stddev=np.sqrt(2/(25*32)))),\n",
313 | " # fully connected, 7*7*64 inputs, 1024 outputs\n",
314 | " 'wd1': tf.Variable(tf.random_normal([7*7*64, 1024],stddev=np.sqrt(2/(7*7*64)))),\n",
315 | " # 1024 inputs, 10 outputs (class prediction)\n",
316 | " 'out': tf.Variable(tf.random_normal([1024, n_classes],stddev=np.sqrt(2/(1024))))\n",
317 | "}\n",
318 | "\n",
319 | "biases = {\n",
320 | " 'bc1': tf.Variable(tf.random_normal([32],stddev=0)),\n",
321 | " 'bc2': tf.Variable(tf.random_normal([64],stddev=0)),\n",
322 | " 'bd1': tf.Variable(tf.random_normal([1024],stddev=0)),\n",
323 | " 'out': tf.Variable(tf.random_normal([n_classes],stddev=0))\n",
324 | "}"
325 | ]
326 | },
327 | {
328 | "cell_type": "markdown",
329 | "metadata": {},
330 | "source": [
331 | "### (4) Initialization with STDDEV of sqrt(1/n)"
332 | ]
333 | },
334 | {
335 | "cell_type": "code",
336 | "execution_count": 10,
337 | "metadata": {
338 | "collapsed": false
339 | },
340 | "outputs": [],
341 | "source": [
342 | "# SNN: Store layers weight & bias\n",
343 | "weights2 = {\n",
344 | " # 5x5 conv, 1 input, 32 outputs\n",
345 | " 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32],stddev=np.sqrt(1/25)) ),\n",
346 | " # 5x5 conv, 32 inputs, 64 outputs\n",
347 | " 'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64],stddev=np.sqrt(1/(25*32)))),\n",
348 | " # fully connected, 7*7*64 inputs, 1024 outputs\n",
349 | " 'wd1': tf.Variable(tf.random_normal([7*7*64, 1024],stddev=np.sqrt(1/(7*7*64)))),\n",
350 | " # 1024 inputs, 10 outputs (class prediction)\n",
351 | " 'out': tf.Variable(tf.random_normal([1024, n_classes],stddev=np.sqrt(1/(1024))))\n",
352 | "}\n",
353 | "\n",
354 | "biases2 = {\n",
355 | " 'bc1': tf.Variable(tf.random_normal([32],stddev=0)),\n",
356 | " 'bc2': tf.Variable(tf.random_normal([64],stddev=0)),\n",
357 | " 'bd1': tf.Variable(tf.random_normal([1024],stddev=0)),\n",
358 | " 'out': tf.Variable(tf.random_normal([n_classes],stddev=0))\n",
359 | "}\n"
360 | ]
361 | },
362 | {
363 | "cell_type": "code",
364 | "execution_count": 11,
365 | "metadata": {
366 | "collapsed": false
367 | },
368 | "outputs": [
369 | {
370 | "name": "stdout",
371 | "output_type": "stream",
372 | "text": [
373 | "WARNING:tensorflow:From :23: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\n",
374 | "Instructions for updating:\n",
375 | "Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n",
376 | "WARNING:tensorflow:From :5: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
377 | "Instructions for updating:\n",
378 | "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
379 | "WARNING:tensorflow:From :12: scalar (from tensorflow.python.framework.tensor_shape) is deprecated and will be removed in a future version.\n",
380 | "Instructions for updating:\n",
381 | "Use tf.TensorShape([]).\n",
382 | "WARNING:tensorflow:From :6: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
383 | "Instructions for updating:\n",
384 | "\n",
385 | "Future major versions of TensorFlow will allow gradients to flow\n",
386 | "into the labels input on backprop by default.\n",
387 | "\n",
388 | "See `tf.nn.softmax_cross_entropy_with_logits_v2`.\n",
389 | "\n"
390 | ]
391 | }
392 | ],
393 | "source": [
394 | "# Construct model\n",
395 | "pred_ReLU = conv_net_ReLU(x, weights, biases, keep_prob)\n",
396 | "pred_SNN = conv_net_SNN(x, weights2, biases2, dropout_prob,is_training)\n",
397 | "\n",
398 | "# Define loss and optimizer\n",
399 | "cost_ReLU = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred_ReLU, labels=y))\n",
400 | "cost_SNN = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred_SNN, labels=y))\n",
401 | "\n",
402 | "optimizer_ReLU = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost_ReLU)\n",
403 | "optimizer_SNN = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost_SNN)\n",
404 | "\n",
405 | "# Evaluate ReLU model\n",
406 | "correct_pred_ReLU = tf.equal(tf.argmax(pred_ReLU, 1), tf.argmax(y, 1))\n",
407 | "accuracy_ReLU = tf.reduce_mean(tf.cast(correct_pred_ReLU, tf.float32))\n",
408 | "\n",
409 | "# Evaluate SNN model\n",
410 | "correct_pred_SNN = tf.equal(tf.argmax(pred_SNN, 1), tf.argmax(y, 1))\n",
411 | "accuracy_SNN = tf.reduce_mean(tf.cast(correct_pred_SNN, tf.float32))\n",
412 | "\n",
413 | "\n",
414 | "# Initializing the variables\n",
415 | "init = tf.global_variables_initializer()"
416 | ]
417 | },
418 | {
419 | "cell_type": "code",
420 | "execution_count": 12,
421 | "metadata": {
422 | "collapsed": true
423 | },
424 | "outputs": [],
425 | "source": [
426 | "training_loss_protocol_ReLU = []\n",
427 | "training_loss_protocol_SNN = []"
428 | ]
429 | },
430 | {
431 | "cell_type": "code",
432 | "execution_count": 13,
433 | "metadata": {
434 | "collapsed": false
435 | },
436 | "outputs": [
437 | {
438 | "name": "stdout",
439 | "output_type": "stream",
440 | "text": [
441 | "RELU: Nbr of updates: 1, Minibatch Loss= 2.529600, Training Accuracy= 0.14062\n",
442 | "SNN: Nbr of updates: 1, Minibatch Loss= 2.043923, Training Accuracy= 0.51562\n",
443 | "RELU: Nbr of updates: 2, Minibatch Loss= 2.308014, Training Accuracy= 0.26562\n",
444 | "SNN: Nbr of updates: 2, Minibatch Loss= 1.727961, Training Accuracy= 0.51562\n",
445 | "RELU: Nbr of updates: 3, Minibatch Loss= 2.068156, Training Accuracy= 0.38281\n",
446 | "SNN: Nbr of updates: 3, Minibatch Loss= 1.357726, Training Accuracy= 0.64844\n",
447 | "RELU: Nbr of updates: 4, Minibatch Loss= 1.670266, Training Accuracy= 0.62500\n",
448 | "SNN: Nbr of updates: 4, Minibatch Loss= 0.805312, Training Accuracy= 0.77344\n",
449 | "RELU: Nbr of updates: 5, Minibatch Loss= 1.599183, Training Accuracy= 0.67969\n",
450 | "SNN: Nbr of updates: 5, Minibatch Loss= 0.634932, Training Accuracy= 0.85156\n",
451 | "RELU: Nbr of updates: 6, Minibatch Loss= 1.444664, Training Accuracy= 0.71094\n",
452 | "SNN: Nbr of updates: 6, Minibatch Loss= 0.472679, Training Accuracy= 0.85156\n",
453 | "RELU: Nbr of updates: 7, Minibatch Loss= 1.424880, Training Accuracy= 0.75000\n",
454 | "SNN: Nbr of updates: 7, Minibatch Loss= 0.443895, Training Accuracy= 0.86719\n",
455 | "RELU: Nbr of updates: 8, Minibatch Loss= 1.238384, Training Accuracy= 0.70312\n",
456 | "SNN: Nbr of updates: 8, Minibatch Loss= 0.433366, Training Accuracy= 0.87500\n",
457 | "RELU: Nbr of updates: 9, Minibatch Loss= 1.223281, Training Accuracy= 0.74219\n",
458 | "SNN: Nbr of updates: 9, Minibatch Loss= 0.446125, Training Accuracy= 0.91406\n",
459 | "RELU: Nbr of updates: 10, Minibatch Loss= 1.126184, Training Accuracy= 0.82812\n",
460 | "SNN: Nbr of updates: 10, Minibatch Loss= 0.353353, Training Accuracy= 0.92188\n",
461 | "RELU: Nbr of updates: 11, Minibatch Loss= 0.945392, Training Accuracy= 0.83594\n",
462 | "SNN: Nbr of updates: 11, Minibatch Loss= 0.323721, Training Accuracy= 0.91406\n",
463 | "RELU: Nbr of updates: 12, Minibatch Loss= 1.061059, Training Accuracy= 0.72656\n",
464 | "SNN: Nbr of updates: 12, Minibatch Loss= 0.319183, Training Accuracy= 0.91406\n",
465 | "RELU: Nbr of updates: 13, Minibatch Loss= 1.053779, Training Accuracy= 0.71094\n",
466 | "SNN: Nbr of updates: 13, Minibatch Loss= 0.341918, Training Accuracy= 0.90625\n",
467 | "RELU: Nbr of updates: 14, Minibatch Loss= 0.861647, Training Accuracy= 0.82031\n",
468 | "SNN: Nbr of updates: 14, Minibatch Loss= 0.247850, Training Accuracy= 0.94531\n",
469 | "RELU: Nbr of updates: 15, Minibatch Loss= 0.859886, Training Accuracy= 0.85938\n",
470 | "SNN: Nbr of updates: 15, Minibatch Loss= 0.300610, Training Accuracy= 0.91406\n",
471 | "RELU: Nbr of updates: 16, Minibatch Loss= 0.803375, Training Accuracy= 0.82031\n",
472 | "SNN: Nbr of updates: 16, Minibatch Loss= 0.233539, Training Accuracy= 0.96094\n",
473 | "RELU: Nbr of updates: 17, Minibatch Loss= 0.770378, Training Accuracy= 0.85156\n",
474 | "SNN: Nbr of updates: 17, Minibatch Loss= 0.292139, Training Accuracy= 0.90625\n",
475 | "RELU: Nbr of updates: 18, Minibatch Loss= 0.703464, Training Accuracy= 0.81250\n",
476 | "SNN: Nbr of updates: 18, Minibatch Loss= 0.214945, Training Accuracy= 0.96094\n",
477 | "RELU: Nbr of updates: 19, Minibatch Loss= 0.667796, Training Accuracy= 0.90625\n",
478 | "SNN: Nbr of updates: 19, Minibatch Loss= 0.267386, Training Accuracy= 0.92969\n",
479 | "RELU: Nbr of updates: 20, Minibatch Loss= 0.739539, Training Accuracy= 0.82812\n",
480 | "SNN: Nbr of updates: 20, Minibatch Loss= 0.301252, Training Accuracy= 0.92188\n",
481 | "RELU: Nbr of updates: 21, Minibatch Loss= 0.712775, Training Accuracy= 0.82031\n",
482 | "SNN: Nbr of updates: 21, Minibatch Loss= 0.229995, Training Accuracy= 0.94531\n",
483 | "RELU: Nbr of updates: 22, Minibatch Loss= 0.668107, Training Accuracy= 0.83594\n",
484 | "SNN: Nbr of updates: 22, Minibatch Loss= 0.302777, Training Accuracy= 0.92188\n",
485 | "RELU: Nbr of updates: 23, Minibatch Loss= 0.662650, Training Accuracy= 0.80469\n",
486 | "SNN: Nbr of updates: 23, Minibatch Loss= 0.277247, Training Accuracy= 0.91406\n",
487 | "RELU: Nbr of updates: 24, Minibatch Loss= 0.751235, Training Accuracy= 0.82031\n",
488 | "SNN: Nbr of updates: 24, Minibatch Loss= 0.312389, Training Accuracy= 0.89844\n",
489 | "RELU: Nbr of updates: 25, Minibatch Loss= 0.610983, Training Accuracy= 0.85938\n",
490 | "SNN: Nbr of updates: 25, Minibatch Loss= 0.230509, Training Accuracy= 0.93750\n",
491 | "RELU: Nbr of updates: 26, Minibatch Loss= 0.598711, Training Accuracy= 0.85156\n",
492 | "SNN: Nbr of updates: 26, Minibatch Loss= 0.257897, Training Accuracy= 0.92969\n",
493 | "RELU: Nbr of updates: 27, Minibatch Loss= 0.649527, Training Accuracy= 0.82031\n",
494 | "SNN: Nbr of updates: 27, Minibatch Loss= 0.225033, Training Accuracy= 0.92969\n",
495 | "RELU: Nbr of updates: 28, Minibatch Loss= 0.513970, Training Accuracy= 0.92188\n",
496 | "SNN: Nbr of updates: 28, Minibatch Loss= 0.170374, Training Accuracy= 0.94531\n",
497 | "RELU: Nbr of updates: 29, Minibatch Loss= 0.548257, Training Accuracy= 0.83594\n",
498 | "SNN: Nbr of updates: 29, Minibatch Loss= 0.211176, Training Accuracy= 0.92188\n",
499 | "RELU: Nbr of updates: 30, Minibatch Loss= 0.541867, Training Accuracy= 0.88281\n",
500 | "SNN: Nbr of updates: 30, Minibatch Loss= 0.221660, Training Accuracy= 0.96094\n",
501 | "RELU: Nbr of updates: 31, Minibatch Loss= 0.485644, Training Accuracy= 0.89844\n",
502 | "SNN: Nbr of updates: 31, Minibatch Loss= 0.212724, Training Accuracy= 0.92188\n",
503 | "RELU: Nbr of updates: 32, Minibatch Loss= 0.450281, Training Accuracy= 0.85938\n",
504 | "SNN: Nbr of updates: 32, Minibatch Loss= 0.169182, Training Accuracy= 0.96094\n",
505 | "RELU: Nbr of updates: 33, Minibatch Loss= 0.633430, Training Accuracy= 0.75000\n",
506 | "SNN: Nbr of updates: 33, Minibatch Loss= 0.212616, Training Accuracy= 0.96875\n",
507 | "RELU: Nbr of updates: 34, Minibatch Loss= 0.477125, Training Accuracy= 0.89062\n",
508 | "SNN: Nbr of updates: 34, Minibatch Loss= 0.202256, Training Accuracy= 0.96094\n",
509 | "RELU: Nbr of updates: 35, Minibatch Loss= 0.549391, Training Accuracy= 0.82812\n",
510 | "SNN: Nbr of updates: 35, Minibatch Loss= 0.310254, Training Accuracy= 0.89844\n",
511 | "RELU: Nbr of updates: 36, Minibatch Loss= 0.368259, Training Accuracy= 0.90625\n",
512 | "SNN: Nbr of updates: 36, Minibatch Loss= 0.153444, Training Accuracy= 0.93750\n",
513 | "RELU: Nbr of updates: 37, Minibatch Loss= 0.492477, Training Accuracy= 0.86719\n",
514 | "SNN: Nbr of updates: 37, Minibatch Loss= 0.211344, Training Accuracy= 0.93750\n",
515 | "RELU: Nbr of updates: 38, Minibatch Loss= 0.556713, Training Accuracy= 0.87500\n",
516 | "SNN: Nbr of updates: 38, Minibatch Loss= 0.203756, Training Accuracy= 0.95312\n",
517 | "RELU: Nbr of updates: 39, Minibatch Loss= 0.442008, Training Accuracy= 0.88281\n",
518 | "SNN: Nbr of updates: 39, Minibatch Loss= 0.194691, Training Accuracy= 0.94531\n",
519 | "RELU: Nbr of updates: 40, Minibatch Loss= 0.427592, Training Accuracy= 0.90625\n",
520 | "SNN: Nbr of updates: 40, Minibatch Loss= 0.226508, Training Accuracy= 0.91406\n",
521 | "RELU: Nbr of updates: 41, Minibatch Loss= 0.598306, Training Accuracy= 0.82812\n",
522 | "SNN: Nbr of updates: 41, Minibatch Loss= 0.207904, Training Accuracy= 0.93750\n",
523 | "RELU: Nbr of updates: 42, Minibatch Loss= 0.551276, Training Accuracy= 0.85938\n",
524 | "SNN: Nbr of updates: 42, Minibatch Loss= 0.198079, Training Accuracy= 0.94531\n",
525 | "RELU: Nbr of updates: 43, Minibatch Loss= 0.404157, Training Accuracy= 0.89844\n",
526 | "SNN: Nbr of updates: 43, Minibatch Loss= 0.127414, Training Accuracy= 0.98438\n",
527 | "RELU: Nbr of updates: 44, Minibatch Loss= 0.368151, Training Accuracy= 0.93750\n",
528 | "SNN: Nbr of updates: 44, Minibatch Loss= 0.153246, Training Accuracy= 0.96875\n",
529 | "RELU: Nbr of updates: 45, Minibatch Loss= 0.461047, Training Accuracy= 0.88281\n",
530 | "SNN: Nbr of updates: 45, Minibatch Loss= 0.242575, Training Accuracy= 0.92969\n",
531 | "RELU: Nbr of updates: 46, Minibatch Loss= 0.456105, Training Accuracy= 0.89844\n",
532 | "SNN: Nbr of updates: 46, Minibatch Loss= 0.231932, Training Accuracy= 0.93750\n",
533 | "RELU: Nbr of updates: 47, Minibatch Loss= 0.414762, Training Accuracy= 0.89062\n",
534 | "SNN: Nbr of updates: 47, Minibatch Loss= 0.234552, Training Accuracy= 0.95312\n",
535 | "RELU: Nbr of updates: 48, Minibatch Loss= 0.371672, Training Accuracy= 0.90625\n",
536 | "SNN: Nbr of updates: 48, Minibatch Loss= 0.172536, Training Accuracy= 0.96094\n",
537 | "RELU: Nbr of updates: 49, Minibatch Loss= 0.396432, Training Accuracy= 0.91406\n",
538 | "SNN: Nbr of updates: 49, Minibatch Loss= 0.162846, Training Accuracy= 0.95312\n",
539 | "RELU: Nbr of updates: 50, Minibatch Loss= 0.281247, Training Accuracy= 0.96875\n",
540 | "SNN: Nbr of updates: 50, Minibatch Loss= 0.125570, Training Accuracy= 0.97656\n",
541 | "Optimization Finished!\n",
542 | "\n",
543 | "ReLU: Testing Accuracy: 0.8339844\n",
544 | "SNN: Testing Accuracy: 0.9140625\n"
545 | ]
546 | }
547 | ],
548 | "source": [
549 | "# Launch the graph\n",
550 | "gpu_options = tf.GPUOptions(allow_growth=True)\n",
551 | "with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n",
552 | " sess.run(init)\n",
553 | " step = 0\n",
554 | " # Keep training until reach max iterations\n",
555 | " while step < training_iters:\n",
556 | " batch_x, batch_y = mnist.train.next_batch(batch_size)\n",
557 | " batch_x_norm = scaler.transform(batch_x)\n",
558 | " # Run optimization op (backprop)\n",
559 | " sess.run(optimizer_ReLU, feed_dict={x: batch_x, y: batch_y,\n",
560 | " keep_prob: keep_prob_ReLU})\n",
561 | " sess.run(optimizer_SNN, feed_dict={x: batch_x_norm, y: batch_y,\n",
562 | " dropout_prob: dropout_prob_SNN,is_training:True})\n",
563 | " \n",
564 | " \n",
565 | " if step % display_step == 0:\n",
566 | " #batch_x, batch_y = mnist.test.next_batch(batch_size)\n",
567 | " #batch_x_norm = scaler.transform(batch_x)\n",
568 | " # Calculate batch loss and accuracy\n",
569 | " loss_ReLU, acc_ReLU = sess.run([cost_ReLU, accuracy_ReLU], feed_dict={x: batch_x,\n",
570 | " y: batch_y,\n",
571 | " keep_prob: 1.0})\n",
572 | " training_loss_protocol_ReLU.append(loss_ReLU)\n",
573 | " \n",
574 | " loss_SNN, acc_SNN = sess.run([cost_SNN, accuracy_SNN], feed_dict={x: batch_x_norm,\n",
575 | " y: batch_y,\n",
576 | " dropout_prob: 0.0, is_training:False})\n",
577 | " training_loss_protocol_SNN.append(loss_SNN)\n",
578 | " \n",
579 | " print( \"RELU: Nbr of updates: \" + str(step+1) + \", Minibatch Loss= \" + \\\n",
580 | " \"{:.6f}\".format(loss_ReLU) + \", Training Accuracy= \" + \\\n",
581 | " \"{:.5f}\".format(acc_ReLU))\n",
582 | " \n",
583 | " print( \"SNN: Nbr of updates: \" + str(step+1) + \", Minibatch Loss= \" + \\\n",
584 | " \"{:.6f}\".format(loss_SNN) + \", Training Accuracy= \" + \\\n",
585 | " \"{:.5f}\".format(acc_SNN))\n",
586 | " step += 1\n",
587 | " print(\"Optimization Finished!\\n\")\n",
588 | "\n",
589 | " # Calculate accuracy for 256 mnist test images\n",
590 | " print(\"ReLU: Testing Accuracy:\", sess.run(accuracy_ReLU, feed_dict={x: mnist.test.images[:512],\n",
591 | " y: mnist.test.labels[:512],\n",
592 | " keep_prob: 1.0}))\n",
593 | " print(\"SNN: Testing Accuracy:\", sess.run(accuracy_SNN, feed_dict={x: scaler.transform(mnist.test.images[:512]),\n",
594 | " y: mnist.test.labels[:512],\n",
595 | " dropout_prob: 0.0, is_training:False}))"
596 | ]
597 | },
598 | {
599 | "cell_type": "code",
600 | "execution_count": 14,
601 | "metadata": {
602 | "collapsed": false,
603 | "scrolled": true,
604 | "pycharm": {
605 | "name": "#%%\n"
606 | }
607 | },
608 | "outputs": [
609 | {
610 | "data": {
611 | "text/plain": "",
612 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAagAAAEYCAYAAAAJeGK1AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAABUOklEQVR4nO3dd3iUVfbA8e+dSSUJgVRKKIEAIYQeekdBqthQUERs2HV1XVdFd137qr9d195QFMVeQUGQLp3Qey+hBkJCCaTe3x83A+mZJNOSnM/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WlppKam0q9fPwBuueUWFi1aBEC7du246aab+Pzzz/HyMmOCXr168cgjj/DGG2+Qmpp68f78zp8/T4cOHQgNDSUlJYVBgwZx9uxZli5dyujRo+nQoQN33XUXR44cKTGu4v7Yrswf4E8++SSvvvoqubm5RR6Ljo6ma9euTJs2rcLnL6xGj6BsvKwWXruuPQE+Xry/aA9nM7J5blQ8FouMpITwZBUZ6bjar7/+yqJFi/jll1947rnn2Lx5M48//jjDhw/nt99+o3v37vzxxx/ExsYWeJ5tDSotLY0RI0bw9ttvM2HCBOrUqcO6devseu3Q0NCLU40AKSkphIWFATBp0iR+/fVXwExPtmnThsTERAYOHFji+WJiYujQoQPffPNNsY8/+eSTXHfddfTt29eu+MpS40dQNhaL4tlRbbirXzO+WHGAR79dT3ZO0b8ShBCisODgYOrWrcvixYsBmDp1Kv369SM3N5eDBw8yYMAAXnnlFVJTUzl79iy7d++mbdu2/P3vfychIaHUdaTg4GDeeOMNXnvtNfz9/YmOjubbb78FTDXy+vXrS3xu//79+frrry8WL0yZMoUBAwYA8MILL7Bu3bqLye6JJ57gscce4+jRowBkZGTwxhtvFDnnpEmTilQL2sTGxhIXF8eMGTPK+MTsIyOofJRSPD4kliBfL16bvQMU/N/o9rImJYQoID09naioqIs/P/LII3z66afcfffdpKen06xZMz755BNycnIYN24caWlpaK15+OGHqVOnDk8//TTz58/HarUSFxfH0KFDS329jh070r59e7766iu++OIL7rnnHp5//nmysrIYM2YM7du3B+D555/n9ddfv/i8pKQkEhMT6dy5M1arlebNm/Pee+8V+xrDhg3j2LFjXH755WitUUoVu57Upk0bOnXqxJo1a4o9z6RJk+jYsWNZH6FdVFVeb0lISNDO2rDwf3/s5L9/7OCBgTH8dXArp7yGEKL8tm7dSuvWrd0dhqig4v79lFKJWuuEwsfKCKoED14Ww+HU87w5bxcN6vgztmtjd4ckhBA1iiSoEiileP7qeI6evsBTP22iXrAfA1pFuDssIYSoMaRIohTeVgtv39SJ2HpB3PfFGjYmpbk7JCGEqDEkQZ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PGQEJWqqDUB23lTdFMz6TFNgTV6hQjLFb089C7g7bzpsO2aaz+YDYINSao3WOn8C+BEzzbYeM4J5TGt9NC/BFScI+Fkp5YcZtTycl9guaK1PA2itDyqlvsl7Hzsx0275+SqlVmD+CB2bd99DwDSl1EOY/a5svgCmK6VWY6YZt+W9xkml1BKl1CZgptb6b0qp1sCyvFqOs8A4IAZ4VSmVC2QB95TwvoQoF+lmLkQVoJQaB0RprV+249h9QILW+oTTAxPCiWQEJUQVkDd9JkSNIiMoIYQQHkmKJIQQQngkSVBCCCE8kiQoIYQQHkkSlBBCCI8kCUoIIYRH+n+paZ6ghG4p/gAAAABJRU5ErkJggg==\n"
613 | },
614 | "metadata": {
615 | "needs_background": "light"
616 | },
617 | "output_type": "display_data"
618 | }
619 | ],
620 | "source": [
621 | "import matplotlib.pyplot as plt\n",
622 | "\n",
623 | "fig, ax = plt.subplots()\n",
624 | "ax.plot( training_loss_protocol_ReLU, label='Loss ReLU-CNN')\n",
625 | "ax.plot( training_loss_protocol_SNN, label='Loss SNN')\n",
626 | "ax.set_yscale('log') # log scale\n",
627 | "ax.set_xlabel('iterations/updates')\n",
628 | "ax.set_ylabel('training loss')\n",
629 | "fig.tight_layout()\n",
630 | "ax.legend()\n",
631 | "plt.show()"
632 | ]
633 | }
634 | ],
635 | "metadata": {
636 | "kernelspec": {
637 | "name": "python3",
638 | "language": "python",
639 | "display_name": "Python 3"
640 | },
641 | "language_info": {
642 | "codemirror_mode": {
643 | "name": "ipython",
644 | "version": 3
645 | },
646 | "file_extension": ".py",
647 | "mimetype": "text/x-python",
648 | "name": "python",
649 | "nbconvert_exporter": "python",
650 | "pygments_lexer": "ipython3",
651 | "version": "3.5.2"
652 | }
653 | },
654 | "nbformat": 4,
655 | "nbformat_minor": 0
656 | }
--------------------------------------------------------------------------------
/TF_1_x/SelfNormalizingNetworks_MLP_MNIST.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Tutorial on self-normalizing networks on the MNIST data set: multi-layer perceptrons\n",
8 | "\n",
9 | "*Author:* Guenter Klambauer, 2017\n",
10 | "\n",
11 | "Derived from: [Aymeric Damien](https://github.com/aymericdamien/TensorFlow-Examples/) \n"
12 | ]
13 | },
14 | {
15 | "cell_type": "code",
16 | "execution_count": 1,
17 | "metadata": {
18 | "collapsed": false
19 | },
20 | "outputs": [
21 | {
22 | "name": "stdout",
23 | "output_type": "stream",
24 | "text": [
25 | "WARNING:tensorflow:From :16: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
26 | "Instructions for updating:\n",
27 | "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
28 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
29 | "Instructions for updating:\n",
30 | "Please write your own downloading logic.\n",
31 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
32 | "Instructions for updating:\n",
33 | "Please use tf.data to implement this functionality.\n",
34 | "Extracting /tmp/data/train-images-idx3-ubyte.gz\n",
35 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
36 | "Instructions for updating:\n",
37 | "Please use tf.data to implement this functionality.\n",
38 | "Extracting /tmp/data/train-labels-idx1-ubyte.gz\n",
39 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
40 | "Instructions for updating:\n",
41 | "Please use tf.one_hot on tensors.\n",
42 | "Extracting /tmp/data/t10k-images-idx3-ubyte.gz\n",
43 | "Extracting /tmp/data/t10k-labels-idx1-ubyte.gz\n",
44 | "WARNING:tensorflow:From /home/kai/miniconda3/envs/snn_tf1_compat/lib/python3.7/site-packages/tensorflow_core/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
45 | "Instructions for updating:\n",
46 | "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
47 | "1.15.0\n"
48 | ]
49 | }
50 | ],
51 | "source": [
52 | "import tensorflow as tf\n",
53 | "import numpy as np\n",
54 | "from sklearn.preprocessing import StandardScaler\n",
55 | "\n",
56 | "import numbers\n",
57 | "from tensorflow.python.framework import ops\n",
58 | "from tensorflow.python.framework import tensor_shape\n",
59 | "from tensorflow.python.framework import tensor_util\n",
60 | "from tensorflow.python.ops import math_ops\n",
61 | "from tensorflow.python.ops import random_ops\n",
62 | "from tensorflow.python.ops import array_ops\n",
63 | "from tensorflow.python.layers import utils\n",
64 | "\n",
65 | "# Import MINST data\n",
66 | "from tensorflow.examples.tutorials.mnist import input_data\n",
67 | "mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n",
68 | "\n",
69 | "print(tf.__version__)"
70 | ]
71 | },
72 | {
73 | "cell_type": "code",
74 | "execution_count": 2,
75 | "metadata": {
76 | "collapsed": true
77 | },
78 | "outputs": [],
79 | "source": [
80 | "# Parameters\n",
81 | "learning_rate = 0.05\n",
82 | "training_epochs = 15\n",
83 | "batch_size = 100\n",
84 | "display_step = 1\n",
85 | "\n",
86 | "# Network Parameters\n",
87 | "n_hidden_1 = 784 # 1st layer number of features\n",
88 | "n_hidden_2 = 784 # 2nd layer number of features\n",
89 | "n_input = 784 # MNIST data input (img shape: 28*28)\n",
90 | "n_classes = 10 # MNIST total classes (0-9 digits)\n",
91 | "\n",
92 | "# tf Graph input\n",
93 | "x = tf.placeholder(\"float\", [None, n_input])\n",
94 | "y = tf.placeholder(\"float\", [None, n_classes])\n",
95 | "dropoutRate = tf.placeholder(tf.float32)\n",
96 | "is_training= tf.placeholder(tf.bool)"
97 | ]
98 | },
99 | {
100 | "cell_type": "markdown",
101 | "metadata": {},
102 | "source": [
103 | "### (1) Definition of scaled exponential linear units (SELUs)"
104 | ]
105 | },
106 | {
107 | "cell_type": "code",
108 | "execution_count": 3,
109 | "metadata": {
110 | "collapsed": true
111 | },
112 | "outputs": [],
113 | "source": [
114 | "def selu(x):\n",
115 | " with ops.name_scope('elu') as scope:\n",
116 | " alpha = 1.6732632423543772848170429916717\n",
117 | " scale = 1.0507009873554804934193349852946\n",
118 | " return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))"
119 | ]
120 | },
121 | {
122 | "cell_type": "markdown",
123 | "metadata": {},
124 | "source": [
125 | "### (2) Definition of dropout variant for SNNs"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": 4,
131 | "metadata": {
132 | "collapsed": true
133 | },
134 | "outputs": [],
135 | "source": [
136 | "def dropout_selu(x, rate, alpha= -1.7580993408473766, fixedPointMean=0.0, fixedPointVar=1.0, \n",
137 | " noise_shape=None, seed=None, name=None, training=False):\n",
138 | " \"\"\"Dropout to a value with rescaling.\"\"\"\n",
139 | "\n",
140 | " def dropout_selu_impl(x, rate, alpha, noise_shape, seed, name):\n",
141 | " keep_prob = 1.0 - rate\n",
142 | " x = ops.convert_to_tensor(x, name=\"x\")\n",
143 | " if isinstance(keep_prob, numbers.Real) and not 0 < keep_prob <= 1:\n",
144 | " raise ValueError(\"keep_prob must be a scalar tensor or a float in the \"\n",
145 | " \"range (0, 1], got %g\" % keep_prob)\n",
146 | " keep_prob = ops.convert_to_tensor(keep_prob, dtype=x.dtype, name=\"keep_prob\")\n",
147 | " keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())\n",
148 | "\n",
149 | " alpha = ops.convert_to_tensor(alpha, dtype=x.dtype, name=\"alpha\")\n",
150 | " keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())\n",
151 | "\n",
152 | " if tensor_util.constant_value(keep_prob) == 1:\n",
153 | " return x\n",
154 | "\n",
155 | " noise_shape = noise_shape if noise_shape is not None else array_ops.shape(x)\n",
156 | " random_tensor = keep_prob\n",
157 | " random_tensor += random_ops.random_uniform(noise_shape, seed=seed, dtype=x.dtype)\n",
158 | " binary_tensor = math_ops.floor(random_tensor)\n",
159 | " ret = x * binary_tensor + alpha * (1-binary_tensor)\n",
160 | "\n",
161 | " a = tf.sqrt(fixedPointVar / (keep_prob *((1-keep_prob) * tf.pow(alpha-fixedPointMean,2) + fixedPointVar)))\n",
162 | "\n",
163 | " b = fixedPointMean - a * (keep_prob * fixedPointMean + (1 - keep_prob) * alpha)\n",
164 | " ret = a * ret + b\n",
165 | " ret.set_shape(x.get_shape())\n",
166 | " return ret\n",
167 | "\n",
168 | " with ops.name_scope(name, \"dropout\", [x]) as name:\n",
169 | " return utils.smart_cond(training,\n",
170 | " lambda: dropout_selu_impl(x, rate, alpha, noise_shape, seed, name),\n",
171 | " lambda: array_ops.identity(x))\n"
172 | ]
173 | },
174 | {
175 | "cell_type": "markdown",
176 | "metadata": {},
177 | "source": [
178 | "### (3) Input data scaled to zero mean and unit variance"
179 | ]
180 | },
181 | {
182 | "cell_type": "code",
183 | "execution_count": 5,
184 | "metadata": {
185 | "collapsed": true
186 | },
187 | "outputs": [],
188 | "source": [
189 | "# (1) Scale input to zero mean and unit variance\n",
190 | "scaler = StandardScaler().fit(mnist.train.images)"
191 | ]
192 | },
193 | {
194 | "cell_type": "code",
195 | "execution_count": 6,
196 | "metadata": {
197 | "collapsed": true
198 | },
199 | "outputs": [],
200 | "source": [
201 | "# Tensorboard\n",
202 | "logs_path = '~/tmp'"
203 | ]
204 | },
205 | {
206 | "cell_type": "code",
207 | "execution_count": 7,
208 | "metadata": {
209 | "collapsed": true
210 | },
211 | "outputs": [],
212 | "source": [
213 | "# Create model\n",
214 | "def multilayer_perceptron(x, weights, biases, rate, is_training):\n",
215 | " # Hidden layer with SELU activation\n",
216 | " layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])\n",
217 | " #netI_1 = layer_1\n",
218 | " layer_1 = selu(layer_1)\n",
219 | " layer_1 = dropout_selu(layer_1,rate, training=is_training)\n",
220 | " \n",
221 | " # Hidden layer with SELU activation\n",
222 | " layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])\n",
223 | " #netI_2 = layer_2\n",
224 | " layer_2 = selu(layer_2)\n",
225 | " layer_2 = dropout_selu(layer_2,rate, training=is_training)\n",
226 | "\n",
227 | " # Output layer with linear activation\n",
228 | " out_layer = tf.matmul(layer_2, weights['out']) + biases['out']\n",
229 | " return out_layer"
230 | ]
231 | },
232 | {
233 | "cell_type": "markdown",
234 | "metadata": {},
235 | "source": [
236 | "### (4) Initialization with STDDEV of sqrt(1/n)"
237 | ]
238 | },
239 | {
240 | "cell_type": "code",
241 | "execution_count": 8,
242 | "metadata": {
243 | "collapsed": false
244 | },
245 | "outputs": [
246 | {
247 | "name": "stdout",
248 | "output_type": "stream",
249 | "text": [
250 | "WARNING:tensorflow:From :5: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
251 | "Instructions for updating:\n",
252 | "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
253 | "WARNING:tensorflow:From :12: scalar (from tensorflow.python.framework.tensor_shape) is deprecated and will be removed in a future version.\n",
254 | "Instructions for updating:\n",
255 | "Use tf.TensorShape([]).\n",
256 | "WARNING:tensorflow:From :16: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
257 | "Instructions for updating:\n",
258 | "\n",
259 | "Future major versions of TensorFlow will allow gradients to flow\n",
260 | "into the labels input on backprop by default.\n",
261 | "\n",
262 | "See `tf.nn.softmax_cross_entropy_with_logits_v2`.\n",
263 | "\n"
264 | ]
265 | }
266 | ],
267 | "source": [
268 | "# Store layers weight & bias\n",
269 | "weights = {\n",
270 | " 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1],stddev=np.sqrt(1/n_input))),\n",
271 | " 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2],stddev=np.sqrt(1/n_hidden_1))),\n",
272 | " 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes],stddev=np.sqrt(1/n_hidden_2)))\n",
273 | "}\n",
274 | "biases = {\n",
275 | " 'b1': tf.Variable(tf.random_normal([n_hidden_1],stddev=0)),\n",
276 | " 'b2': tf.Variable(tf.random_normal([n_hidden_2],stddev=0)),\n",
277 | " 'out': tf.Variable(tf.random_normal([n_classes],stddev=0))\n",
278 | "}\n",
279 | "# Construct model\n",
280 | "pred = multilayer_perceptron(x, weights, biases, rate=dropoutRate, is_training=is_training)\n",
281 | "\n",
282 | "# Define loss and optimizer\n",
283 | "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\n",
284 | "optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)\n",
285 | "\n",
286 | " # Test model\n",
287 | "correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n",
288 | "# Calculate accuracy\n",
289 | "accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n",
290 | " \n",
291 | "# Initializing the variables\n",
292 | "init = tf.global_variables_initializer()"
293 | ]
294 | },
295 | {
296 | "cell_type": "code",
297 | "execution_count": 9,
298 | "metadata": {
299 | "collapsed": false
300 | },
301 | "outputs": [],
302 | "source": [
303 | "# Create a histogramm for weights\n",
304 | "tf.summary.histogram(\"weights2\", weights['h2'])\n",
305 | "tf.summary.histogram(\"weights1\", weights['h1'])\n",
306 | "\n",
307 | "# Create a summary to monitor cost tensor\n",
308 | "tf.summary.scalar(\"loss\", cost)\n",
309 | "# Create a summary to monitor accuracy tensor\n",
310 | "tf.summary.scalar(\"accuracy\", accuracy)\n",
311 | "# Merge all summaries into a single op\n",
312 | "merged_summary_op = tf.summary.merge_all()"
313 | ]
314 | },
315 | {
316 | "cell_type": "code",
317 | "execution_count": 10,
318 | "metadata": {
319 | "collapsed": false,
320 | "pycharm": {
321 | "name": "#%%\n"
322 | }
323 | },
324 | "outputs": [
325 | {
326 | "name": "stdout",
327 | "output_type": "stream",
328 | "text": [
329 | "Epoch: 0001 cost= 0.378099435\n",
330 | "Train-Accuracy: 0.94 Train-Loss: 0.17783636\n",
331 | "Validation-Accuracy: 0.9375 Val-Loss: 0.19006419 \n",
332 | "\n",
333 | "Epoch: 0002 cost= 0.260677475\n",
334 | "Train-Accuracy: 0.98 Train-Loss: 0.17112085\n",
335 | "Validation-Accuracy: 0.953125 Val-Loss: 0.18273504 \n",
336 | "\n",
337 | "Epoch: 0003 cost= 0.209526656\n",
338 | "Train-Accuracy: 0.99 Train-Loss: 0.038006987\n",
339 | "Validation-Accuracy: 0.9433594 Val-Loss: 0.18926144 \n",
340 | "\n",
341 | "Epoch: 0004 cost= 0.172529011\n",
342 | "Train-Accuracy: 0.99 Train-Loss: 0.04645816\n",
343 | "Validation-Accuracy: 0.9550781 Val-Loss: 0.18212736 \n",
344 | "\n",
345 | "Epoch: 0005 cost= 0.143096214\n",
346 | "Train-Accuracy: 1.0 Train-Loss: 0.023179742\n",
347 | "Validation-Accuracy: 0.98046875 Val-Loss: 0.08168894 \n",
348 | "\n",
349 | "Epoch: 0006 cost= 0.120568850\n",
350 | "Train-Accuracy: 0.99 Train-Loss: 0.042775374\n",
351 | "Validation-Accuracy: 0.96484375 Val-Loss: 0.15286936 \n",
352 | "\n",
353 | "Epoch: 0007 cost= 0.109314255\n",
354 | "Train-Accuracy: 0.99 Train-Loss: 0.023606239\n",
355 | "Validation-Accuracy: 0.96875 Val-Loss: 0.13182782 \n",
356 | "\n",
357 | "Epoch: 0008 cost= 0.095551941\n",
358 | "Train-Accuracy: 1.0 Train-Loss: 0.016547382\n",
359 | "Validation-Accuracy: 0.9511719 Val-Loss: 0.15446913 \n",
360 | "\n",
361 | "Epoch: 0009 cost= 0.086288710\n",
362 | "Train-Accuracy: 1.0 Train-Loss: 0.007214434\n",
363 | "Validation-Accuracy: 0.9746094 Val-Loss: 0.19779019 \n",
364 | "\n",
365 | "Epoch: 0010 cost= 0.076114546\n",
366 | "Train-Accuracy: 1.0 Train-Loss: 0.006380536\n",
367 | "Validation-Accuracy: 0.96484375 Val-Loss: 0.123645395 \n",
368 | "\n",
369 | "Epoch: 0011 cost= 0.069839616\n",
370 | "Train-Accuracy: 1.0 Train-Loss: 0.016955461\n",
371 | "Validation-Accuracy: 0.9824219 Val-Loss: 0.07528831 \n",
372 | "\n",
373 | "Epoch: 0012 cost= 0.063571214\n",
374 | "Train-Accuracy: 1.0 Train-Loss: 0.0137194265\n",
375 | "Validation-Accuracy: 0.9765625 Val-Loss: 0.119060434 \n",
376 | "\n",
377 | "Epoch: 0013 cost= 0.058336736\n",
378 | "Train-Accuracy: 0.99 Train-Loss: 0.014294322\n",
379 | "Validation-Accuracy: 0.97265625 Val-Loss: 0.12580527 \n",
380 | "\n",
381 | "Epoch: 0014 cost= 0.053450938\n",
382 | "Train-Accuracy: 1.0 Train-Loss: 0.019194987\n",
383 | "Validation-Accuracy: 0.97265625 Val-Loss: 0.06765857 \n",
384 | "\n",
385 | "Epoch: 0015 cost= 0.048051286\n",
386 | "Train-Accuracy: 1.0 Train-Loss: 0.008367514\n",
387 | "Validation-Accuracy: 0.9589844 Val-Loss: 0.17628105 \n",
388 | "\n"
389 | ]
390 | }
391 | ],
392 | "source": [
393 | "# Launch the graph\n",
394 | "gpu_options = tf.GPUOptions(allow_growth=True)\n",
395 | "with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n",
396 | " sess.run(init)\n",
397 | "\n",
398 | " summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())\n",
399 | "\n",
400 | " # Training cycle\n",
401 | " for epoch in range(training_epochs):\n",
402 | " avg_cost = 0.\n",
403 | " total_batch = int(mnist.train.num_examples/batch_size)\n",
404 | " # Loop over all batches\n",
405 | " for i in range(total_batch):\n",
406 | " batch_x, batch_y = mnist.train.next_batch(batch_size)\n",
407 | " batch_x = scaler.transform(batch_x)\n",
408 | " # Run optimization op (backprop) and cost op (to get loss value)\n",
409 | " _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,\n",
410 | " y: batch_y, dropoutRate: 0.05, is_training:True})\n",
411 | "\n",
412 | " # Compute average loss\n",
413 | " avg_cost += c / total_batch\n",
414 | " # Display logs per epoch step\n",
415 | " if epoch % display_step == 0:\n",
416 | " print (\"Epoch:\", '%04d' % (epoch+1), \"cost=\",\"{:.9f}\".format(avg_cost))\n",
417 | " \n",
418 | " accTrain, costTrain = sess.run([accuracy, cost],\n",
419 | " feed_dict={x: batch_x, y: batch_y, \n",
420 | " dropoutRate: 0.0, is_training:False})\n",
421 | " \n",
422 | " print(\"Train-Accuracy:\", accTrain,\"Train-Loss:\", costTrain)\n",
423 | "\n",
424 | " batch_x_test, batch_y_test = mnist.test.next_batch(512)\n",
425 | " batch_x_test = scaler.transform(batch_x_test)\n",
426 | "\n",
427 | " accTest, costVal = sess.run([accuracy, cost], feed_dict={x: batch_x_test, y: batch_y_test, \n",
428 | " dropoutRate: 0.0, is_training:False})\n",
429 | "\n",
430 | " print(\"Validation-Accuracy:\", accTest,\"Val-Loss:\", costVal,\"\\n\")"
431 | ]
432 | }
433 | ],
434 | "metadata": {
435 | "kernelspec": {
436 | "name": "python3",
437 | "language": "python",
438 | "display_name": "Python 3"
439 | },
440 | "language_info": {
441 | "codemirror_mode": {
442 | "name": "ipython",
443 | "version": 3
444 | },
445 | "file_extension": ".py",
446 | "mimetype": "text/x-python",
447 | "name": "python",
448 | "nbconvert_exporter": "python",
449 | "pygments_lexer": "ipython3",
450 | "version": "3.5.2"
451 | }
452 | },
453 | "nbformat": 4,
454 | "nbformat_minor": 0
455 | }
--------------------------------------------------------------------------------
/TF_1_x/environment.yml:
--------------------------------------------------------------------------------
1 | name: snn_tf1_compat
2 | channels:
3 | - conda-forge
4 | - defaults
5 | dependencies:
6 | - python=3.7
7 | - pip=21.0.1
8 | - numpy=1.20.0
9 | - scipy=1.6.0
10 | - sympy=1.7.1
11 | - pandas=1.2.2
12 | - scikit-learn=0.24.1
13 | - matplotlib=3.3.4
14 | - jupyter=1.0.0
15 | # CPU mode only, comment if using gpu mode
16 | # - tensorflow=1.15.0
17 | # GPU mode, take take that your gpu might need a different cudatoolkit!
18 | - cudatoolkit=10.0
19 | - tensorflow-gpu=1.15.0
--------------------------------------------------------------------------------
/TF_1_x/getSELUparameters.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Obtain the SELU parameters for arbitrary fixed points\n",
8 | "\n",
9 | "*Author:* Guenter Klambauer, 2017\n"
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": 1,
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "import numpy as np\n",
19 | "from scipy.special import erf,erfc\n",
20 | "from sympy import Symbol, solve, nsolve"
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "metadata": {},
26 | "source": [
27 | "### Function to obtain the parameters for the SELU with arbitrary fixed point (mean variance)"
28 | ]
29 | },
30 | {
31 | "cell_type": "code",
32 | "execution_count": 2,
33 | "metadata": {},
34 | "outputs": [],
35 | "source": [
36 | "def getSeluParameters(fixedpointMean=0,fixedpointVar=1):\n",
37 | " \"\"\" Finding the parameters of the SELU activation function. The function returns alpha and lambda for the desired fixed point. \"\"\"\n",
38 | " \n",
39 | " import sympy\n",
40 | " from sympy import Symbol, solve, nsolve\n",
41 | "\n",
42 | " aa = Symbol('aa')\n",
43 | " ll = Symbol('ll')\n",
44 | " nu = fixedpointMean \n",
45 | " tau = fixedpointVar \n",
46 | "\n",
47 | " mean = 0.5*ll*(nu + np.exp(-nu**2/(2*tau))*np.sqrt(2/np.pi)*np.sqrt(tau) + \\\n",
48 | " nu*erf(nu/(np.sqrt(2*tau))) - aa*erfc(nu/(np.sqrt(2*tau))) + \\\n",
49 | " np.exp(nu+tau/2)*aa*erfc((nu+tau)/(np.sqrt(2*tau))))\n",
50 | "\n",
51 | " var = 0.5*ll**2*(np.exp(-nu**2/(2*tau))*np.sqrt(2/np.pi*tau)*nu + (nu**2+tau)* \\\n",
52 | " (1+erf(nu/(np.sqrt(2*tau)))) + aa**2 *erfc(nu/(np.sqrt(2*tau))) \\\n",
53 | " - aa**2 * 2 *np.exp(nu+tau/2)*erfc((nu+tau)/(np.sqrt(2*tau)))+ \\\n",
54 | " aa**2*np.exp(2*(nu+tau))*erfc((nu+2*tau)/(np.sqrt(2*tau))) ) - mean**2\n",
55 | "\n",
56 | " eq1 = mean - nu\n",
57 | " eq2 = var - tau\n",
58 | "\n",
59 | " res = nsolve( (eq2, eq1), (aa,ll), (1.67,1.05))\n",
60 | " return float(res[0]),float(res[1])\n"
61 | ]
62 | },
63 | {
64 | "cell_type": "code",
65 | "execution_count": 3,
66 | "metadata": {},
67 | "outputs": [
68 | {
69 | "data": {
70 | "text/plain": [
71 | "(1.6732632423543778, 1.0507009873554805)"
72 | ]
73 | },
74 | "execution_count": 3,
75 | "metadata": {},
76 | "output_type": "execute_result"
77 | }
78 | ],
79 | "source": [
80 | "### To recover the parameters of the SELU with mean zero and unit variance\n",
81 | "getSeluParameters(0,1)"
82 | ]
83 | },
84 | {
85 | "cell_type": "code",
86 | "execution_count": 4,
87 | "metadata": {},
88 | "outputs": [
89 | {
90 | "data": {
91 | "text/plain": [
92 | "(1.9769021954242014, 1.073851239616046)"
93 | ]
94 | },
95 | "execution_count": 4,
96 | "metadata": {},
97 | "output_type": "execute_result"
98 | }
99 | ],
100 | "source": [
101 | "### To obtain new parameters for mean zero and variance 2\n",
102 | "myFixedPointMean = -0.1\n",
103 | "myFixedPointVar = 2.0\n",
104 | "myAlpha, myLambda = getSeluParameters(myFixedPointMean,myFixedPointVar)\n",
105 | "getSeluParameters(myFixedPointMean,myFixedPointVar)"
106 | ]
107 | },
108 | {
109 | "cell_type": "markdown",
110 | "metadata": {},
111 | "source": [
112 | "### Adjust the SELU function and Dropout to your new parameters"
113 | ]
114 | },
115 | {
116 | "cell_type": "code",
117 | "execution_count": 5,
118 | "metadata": {},
119 | "outputs": [],
120 | "source": [
121 | "def selu(x):\n",
122 | " with ops.name_scope('elu') as scope:\n",
123 | " alpha = myAlpha\n",
124 | " scale = myLambda\n",
125 | " return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": 6,
131 | "metadata": {},
132 | "outputs": [],
133 | "source": [
134 | "def dropout_selu(x, rate, alpha= -myAlpha*myLambda, fixedPointMean=myFixedPointMean, fixedPointVar=myFixedPointVar, \n",
135 | " noise_shape=None, seed=None, name=None, training=False):\n",
136 | " \"\"\"Dropout to a value with rescaling.\"\"\"\n",
137 | "\n",
138 | " def dropout_selu_impl(x, rate, alpha, noise_shape, seed, name):\n",
139 | " keep_prob = 1.0 - rate\n",
140 | " x = ops.convert_to_tensor(x, name=\"x\")\n",
141 | " if isinstance(keep_prob, numbers.Real) and not 0 < keep_prob <= 1:\n",
142 | " raise ValueError(\"keep_prob must be a scalar tensor or a float in the \"\n",
143 | " \"range (0, 1], got %g\" % keep_prob)\n",
144 | " keep_prob = ops.convert_to_tensor(keep_prob, dtype=x.dtype, name=\"keep_prob\")\n",
145 | " keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())\n",
146 | "\n",
147 | " alpha = ops.convert_to_tensor(alpha, dtype=x.dtype, name=\"alpha\")\n",
148 | " keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())\n",
149 | "\n",
150 | " if tensor_util.constant_value(keep_prob) == 1:\n",
151 | " return x\n",
152 | "\n",
153 | " noise_shape = noise_shape if noise_shape is not None else array_ops.shape(x)\n",
154 | " random_tensor = keep_prob\n",
155 | " random_tensor += random_ops.random_uniform(noise_shape, seed=seed, dtype=x.dtype)\n",
156 | " binary_tensor = math_ops.floor(random_tensor)\n",
157 | " ret = x * binary_tensor + alpha * (1-binary_tensor)\n",
158 | "\n",
159 | "\n",
160 | " a = tf.sqrt(fixedPointVar / (keep_prob *((1-keep_prob) * tf.pow(alpha-fixedPointMean,2) + fixedPointVar)))\n",
161 | " \n",
162 | " b = fixedPointMean - a * (keep_prob * fixedPointMean + (1 - keep_prob) * alpha)\n",
163 | " ret = a * ret + b\n",
164 | " ret.set_shape(x.get_shape())\n",
165 | " return ret\n",
166 | "\n",
167 | " with ops.name_scope(name, \"dropout\", [x]) as name:\n",
168 | " return utils.smart_cond(training,\n",
169 | " lambda: dropout_selu_impl(x, rate, alpha, noise_shape, seed, name),\n",
170 | " lambda: array_ops.identity(x))\n"
171 | ]
172 | },
173 | {
174 | "cell_type": "code",
175 | "execution_count": 7,
176 | "metadata": {
177 | "scrolled": true
178 | },
179 | "outputs": [
180 | {
181 | "name": "stdout",
182 | "output_type": "stream",
183 | "text": [
184 | "WARNING:tensorflow:From :5: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
185 | "Instructions for updating:\n",
186 | "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
187 | "WARNING:tensorflow:From :12: scalar (from tensorflow.python.framework.tensor_shape) is deprecated and will be removed in a future version.\n",
188 | "Instructions for updating:\n",
189 | "Use tf.TensorShape([]).\n",
190 | "mean/var should be at: -0.1 / 2.0\n",
191 | "Input data mean/var: -0.114250198007 / 1.969062447548\n",
192 | "After selu: -0.114625535905 / 1.961883544922\n",
193 | "After dropout mean/var -0.127010405064 / 1.969492197037\n"
194 | ]
195 | }
196 | ],
197 | "source": [
198 | "import tensorflow as tf\n",
199 | "import numpy as np\n",
200 | "\n",
201 | "import numbers\n",
202 | "from tensorflow.python.framework import ops\n",
203 | "from tensorflow.python.framework import tensor_shape\n",
204 | "from tensorflow.python.framework import tensor_util\n",
205 | "from tensorflow.python.ops import math_ops\n",
206 | "from tensorflow.python.ops import random_ops\n",
207 | "from tensorflow.python.ops import array_ops\n",
208 | "from tensorflow.python.layers import utils\n",
209 | "\n",
210 | "\n",
211 | "x = tf.Variable(tf.random.normal([10000],mean=myFixedPointMean, stddev=np.sqrt(myFixedPointVar)))\n",
212 | "w = selu(x)\n",
213 | "y = dropout_selu(w,0.2,training=True)\n",
214 | "init = tf.global_variables_initializer()\n",
215 | " \n",
216 | "gpu_options = tf.GPUOptions(allow_growth=True)\n",
217 | "with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n",
218 | " sess.run(init)\n",
219 | " z,zz, zzz = sess.run([x, w, y]) \n",
220 | " #print(z)\n",
221 | " #print(zz)\n",
222 | " print(\"mean/var should be at:\", myFixedPointMean, \"/\", myFixedPointVar)\n",
223 | " print(\"Input data mean/var: \", \"{:.12f}\".format(np.mean(z)), \"/\", \"{:.12f}\".format(np.var(z))) \n",
224 | " print(\"After selu: \", \"{:.12f}\".format(np.mean(zz)), \"/\", \"{:.12f}\".format(np.var(zz)))\n",
225 | " print(\"After dropout mean/var\", \"{:.12f}\".format(np.mean(zzz)), \"/\", \"{:.12f}\".format(np.var(zzz)))"
226 | ]
227 | },
228 | {
229 | "cell_type": "markdown",
230 | "metadata": {},
231 | "source": [
232 | "### For completeness: These are the correct expressions for mean zero and unit variance"
233 | ]
234 | },
235 | {
236 | "cell_type": "code",
237 | "execution_count": 8,
238 | "metadata": {},
239 | "outputs": [],
240 | "source": [
241 | "myAlpha = -np.sqrt(2/np.pi) / (np.exp(0.5) * erfc(1/np.sqrt(2))-1 ) \n",
242 | "myLambda = (1-np.sqrt(np.exp(1))*erfc(1/np.sqrt(2))) * \\\n",
243 | " np.sqrt( 2*np.pi/ (2 + np.pi -2*np.sqrt(np.exp(1))*(2+np.pi)*erfc(1/np.sqrt(2)) + \\\n",
244 | " np.exp(1)*np.pi*erfc(1/np.sqrt(2))**2 + 2*np.exp(2)*erfc(np.sqrt(2))))"
245 | ]
246 | },
247 | {
248 | "cell_type": "code",
249 | "execution_count": 9,
250 | "metadata": {},
251 | "outputs": [
252 | {
253 | "name": "stdout",
254 | "output_type": "stream",
255 | "text": [
256 | "Alpha parameter of the SELU: 1.6732632423543778\n",
257 | "Lambda parameter of the SELU: 1.0507009873554807\n"
258 | ]
259 | }
260 | ],
261 | "source": [
262 | "print(\"Alpha parameter of the SELU: \", myAlpha)\n",
263 | "print(\"Lambda parameter of the SELU: \", myLambda)"
264 | ]
265 | }
266 | ],
267 | "metadata": {
268 | "kernelspec": {
269 | "display_name": "Python 3",
270 | "language": "python",
271 | "name": "python3"
272 | },
273 | "language_info": {
274 | "codemirror_mode": {
275 | "name": "ipython",
276 | "version": 3
277 | },
278 | "file_extension": ".py",
279 | "mimetype": "text/x-python",
280 | "name": "python",
281 | "nbconvert_exporter": "python",
282 | "pygments_lexer": "ipython3",
283 | "version": "3.7.9"
284 | }
285 | },
286 | "nbformat": 4,
287 | "nbformat_minor": 1
288 | }
289 |
--------------------------------------------------------------------------------
/TF_1_x/selu.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | '''
3 | Tensorflow Implementation of the Scaled ELU function and Dropout
4 | '''
5 |
6 | from __future__ import absolute_import, division, print_function
7 | import numbers
8 | from tensorflow.contrib import layers
9 | from tensorflow.python.framework import ops
10 | from tensorflow.python.framework import tensor_shape
11 | from tensorflow.python.framework import tensor_util
12 | from tensorflow.python.ops import math_ops
13 | from tensorflow.python.ops import random_ops
14 | from tensorflow.python.ops import array_ops
15 | from tensorflow.python.layers import utils
16 | import tensorflow as tf
17 |
18 | # (1) scale inputs to zero mean and unit variance
19 |
20 |
21 | # (2) use SELUs
22 | def selu(x):
23 | with ops.name_scope('elu') as scope:
24 | alpha = 1.6732632423543772848170429916717
25 | scale = 1.0507009873554804934193349852946
26 | return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))
27 |
28 |
29 | # (3) initialize weights with stddev sqrt(1/n)
30 | # e.g. use:
31 | initializer = layers.variance_scaling_initializer(factor=1.0, mode='FAN_IN')
32 |
33 |
34 | # (4) use this dropout
35 | def dropout_selu(x, rate, alpha= -1.7580993408473766, fixedPointMean=0.0, fixedPointVar=1.0,
36 | noise_shape=None, seed=None, name=None, training=False):
37 | """Dropout to a value with rescaling."""
38 |
39 | def dropout_selu_impl(x, rate, alpha, noise_shape, seed, name):
40 | keep_prob = 1.0 - rate
41 | x = ops.convert_to_tensor(x, name="x")
42 | if isinstance(keep_prob, numbers.Real) and not 0 < keep_prob <= 1:
43 | raise ValueError("keep_prob must be a scalar tensor or a float in the "
44 | "range (0, 1], got %g" % keep_prob)
45 | keep_prob = ops.convert_to_tensor(keep_prob, dtype=x.dtype, name="keep_prob")
46 | keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())
47 |
48 | alpha = ops.convert_to_tensor(alpha, dtype=x.dtype, name="alpha")
49 | alpha.get_shape().assert_is_compatible_with(tensor_shape.scalar())
50 |
51 | if tensor_util.constant_value(keep_prob) == 1:
52 | return x
53 |
54 | noise_shape = noise_shape if noise_shape is not None else array_ops.shape(x)
55 | random_tensor = keep_prob
56 | random_tensor += random_ops.random_uniform(noise_shape, seed=seed, dtype=x.dtype)
57 | binary_tensor = math_ops.floor(random_tensor)
58 | ret = x * binary_tensor + alpha * (1-binary_tensor)
59 |
60 | a = math_ops.sqrt(fixedPointVar / (keep_prob *((1-keep_prob) * math_ops.pow(alpha-fixedPointMean,2) + fixedPointVar)))
61 |
62 | b = fixedPointMean - a * (keep_prob * fixedPointMean + (1 - keep_prob) * alpha)
63 | ret = a * ret + b
64 | ret.set_shape(x.get_shape())
65 | return ret
66 |
67 | with ops.name_scope(name, "dropout", [x]) as name:
68 | return utils.smart_cond(training,
69 | lambda: dropout_selu_impl(x, rate, alpha, noise_shape, seed, name),
70 | lambda: array_ops.identity(x))
71 |
--------------------------------------------------------------------------------
/TF_2_x/CIFAR10-Conv-SELU.py:
--------------------------------------------------------------------------------
1 | # Adapted KERAS tutorial
2 |
3 | import tensorflow as tf
4 | import tensorflow.keras as keras
5 | from tensorflow.keras.datasets import cifar10
6 | from tensorflow.keras.preprocessing.image import ImageDataGenerator
7 | from tensorflow.keras.models import Sequential
8 | from tensorflow.keras.layers import Dense, AlphaDropout, Activation, Flatten
9 | from tensorflow.keras.layers import Conv2D, MaxPooling2D
10 |
11 |
12 | import os
13 | import pickle
14 | import numpy as np
15 |
16 | batch_size = 32
17 | num_classes = 10
18 | epochs = 2
19 | data_augmentation = True
20 | num_predictions = 20
21 | save_dir = os.path.join(os.getcwd(), 'saved_models')
22 | model_name = 'keras_cifar10_trained_model.h5'
23 |
24 | # list devices so you can check whether your gpu is available
25 | print(tf.config.list_physical_devices())
26 |
27 | # The data, shuffled and split between train and test sets:
28 | (x_train, y_train), (x_test, y_test) = cifar10.load_data()
29 | print('x_train shape:', x_train.shape)
30 | print(x_train.shape[0], 'train samples')
31 | print(x_test.shape[0], 'test samples')
32 |
33 | # Convert class vectors to binary class matrices.
34 | y_train = keras.utils.to_categorical(y_train, num_classes)
35 | y_test = keras.utils.to_categorical(y_test, num_classes)
36 |
37 | model = Sequential()
38 |
39 | model.add(Conv2D(32, (3, 3), padding='same',
40 | input_shape=x_train.shape[1:],kernel_initializer='lecun_normal',bias_initializer='zeros'))
41 | model.add(Activation('selu'))
42 | model.add(Conv2D(32, (3, 3),kernel_initializer='lecun_normal',bias_initializer='zeros'))
43 | model.add(Activation('selu'))
44 | model.add(MaxPooling2D(pool_size=(2, 2)))
45 | model.add(AlphaDropout(0.1))
46 |
47 | model.add(Conv2D(64, (3, 3), padding='same',kernel_initializer='lecun_normal',bias_initializer='zeros'))
48 | model.add(Activation('selu'))
49 | model.add(Conv2D(64, (3, 3),kernel_initializer='lecun_normal',bias_initializer='zeros'))
50 | model.add(Activation('selu'))
51 | model.add(MaxPooling2D(pool_size=(2, 2)))
52 | model.add(AlphaDropout(0.1))
53 |
54 | model.add(Flatten())
55 | model.add(Dense(512,kernel_initializer='lecun_normal',bias_initializer='zeros'))
56 | model.add(Activation('selu'))
57 | model.add(AlphaDropout(0.2))
58 | model.add(Dense(num_classes,kernel_initializer='lecun_normal',bias_initializer='zeros'))
59 | model.add(Activation('softmax'))
60 |
61 | # initiate RMSprop optimizer
62 | opt = keras.optimizers.RMSprop(lr=0.0001, decay=1e-6)
63 |
64 | # Let's train the model using RMSprop
65 | model.compile(loss='categorical_crossentropy',
66 | optimizer=opt,
67 | metrics=['accuracy'])
68 |
69 | x_train = x_train.astype('float32')
70 | x_test = x_test.astype('float32')
71 | x_train /= 255
72 | x_test /= 255
73 |
74 | if not data_augmentation:
75 | print('Not using data augmentation.')
76 | model.fit(x_train, y_train,
77 | batch_size=batch_size,
78 | epochs=epochs,
79 | validation_data=(x_test, y_test),
80 | shuffle=True)
81 | else:
82 | print('Using real-time data augmentation.')
83 | # This will do preprocessing and realtime data augmentation:
84 | datagen = ImageDataGenerator(
85 | featurewise_center=False, # set input mean to 0 over the dataset
86 | samplewise_center=False, # set each sample mean to 0
87 | featurewise_std_normalization=False, # divide inputs by std of the dataset
88 | samplewise_std_normalization=False, # divide each input by its std
89 | zca_whitening=False, # apply ZCA whitening
90 | rotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)
91 | width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
92 | height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
93 | horizontal_flip=True, # randomly flip images
94 | vertical_flip=False) # randomly flip images
95 |
96 | # Compute quantities required for feature-wise normalization
97 | # (std, mean, and principal components if ZCA whitening is applied).
98 | datagen.fit(x_train)
99 |
100 | # Fit the model on the batches generated by datagen.flow().
101 | model.fit(datagen.flow(x_train, y_train,
102 | batch_size=batch_size),
103 | steps_per_epoch=x_train.shape[0] // batch_size,
104 | epochs=epochs,
105 | validation_data=(x_test, y_test))
106 |
107 | # Save model and weights
108 | if not os.path.isdir(save_dir):
109 | os.makedirs(save_dir)
110 | model_path = os.path.join(save_dir, model_name)
111 | model.save(model_path)
112 | print('Saved trained model at %s ' % model_path)
113 |
114 | # Load label names to use in prediction results
115 | label_list_path = 'datasets/cifar-10-batches-py/batches.meta'
116 |
117 |
118 | keras_dir = os.path.expanduser(os.path.join('~', '.keras'))
119 | datadir_base = os.path.expanduser(keras_dir)
120 | if not os.access(datadir_base, os.W_OK):
121 | datadir_base = os.path.join('/tmp', '.keras')
122 | label_list_path = os.path.join(datadir_base, label_list_path)
123 |
124 | with open(label_list_path, mode='rb') as f:
125 | labels = pickle.load(f)
126 |
127 | # Evaluate model with test data set and share sample prediction results
128 | evaluation = model.evaluate(datagen.flow(x_test, y_test,
129 | batch_size=batch_size),
130 | steps=x_test.shape[0] // batch_size)
131 |
132 | print('Model Accuracy = %.5f' % (evaluation[1]))
133 |
134 | f = open('CIFAR10_SELU_results.txt', 'a')
135 | f.write(' Test accuracy:' + str(evaluation[1]) + '\n')
136 | f.close()
137 |
138 |
139 | predict_gen = model.predict(datagen.flow(x_test, y_test,
140 | batch_size=batch_size),
141 | steps=x_test.shape[0] // batch_size)
142 |
143 | for predict_index, predicted_y in enumerate(predict_gen):
144 | actual_label = labels['label_names'][np.argmax(y_test[predict_index])]
145 | predicted_label = labels['label_names'][np.argmax(predicted_y)]
146 | print('Actual Label = %s vs. Predicted Label = %s' % (actual_label,
147 | predicted_label))
148 | if predict_index == num_predictions:
149 | break
150 |
--------------------------------------------------------------------------------
/TF_2_x/MNIST-Conv-SELU.py:
--------------------------------------------------------------------------------
1 | # Adapted KERAS tutorial
2 |
3 | import tensorflow as tf
4 | import tensorflow.keras as keras
5 | from tensorflow.keras.datasets import mnist
6 | from tensorflow.keras.models import Sequential
7 | from tensorflow.keras.layers import Dense, AlphaDropout, Flatten
8 | from tensorflow.keras.layers import Conv2D, MaxPooling2D
9 | from tensorflow.keras import backend as K
10 |
11 |
12 | batch_size = 128
13 | num_classes = 10
14 | epochs = 5
15 |
16 | # input image dimensions
17 | img_rows, img_cols = 28, 28
18 |
19 | # list devices so you can check whether your gpu is available
20 | print(tf.config.list_physical_devices())
21 |
22 | # the data, shuffled and split between train and test sets
23 | (x_train, y_train), (x_test, y_test) = mnist.load_data()
24 |
25 | if K.image_data_format() == 'channels_first':
26 | x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
27 | x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
28 | input_shape = (1, img_rows, img_cols)
29 | else:
30 | x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
31 | x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
32 | input_shape = (img_rows, img_cols, 1)
33 |
34 | x_train = x_train.astype('float32')
35 | x_test = x_test.astype('float32')
36 | x_train /= 255
37 | #x_train = (x_train - np.mean(x_train))/np.std(x_train)
38 |
39 | x_test /= 255
40 | #x_test = (x_test - np.mean(x_train))/np.std(x_train)
41 |
42 | # create validation file
43 | x_val = x_train[:10000]
44 | x_train = x_train[10000:]
45 | y_val = y_train[:10000]
46 | y_train = y_train[10000:]
47 |
48 | print('x_train shape:', x_train.shape)
49 | print(x_train.shape[0], 'train samples')
50 | print(x_val.shape[0], 'val samples')
51 | print(x_test.shape[0], 'test samples')
52 |
53 | # convert class vectors to binary class matrices
54 | y_train = keras.utils.to_categorical(y_train, num_classes)
55 | y_val = keras.utils.to_categorical(y_val, num_classes)
56 | y_test = keras.utils.to_categorical(y_test, num_classes)
57 |
58 | model = Sequential()
59 | model.add(Conv2D(32, (3, 3),activation='selu',kernel_initializer='lecun_normal',bias_initializer='zeros'))
60 | model.add(Conv2D(64, (3, 3), activation='selu',kernel_initializer='lecun_normal',bias_initializer='zeros'))
61 | model.add(MaxPooling2D(pool_size=(2, 2)))
62 | model.add(AlphaDropout(0.05))
63 | model.add(Flatten())
64 | model.add(Dense(512, activation='selu',kernel_initializer='lecun_normal',bias_initializer='zeros'))
65 | model.add(AlphaDropout(0.05))
66 | model.add(Dense(num_classes, activation='softmax',kernel_initializer='lecun_normal',bias_initializer='zeros'))
67 |
68 | model.compile(loss=keras.losses.categorical_crossentropy,
69 | optimizer=keras.optimizers.Adam(learning_rate=1e-3),
70 | metrics=['accuracy'])
71 |
72 | model.fit(x_train, y_train,
73 | batch_size=batch_size,
74 | epochs=epochs,
75 | verbose=1,
76 | validation_data=(x_val, y_val))
77 |
78 | score = model.evaluate(x_test, y_test, verbose=0)
79 | print('Test loss:', score[0])
80 | print('Test accuracy:', score[1])
81 |
82 |
83 |
--------------------------------------------------------------------------------
/TF_2_x/MNIST-MLP-SELU.py:
--------------------------------------------------------------------------------
1 | # Adapted KERAS tutorial
2 |
3 | import tensorflow as tf
4 | import tensorflow.keras as keras
5 | from tensorflow.keras.datasets import mnist
6 | from tensorflow.keras.models import Sequential
7 | from tensorflow.keras.layers import Dense, AlphaDropout, Flatten
8 | from tensorflow.keras.layers import Conv2D, MaxPooling2D
9 | from tensorflow.keras import backend as K
10 | import numpy as np
11 |
12 |
13 | batch_size = 128
14 | num_classes = 10
15 | epochs = 20
16 |
17 | # input image dimensions
18 | img_rows, img_cols = 28, 28
19 |
20 | # list devices so you can check whether your gpu is available
21 | print(tf.config.list_physical_devices())
22 |
23 | # the data, shuffled and split between train and test sets
24 | (x_train, y_train), (x_test, y_test) = mnist.load_data()
25 |
26 | if K.image_data_format() == 'channels_first':
27 | x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
28 | x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
29 | input_shape = (1, img_rows, img_cols)
30 | else:
31 | x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
32 | x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
33 | input_shape = (img_rows, img_cols, 1)
34 |
35 | x_train = x_train.astype('float32')
36 | x_test = x_test.astype('float32')
37 | x_train /= 255
38 | #x_train = (x_train - np.mean(x_train))/np.std(x_train)
39 |
40 | x_test /= 255
41 | #x_test = (x_test - np.mean(x_train))/np.std(x_train)
42 |
43 | # create validation file
44 | x_val = x_train[:10000]
45 | x_train = x_train[10000:]
46 | y_val = y_train[:10000]
47 | y_train = y_train[10000:]
48 |
49 | print('x_train shape:', x_train.shape)
50 | print(x_train.shape[0], 'train samples')
51 | print(x_val.shape[0], 'val samples')
52 | print(x_test.shape[0], 'test samples')
53 |
54 | # convert class vectors to binary class matrices
55 | y_train = keras.utils.to_categorical(y_train, num_classes)
56 | y_val = keras.utils.to_categorical(y_val, num_classes)
57 | y_test = keras.utils.to_categorical(y_test, num_classes)
58 |
59 | model = Sequential()
60 | model.add(Flatten())
61 | model.add(Dense(512, activation='selu',kernel_initializer='lecun_normal',bias_initializer='zeros'))
62 | model.add(AlphaDropout(0.05))
63 | model.add(Dense(256, activation='selu',kernel_initializer='lecun_normal',bias_initializer='zeros'))
64 | model.add(AlphaDropout(0.05))
65 | model.add(Dense(num_classes, activation='softmax',kernel_initializer='lecun_normal',bias_initializer='zeros'))
66 |
67 | model.compile(loss=keras.losses.categorical_crossentropy,
68 | optimizer=keras.optimizers.Adam(learning_rate=0.001),
69 | metrics=['accuracy'])
70 |
71 | model.fit(x_train, y_train,
72 | batch_size=batch_size,
73 | epochs=epochs,
74 | verbose=1,
75 | validation_data=(x_val, y_val))
76 |
77 | score = model.evaluate(x_test, y_test, verbose=0)
78 | print('Test loss:', score[0])
79 | print('Test accuracy:', score[1])
80 |
81 |
--------------------------------------------------------------------------------
/TF_2_x/README.md:
--------------------------------------------------------------------------------
1 | Both Keras examples are based on dependencies described in [this](../environment.yml) environment file.
--------------------------------------------------------------------------------
/Tox21/README.md:
--------------------------------------------------------------------------------
1 | ## Tox21 data set
2 | - [download](http://bioinf.jku.at/research/DeepTox/tox21.zip)
3 |
4 |
--------------------------------------------------------------------------------
/UCI/README.md:
--------------------------------------------------------------------------------
1 | ## UCI data set
2 | - [download from original source](http://persoal.citius.usc.es/manuel.fernandez.delgado/papers/jmlr/data.tar.gz)
3 | - [download our processed version of the data set](http://www.bioinf.jku.at/people/klambauer/data_py.zip)
4 |
--------------------------------------------------------------------------------
/environment.yml:
--------------------------------------------------------------------------------
1 | name: snn
2 | channels:
3 | - pytorch
4 | - conda-forge
5 | - defaults
6 | dependencies:
7 | - python=3.7
8 | - pip=21.0.1
9 | - numpy=1.20.0
10 | - scipy=1.6.0
11 | - sympy=1.7.1
12 | - pandas=1.2.2
13 | - scikit-learn=0.24.1
14 | - matplotlib=3.3.4
15 | - jupyter=1.0.0
16 | - tqdm=4.56.0
17 | - tensorflow=2.3.0
18 | # GPU compatibility, check your nvidia drivers to find what toolkit is supported by your GPU
19 | - cudatoolkit=10.1
20 | # Pytorch dependencies
21 | - pytorch=1.7.1
22 | - torchvision=0.8.2
23 |
--------------------------------------------------------------------------------
/figure1/README.md:
--------------------------------------------------------------------------------
1 | # Reproducing Figure 1
2 |
3 | This contains the code necessary to reproduce Figure 1 from the SNN paper. Note that the code uses the [biutils](https://github.com/untom/biutils) package to load the MNIST/CIFAR10 datasets.
4 | You can use
5 |
6 | `pip install git+https://github.com/untom/biutils.git`
7 |
8 | to easily install the package.
9 |
10 | The data for the plot was created by running
11 |
12 | ./run.py -g 0 -d 08 -a selu -l 1e-5 -e 2000 --dataset mnist
13 | ./run.py -g 1 -d 16 -a selu -l 1e-5 -e 2000 --dataset mnist
14 | ./run.py -g 2 -d 32 -a selu -l 1e-5 -e 2000 --dataset mnist
15 | ./run.py -g 3 -d 08 -a relu --batchnorm -l 1e-5 -e 2000 --dataset mnist
16 | ./run.py -g 0 -d 16 -a relu --batchnorm -l 1e-5 -e 2000 --dataset mnist
17 | ./run.py -g 1 -d 32 -a relu --batchnorm -l 1e-5 -e 2000 --dataset mnist
18 |
19 | ./run.py -g 0 -d 08 -a selu -l 1e-5 -e 2000 --dataset cifar10
20 | ./run.py -g 1 -d 16 -a selu -l 1e-5 -e 2000 --dataset cifar10
21 | ./run.py -g 2 -d 32 -a selu -l 1e-5 -e 2000 --dataset cifar10
22 | ./run.py -g 3 -d 08 -a relu --batchnorm -l 1e-5 -e 2000 --dataset cifar10
23 | ./run.py -g 0 -d 16 -a relu --batchnorm -l 1e-5 -e 2000 --dataset cifar10
24 | ./run.py -g 1 -d 32 -a relu --batchnorm -l 1e-5 -e 2000 --dataset cifar10
25 |
26 | The plots where then created using `create_plots.ipynb`.
27 |
--------------------------------------------------------------------------------
/figure1/run.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import os
4 |
5 | from sklearn.preprocessing import StandardScaler
6 |
7 | import biutils # used to load the dataset
8 | import utils
9 |
10 |
11 | def model(dataset, n_layers, n_hidden, activation, dropout_rate, use_batchnorm):
12 |
13 | x_tr, y_tr, x_va, y_va = biutils.load_dataset(dataset)
14 | s = StandardScaler()
15 | s.fit(x_tr)
16 | x_tr = s.transform(x_tr)
17 | x_va = s.transform(x_va)
18 |
19 | if n_hidden == -1: # use as many hidden# as there are input features
20 | n_hidden = x_tr.shape[1]
21 |
22 | if activation == 'relu':
23 | act_fn = tf.nn.relu
24 | init_scale = 2.0
25 | elif activation == 'tanh':
26 | act_fn = tf.nn.tanh
27 | init_scale = 1.0
28 | elif activation == 'selu':
29 | act_fn = utils.selu
30 | init_scale = 1.0
31 | else:
32 | assert False, "Unknown activation"
33 |
34 | tf.reset_default_graph()
35 | x = tf.placeholder(np.float32, [None, x_tr.shape[1]], name="x")
36 | y = tf.placeholder(np.float32, [None, y_tr.shape[1]], name="y")
37 | is_training = tf.placeholder_with_default(tf.constant(False, tf.bool), shape=[], name='is_training')
38 |
39 | h = x
40 | if dropout_rate > 0.0:
41 | h = tf.layers.dropout(h, 0.2, training=is_training)
42 |
43 | for i in range(n_layers):
44 | s = np.sqrt(init_scale/h.get_shape().as_list()[1])
45 | init = tf.random_normal_initializer(stddev=s)
46 | h = tf.layers.dense(h, n_hidden, activation=act_fn, name='layer%d' % i, kernel_initializer=init)
47 | if use_batchnorm:
48 | h = tf.layers.batch_normalization(h, training=is_training)
49 | if dropout_rate > 0.0:
50 | h = tf.layers.dropout(h, dropout_rate, training=is_training)
51 |
52 | with tf.variable_scope('output_layer') as scope:
53 | o = tf.layers.dense(h, y_tr.shape[1], activation=None, name=scope)
54 | scope.reuse_variables()
55 |
56 | return (x_tr, y_tr, x_va, y_va), (x, y, is_training), o
57 |
58 |
59 | def run(n_layers, n_hidden, n_epochs, learning_rate, dataset, activation, logdir_base='/tmp',
60 | batch_size=64, dropout_rate=0.0, use_batchnorm=False):
61 |
62 | ld = '%s%s_d%02d_h%d_l%1.0e_%s' % (activation,
63 | 'bn' if use_batchnorm else '',
64 | n_layers, n_hidden, learning_rate,
65 | utils.get_timestamp())
66 | logdir = os.path.join(logdir_base, dataset, ld)
67 | print(logdir)
68 |
69 | dataset, variables, logits = model(dataset, n_layers, n_hidden, activation, dropout_rate, use_batchnorm)
70 | x_tr, y_tr, x_va, y_va = dataset
71 | x, y, is_training = variables
72 |
73 | prob_op = tf.nn.softmax(logits)
74 | loss_op = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=logits)
75 |
76 | optimizer = tf.train.GradientDescentOptimizer(learning_rate)
77 | variables_to_train = tf.trainable_variables()
78 | grads = optimizer.compute_gradients(loss_op, variables_to_train)
79 | global_step = tf.train.get_global_step()
80 | train_op = optimizer.apply_gradients(grads, global_step=global_step)
81 |
82 | loss_val = tf.Variable(0.0, trainable=False, dtype=np.float32)
83 | acc_op, acc_upd = tf.metrics.accuracy(tf.argmax(y, 1), tf.argmax(prob_op, 1), name='accuracy')
84 | acc_tr_op = tf.summary.scalar('acc_tr', acc_op)
85 | acc_va_op = tf.summary.scalar('acc_va', acc_op)
86 | loss_tr_op = tf.summary.scalar('loss_tr', loss_val / x_tr.shape[0])
87 | loss_va_op = tf.summary.scalar('loss_va', loss_val / x_va.shape[0])
88 | metric_vars = [i for i in tf.local_variables() if i.name.split('/')[0] == 'accuracy']
89 | reset_op = [tf.variables_initializer(metric_vars), loss_val.assign(0.0)]
90 | loss_upd = loss_val.assign_add(tf.reduce_sum(loss_op))
91 | smry_tr = tf.summary.merge([acc_tr_op, loss_tr_op])
92 |
93 | smry_va = tf.summary.merge([acc_va_op, loss_va_op])
94 | config = tf.ConfigProto(intra_op_parallelism_threads=2,
95 | use_per_session_threads=True,
96 | gpu_options = tf.GPUOptions(allow_growth=True)
97 | )
98 | with tf.Session(config=config) as sess:
99 | log = tf.summary.FileWriter(logdir, sess.graph)
100 | saver = tf.train.Saver(max_to_keep=100)
101 | sess.run(tf.global_variables_initializer())
102 | sess.run(tf.local_variables_initializer())
103 | fd_tr = {is_training: True}
104 |
105 | for cur_epoch in range(n_epochs):
106 | # get stats over whole training set
107 | for fd in utils.generate_minibatches(batch_size, [x, y], [x_tr, y_tr], feed_dict=fd_tr, shuffle=False):
108 | sess.run([acc_upd, loss_upd], feed_dict=fd)
109 | log.add_summary(sess.run(smry_tr, feed_dict=fd), cur_epoch)
110 | sess.run(reset_op)
111 |
112 | # training
113 | for fd in utils.generate_minibatches(batch_size, [x, y], [x_tr, y_tr], feed_dict=fd_tr):
114 | sess.run([train_op], feed_dict=fd)
115 |
116 | # validation
117 | for fd in utils.generate_minibatches(batch_size, [x, y], [x_va, y_va], shuffle=False):
118 | sess.run([acc_upd, loss_upd], feed_dict=fd)
119 | smry, acc = sess.run([smry_va, acc_op])
120 | log.add_summary(smry, cur_epoch)
121 | sess.run(reset_op)
122 | print("%3d: %3.3f" % (cur_epoch, acc), flush=True)
123 |
124 | if cur_epoch % 250 == 0 and cur_epoch > 0:
125 | saver.save(sess, os.path.join(logdir, 'model'), global_step=cur_epoch)
126 |
127 |
128 | from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
129 | parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
130 | parser.add_argument("-n", "--nhidden", type=int, help='hidden units (-1: use input size)', default=-1)
131 | parser.add_argument("-d", "--depth", type=int, help='number of hidden layers', default=3)
132 | parser.add_argument("-a", "--activation", choices=['relu', 'selu', 'tanh'], default='relu')
133 | parser.add_argument("-b", "--batchsize", type=int, help='batch size', default=128)
134 | parser.add_argument("-e", "--epochs", type=int, help='number of training epochs', default=30)
135 | parser.add_argument("-l", "--learningrate", type=float, help='learning rate', default=1e-5)
136 | parser.add_argument("-g", "--gpuid", type=str, help='GPU to use (leave blank for CPU only)', default="")
137 | parser.add_argument("--batchnorm", help='use batchnorm', action="store_true")
138 | parser.add_argument("--dropout", type=float, help='hidden dropout rate (implies input-dropout of 0.2)', default=0.0)
139 | parser.add_argument("--dataset", type=str, help='name of dataset', default='mnist_bgimg')
140 | parser.add_argument("--logdir", type=str, help='directory for TF logs and summaries', default="logs")
141 |
142 | # by parsing the arguments already, we can bail out now instead of waiting
143 | # for TF to load, in case the arguments aren't ok
144 | args = parser.parse_args()
145 | os.environ['CUDA_VISIBLE_DEVICES'] = args.gpuid
146 |
147 | import numpy as np
148 | import tensorflow as tf
149 |
150 | logdir_base = os.getcwd()
151 | run(args.depth, args.nhidden, args.epochs, args.learningrate, args.dataset,
152 | args.activation, args.logdir, args.batchsize, args.dropout, args.batchnorm)
153 |
--------------------------------------------------------------------------------
/figure1/utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | '''
3 | Tensorflow Implementation of the Scaled ELU function and Dropout
4 | '''
5 |
6 | import numbers
7 |
8 | import numpy as np
9 | import tensorflow as tf
10 | from tensorflow.contrib import layers
11 | from tensorflow.python.framework import ops
12 | from tensorflow.python.framework import tensor_shape
13 | from tensorflow.python.framework import tensor_util
14 | from tensorflow.python.layers import utils
15 | from tensorflow.python.ops import array_ops
16 | from tensorflow.python.ops import math_ops
17 | from tensorflow.python.ops import random_ops
18 |
19 |
20 | # (1) scale inputs to zero mean and unit variance
21 |
22 |
23 | # (2) use SELUs
24 | def selu(x):
25 | with ops.name_scope('elu') as scope:
26 | alpha = 1.6732632423543772848170429916717
27 | scale = 1.0507009873554804934193349852946
28 | return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))
29 |
30 |
31 | # (3) initialize weights with stddev sqrt(1/n)
32 | # e.g. use:
33 | initializer = layers.variance_scaling_initializer(factor=1.0, mode='FAN_IN')
34 |
35 |
36 | # (4) use this dropout
37 | def dropout_selu(x, rate, alpha= -1.7580993408473766, fixedPointMean=0.0, fixedPointVar=1.0,
38 | noise_shape=None, seed=None, name=None, training=False):
39 | """Dropout to a value with rescaling."""
40 |
41 | def dropout_selu_impl(x, rate, alpha, noise_shape, seed, name):
42 | keep_prob = 1.0 - rate
43 | x = ops.convert_to_tensor(x, name="x")
44 | if isinstance(keep_prob, numbers.Real) and not 0 < keep_prob <= 1:
45 | raise ValueError("keep_prob must be a scalar tensor or a float in the "
46 | "range (0, 1], got %g" % keep_prob)
47 | keep_prob = ops.convert_to_tensor(keep_prob, dtype=x.dtype, name="keep_prob")
48 | keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())
49 |
50 | alpha = ops.convert_to_tensor(alpha, dtype=x.dtype, name="alpha")
51 | keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())
52 |
53 | if tensor_util.constant_value(keep_prob) == 1:
54 | return x
55 |
56 | noise_shape = noise_shape if noise_shape is not None else array_ops.shape(x)
57 | random_tensor = keep_prob
58 | random_tensor += random_ops.random_uniform(noise_shape, seed=seed, dtype=x.dtype)
59 | binary_tensor = math_ops.floor(random_tensor)
60 | ret = x * binary_tensor + alpha * (1-binary_tensor)
61 |
62 | a = math_ops.sqrt(fixedPointVar / (keep_prob *((1-keep_prob) * math_ops.pow(alpha-fixedPointMean,2) + fixedPointVar)))
63 |
64 | b = fixedPointMean - a * (keep_prob * fixedPointMean + (1 - keep_prob) * alpha)
65 | ret = a * ret + b
66 | ret.set_shape(x.get_shape())
67 | return ret
68 |
69 | with ops.name_scope(name, "dropout", [x]) as name:
70 | return utils.smart_cond(training,
71 | lambda: dropout_selu_impl(x, rate, alpha, noise_shape, seed, name),
72 | lambda: array_ops.identity(x))
73 |
74 |
75 | def get_timestamp(fmt='%y%m%d_%H%M'):
76 | '''Returns a string that contains the current date and time.
77 |
78 | Suggested formats:
79 | short_format=%y%m%d_%H%M (default)
80 | long format=%Y%m%d_%H%M%S
81 | '''
82 | import datetime
83 | now = datetime.datetime.now()
84 | return datetime.datetime.strftime(now, fmt)
85 |
86 |
87 | def generate_slices(n, slice_size, allow_smaller_final_batch=True):
88 | """Generates slices of given slice_size up to n"""
89 | start, end = 0, 0
90 | for pack_num in range(int(n / slice_size)):
91 | end = start + slice_size
92 | yield slice(start, end, None)
93 | start = end
94 | # last slice might not be a full batch
95 | if allow_smaller_final_batch:
96 | if end < n:
97 | yield slice(end, n, None)
98 |
99 |
100 | def generate_minibatches(batch_size, ph_list, data_list, n_epochs=1,
101 | allow_smaller_final_batch=False, shuffle=True,
102 | feed_dict=None):
103 | cnt_epochs = 0
104 | assert len(ph_list) == len(data_list), "Passed different number of data and placeholders"
105 | assert len(data_list) >= 0, "Passed empty lists"
106 |
107 | n_samples = data_list[0].shape[0]
108 | n_items = len(data_list)
109 |
110 | while True:
111 | if shuffle:
112 | idx = np.arange(n_samples)
113 | np.random.shuffle(idx)
114 | for i in range(n_items):
115 | data_list[i] = data_list[i][idx]
116 |
117 | if feed_dict is None:
118 | feed_dict = {}
119 |
120 | for s in generate_slices(n_samples, batch_size, allow_smaller_final_batch):
121 | for i in range(n_items):
122 | ph = ph_list[i]
123 | d = data_list[i][s]
124 | feed_dict[ph] = d
125 | yield feed_dict
126 | cnt_epochs += 1
127 | if n_epochs is not None and cnt_epochs >= n_epochs:
128 | break
129 |
--------------------------------------------------------------------------------