Repository: fvisin/reseg Branch: master Commit: 8040d190fcdb Files: 13 Total size: 224.8 KB Directory structure: gitextract_ir9a6mvo/ ├── .gitignore ├── LICENSE ├── README.md ├── camvid.py ├── config_datasets.py ├── evaluate_camvid.py ├── get_info_model.py ├── helper_dataset.py ├── layers.py ├── padded.py ├── reseg.py ├── utils.py └── vgg16.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.pyc segmentations *_models/ tmp evaluate* *.pkl !evaluate_camvid.py ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ If you use this code, please cite one of the following papers: * \[1\] Francesco Visin, Kyle Kastner, Kyunghyun Cho, Matteo Matteucci, Aaron Courville, Yoshua Bengio - [ReNet: A Recurrent Neural Network Based Alternative to Convolutional Networks]( https://arxiv.org/pdf/1505.00393.pdf) ([BibTeX]( https://gist.github.com/fvisin/e450c4f55a527c5db802e69574b79a95#file-renet-bib)) * \[2\] Francesco Visin, Marco Ciccone, Adriana Romero, Kyle Kastner, Kyunghyun Cho, Yoshua Bengio, Matteo Matteucci, Aaron Courville - [ReSeg: A Recurrent Neural Network-based Model for Semantic Segmentation]( http://arxiv.org/pdf/1511.07053) ([BibTeX]( https://gist.github.com/fvisin/61b1dd3777ea91a0e3ad963366a61fb1#file-reseg-bib)) Setup ----- #### Install Theano Download Theano and make sure it's working properly. All the information you need can be found by following this link: http://deeplearning.net/software/theano/ #### Install other dependencies This software relies on some amazing third-party software libraries. You can install them with *pip*: `pip install <--user> lasagne matplotlib Pillow progressbar2 pydot-ng retrying scikit-image scikit-learn tabulate` *(Use the `--user` option if you don't want to install them globally or you don't have sudo privileges on your machine.)* #### Download the CamVid dataset Download the CamVid dataset from http://mi.eng.cam.ac.uk/research/projects/VideoRec/CamVid/ Resize the images to 480X360 resolution. The program expects to find the dataset data in `./datasets/camvid/`. You can change this path modifying `camvid.py` if you want. #### Download the VGG-16 weights Download the VGG weights for Lasagne from: https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/vgg16.pkl Once downloaded, rename them as `w_vgg16.pkl` and put them in the root directory of this code. Reproducing the Results ----------------------- To reproduce the results of the ReSeg paper run `python evaluate_camvid.py` (or `python evaluate_camvid_with_cb.py` to reproduce the experiment with class balancing). Make sure to set the appropriate THEANO_FLAGS to run the model on your machine (most probably `export THEANO_FLAGS=device=gpu,floatX=float32`) The program will output some metrics on the current minibatch iteration during training: Epoch 0/5000 Up 367 Cost 270034.031250, DD 0.000046, UD 0.848205 (None, 360, 480, 3) More in detail, it will show the current epoch, the incremental update counter (i.e. number of minibatches seen), the cost of the current iteration, the time (in seconds) required to load the data `DD` and to train and update the network's parameters `DD`. Finally, it will print the size of the currently processed minibatch. `None` will be displayed on variable-sized dimensions. At the end of each epoch, it will validate the performances on the training, validation and test set and save some sample images for each set in a *segmentations* directory inside the root directory of the script. At the end of the training `get_info_model.py` can be used to show some information on the trained model. Run `python get_info_model.py -h` for a list of the arguments and their explanation. **** Note: In case you want to modify this code to reproduce the results of "Combining the best of convolutional layers and recurrent layers: A hybrid network for semantic segmentation" please let us know! Acknowledgments --------------- Many people contributed in different ways to this project. We are extremely thankful to the [Theano](http://deeplearning.net/software/theano/) developers and to many people at [MILA](http://mila.umontreal.ca/) for their support and for the many insightful discussions. We also thank the developer of [Lasagne](http://lasagne.readthedocs.io/), a powerful yet light framework on top of Theano. I wish I discovered it at the beginning of this project! :) Finally, our gratitude goes to the developers of all the great libraries we used in this project, to all the people who got involved with the project at any level and to our generous sponsors. ================================================ FILE: camvid.py ================================================ from __future__ import division import os from collections import OrderedDict import numpy as np from skimage import img_as_ubyte from skimage.color import label2rgb, rgb2hsv from skimage.io import ImageCollection from skimage.transform import resize from itertools import izip from config_datasets import (colormap_datasets as colors_list) from helper_dataset import convert_RGB_mask_to_index, save_image N_DEBUG = -5 DEBUG_SAVE_IMG = False DEBUG_SAVE_MASK = False intX = 'uint8' def properties(): return { # 'reshape': [212, 264, 3], # 'reorder': [0, 1, 2], # 'rereorder': [0, 1, 2] 'has_void_class': True } """ compare_mask_image_filenames: mask = [i.split('/')[-1].replace('_L.png', '.png') for i in filenames_mask] compare_mask_image_filenames_segnet mask = [i.split('/')[-1].replace('annot', '') for i in filenames_mask] """ def load_images(img_path, gt_path, colors, load_greylevel_mask=False, resize_images=False, resize_size=-1, save=False, color_space='RGB'): if load_greylevel_mask: assert not save images = [] masks = [] filenames_images = [] print "Loading images..." # print img_path labs = ImageCollection(os.path.join(img_path, "*.png")) for i, (inpath, im) in enumerate(izip(labs.files, labs)): if i == N_DEBUG: break assert np.amax(im) <= 255, "Image is not 8-bit" if resize_images and resize_size != -1: w, h = resize_size im = resize(im, (h, w), order=3) # order=3 : bicubic interpolation # it's normalized by default btw 0-1 by the resize function # so we want to preserve the range im = img_as_ubyte(im) im = im.astype(intX) if color_space == "HSV": im = rgb2hsv(im) if DEBUG_SAVE_IMG: outpath = inpath.replace('imgs', 'debug_imgs') save_image(outpath, im) images.append(im) filenames_images.append(inpath) print "Loading masks..." if load_greylevel_mask: gt_path = gt_path.replace("gt", "gt_grey") filenames_mask = [] labs = ImageCollection(os.path.join(gt_path, "*.png")) for i, (inpath, im) in enumerate(izip(labs.files, labs)): if i == N_DEBUG: break if resize_images and resize_size != -1: w, h = resize_size im = (resize(im, (h, w), order=0) * 255).astype(np.uint8) filenames_mask.append(inpath) # print inpath if load_greylevel_mask: mask = im else: mask = convert_RGB_mask_to_index( im, colors, ignore_missing_labels=True) if save: outpath = inpath.replace("gt", "gt_grey") save_image(outpath, mask) mask = np.array(mask).astype(intX) if DEBUG_SAVE_MASK: outpath = inpath.replace('gt', 'debug_gt') outpath = inpath.replace('annot', 'debug_annot') # print np.unique(mask) save_image(outpath, label2rgb(mask, colors=colors_list['camvid'])) masks.append(mask) assert len(images) == len( masks), "Train Images and masks are not in the same quantity" return images, masks, filenames_images def load_dataset_camvid(path, load_greylevel_mask=False, classes='subset_11', resize_images=False, resize_size=-1, use_standard_split=True, save=False, color_space='RGB'): # WORKING: but image Seq05VD_f02610_L.png has some problems, some pixels # have other values so I treated as Void img_train_path = os.path.join(path, 'imgs', 'train') img_test_path = os.path.join(path, 'imgs', 'test') img_val_path = os.path.join(path, 'imgs', 'val') gt_train_path = os.path.join(path, 'gt', 'train') gt_test_path = os.path.join(path, 'gt', 'test') gt_val_path = os.path.join(path, 'gt', 'val') camvid_all_colors = OrderedDict([ ("Animal", np.array([[64, 128, 64]], dtype=np.uint8)), ("Archway", np.array([[192, 0, 128]], dtype=np.uint8)), ("Bicyclist", np.array([[0, 128, 192]], dtype=np.uint8)), ("Bridge", np.array([[0, 128, 64]], dtype=np.uint8)), ("Building", np.array([[128, 0, 0]], dtype=np.uint8)), ("Car", np.array([[64, 0, 128]], dtype=np.uint8)), ("CartLuggagePram", np.array([[64, 0, 192]], dtype=np.uint8)), ("Child", np.array([[192, 128, 64]], dtype=np.uint8)), ("Column_Pole", np.array([[192, 192, 128]], dtype=np.uint8)), ("Fence", np.array([[64, 64, 128]], dtype=np.uint8)), ("LaneMkgsDriv", np.array([[128, 0, 192]], dtype=np.uint8)), ("LaneMkgsNonDriv", np.array([[192, 0, 64]], dtype=np.uint8)), ("Misc_Text", np.array([[128, 128, 64]], dtype=np.uint8)), ("MotorcycleScooter", np.array([[192, 0, 192]], dtype=np.uint8)), ("OtherMoving", np.array([[128, 64, 64]], dtype=np.uint8)), ("ParkingBlock", np.array([[64, 192, 128]], dtype=np.uint8)), ("Pedestrian", np.array([[64, 64, 0]], dtype=np.uint8)), ("Road", np.array([[128, 64, 128]], dtype=np.uint8)), ("RoadShoulder", np.array([[128, 128, 192]], dtype=np.uint8)), ("Sidewalk", np.array([[0, 0, 192]], dtype=np.uint8)), ("SignSymbol", np.array([[192, 128, 128]], dtype=np.uint8)), ("Sky", np.array([[128, 128, 128]], dtype=np.uint8)), ("SUVPickupTruck", np.array([[64, 128, 192]], dtype=np.uint8)), ("TrafficCone", np.array([[0, 0, 64]], dtype=np.uint8)), ("TrafficLight", np.array([[0, 64, 64]], dtype=np.uint8)), ("Train", np.array([[192, 64, 128]], dtype=np.uint8)), ("Tree", np.array([[128, 128, 0]], dtype=np.uint8)), ("Truck_Bus", np.array([[192, 128, 192]], dtype=np.uint8)), ("Tunnel", np.array([[64, 0, 64]], dtype=np.uint8)), ("VegetationMisc", np.array([[192, 192, 0]], dtype=np.uint8)), ("Wall", np.array([[64, 192, 0]], dtype=np.uint8)), ("Void", np.array([[0, 0, 0]], dtype=np.uint8)) ]) camvid_11_colors = OrderedDict([ ("Sky", np.array([[128, 128, 128]], dtype=np.uint8)), ("Building", np.array([[128, 0, 0], # Building [64, 192, 0], # Wall [0, 128, 64] # Bridge ], dtype=np.uint8)), ("Column_Pole", np.array([[192, 192, 128]], dtype=np.uint8)), ("Road", np.array([[128, 64, 128], # Road [128, 0, 192], # LaneMkgsDriv [192, 0, 64], # LaneMkgsNonDriv [128, 128, 192] # RoadShoulder ], dtype=np.uint8)), ("Sidewalk", np.array([[0, 0, 192], # Sidewalk [64, 192, 128] # ParkingBlock ], dtype=np.uint8)), ("Tree", np.array([[128, 128, 0], # Tree [192, 192, 0] # VegetationMisc ], dtype=np.uint8)), ("SignSymbol", np.array([[192, 128, 128], # SignSymbol # [128, 128, 64], # Misc_Text [0, 64, 64], # TrafficLight [0, 0, 64] # TrafficCone ], dtype=np.uint8)), ("Fence", np.array([[64, 64, 128]], dtype=np.uint8)), ("Car", np.array([[64, 0, 128], # Car [192, 128, 192], # Truck_Bus [64, 128, 192], # SUVPickupTruck [128, 64, 64], # OtherMoving [64, 0, 192], # CartLuggagePram ], dtype=np.uint8)), ("Pedestrian", np.array([[64, 64, 0], # Pedestrian [192, 128, 64] # Child ], dtype=np.uint8)), ("Bicyclist", np.array([[0, 128, 192], # Bicyclist [192, 0, 192], # MotorcycleScooter ], dtype=np.uint8)), ("Void", np.array([[0, 0, 0]], dtype=np.uint8)) ]) # consider as void all the other classes camvid_colors = camvid_11_colors if classes == 'subset_11' else \ camvid_all_colors print "Processing Camvid train dataset..." img_train, mask_train, filenames_train = load_images( img_train_path, gt_train_path, camvid_colors, load_greylevel_mask, resize_images, resize_size, save, color_space) print "Processing Camvid test dataset..." img_test, mask_test, filenames_test = load_images( img_test_path, gt_test_path, camvid_colors, load_greylevel_mask, resize_images, resize_size, save, color_space) print "Processing Camvid validation dataset..." img_val, mask_val, filenames_val = load_images( img_val_path, gt_val_path, camvid_colors, load_greylevel_mask, resize_images, resize_size, save, color_space) return (img_train, mask_train, filenames_train, img_test, mask_test, filenames_test, img_val, mask_val, filenames_val) def load_dataset_camvid_segnet(path): img_train_path = os.path.join(path, 'train') img_valid_path = os.path.join(path, 'val') img_test_path = os.path.join(path, 'test') gt_train_path = os.path.join(path, 'trainannot') gt_valid_path = os.path.join(path, 'valannot') gt_test_path = os.path.join(path, 'testannot') camvid_colors = OrderedDict([ ("Sky", np.array([128, 128, 128], dtype=np.uint8)), ("Building", np.array([128, 0, 0], dtype=np.uint8)), ("Column_Pole", np.array([192, 192, 128], dtype=np.uint8)), ("Road", np.array([128, 64, 128], dtype=np.uint8)), ("Sidewalk", np.array([0, 0, 192], dtype=np.uint8)), ("Tree", np.array([128, 128, 0], dtype=np.uint8)), ("SignSymbol", np.array([192, 128, 128], dtype=np.uint8)), ("Fence", np.array([64, 64, 128], dtype=np.uint8)), ("Car", np.array([64, 0, 128], dtype=np.uint8)), ("Pedestrian", np.array([64, 64, 0], dtype=np.uint8)), ("Bicyclist", np.array([0, 128, 192], dtype=np.uint8)), ("Void", np.array([0, 0, 0], dtype=np.uint8)) ]) print "Processing Camvid SegNet train dataset..." img_train, mask_train, filenames_train = load_images( img_train_path, gt_train_path, camvid_colors, load_greylevel_mask=True, save=False) # load_greylevel_mask=True by default because it's grey print "Processing Camvid SegNet valid dataset..." img_valid, mask_valid, filenames_valid = load_images( img_valid_path, gt_valid_path, camvid_colors, load_greylevel_mask=True, save=False) # load_greylevel_mask=True by default because it's grey print "Processing Camvid SegNet test dataset..." img_test, mask_test, filenames_test = load_images( img_test_path, gt_test_path, camvid_colors, load_greylevel_mask=True, save=False) # load_greylevel_mask=True by default because it's grey return (img_train, mask_train, filenames_train, img_test, mask_test, filenames_test, img_valid, mask_valid, filenames_valid) def load_data( path=os.path.expanduser('./datasets/camvid/'), randomize=False, resize_images=True, resize_size=[320, 240], # w x h : 960x720, 480x360, 320x240 color=False, color_space='RGB', normalize=False, classes='subset_11', # subset_11 , all version='segnet', # standard, segnet split=[.44, .22], with_filenames=False, load_greylevel_mask=False, save=False, compute_stats='all', rng=None, with_fullmasks=False, **kwargs ): """Dataset loader Parameter --------- path : string the path to the dataset images. randomize False resize False use_fullsize_images True version: string standard, segnet compute_stas: string train, all """ ############# # LOAD DATA # ############# if version == 'segnet': path = os.path.join(path, 'segnet') (img_train_segnet, mask_train_segnet, filenames_train_segnet, img_test, mask_test, filenames_test, img_val_segnet, mask_val_segnet, filenames_val_segnet) = load_dataset_camvid_segnet(path) img_train = img_train_segnet mask_train = mask_train_segnet filenames_train = filenames_train_segnet img_val = img_val_segnet mask_val = mask_val_segnet filenames_val = filenames_val_segnet elif version == 'standard': path = os.path.join(path, 'splitted_960x720') (img_train, mask_train, filenames_train, img_test, mask_test, filenames_test, img_val, mask_val, filenames_val) = load_dataset_camvid( path, resize_images=resize_images, resize_size=resize_size, load_greylevel_mask=load_greylevel_mask, classes=classes, save=save, color_space=color_space) # if compute_stats == 'all': # images = np.asarray(img_train + img_val + img_test) # elif compute_stats == 'train': # images = np.asarray(img_train) # all images have the same dimension --> we can compute perpixel statistics # mean = images.mean(axis=0)[np.newaxis, ...] # std = np.maximum(images.std(axis=0), 1e-8)[np.newaxis, ...] # print "Computing dataset statistics ..." mean = 0 std = 0 # split datasets ntrain = len(img_train) ntest = len(img_test) nvalid = len(img_val) ntot = ntrain + ntest + nvalid train_set_x = np.array(img_train) train_set_y = np.array(mask_train) test_set_x = np.array(img_test) test_set_y = np.array(mask_test) valid_set_x = np.array(img_val) valid_set_y = np.array(mask_val) # u_train, c_train = np.unique(train_set_y, return_counts=True) # u_valid, c_valid = np.unique(valid_set_y, return_counts=True) # u_test, c_test = np.unique(test_set_y, return_counts=True) # # print u_train # print np.round(100 * c_train / np.sum(c_train), 2) # # print u_valid # print np.round(100 * c_valid / np.sum(c_valid), 2) # # print u_test # print np.round(100 * c_test / np.sum(c_test), 2) train = (train_set_x, train_set_y) valid = (valid_set_x, valid_set_y) test = (test_set_x, test_set_y) filenames = [np.array(filenames_train), np.array(filenames_val), np.array(filenames_test)] print "load_data Done!" print('Tot images:{} Train:{} Valid:{} Test:{}').format( ntot, ntrain, nvalid, ntest) """ # Debug for types print (train_set_x.dtype) print (test_set_x.dtype) print (valid_set_x.dtype) print (train_set_y.dtype) print (test_set_y.dtype) print (valid_set_y.dtype) print (train_set_x[0].dtype) print (test_set_x[0].dtype) print (valid_set_x[0].dtype) print (train_set_y[0].dtype) print (test_set_y[0].dtype) print (valid_set_y[0].dtype) """ out_list = [train, valid, test, mean, std] if with_filenames: out_list.append(filenames) if with_fullmasks: out_list.append([]) return out_list if __name__ == '__main__': load_data(save=False) ================================================ FILE: config_datasets.py ================================================ from collections import OrderedDict import numpy as np # COLORMAPS cmaps = [('Perceptually Uniform Sequential', ['viridis', 'inferno', 'plasma', 'magma']), ('Sequential', ['Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']), ('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool', 'copper', 'gist_heat', 'gray', 'hot', 'pink', 'spring', 'summer', 'winter']), ('Diverging', ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral', 'seismic']), ('Qualitative', ['Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3']), ('Miscellaneous', ['gist_earth', 'terrain', 'ocean', 'gist_stern', 'brg', 'CMRmap', 'cubehelix', 'gnuplot', 'gnuplot2', 'gist_ncar', 'nipy_spectral', 'jet', 'rainbow', 'gist_rainbow', 'hsv', 'flag', 'prism'])] # ##### CAMVID ##### # colormap_camvid = OrderedDict([ (0, np.array([128, 128, 128], dtype=np.uint8)), # sky (1, np.array([128, 0, 0], dtype=np.uint8)), # Building (2, np.array([192, 192, 128], dtype=np.uint8)), # Pole (3, np.array([128, 64, 128], dtype=np.uint8)), # Road (4, np.array([0, 0, 192], dtype=np.uint8)), # Sidewalk (5, np.array([128, 128, 0], dtype=np.uint8)), # Tree (6, np.array([192, 128, 128], dtype=np.uint8)), # SignSymbol (7, np.array([64, 64, 128], dtype=np.uint8)), # Fence (8, np.array([64, 0, 128], dtype=np.uint8)), # Car (9, np.array([64, 64, 0], dtype=np.uint8)), # Pedestrian (10, np.array([0, 128, 192], dtype=np.uint8)), # Bicyclist (11, np.array([0, 0, 0], dtype=np.uint8)) # Unlabeled ]) headers_camvid = ["Sky", "Building", "Column_Pole", "Road", "Sidewalk", "Tree", "SignSymbol", "Fence", "Car", "Pedestrian", "Bicyclist", "Void"] # DATASET DICTIONARIES # colormap_datasets = dict() colormap_datasets["camvid"] = colormap_camvid for key, value in colormap_datasets.iteritems(): colormap_datasets[key] = np.asarray( [z for z in zip(*value.items())[1]]) / 255. headers_datasets = dict() headers_datasets["camvid"] = headers_camvid ================================================ FILE: evaluate_camvid.py ================================================ from reseg import train import lasagne def main(job_id, params): result = train( saveto=params['saveto'], tmp_saveto=params['tmp-saveto'], # Input Conv layers in_nfilters=params['in-nfilters'], in_filters_size=params['in-filters-size'], in_filters_stride=params['in-filters-stride'], in_W_init=params['in-W-init'], in_b_init=params['in-b-init'], in_nonlinearity=params['in-nonlinearity'], # RNNs layers dim_proj=params['dim-proj'], pwidth=params['pwidth'], pheight=params['pheight'], stack_sublayers=params['stack-sublayers'], RecurrentNet=params['RecurrentNet'], nonlinearity=params['nonlinearity'], hid_init=params['hid-init'], grad_clipping=params['grad-clipping'], precompute_input=params['precompute-input'], mask_input=params['mask-input'], # GRU specific params gru_resetgate=params['gru-resetgate'], gru_updategate=params['gru-updategate'], gru_hidden_update=params['gru-hidden-update'], gru_hid_init=params['gru-hid-init'], # LSTM specific params lstm_ingate=params['lstm-ingate'], lstm_forgetgate=params['lstm-forgetgate'], lstm_cell=params['lstm-cell'], lstm_outgate=params['lstm-outgate'], # RNN specific params rnn_W_in_to_hid=params['rnn-W-in-to-hid'], rnn_W_hid_to_hid=params['rnn-W-hid-to-hid'], rnn_b=params['rnn-b'], # Output upsampling layers out_upsampling=params['out-upsampling'], out_nfilters=params['out-nfilters'], out_filters_size=params['out-filters-size'], out_filters_stride=params['out-filters-stride'], out_W_init=params['out-W-init'], out_b_init=params['out-b-init'], out_nonlinearity=params['out-nonlinearity'], # Prediction, Softmax intermediate_pred=params['intermediate-pred'], class_balance=params['class-balance'], # Special layers batch_norm=params['batch-norm'], use_dropout=params['use-dropout'], dropout_rate=params['dropout-rate'], use_dropout_x=params['use-dropout-x'], dropout_x_rate=params['dropout-x-rate'], # Optimization method optimizer=params['optimizer'], learning_rate=params['learning-rate'], momentum=params['momentum'], rho=params['rho'], beta1=params['beta1'], beta2=params['beta2'], epsilon=params['epsilon'], weight_decay=params['weight-decay'], weight_noise=params['weight-noise'], # Early stopping patience=params['patience'], max_epochs=params['max-epochs'], min_epochs=params['min-epochs'], # Sampling and validation params validFreq=params['validFreq'], saveFreq=params['saveFreq'], n_save=params['n-save'], # Batch params batch_size=params['batch-size'], valid_batch_size=params['valid-batch-size'], shuffle=params['shuffle'], # Dataset dataset=params['dataset'], color_space=params['color-space'], color=params['color'], resize_images=params['resize-images'], resize_size=params['resize-size'], # Pre_processing preprocess_type=params['preprocess-type'], patch_size=params['patch-size'], max_patches=params['max-patches'], # Data augmentation do_random_flip=params['do-random-flip'], do_random_shift=params['do-random-shift'], do_random_invert_color=params['do-random-invert-color'], shift_pixels=params['shift-pixels'], reload_=params['reload'] # fixed params ) return result if __name__ == '__main__': dataset = 'camvid' path = dataset + '_models/model_recseg' + __file__[8:-3] + '.npz' main(1, { 'saveto': path, 'tmp-saveto': 'tmp/' + path, # Note: with linear_conv you cannot select every filter size. # It is not trivial to invert with expand unless they are a # multiple of the image size, i.e., you would have to "blend" together # multiple predictions because one pixel cannot be fully predicted just # by one element of the last feature map # call ConvNet.compute_reasonable_values() to find these # note you should pick one pair (p1, p2) from the first list and # another pair (p3, p4) from the second, then set in_filter_size # to be (p1, p3),(p2, p4) # valid: 1 + (input_dim - filter_dim) / stride_dim # Input Conv layers 'in-nfilters': 'conv3_3', # None = no input convolution 'in-filters-size': (), 'in-filters-stride': (), 'in-W-init': lasagne.init.GlorotUniform(), 'in-b-init': lasagne.init.Constant(0.), 'in-nonlinearity': lasagne.nonlinearities.rectify, # RNNs layers 'dim-proj': [100, 100], 'pwidth': [1, 1], 'pheight': [1, 1], 'stack-sublayers': (True, True), 'RecurrentNet': lasagne.layers.GRULayer, 'nonlinearity': lasagne.nonlinearities.rectify, 'hid-init': lasagne.init.Constant(0.), 'grad-clipping': 0, 'precompute-input': True, 'mask-input': None, # GRU specific params 'gru-resetgate': lasagne.layers.Gate(W_cell=None), 'gru-updategate': lasagne.layers.Gate(W_cell=None), 'gru-hidden-update': lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), 'gru-hid-init': lasagne.init.Constant(0.), # LSTM specific params 'lstm-ingate': lasagne.layers.Gate(), 'lstm-forgetgate': lasagne.layers.Gate(), 'lstm-cell': lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), 'lstm-outgate': lasagne.layers.Gate(), # RNN specific params 'rnn-W-in-to-hid': lasagne.init.Uniform(), 'rnn-W-hid-to-hid': lasagne.init.Uniform(), 'rnn-b': lasagne.init.Constant(0.), # Output upsampling layers 'out-upsampling': 'grad', 'out-nfilters': [50, 50], 'out-filters-size': [(2, 2), (2, 2)], 'out-filters-stride': [(2, 2), (2, 2)], 'out-W-init': lasagne.init.GlorotUniform(), 'out-b-init': lasagne.init.Constant(0.), 'out-nonlinearity': lasagne.nonlinearities.rectify, # Prediction, Softmax 'intermediate-pred': None, 'class-balance': None, # Special layers 'batch-norm': False, 'use-dropout': False, 'dropout-rate': 0.5, 'use-dropout-x': False, 'dropout-x-rate': 0.8, # Optimization method 'optimizer': lasagne.updates.adadelta, 'learning-rate': None, 'momentum': None, 'rho': None, 'beta1': None, 'beta2': None, 'epsilon': None, 'weight-decay': 0., # l2 reg 'weight-noise': 0., # Early stopping 'patience': 500, # Num updates with no improvement before early stop 'max-epochs': 5000, 'min-epochs': 100, # Sampling and validation params 'validFreq': -1, 'saveFreq': -1, # Parameters pickle frequency 'n-save': -1, # If n-save is a list of indexes, the corresponding # elements of each split are saved. If n-save is an # integer, n-save random elements for each split are # saved. If n-save is -1, all the dataset is saved # Batch params 'batch-size': 5, 'valid-batch-size': 5, 'shuffle': True, # Dataset 'dataset': dataset, 'color-space': 'RGB', 'color': True, 'resize-images': True, 'resize-size': (360, 480), # Pre-processing 'preprocess-type': None, 'patch-size': (9, 9), 'max-patches': 1e5, # Data augmentation 'do-random-flip': False, 'do-random-shift': False, 'do-random-invert-color': False, 'shift-pixels': 2, 'reload': False }) ================================================ FILE: get_info_model.py ================================================ import argparse import collections import cPickle as pkl import matplotlib.pyplot as plt import numpy from tabulate import tabulate from config_datasets import headers_datasets def print_pkl_params(pkl_path, *args): """Loads a parameter pkl archive and prints the parameters Parameters ---------- pkl_path : string The path of the .pkl parameter archive. *args : dict The arguments to print_params. """ try: options = pkl.load(open(pkl_path, 'rb')) except IOError: print "Couldn't load " + pkl_path return 0 save_plot_path = pkl_path.replace('models', 'plots').replace('.npz.pkl', '.pdf') return print_params(options, save_plot_path, *args) def print_params(fp, save_plot_path='', print_commit_hash=False, plot=False, print_history=False, print_best_class_accuracy=False, ): """Prints the parameter of the model Parameters ---------- fp : dict The dictionary of the model's parameters print_commit_hash : bool If True, the commit hash will be printed plot : bool If True, the error curves will be plotted print_history : bool If True the history of the accuracies will be printed """ dataset = fp.get("dataset", "camvid") errs = fp.get('history_acc', None) if errs is None: errs = fp.get('history_errs', None) conf_matrices = numpy.array(fp['history_conf_matrix']) iou_indeces = numpy.array(fp['history_iou_index']) #nclasses = conf_matrices.shape[2] if len(conf_matrices) > 0 else -1 # hack for nyu because now I don't have the time to think to something else # if dataset == 'nyu_depth': # dataset = 'nyu_depth40' if nclasses == 41 else 'nyu_depth04' headers = headers_datasets.get(dataset, None) if headers is None: headers = [str(i) for i in range(0, fp['out_nfilters'][-1])] # they're already accuracies if len(errs): G_valid_idx = 3 C_valid_idx = 4 iou_valid_idx = 5 min_valid = numpy.argmax(errs[:, iou_valid_idx]) best = errs[min_valid] if 'cityscapes' in dataset: # for cityscapes we need to print the best iou index of the # validation set (we don't have the test) best_test_class_acc = numpy.round(iou_indeces[min_valid][1], 3) else: # in general we need to print the best accuracies of the test # given by the best validation model best_test_class_acc = numpy.round( numpy.diagonal(conf_matrices[min_valid][2]) / conf_matrices[min_valid][2].sum(axis=1), 3) if len(best_test_class_acc) > 0 and print_best_class_accuracy: best_per_class_accuracy = "|".join( best_test_class_acc.astype('str')) else: best_per_class_accuracy = '' # best_test_iou_indeces = numpy.round(iou_indeces[min_valid][2], 3) if len(best) == 2: error = (" ", round(best[0], 3), round(best[3], 3)) else: if 'cityscapes' in dataset: # print the validation errors error = (round(best[0], 3), round(best[3], 3), round(best[6], 3), round(best[4], 3), round(best[5], 3)) else: # print the test errors error = (round(best[0], 3), round(best[3], 3), round(best[6], 3), round(best[7], 3), round(best[8], 3)) else: error = [' ', ' ', ' ', ' ', ' '] best_per_class_accuracy = '' if 'history_unoptimized_cost' in fp: huc = fp['history_unoptimized_cost'] else: huc = None # GRU specific fp rnn_params = ' ' if fp['RecurrentNet'].__name__ == 'GRULayer': rnn_params = ' '.join((fp['gru_resetgate'].__class__.__name__, fp['gru_updategate'].__class__.__name__, fp['gru_hidden_update'].__class__.__name__, fp['gru_hid_init'].__class__.__name__, str(fp['gru_hid_init'].val))) # LSTM specific fp if fp['RecurrentNet'].__name__ == 'LSTMLayer': rnn_params = ' '.join((fp['lstm_ingate'].__class__.__name__, fp['lstm_forgetgate'].__class__.__name__, fp['lstm_cell'].__class__.__name__, fp['lstm_outgate'].__class__.__name__)) # RNN specific fp if fp['RecurrentNet'].__name__ == 'RNNLayer': rnn_params = ' '.join((fp['rnn_W_hid_to_hid'].__class__.__name__, fp['rnn_W_in_to_hid'].__class__.__name__, fp['rnn_b'].__class__.__name__, str(fp['rnn_b'].val))) print("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}|" "{14}|{15}|{16}|{17}|{18}|{19}|{20}|{21}|{22}|{23}|{24}|{25}|" "{26}|{27}|{28}|{29}|{30}|{31}|{32}|{33}|{34}|{35}|{36}|{37}|" "{38}|{39}|{40}|{41}|{42}|{43}|{44}|{45}|{46}|{47}|{48}|{49}|" "{50}|{51}|{52}|" ).format( # Batch fp fp['batch_size'], # Dataset fp['color'], fp['color_space'], fp.get('use_depth', ' '), fp['shuffle'], # Pre_processing fp['preprocess_type'], str(fp['patch_size']) + ' ' + str(fp['max_patches']) if fp['preprocess_type'] in ('conv-zca', 'sub-lcn', 'subdiv-lcn', 'local_mean_sub') else ' ', fp['resize_images'], fp['resize_size'], # Data augmentation fp['do_random_flip'], fp['do_random_shift'], fp['do_random_invert_color'], # Input Conv layers fp['in_vgg_layer'] if 'in_vgg_layer' in fp else fp['in_nfilters'], fp['in_filters_size'] if isinstance(fp['in_nfilters'], collections.Iterable) else ' ', fp['in_filters_stride'] if isinstance(fp['in_nfilters'], collections.Iterable) else ' ', fp['in_W_init'].__class__.__name__ + ' , ' + fp['in_b_init'].__class__.__name__ + ' ' + str(fp['in_b_init'].val) if isinstance(fp['in_nfilters'], collections.Iterable) else ' ', fp['in_nonlinearity'].__name__ if isinstance(fp['in_nfilters'], collections.Iterable) else ' ', # RNNs layers fp['dim_proj'], (fp['pwidth'], fp['pheight']), fp['stack_sublayers'], fp['RecurrentNet'].__name__, fp['nonlinearity'].__name__ if fp['RecurrentNet'].__name__ in ('LSTMLayer', 'RNNLayer') else ' ', fp['hid_init'].__class__.__name__ + ' ' + str(fp['hid_init'].val), fp['grad_clipping'], # fp['precompute_input'], # fp['mask_input'], rnn_params, # Output upsampling layers fp['out_upsampling'], fp['out_nfilters'] if fp['out_upsampling'] == 'grad' else ' ', fp['out_filters_size'] if fp['out_upsampling'] == 'grad' else ' ', fp['out_filters_stride'] if fp['out_upsampling'] == 'grad' else ' ', fp['out_W_init'].__class__.__name__ + ', ' + fp['out_b_init'].__class__.__name__ + ' ' + str(fp['out_b_init'].val), fp['out_nonlinearity'].__name__ if fp['out_upsampling'] != 'linear' else ' ', # Prediction, Softmax fp['intermediate_pred'], fp['class_balance'], # Special layers fp['batch_norm'], fp['use_dropout'], fp['dropout_rate'] if fp['use_dropout'] else ' ', fp['use_dropout_x'], fp['dropout_x_rate'] if fp['use_dropout_x'] else ' ', # Optimization method fp['optimizer'].__name__, fp.get('learning_rate', ' '), ','.join((str(fp.get('momentum', ' ')), str(fp.get('beta1', ' ')), str(fp.get('beta2', ' ')), str(fp.get('epsilon', ' ')) )), fp['weight_decay'], fp['weight_noise'], # Early stopping fp['patience'], fp['max_epochs'], fp['min_epochs'], len(errs), error[0], error[1], error[2], error[3], error[4], best_per_class_accuracy ) if 'recseg_git_commit' in fp and print_commit_hash: print("Recseg commit: %s" % fp['recseg_git_commit']) if 'recseg_version' in fp and print_commit_hash: print("Recseg commit: %s" % fp['recseg_version']) if 'lasagne_version' in fp and print_commit_hash: print("Lasagne commit: %s" % fp['lasagne_version']) if 'theano_version' in fp and print_commit_hash: print("theano commit: %s" % fp['theano_version']) # plot error curves if plot: if errs.shape[1] == 2: newerrs = numpy.zeros([errs.shape[0], errs.shape[1]+1]) newerrs[:, 1:3] = errs errs = newerrs # plt.subplot(2 if huc is not None else 1, 1, 1) # Plot Global Pixels % error plt.subplot(3, 1, 1) plt_range = range(len(errs)) plt.plot(plt_range, 1 - errs[:, 0], label='train') plt.plot(plt_range, 1 - errs[:, 3], label='valid') plt.plot(plt_range, 1 - errs[:, 6], label='test') plt.grid(True) plt.ylim(-0.001, 1.1) plt.ylabel('Global Pixels error %') plt.legend(loc=1, fancybox=True, framealpha=0.1, fontsize='small') # plot Mean Pixels error % plt.subplot(3, 1, 2) plt_range = range(len(errs)) plt.plot(plt_range, 1 - errs[:, 1], label='train') plt.plot(plt_range, 1 - errs[:, 4], label='valid') plt.plot(plt_range, 1 - errs[:, 7], label='test') plt.grid(True) plt.ylim(-0.001, 1.1) plt.ylabel('Avg Class error %') plt.legend(loc=1, fancybox=True, framealpha=0.1, fontsize='small') # Plot Mean IoU error % plt.subplot(3, 1, 3) plt_range = range(len(errs)) plt.plot(plt_range, 1 - errs[:, 2], label='train') plt.plot(plt_range, 1 - errs[:, 5], label='valid') plt.plot(plt_range, 1 - errs[:, 8], label='test') plt.grid(True) plt.ylim(-0.001, 1.1) plt.ylabel('Avg IoU error %') plt.legend(loc=1, fancybox=True, framealpha=0.1, fontsize='small') if huc is not None: plt.subplot(2, 1, 2) scale = float(len(errs)) / len(huc) huc_range = [i * scale for i in range(len(huc))] plt.plot(huc_range, huc) plt.ylabel('Training cost') plt.grid(True) # plt.show() plt.savefig(save_plot_path, format="pdf") if print_history: for i, (e, c, iou) in enumerate(zip(errs, conf_matrices, iou_indeces)): (train_global_acc, train_mean_class_acc, train_mean_iou_index, valid_global_acc, valid_mean_class_acc, valid_mean_iou_index, test_global_acc, test_mean_class_acc, test_mean_iou_index) = e (train_conf_matrix, valid_conf_matrix, test_conf_matrix) = c # (train_iou_index, valid_iou_index, test_iou_index) = iou print "" print "" print "" print "" headers_acc = ["Global Accuracies", "Mean Class Accuracies", "Mean Intersection Over Union"] rows = list() rows.append(['Train ', round(train_global_acc, 6), round(train_mean_class_acc, 6), round(train_mean_iou_index, 6)]) rows.append(['Valid ', round(valid_global_acc, 6), round(valid_mean_class_acc, 6), round(valid_mean_iou_index, 6)]) rows.append(['Test ', round(test_global_acc, 6), round(test_mean_class_acc, 6), round(test_mean_iou_index, 6)]) print(tabulate(rows, headers=headers_acc)) train_conf_matrix_norm = (train_conf_matrix / train_conf_matrix.sum(axis=1)) valid_conf_matrix_norm = (valid_conf_matrix / valid_conf_matrix.sum(axis=1)) test_conf_matrix_norm = (test_conf_matrix / test_conf_matrix.sum(axis=1)) class_acc = list() class_acc.append(numpy.concatenate([["Train"], numpy.round( numpy.diagonal(train_conf_matrix_norm), 3)])) class_acc.append(numpy.concatenate([["Valid"], numpy.round( numpy.diagonal(valid_conf_matrix_norm), 3)])) if len(test_conf_matrix) > 0: class_acc.append(numpy.concatenate([["Test"], numpy.round( numpy.diagonal(test_conf_matrix_norm), 3)])) print(tabulate(class_acc, headers=headers)) if dataset != "nyu_depth40": numpy.set_printoptions(precision=3) print "" print('Train Confusion matrix') print(tabulate(train_conf_matrix_norm, headers=headers)) print "" print('Valid Confusion matrix') print(tabulate(valid_conf_matrix_norm, headers=headers)) if len(test_conf_matrix_norm) > 0: print "" print('Test Confusion matrix') print(tabulate(test_conf_matrix_norm, headers=headers)) if i == -6: break return 1 if __name__ == '__main__': parser = argparse.ArgumentParser( description='Show the desired parameters of the network') parser.add_argument( 'dataset', default='horses', help='The name of the esperiment.') parser.add_argument( 'experiment', default='', nargs='?', help='The of the esperiment.') parser.add_argument( '--plot', '-p', action='store_true', help='Boolean. If set will plot the training curves') parser.add_argument( '--print-error-history', '-peh', action='store_true', help='Boolean. If set will print the value of the different ' 'metrics in every epoch') parser.add_argument( '--print_best_class_accuracy', '-pca', action='store_true', help='Boolean. If set will print the best per-class accuracy') parser.add_argument( '--print-commit-hash', '-ph', action='store_true', help='Boolean. If set will print the commit hash') parser.add_argument( '--model', default='model_recseg', help='The name of the model.') parser.add_argument( '--cycle', '-c', action='store_true', help='Boolean. If set will cycle through all the available ' 'saved models.') parser.add_argument( '--skip', '-s', nargs='*', type=int, default=[], help='List of experiment to skip from the cycle') args = parser.parse_args() if not args.cycle: print_pkl_params(args.dataset + '_models/' + args.model + '_' + args.dataset + args.experiment + '.npz.pkl', args.print_commit_hash, args.plot, args.print_error_history, args.print_best_class_accuracy) else: n = 0 ok = 1 while ok: n += 1 if n in args.skip: print '' continue ok = print_pkl_params(args.dataset + '_models/' + args.model + '_' + args.dataset + str(n) + '.npz.pkl', args.print_commit_hash, args.plot, args.print_error_history, args.print_best_class_accuracy) if not ok: ok = print_pkl_params('/Tmp/visin/' + args.dataset + '_models/' + args.model + '_' + args.dataset + str(n) + '.npz.pkl', args.print_commit_hash, args.plot, args.print_error_history, args.print_best_class_accuracy) print('Printed models from 1 to {}').format(n-1) ================================================ FILE: helper_dataset.py ================================================ import numpy as np import os, sys from numpy import sqrt, prod, ones, floor, repeat, pi, exp, zeros, sum from numpy.random import RandomState from theano.tensor.nnet import conv2d from theano import shared, config, _asarray, function import theano.tensor as T floatX = config.floatX from sklearn.feature_extraction.image import PatchExtractor from sklearn.decomposition import PCA from skimage import exposure from skimage import io from skimage import img_as_float, img_as_ubyte, img_as_uint, img_as_int from skimage.color import label2rgb, rgb2hsv, hsv2rgb from skimage.io import ImageCollection, imsave, imshow from skimage.transform import resize def compare_mask_image_filenames(filenames_images, filenames_mask, replace_from='', replace_to='', msg="Filename images and mask mismatch"): image = [i.split('/')[-1] for i in filenames_images] mask = [i.split('/')[-1].replace(replace_from, replace_to) for i in filenames_mask] assert np.array_equal(image, mask), msg def convert_RGB_mask_to_index(im, colors, ignore_missing_labels=False): """ :param im: mask in RGB format (classes are RGB colors) :param colors: the color map should be in the following format colors = OrderedDict([ ("Sky", np.array([[128, 128, 128]], dtype=np.uint8)), ("Building", np.array([[128, 0, 0], # Building [64, 192, 0], # Wall [0, 128, 64] # Bridge ], dtype=np.uint8) ... ]) :param ignore_missing_labels: if True the function continue also if some pixels fail the mappint :return: the mask in index class format """ out = (np.ones(im.shape[:2]) * 255).astype(np.uint8) for grey_val, (label, rgb) in enumerate(colors.items()): for el in rgb: match_pxls = np.where((im == np.asarray(el)).sum(-1) == 3) out[match_pxls] = grey_val if ignore_missing_labels: # retrieve the void label if [0, 0, 0] in rgb: void_label = grey_val # debug # outpath = '/Users/marcus/exp/datasets/camvid/grey_test/o.png' # imsave(outpath, out) ###### if ignore_missing_labels: match_missing = np.where(out == 255) if match_missing[0].size > 0: print "Ignoring missing labels" out[match_missing] = void_label assert (out != 255).all(), "rounding errors or missing classes in colors" return out.astype(np.uint8) def resize(): pass def crop(): pass def zero_pad(im, resize_size, inpath="", pad_value=0): """ :param im: the image you want to resize :param resize_size: the new size of the image :param inpath: [optional] to debug, the path of the image :return: the zero-pad image in the new dimensions """ if im.ndim == 3: h, w, _ = im.shape elif im.ndim == 2: h, w = im.shape rw, rh = resize_size pad_w = rw - w pad_h = rh - h pad_l = pad_r = pad_u = pad_d = 0 if pad_w > 0: pad_l = int(pad_w / 2) pad_r = pad_w - pad_l if pad_h > 0: pad_u = int(pad_h / 2) pad_d = pad_h - pad_u if im.ndim == 3: im = np.pad(im, ((pad_u, pad_d), (pad_l, pad_r), (0, 0)), mode='constant', constant_values=pad_value) elif im.ndim == 2: im = np.pad(im, ((pad_u, pad_d), (pad_l, pad_r)), mode='constant', constant_values=pad_value) assert (im.shape[1], im.shape[0]) == resize_size, \ "Resize size doesn't match: resize_size->{} resized->{}"\ " filename : {}".format(resize_size, [im.shape[1], im.shape[0]], inpath ) return im def rgb2illumination_invariant(img, alpha, hist_eq=False): """ this is an implementation of the illuminant-invariant color space published by Maddern2014 http://www.robots.ox.ac.uk/~mobile/Papers/2014ICRA_maddern.pdf :param img: :param alpha: camera paramete :return: """ ii_img = 0.5 + np.log(img[:, :, 1] + 1e-8) - \ alpha * np.log(img[:, :, 2] + 1e-8) - \ (1 - alpha) * np.log(img[:, :, 0] + 1e-8) # ii_img = exposure.rescale_intensity(ii_img, out_range=(0, 1)) if hist_eq: ii_img = exposure.equalize_hist(ii_img) print np.max(ii_img) print np.min(ii_img) return ii_img def save_image(outpath, img): import errno try: os.makedirs(os.path.dirname(outpath)) except OSError as e: if e.errno != errno.EEXIST: raise e pass imsave(outpath, img) def save_RGB_mask(outpath, mask): return def preprocess_dataset(train, valid, test, input_to_float, preprocess_type, patch_size, max_patches): if input_to_float and preprocess_type is None: train_norm = train[0].astype(floatX) / 255. train = (train_norm, train[1]) valid_norm = valid[0].astype(floatX) / 255. valid = (valid_norm, valid[1]) test_norm = test[0].astype(floatX) / 255. test = (test_norm, test[1]) if preprocess_type is None: return train, valid, test # whiten, LCN, GCN, Local Mean Subtract, or normalize if len(train[0]) > 0: train_pre = [] print "" print "Preprocessing {} images of the train set with {} {} ".format( len(train[0]), preprocess_type, patch_size), print "" i = 0 print "Progress: {0:.3g} %".format(i * 100 / len(train[0])), for i, x in enumerate(train[0]): img = np.expand_dims(x, axis=0) x_pre = preprocess(img, preprocess_type, patch_size, max_patches) train_pre.append(x_pre[0]) print "\rProgress: {0:.3g} %".format(i * 100 / len(train[0])), sys.stdout.flush() if input_to_float: train_pre = np.array(train_pre).astype(floatX) / 255. train = (np.array(train_pre), np.array(train[1])) if len(valid[0]) > 0: valid_pre = [] print "" print "Preprocessing {} images of the valid set with {} {} ".format( len(valid[0]), preprocess_type, patch_size), print "" i = 0 print "Progress: {0:.3g} %".format(i * 100 / len(valid[0])), for i, x in enumerate(valid[0]): img = np.expand_dims(x, axis=0) x_pre = preprocess(img, preprocess_type, patch_size, max_patches) valid_pre.append(x_pre[0]) print "\rProgress: {0:.3g} %".format(i * 100 / len(valid[0])), sys.stdout.flush() if input_to_float: valid_pre = np.array(valid_pre).astype(floatX) / 255. valid = (np.array(valid_pre), np.array(valid[1])) if len(test[0]) > 0: test_pre = [] print "" print "Preprocessing {} images of the test set with {} {} ".format( len(test[0]), preprocess_type, patch_size), print "" i = 0 print "Progress: {0:.3g} %".format(i * 100 / len(test[0])), for i, x in enumerate(test[0]): img = np.expand_dims(x, axis=0) x_pre = preprocess(img, preprocess_type, patch_size, max_patches) test_pre.append(x_pre[0]) print "\rProgress: {0:.3g} %".format(i * 100 / len(test[0])), sys.stdout.flush() if input_to_float: test_pre = np.array(test_pre).astype(floatX) / 255. test = (np.array(test_pre), np.array(test[1])) return train, valid, test def preprocess(x, mode=None, patch_size=9, max_patches=int(1e5)): """ :param x: :param mode: :param rng: :param patch_size: :param max_patches: :return: """ if mode == 'conv-zca': x = convolutional_zca(x, patch_size=patch_size, max_patches=max_patches) elif mode == 'sub-lcn': for d in range(x.shape[-1]): x[:, :, :, d] = lecun_lcn(x[:, :, :, d], kernel_size=patch_size) elif mode == 'subdiv-lcn': for d in range(x.shape[-1]): x[:, :, :, d] = lecun_lcn(x[:, :, :, d], kernel_size=patch_size, use_divisor=True) elif mode == 'gcn': for d in range(x.shape[-1]): x[:, :, :, d] = global_contrast_normalization(x[:, :, :, d]) elif mode == 'local_mean_sub': for d in range(x.shape[-1]): x[:, :, :, d] = local_mean_subtraction(x[:, :, :, d], kernel_size=patch_size) # x = x.astype(floatX) return x def lecun_lcn(input, kernel_size=9, threshold=1e-4, use_divisor=False): """ Yann LeCun's local contrast normalization Orginal code in Theano by: Guillaume Desjardins :param input: :param kernel_size: :param threshold: :param use_divisor: :return: """ input_shape = (input.shape[0], 1, input.shape[1], input.shape[2]) input = input.reshape(input_shape).astype(floatX) X = T.tensor4(dtype=floatX) filter_shape = (1, 1, kernel_size, kernel_size) filters = gaussian_filter(kernel_size).reshape(filter_shape) filters = shared(_asarray(filters, dtype=floatX), borrow=True) convout = conv2d(input=X, filters=filters, input_shape=input.shape, filter_shape=filter_shape, border_mode='half') new_X = X - convout if use_divisor: # Scale down norm of kernel_size x kernel_size patch sum_sqr_XX = conv2d(input=T.sqr(T.abs_(new_X)), filters=filters, input_shape=input.shape, filter_shape=filter_shape, border_mode='half') denom = T.sqrt(sum_sqr_XX) per_img_mean = denom.mean(axis=[2, 3]) divisor = T.largest(per_img_mean.dimshuffle(0, 1, 'x', 'x'), denom) divisor = T.maximum(divisor, threshold) new_X = new_X / divisor new_X = new_X.dimshuffle(0, 2, 3, 1) new_X = new_X.flatten(ndim=3) f = function([X], new_X) return f(input) def local_mean_subtraction(input, kernel_size=5): input_shape = (input.shape[0], 1, input.shape[1], input.shape[2]) input = input.reshape(input_shape).astype(floatX) X = T.tensor4(dtype=floatX) filter_shape = (1, 1, kernel_size, kernel_size) filters = mean_filter(kernel_size).reshape(filter_shape) filters = shared(_asarray(filters, dtype=floatX), borrow=True) mean = conv2d(input=X, filters=filters, input_shape=input.shape, filter_shape=filter_shape, border_mode='half') new_X = X - mean f = function([X], new_X) return f(input) def global_contrast_normalization(input, scale=1., subtract_mean=True, use_std=False, sqrt_bias=0., min_divisor=1e-8): input_shape = (input.shape[0], 1, input.shape[1], input.shape[2]) input = input.reshape(input_shape).astype(floatX) X = T.tensor4(dtype=floatX) ndim = X.ndim if not ndim in [3, 4]: raise NotImplementedError("X.dim>4 or X.ndim<3") scale = float(scale) mean = X.mean(axis=ndim-1) new_X = X.copy() if subtract_mean: if ndim == 3: new_X = X - mean[:, :, None] else: new_X = X - mean[:, :, :, None] if use_std: normalizers = T.sqrt(sqrt_bias + X.var(axis=ndim-1)) / scale else: normalizers = T.sqrt(sqrt_bias + (new_X ** 2).sum(axis=ndim-1)) / scale # Don't normalize by anything too small. T.set_subtensor(normalizers[(normalizers < min_divisor).nonzero()], 1.) if ndim == 3: new_X /= normalizers[:, :, None] else: new_X /= normalizers[:, :, :, None] f = function([X], new_X) return f(input) def gaussian_filter(kernel_shape): x = zeros((kernel_shape, kernel_shape), dtype='float32') def gauss(x, y, sigma=2.0): Z = 2 * pi * sigma**2 return 1./Z * exp(-(x**2 + y**2) / (2. * sigma**2)) mid = floor(kernel_shape/ 2.) for i in xrange(0,kernel_shape): for j in xrange(0,kernel_shape): x[i, j] = gauss(i-mid, j-mid) return x / sum(x) def mean_filter(kernel_size): s = kernel_size**2 x = repeat(1. / s, s).reshape((kernel_size, kernel_size)) return x def convolutional_zca(input, patch_size=(9, 9), max_patches=int(1e5)): """ This is an implementation of the convolutional ZCA whitening presented by David Eigen in his phd thesis http://www.cs.nyu.edu/~deigen/deigen-thesis.pdf "Predicting Images using Convolutional Networks: Visual Scene Understanding with Pixel Maps" From paragraph 8.4: A simple adaptation of ZCA to convolutional application is to find the ZCA whitening transformation for a sample of local image patches across the dataset, and then apply this transform to every patch in a larger image. We then use the center pixel of each ZCA patch to create the conv-ZCA output image. The operations of applying local ZCA and selecting the center pixel can be combined into a single convolution kernel, resulting in the following algorithm (explained using RGB inputs and 9x9 kernel): 1. Sample 10M random 9x9 image patches (each with 3 colors) 2. Perform PCA on these to get eigenvectors V and eigenvalues D. 3. Optionally remove small eigenvalues, so V has shape [npca x 3 x 9 x 9]. 4. Construct the whitening kernel k: for each pair of colors (ci,cj), set k[j,i, :, :] = V[:, j, x0, y0]^T * D^{-1/2} * V[:, i, :, :] where (x0, y0) is the center pixel location (e.g. (5,5) for a 9x9 kernel) :param input: 4D tensor of shape [batch_size, rows, col, channels] :param patch_size: size of the patches extracted from the dataset :param max_patches: max number of patches extracted from the dataset :return: conv-zca whitened dataset """ # I don't know if it's correct or not.. but it seems to work mean = np.mean(input, axis=(0, 1, 2)) input -= mean # center the data n_imgs, h, w, n_channels = input.shape patch_size = (patch_size, patch_size) patches = PatchExtractor(patch_size=patch_size, max_patches=max_patches).transform(input) pca = PCA() pca.fit(patches.reshape(patches.shape[0], -1)) # Transpose the components into theano convolution filter type dim = (-1,) + patch_size + (n_channels,) V = shared(pca.components_.reshape(dim). transpose(0, 3, 1, 2).astype(input.dtype)) D = T.nlinalg.diag(1. / np.sqrt(pca.explained_variance_)) x_0 = int(np.floor(patch_size[0] / 2)) y_0 = int(np.floor(patch_size[1] / 2)) filter_shape = [n_channels, n_channels, patch_size[0], patch_size[1]] image_shape = [n_imgs, n_channels, h, w] kernel = T.zeros(filter_shape) VT = V.dimshuffle(2, 3, 1, 0) # V : 243 x 3 x 9 x 9 # VT : 9 x 9 x 3 x 243 # build the kernel for i in range(n_channels): for j in range(n_channels): a = T.dot(VT[x_0, y_0, j, :], D).reshape([1, -1]) b = V[:, i, :, :].reshape([-1, patch_size[0] * patch_size[1]]) c = T.dot(a, b).reshape([patch_size[0], patch_size[1]]) kernel = T.set_subtensor(kernel[j, i, :, :], c) kernel = kernel.astype(floatX) input = input.astype(floatX) input_images = T.tensor4(dtype=floatX) conv_whitening = conv2d(input_images.dimshuffle((0, 3, 1, 2)), kernel, input_shape=image_shape, filter_shape=filter_shape, border_mode='full') s_crop = [(patch_size[0] - 1) // 2, (patch_size[1] - 1) // 2] # e_crop = [s_crop[0] if (s_crop[0] % 2) != 0 else s_crop[0] + 1, # s_crop[1] if (s_crop[1] % 2) != 0 else s_crop[1] + 1] conv_whitening = conv_whitening[:, :, s_crop[0]:-s_crop[0], s_crop[ 1]:-s_crop[1]] conv_whitening = conv_whitening.dimshuffle(0, 2, 3, 1) f_convZCA = function([input_images], conv_whitening) return f_convZCA(input) ================================================ FILE: layers.py ================================================ from collections import Iterable import numpy as np import lasagne from lasagne.layers import get_output, get_output_shape from lasagne.layers.conv import TransposedConv2DLayer import theano.tensor as T from padded import DynamicPaddingLayer, PaddedConv2DLayer as ConvLayer from utils import ceildiv, to_int class ReSegLayer(lasagne.layers.Layer): def __init__(self, l_in, n_layers, pheight, pwidth, dim_proj, nclasses, stack_sublayers, # outsampling out_upsampling_type, out_nfilters, out_filters_size, out_filters_stride, out_W_init=lasagne.init.GlorotUniform(), out_b_init=lasagne.init.Constant(0.), out_nonlinearity=lasagne.nonlinearities.identity, hypotetical_fm_size=np.array((100.0, 100.0)), # input ConvLayers in_nfilters=None, in_filters_size=((3, 3), (3, 3)), in_filters_stride=((1, 1), (1, 1)), in_W_init=lasagne.init.GlorotUniform(), in_b_init=lasagne.init.Constant(0.), in_nonlinearity=lasagne.nonlinearities.rectify, in_vgg_layer='conv3_3', # common recurrent layer params RecurrentNet=lasagne.layers.GRULayer, nonlinearity=lasagne.nonlinearities.rectify, hid_init=lasagne.init.Constant(0.), grad_clipping=0, precompute_input=True, mask_input=None, # 1x1 Conv layer for dimensional reduction conv_dim_red=False, conv_dim_red_nonlinearity=lasagne.nonlinearities.identity, # GRU specific params gru_resetgate=lasagne.layers.Gate(W_cell=None), gru_updategate=lasagne.layers.Gate(W_cell=None), gru_hidden_update=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), gru_hid_init=lasagne.init.Constant(0.), # LSTM specific params lstm_ingate=lasagne.layers.Gate(), lstm_forgetgate=lasagne.layers.Gate(), lstm_cell=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), lstm_outgate=lasagne.layers.Gate(), # RNN specific params rnn_W_in_to_hid=lasagne.init.Uniform(), rnn_W_hid_to_hid=lasagne.init.Uniform(), rnn_b=lasagne.init.Constant(0.), # Special layers batch_norm=False, name=''): """A ReSeg layer The ReSeg layer is composed by multiple ReNet layers and an upsampling layer Parameters ---------- l_in : lasagne.layers.Layer The input layer, in bc01 format n_layers : int The number of layers pheight : tuple The height of the patches, for each layer pwidth : tuple The width of the patches, for each layer dim_proj : tuple The number of hidden units of each RNN, for each layer nclasses : int The number of classes of the data stack_sublayers : bool If True the bidirectional RNNs in the ReNet layers will be stacked one over the other. See ReNet for more details. out_upsampling_type : string The kind of upsampling to be used out_nfilters : int The number of hidden units of the upsampling layer out_filters_size : tuple The size of the upsampling filters, if any out_filters_stride : tuple The stride of the upsampling filters, if any out_W_init : Theano shared variable, numpy array or callable Initializer for W out_b_init : Theano shared variable, numpy array or callable Initializer for b out_nonlinearity : Theano shared variable, numpy array or callable The nonlinearity to be applied after the upsampling hypotetical_fm_size : float The hypotetical size of the feature map that would be input of the layer if the input image of the whole network was of size (100, 100) RecurrentNet : lasagne.layers.Layer A recurrent layer class nonlinearity : callable or None The nonlinearity that is applied to the output. If None is provided, no nonlinearity will be applied. hid_init : callable, np.ndarray, theano.shared or lasagne.layers.Layer Initializer for initial hidden state grad_clipping : float If nonzero, the gradient messages are clipped to the given value during the backward pass. precompute_input : bool If True, precompute input_to_hid before iterating through the sequence. This can result in a speedup at the expense of an increase in memory usage. mask_input : lasagne.layers.Layer Layer which allows for a sequence mask to be input, for when sequences are of variable length. Default None, which means no mask will be supplied (i.e. all sequences are of the same length). gru_resetgate : lasagne.layers.Gate Parameters for the reset gate, if RecurrentNet is GRU gru_updategate : lasagne.layers.Gate Parameters for the update gate, if RecurrentNet is GRU gru_hidden_update : lasagne.layers.Gate Parameters for the hidden update, if RecurrentNet is GRU gru_hid_init : callable, np.ndarray, theano.shared or lasagne.layers.Layer Initializer for initial hidden state, if RecurrentNet is GRU lstm_ingate : lasagne.layers.Gate Parameters for the input gate, if RecurrentNet is LSTM lstm_forgetgate : lasagne.layers.Gate Parameters for the forget gate, if RecurrentNet is LSTM lstm_cell : lasagne.layers.Gate Parameters for the cell computation, if RecurrentNet is LSTM lstm_outgate : lasagne.layers.Gate Parameters for the output gate, if RecurrentNet is LSTM rnn_W_in_to_hid : Theano shared variable, numpy array or callable Initializer for input-to-hidden weight matrix, if RecurrentNet is RecurrentLayer rnn_W_hid_to_hid : Theano shared variable, numpy array or callable Initializer for hidden-to-hidden weight matrix, if RecurrentNet is RecurrentLayer rnn_b : Theano shared variable, numpy array, callable or None Initializer for bias vector, if RecurrentNet is RecurrentLaye. If None is provided there will be no bias batch_norm: this add a batch normalization layer at the end of the network right after each Gradient Upsampling layers name : string The name of the layer, optional """ super(ReSegLayer, self).__init__(l_in, name) self.l_in = l_in self.n_layers = n_layers self.pheight = pheight self.pwidth = pwidth self.dim_proj = dim_proj self.nclasses = nclasses self.stack_sublayers = stack_sublayers # upsampling self.out_upsampling_type = out_upsampling_type self.out_nfilters = out_nfilters self.out_filters_size = out_filters_size self.out_filters_stride = out_filters_stride self.out_W_init = out_W_init self.out_b_init = out_b_init self.out_nonlinearity = out_nonlinearity self.hypotetical_fm_size = hypotetical_fm_size # input ConvLayers self.in_nfilters = in_nfilters self.in_filters_size = in_filters_size self.in_filters_stride = in_filters_stride self.in_W_init = in_W_init self.in_b_init = in_b_init self.in_nonlinearity = in_nonlinearity self.in_vgg_layer = in_vgg_layer # common recurrent layer params self.RecurrentNet = RecurrentNet self.nonlinearity = nonlinearity self.hid_init = hid_init self.grad_clipping = grad_clipping self.precompute_input = precompute_input self.mask_input = mask_input # GRU specific params self.gru_resetgate = gru_resetgate self.gru_updategate = gru_updategate self.gru_hidden_update = gru_hidden_update self.gru_hid_init = gru_hid_init # LSTM specific params self.lstm_ingate = lstm_ingate self.lstm_forgetgate = lstm_forgetgate self.lstm_cell = lstm_cell self.lstm_outgate = lstm_outgate # RNN specific params self.rnn_W_in_to_hid = rnn_W_in_to_hid self.rnn_W_hid_to_hid = rnn_W_hid_to_hid self.name = name self.sublayers = [] expand_height = expand_width = 1 # Input ConvLayers l_conv = l_in if isinstance(in_nfilters, Iterable) and not isinstance(in_nfilters, str): for i, (nf, f_size, stride) in enumerate( zip(in_nfilters, in_filters_size, in_filters_stride)): l_conv = ConvLayer( l_conv, num_filters=nf, filter_size=f_size, stride=stride, W=in_W_init, b=in_b_init, pad='valid', name=self.name + '_input_conv_layer' + str(i) ) self.sublayers.append(l_conv) self.hypotetical_fm_size = ( (self.hypotetical_fm_size - 1) * stride + f_size) # TODO This is right only if stride == filter... expand_height *= f_size[0] expand_width *= f_size[1] # Print shape out_shape = get_output_shape(l_conv) print('ConvNet: After in-convnet: {}'.format(out_shape)) # Pretrained vgg16 elif type(in_nfilters) == str: from vgg16 import Vgg16Layer l_conv = Vgg16Layer(l_in, self.in_nfilters, False, False) hypotetical_fm_size /= 8 expand_height = expand_width = 8 self.sublayers.append(l_conv) # Print shape out_shape = get_output_shape(l_conv) print('Vgg: After vgg: {}'.format(out_shape)) # ReNet layers l_renet = l_conv for lidx in xrange(n_layers): l_renet = ReNetLayer(l_renet, patch_size=(pwidth[lidx], pheight[lidx]), n_hidden=dim_proj[lidx], stack_sublayers=stack_sublayers[lidx], RecurrentNet=RecurrentNet, nonlinearity=nonlinearity, hid_init=hid_init, grad_clipping=grad_clipping, precompute_input=precompute_input, mask_input=mask_input, # GRU specific params gru_resetgate=gru_resetgate, gru_updategate=gru_updategate, gru_hidden_update=gru_hidden_update, gru_hid_init=gru_hid_init, # LSTM specific params lstm_ingate=lstm_ingate, lstm_forgetgate=lstm_forgetgate, lstm_cell=lstm_cell, lstm_outgate=lstm_outgate, # RNN specific params rnn_W_in_to_hid=rnn_W_in_to_hid, rnn_W_hid_to_hid=rnn_W_hid_to_hid, rnn_b=rnn_b, batch_norm=batch_norm, name=self.name + '_renet' + str(lidx)) self.sublayers.append(l_renet) self.hypotetical_fm_size /= (pwidth[lidx], pheight[lidx]) # Print shape out_shape = get_output_shape(l_renet) if stack_sublayers: msg = 'ReNet: After 2 rnns {}x{}@{} and 2 rnns 1x1@{}: {}' print(msg.format(pheight[lidx], pwidth[lidx], dim_proj[lidx], dim_proj[lidx], out_shape)) else: print('ReNet: After 4 rnns {}x{}@{}: {}'.format( pheight[lidx], pwidth[lidx], dim_proj[lidx], out_shape)) # 1x1 conv layer : dimensionality reduction layer if conv_dim_red: l_renet = lasagne.layers.Conv2DLayer( l_renet, num_filters=dim_proj[lidx], filter_size=(1, 1), W=lasagne.init.GlorotUniform(), b=lasagne.init.Constant(0.), pad='valid', nonlinearity=conv_dim_red_nonlinearity, name=self.name + '_1x1_conv_layer' + str(lidx) ) # Print shape out_shape = get_output_shape(l_renet) print('Dim reduction: After 1x1 convnet: {}'.format(out_shape)) # Upsampling if out_upsampling_type == 'autograd': raise NotImplementedError( 'This will not work as the dynamic cropping will crop ' 'part of the image.') nlayers = len(out_nfilters) assert nlayers > 1 # Compute the upsampling ratio and the corresponding params h2 = np.array((100., 100.)) up_ratio = (h2 / self.hypotetical_fm_size) ** (1. / nlayers) h1 = h2 / up_ratio h0 = h1 / up_ratio stride = to_int(ceildiv(h2 - h1, h1 - h0)) filter_size = to_int(ceildiv((h1 * (h1 - 1) + h2 - h2 * h0), (h1 - h0))) target_shape = get_output(l_renet).shape[2:] l_upsampling = l_renet for l in range(nlayers): target_shape = target_shape * up_ratio l_upsampling = TransposedConv2DLayer( l_upsampling, num_filters=out_nfilters[l], filter_size=filter_size, stride=stride, W=out_W_init, b=out_b_init, nonlinearity=out_nonlinearity) self.sublayers.append(l_upsampling) up_shape = get_output(l_upsampling).shape[2:] # Print shape out_shape = get_output_shape(l_upsampling) print('Transposed autograd: {}x{} (str {}x{}) @ {}:{}'.format( filter_size[0], filter_size[1], stride[0], stride[1], out_nfilters[l], out_shape)) # CROP # pad in TransposeConv2DLayer cannot be a tensor --> we cannot # crop unless we know in advance by how much! crop = T.max(T.stack([up_shape - target_shape, T.zeros(2)]), axis=0) crop = crop.astype('uint8') # round down l_upsampling = CropLayer( l_upsampling, crop, data_format='bc01') self.sublayers.append(l_upsampling) # Print shape print('Dynamic cropping') elif out_upsampling_type == 'grad': l_upsampling = l_renet for i, (nf, f_size, stride) in enumerate(zip( out_nfilters, out_filters_size, out_filters_stride)): l_upsampling = TransposedConv2DLayer( l_upsampling, num_filters=nf, filter_size=f_size, stride=stride, crop=0, W=out_W_init, b=out_b_init, nonlinearity=out_nonlinearity) self.sublayers.append(l_upsampling) if batch_norm: l_upsampling = lasagne.layers.batch_norm( l_upsampling, axes='auto') self.sublayers.append(l_upsampling) print "Batch normalization after Grad layer " # Print shape out_shape = get_output_shape(l_upsampling) print('Transposed conv: {}x{} (str {}x{}) @ {}:{}'.format( f_size[0], f_size[1], stride[0], stride[1], nf, out_shape)) elif out_upsampling_type == 'linear': # Go to b01c l_upsampling = lasagne.layers.DimshuffleLayer( l_renet, (0, 2, 3, 1), name=self.name + '_grad_undimshuffle') self.sublayers.append(l_upsampling) expand_height *= np.prod(pheight) expand_width *= np.prod(pwidth) l_upsampling = LinearUpsamplingLayer(l_upsampling, expand_height, expand_width, nclasses, batch_norm=batch_norm, name="linear_upsample_layer") self.sublayers.append(l_upsampling) print('Linear upsampling') if batch_norm: l_upsampling = lasagne.layers.batch_norm( l_upsampling, axes=(0, 1, 2)) self.sublayers.append(l_upsampling) print "Batch normalization after Linear upsampling layer " # Go back to bc01 l_upsampling = lasagne.layers.DimshuffleLayer( l_upsampling, (0, 3, 1, 2), name=self.name + '_grad_undimshuffle') self.sublayers.append(l_upsampling) self.l_out = l_upsampling # HACK LASAGNE # This will set `self.input_layer`, which is needed by Lasagne to find # the layers with the get_all_layers() helper function in the # case of a layer with sublayers if isinstance(self.l_out, tuple): self.input_layer = None else: self.input_layer = self.l_out def get_output_shape_for(self, input_shape): for layer in self.sublayers: output_shape = layer.get_output_shape_for(input_shape) input_shape = output_shape return output_shape # return self.l_out.get_output_shape_for(input_shape) # return list(input_shape[0:3]) + [self.nclasses] def get_output_for(self, input_var, **kwargs): # HACK LASAGNE # This is needed, jointly with the previous hack, to ensure that # this layer behaves as its last sublayer (namely, # self.input_layer) return input_var class ReNetLayer(lasagne.layers.Layer): def __init__(self, l_in, patch_size=(2, 2), n_hidden=50, stack_sublayers=False, RecurrentNet=lasagne.layers.GRULayer, nonlinearity=lasagne.nonlinearities.rectify, hid_init=lasagne.init.Constant(0.), grad_clipping=0, precompute_input=True, mask_input=None, # GRU specific params gru_resetgate=lasagne.layers.Gate(W_cell=None), gru_updategate=lasagne.layers.Gate(W_cell=None), gru_hidden_update=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), gru_hid_init=lasagne.init.Constant(0.), # LSTM specific params lstm_ingate=lasagne.layers.Gate(), lstm_forgetgate=lasagne.layers.Gate(), lstm_cell=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), lstm_outgate=lasagne.layers.Gate(), # RNN specific params rnn_W_in_to_hid=lasagne.init.Uniform(), rnn_W_hid_to_hid=lasagne.init.Uniform(), rnn_b=lasagne.init.Constant(0.), batch_norm=False, name='', **kwargs): """A ReNet layer Each ReNet layer is composed by 4 RNNs (or 2 bidirectional RNNs): * First SubLayer: 2 RNNs scan the image vertically (up and down) * Second Sublayer: 2 RNNs scan the image horizontally (left and right) The sublayers can be stacked one over the other or can scan the image in parallel Parameters ---------- l_in : lasagne.layers.Layer The input layer, in format batches, channels, rows, cols patch_size : tuple The size of the patch expressed as (pheight, pwidth). Optional n_hidden : int The number of hidden units of each RNN. Optional stack_sublayers : bool If True, the sublayers (i.e. the bidirectional RNNs) will be stacked one over the other, meaning that the second bidirectional RNN will read the feature map coming from the first bidirectional RNN. If False, all the RNNs will read the input. Optional RecurrentNet : lasagne.layers.Layer A recurrent layer class nonlinearity : callable or None The nonlinearity that is applied to the output. If None is provided, no nonlinearity will be applied. hid_init : callable, np.ndarray, theano.shared or lasagne.layers.Layer Initializer for initial hidden state grad_clipping : float If nonzero, the gradient messages are clipped to the given value during the backward pass. precompute_input : bool If True, precompute input_to_hid before iterating through the sequence. This can result in a speedup at the expense of an increase in memory usage. mask_input : lasagne.layers.Layer Layer which allows for a sequence mask to be input, for when sequences are of variable length. Default None, which means no mask will be supplied (i.e. all sequences are of the same length). gru_resetgate : lasagne.layers.Gate Parameters for the reset gate, if RecurrentNet is GRU gru_updategate : lasagne.layers.Gate Parameters for the update gate, if RecurrentNet is GRU gru_hidden_update : lasagne.layers.Gate Parameters for the hidden update, if RecurrentNet is GRU gru_hid_init : callable, np.ndarray, theano.shared or lasagne.layers.Layer Initializer for initial hidden state, if RecurrentNet is GRU lstm_ingate : lasagne.layers.Gate Parameters for the input gate, if RecurrentNet is LSTM lstm_forgetgate : lasagne.layers.Gate Parameters for the forget gate, if RecurrentNet is LSTM lstm_cell : lasagne.layers.Gate Parameters for the cell computation, if RecurrentNet is LSTM lstm_outgate : lasagne.layers.Gate Parameters for the output gate, if RecurrentNet is LSTM rnn_W_in_to_hid : Theano shared variable, numpy array or callable Initializer for input-to-hidden weight matrix, if RecurrentNet is RecurrentLayer rnn_W_hid_to_hid : Theano shared variable, numpy array or callable Initializer for hidden-to-hidden weight matrix, if RecurrentNet is RecurrentLayer rnn_b : Theano shared variable, numpy array, callable or None Initializer for bias vector, if RecurrentNet is RecurrentLaye. If None is provided there will be no bias name : string The name of the layer, optional """ super(ReNetLayer, self).__init__(l_in, name) self.l_in = l_in self.patch_size = patch_size self.n_hidden = n_hidden self.stack_sublayers = stack_sublayers self.name = name self.stride = self.patch_size # for now, it's not parametrized # Dynamically add padding if the input is not a multiple of the # patch size (expected input format: bs, ch, rows, cols) l_in = DynamicPaddingLayer(l_in, patch_size, self.stride, name=self.name + '_padding') # get_output(l_in).shape will result in an error in the # recurrent layers batch_size = -1 cchannels, cheight, cwidth = get_output_shape(l_in)[1:] pheight, pwidth = patch_size psize = pheight * pwidth * cchannels # Number of patches in each direction npatchesH = cheight / pheight npatchesW = cwidth / pwidth # Split in patches: bs, cc, #H, ph, #W, pw l_in = lasagne.layers.ReshapeLayer( l_in, (batch_size, cchannels, npatchesH, pheight, npatchesW, pwidth), name=self.name + "_pre_reshape0") # bs, #H, #W, ph, pw, cc l_in = lasagne.layers.DimshuffleLayer( l_in, (0, 2, 4, 3, 5, 1), name=self.name + "_pre_dimshuffle0") # FIRST SUBLAYER # The RNN Layer needs a 3D tensor input: bs*#H, #W, psize # bs*#H, #W, ph * pw * cc l_sub0 = lasagne.layers.ReshapeLayer( l_in, (-1, npatchesW, psize), name=self.name + "_sub0_reshape0") # Left/right scan: bs*#H, #W, 2*hid l_sub0 = BidirectionalRNNLayer( l_sub0, n_hidden, RecurrentNet=RecurrentNet, nonlinearity=nonlinearity, hid_init=hid_init, grad_clipping=grad_clipping, precompute_input=precompute_input, mask_input=mask_input, # GRU specific params gru_resetgate=gru_resetgate, gru_updategate=gru_updategate, gru_hidden_update=gru_hidden_update, gru_hid_init=gru_hid_init, batch_norm=batch_norm, # LSTM specific params lstm_ingate=lstm_ingate, lstm_forgetgate=lstm_forgetgate, lstm_cell=lstm_cell, lstm_outgate=lstm_outgate, # RNN specific params rnn_W_in_to_hid=rnn_W_in_to_hid, rnn_W_hid_to_hid=rnn_W_hid_to_hid, rnn_b=rnn_b, name=self.name + "_sub0_renetsub") # Revert reshape: bs, #H, #W, 2*hid l_sub0 = lasagne.layers.ReshapeLayer( l_sub0, (batch_size, npatchesH, npatchesW, 2 * n_hidden), name=self.name + "_sub0_unreshape") # # Invert rows and columns: #H, bs, #W, 2*hid # l_sub0 = lasagne.layers.DimshuffleLayer( # l_sub0, # (2, 1, 0, 3), # name=self.name + "_sub0_undimshuffle") # If stack_sublayers is True, the second sublayer takes as an input the # first sublayer's output, otherwise the input of the ReNetLayer (e.g # the image) if stack_sublayers: # bs, #H, #W, 2*hid input_sublayer1 = l_sub0 psize = 2 * n_hidden else: # # #H, bs, #W, ph, pw, cc # input_sublayer1 = lasagne.layers.DimshuffleLayer( # l_in, # (2, 1, 0, 3, 4, 5), # name=self.name + "_presub1_in_dimshuffle") # bs, #H, #W, ph*pw*cc input_sublayer1 = lasagne.layers.ReshapeLayer( l_in, (batch_size, npatchesH, npatchesW, psize), name=self.name + "_presub1_in_dimshuffle") # SECOND SUBLAYER # Invert rows and columns: bs, #W, #H, psize l_sub1 = lasagne.layers.DimshuffleLayer( input_sublayer1, (0, 2, 1, 3), name=self.name + "_presub1_dimshuffle") # The RNN Layer needs a 3D tensor input: bs*#W, #H, psize l_sub1 = lasagne.layers.ReshapeLayer( l_sub1, (-1, npatchesH, psize), name=self.name + "_sub1_reshape") # Down/up scan: bs*#W, #H, 2*hid l_sub1 = BidirectionalRNNLayer( l_sub1, n_hidden, RecurrentNet=RecurrentNet, nonlinearity=nonlinearity, hid_init=hid_init, grad_clipping=grad_clipping, precompute_input=precompute_input, mask_input=mask_input, # GRU specific params gru_resetgate=gru_resetgate, gru_updategate=gru_updategate, gru_hidden_update=gru_hidden_update, gru_hid_init=gru_hid_init, # LSTM specific params lstm_ingate=lstm_ingate, lstm_forgetgate=lstm_forgetgate, lstm_cell=lstm_cell, lstm_outgate=lstm_outgate, # RNN specific params rnn_W_in_to_hid=rnn_W_in_to_hid, rnn_W_hid_to_hid=rnn_W_hid_to_hid, rnn_b=rnn_b, name=self.name + "_sub1_renetsub") psize = 2 * n_hidden # Revert the reshape: bs, #W, #H, 2*hid l_sub1 = lasagne.layers.ReshapeLayer( l_sub1, (batch_size, npatchesW, npatchesH, psize), name=self.name + "_sub1_unreshape") # Invert rows and columns: bs, #H, #W, psize l_sub1 = lasagne.layers.DimshuffleLayer( l_sub1, (0, 2, 1, 3), name=self.name + "_sub1_undimshuffle") # Concat all 4 layers if needed: bs, #H, #W, {2,4}*hid if not stack_sublayers: l_sub1 = lasagne.layers.ConcatLayer([l_sub0, l_sub1], axis=3) # Get back to bc01: bs, psize, #H, #W self.out_layer = lasagne.layers.DimshuffleLayer( l_sub1, (0, 3, 1, 2), name=self.name + "_out_undimshuffle") # HACK LASAGNE # This will set `self.input_layer`, which is needed by Lasagne to find # the layers with the get_all_layers() helper function in the # case of a layer with sublayers if isinstance(self.out_layer, tuple): self.input_layer = None else: self.input_layer = self.out_layer def get_output_shape_for(self, input_shape): pheight, pwidth = self.patch_size npatchesH = ceildiv(input_shape[2], pheight) npatchesW = ceildiv(input_shape[3], pwidth) if self.stack_sublayers: dim = 2 * self.n_hidden else: dim = 4 * self.n_hidden return input_shape[0], dim, npatchesH, npatchesW def get_output_for(self, input_var, **kwargs): # HACK LASAGNE # This is needed, jointly with the previous hack, to ensure that # this layer behaves as its last sublayer (namely, # self.input_layer) return input_var class BidirectionalRNNLayer(lasagne.layers.Layer): # Setting a value for grad_clipping will clip the gradients in the layer def __init__( self, l_in, num_units, RecurrentNet=lasagne.layers.GRULayer, # common parameters nonlinearity=lasagne.nonlinearities.rectify, hid_init=lasagne.init.Constant(0.), grad_clipping=0, precompute_input=True, mask_input=None, # GRU specific params gru_resetgate=lasagne.layers.Gate(W_cell=None), gru_updategate=lasagne.layers.Gate(W_cell=None), gru_hidden_update=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), gru_hid_init=lasagne.init.Constant(0.), batch_norm=False, # LSTM specific params lstm_ingate=lasagne.layers.Gate(), lstm_forgetgate=lasagne.layers.Gate(), lstm_cell=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), lstm_outgate=lasagne.layers.Gate(), # RNN specific params rnn_W_in_to_hid=lasagne.init.Uniform(), rnn_W_hid_to_hid=lasagne.init.Uniform(), rnn_b=lasagne.init.Constant(0.), name='', **kwargs): """A Bidirectional RNN Layer Parameters ---------- l_in : lasagne.layers.Layer The input layer num_units : int The number of hidden units of each RNN RecurrentNet : lasagne.layers.Layer A recurrent layer class nonlinearity : callable or None The nonlinearity that is applied to the output. If None is provided, no nonlinearity will be applied. Only for LSTMLayer and RecurrentLayer hid_init : callable, np.ndarray, theano.shared or lasagne.layers.Layer Initializer for initial hidden state grad_clipping : float If nonzero, the gradient messages are clipped to the given value during the backward pass. precompute_input : bool If True, precompute input_to_hid before iterating through the sequence. This can result in a speedup at the expense of an increase in memory usage. mask_input : lasagne.layers.Layer Layer which allows for a sequence mask to be input, for when sequences are of variable length. Default None, which means no mask will be supplied (i.e. all sequences are of the same length). gru_resetgate : lasagne.layers.Gate Parameters for the reset gate, if RecurrentNet is GRU gru_updategate : lasagne.layers.Gate Parameters for the update gate, if RecurrentNet is GRU gru_hidden_update : lasagne.layers.Gate Parameters for the hidden update, if RecurrentNet is GRU gru_hid_init : callable, np.ndarray, theano.shared or lasagne.layers.Layer Initializer for initial hidden state, if RecurrentNet is GRU lstm_ingate : lasagne.layers.Gate Parameters for the input gate, if RecurrentNet is LSTM lstm_forgetgate : lasagne.layers.Gate Parameters for the forget gate, if RecurrentNet is LSTM lstm_cell : lasagne.layers.Gate Parameters for the cell computation, if RecurrentNet is LSTM lstm_outgate : lasagne.layers.Gate Parameters for the output gate, if RecurrentNet is LSTM rnn_W_in_to_hid : Theano shared variable, numpy array or callable Initializer for input-to-hidden weight matrix, if RecurrentNet is RecurrentLayer rnn_W_hid_to_hid : Theano shared variable, numpy array or callable Initializer for hidden-to-hidden weight matrix, if RecurrentNet is RecurrentLayer rnn_b : Theano shared variable, numpy array, callable or None Initializer for bias vector, if RecurrentNet is RecurrentLaye. If None is provided there will be no bias name = string The name of the layer, optional """ super(BidirectionalRNNLayer, self).__init__(l_in, name, **kwargs) self.l_in = l_in self.num_units = num_units self.grad_clipping = grad_clipping self.name = name # We use a bidirectional RNN, which means we combine two # RecurrentLayers, the second of which with backwards=True # Setting only_return_final=True makes the layers only return their # output for the final time step, which is all we need for this task # GRU if RecurrentNet.__name__ == 'GRULayer': if batch_norm: RecurrentNet = lasagne.layers.BNGRULayer rnn_params = dict( resetgate=gru_resetgate, updategate=gru_updategate, hidden_update=gru_hidden_update, hid_init=gru_hid_init) # LSTM elif RecurrentNet.__name__ == 'LSTMLayer': rnn_params = dict( nonlinearity=nonlinearity, ingate=lstm_ingate, forgetgate=lstm_forgetgate, cell=lstm_cell, outgate=lstm_outgate) # RNN elif RecurrentNet.__name__ == 'RecurrentLayer': rnn_params = dict( nonlinearity=nonlinearity, W_in_to_hid=rnn_W_in_to_hid, W_hid_to_hid=rnn_W_hid_to_hid, b=rnn_b) else: raise NotImplementedError('RecurrentNet not implemented') common_params = dict( hid_init=hid_init, grad_clipping=grad_clipping, precompute_input=precompute_input, mask_input=mask_input, only_return_final=False) rnn_params.update(common_params) l_forward = RecurrentNet( l_in, num_units, name=name + '_l_forward_sub', **rnn_params) l_backward = RecurrentNet( l_forward, num_units, backwards=True, name=name + '_l_backward_sub', **rnn_params) # Now we'll concatenate the outputs to combine them # Note that l_backward is already inverted by Lasagne l_concat = lasagne.layers.ConcatLayer([l_forward, l_backward], axis=2, name=name+'_concat') # HACK LASAGNE # This will set `self.input_layer`, which is needed by Lasagne to find # the layers with the get_all_layers() helper function in the # case of a layer with sublayers if isinstance(l_concat, tuple): self.input_layer = None else: self.input_layer = l_concat def get_output_shape_for(self, input_shape): return list(input_shape[0:2]) + [self.num_units * 2] def get_output_for(self, input_var, **kwargs): # HACK LASAGNE # This is needed, jointly with the previous hack, to ensure that # this layer behaves as its last sublayer (namely, # self.input_layer) return input_var class LinearUpsamplingLayer(lasagne.layers.Layer): def __init__(self, incoming, expand_height, expand_width, nclasses, W=lasagne.init.Normal(0.01), b=lasagne.init.Constant(.0), batch_norm=False, **kwargs): super(LinearUpsamplingLayer, self).__init__(incoming, **kwargs) nfeatures_in = self.input_shape[-1] nfeatures_out = expand_height * expand_width * nclasses self.nfeatures_out = nfeatures_out self.incoming = incoming self.expand_height = expand_height self.expand_width = expand_width self.nclasses = nclasses self.batch_norm = batch_norm # ``regularizable`` and ``trainable`` by default self.W = self.add_param(W, (nfeatures_in, nfeatures_out), name='W') if not batch_norm: self.b = self.add_param(b, (nfeatures_out,), name='b') def get_output_for(self, input_arr, **kwargs): # upsample pred = T.dot(input_arr, self.W) if not self.batch_norm: pred += self.b nrows, ncolumns = self.input_shape[1:3] batch_size = -1 nclasses = self.nclasses expand_height = self.expand_height expand_width = self.expand_width # Reshape after the upsampling to come back to the original # dimensions and move the pixels in the right place pred = pred.reshape((batch_size, nrows, ncolumns, expand_height, expand_width, nclasses)) pred = pred.dimshuffle((0, 1, 4, 2, 5, 3)) pred = pred.reshape((batch_size, nrows * expand_height, ncolumns * expand_width, nclasses)) return pred def get_output_shape_for(self, input_shape): return (input_shape[0], input_shape[1] * self.expand_height, input_shape[2] * self.expand_width, self.nclasses) class CropLayer(lasagne.layers.Layer): def __init__(self, l_in, crop, data_format='bc01', centered=True, **kwargs): super(CropLayer, self).__init__(l_in, crop, **kwargs) assert data_format in ['bc01', 'b01c'] if not isinstance(crop, T.TensorVariable): crop = lasagne.utils.as_tuple(crop, 2) self.crop = crop self.data_format = data_format self.centered = centered def get_output_shape_for(self, input_shape, **kwargs): # self.crop is a tensor --> we cannot know in advance how much # we will crop if isinstance(self.crop, T.TensorVariable): if self.data_format == 'bc01': input_shape = list(input_shape) input_shape[2] = None input_shape[3] = None else: input_shape = list(input_shape) input_shape[1] = None input_shape[2] = None # self.crop is a list of ints else: if self.data_format == 'bc01': input_shape = list(input_shape) input_shape[2] -= self.crop[0] input_shape[3] -= self.crop[1] else: input_shape = list(input_shape) input_shape[1] -= self.crop[0] input_shape[2] -= self.crop[1] return input_shape def get_output_for(self, input_arr, **kwargs): crop = self.crop.astype('int32') # Indices have to be int sz = input_arr.shape if self.data_format == 'bc01': if self.centered: idx0 = T.switch(T.eq(-crop[0] + crop[0]/2, 0), sz[2], -crop[0] + crop[0]/2) idx1 = T.switch(T.eq(-crop[1] + crop[1]/2, 0), sz[3], -crop[1] + crop[1]/2) return input_arr[:, :, crop[0]/2:idx0, crop[1]/2:idx1] else: idx0 = T.switch(T.eq(crop[0], 0), sz[2], -crop[0]) idx1 = T.switch(T.eq(crop[1], 0), sz[3], -crop[1]) return input_arr[:, :, :idx0, :idx1] else: if self.centered: idx0 = T.switch(T.eq(-crop[0] + crop[0]/2, 0), sz[1], -crop[0] + crop[0]/2) idx1 = T.switch(T.eq(-crop[1] + crop[1]/2, 0), sz[2], -crop[1] + crop[1]/2) return input_arr[:, crop[0]/2:idx0, crop[1]/2:idx1, :] else: idx0 = T.switch(T.eq(crop[0], 0), sz[1], -crop[0]) idx1 = T.switch(T.eq(crop[1], 0), sz[2], -crop[1]) return input_arr[:, :idx0, :idx1, :] ================================================ FILE: padded.py ================================================ import warnings import numpy import lasagne from lasagne import init, nonlinearities from lasagne.layers import get_all_layers, Conv2DLayer, Layer, Pool2DLayer import theano from theano import tensor as T from theano.ifelse import ifelse class PaddedConv2DLayer(Conv2DLayer): def __init__(self, incoming, num_filters, filter_size, stride=(1, 1), pad=0, untie_biases=False, W=init.GlorotUniform(), b=init.Constant(0.), nonlinearity=nonlinearities.rectify, flip_filters=True, convolution=theano.tensor.nnet.conv2d, centered=True, **kwargs): """A padded convolutional layer Note ---- If used in place of a :class:``lasagne.layers.Conv2DLayer`` be sure to specify `flag_filters=False`, which is the default for that layer Parameters ---------- incoming : lasagne.layers.Layer The input layer num_filters : int The number of filters or kernels of the convolution filter_size : int or iterable of int The size of the filters stride : int or iterable of int The stride or subsampling of the convolution pad : int, iterable of int, ``full``, ``same`` or ``valid`` **Ignored!** Kept for compatibility with the :class:``lasagne.layers.Conv2DLayer`` untie_biases : bool See :class:``lasagne.layers.Conv2DLayer`` W : Theano shared variable, expression, numpy array or callable See :class:``lasagne.layers.Conv2DLayer`` b : Theano shared variable, expression, numpy array, callable or None See :class:``lasagne.layers.Conv2DLayer`` nonlinearity : callable or None See :class:``lasagne.layers.Conv2DLayer`` flip_filters : bool See :class:``lasagne.layers.Conv2DLayer`` convolution : callable See :class:``lasagne.layers.Conv2DLayer`` centered : bool If True, the padding will be added on both sides. If False the zero padding will be applied on the upper left side. **kwargs Any additional keyword arguments are passed to the :class:``lasagne.layers.Layer`` superclass """ self.centered = centered if pad not in [0, (0, 0), [0, 0]]: warnings.warn('The specified padding will be ignored', RuntimeWarning) super(PaddedConv2DLayer, self).__init__(incoming, num_filters, filter_size, stride, pad, untie_biases, W, b, nonlinearity, flip_filters, **kwargs) if self.input_shape[2:] != (None, None): warnings.warn('This Layer should only be used when the size of ' 'the image is not known', RuntimeWarning) def get_output_for(self, input_arr, **kwargs): # Compute the padding required not to crop any pixel input_arr, pad = zero_pad( input_arr, self.filter_size, self.stride, self.centered, 'bc01') # Erase self.pad to prevent theano from padding the input self.pad = 0 ret = super(PaddedConv2DLayer, self).get_output_for(input_arr, **kwargs) # Set pad to access it from outside self.pad = pad return ret def get_output_shape_for(self, input_shape): return zero_pad_shape(input_shape, self.filter_size, self.stride, 'bc01') def get_equivalent_input_padding(self, layers_args=[]): """Compute the equivalent padding in the input layer See :func:`padded.get_equivalent_input_padding` """ return(get_equivalent_input_padding(self, layers_args)) class PaddedPool2DLayer(Pool2DLayer): def __init__(self, incoming, pool_size, stride=None, pad=(0, 0), ignore_border=True, centered=True, **kwargs): """A padded pooling layer Parameters ---------- incoming : lasagne.layers.Layer The input layer pool_size : int The size of the pooling stride : int or iterable of int The stride or subsampling of the convolution pad : int, iterable of int, ``full``, ``same`` or ``valid`` **Ignored!** Kept for compatibility with the :class:``lasagne.layers.Pool2DLayer`` ignore_border : bool See :class:``lasagne.layers.Pool2DLayer`` centered : bool If True, the padding will be added on both sides. If False the zero padding will be applied on the upper left side. **kwargs Any additional keyword arguments are passed to the Layer superclass """ self.centered = centered if pad not in [0, (0, 0), [0, 0]]: warnings.warn('The specified padding will be ignored', RuntimeWarning) super(PaddedPool2DLayer, self).__init__(incoming, pool_size, stride, pad, ignore_border, **kwargs) if self.input_shape[2:] != (None, None): warnings.warn('This Layer should only be used when the size of ' 'the image is not known', RuntimeWarning) def get_output_for(self, input_arr, **kwargs): # Compute the padding required not to crop any pixel input_arr, pad = zero_pad( input_arr, self.pool_size, self.stride, self.centered, 'bc01') # Erase self.pad to prevent theano from padding the input self.pad = 0 ret = super(PaddedConv2DLayer, self).convolve(input_arr, **kwargs) # Set pad to access it from outside self.pad = pad return ret def get_output_shape_for(self, input_shape): return zero_pad_shape(input_shape, self.pool_size, self.stride, 'bc01') def get_equivalent_input_padding(self, layers_args=[]): """Compute the equivalent padding in the input layer See :func:`padded.get_equivalent_input_padding` """ return(get_equivalent_input_padding(self, layers_args)) class DynamicPaddingLayer(Layer): def __init__( self, l_in, patch_size, stride, data_format='bc01', centered=True, name='', **kwargs): """A Layer that zero-pads the input Parameters ---------- l_in : lasagne.layers.Layer The input layer patch_size : iterable of int The patch size stride : iterable of int The stride data_format : string The format of l_in, either `b01c` (batch, rows, cols, channels) or `bc01` (batch, channels, rows, cols) centered : bool If True, the padding will be added on both sides. If False the zero padding will be applied on the upper left side. name = string The name of the layer, optional """ super(DynamicPaddingLayer, self).__init__(l_in, name, **kwargs) self.l_in = l_in self.patch_size = patch_size self.stride = stride self.data_format = data_format self.centered = centered self.name = name def get_output_for(self, input_arr, **kwargs): input_arr, pad = zero_pad( input_arr, self.patch_size, self.stride, self.centered, self.data_format) self.pad = pad return input_arr def get_output_shape_for(self, input_shape): return zero_pad_shape(input_shape, self.patch_size, self.stride, self.data_format, True) def zero_pad(input_arr, patch_size, stride, centered=True, data_format='bc01'): assert data_format in ['bc01', 'b01c'] if data_format == 'b01c': in_shape = input_arr.shape[1:3] else: in_shape = input_arr.shape[2:] # bs, ch, rows, cols in_shape -= patch_size pad = in_shape % stride pad = (stride - pad) % stride # TODO improve efficiency by allocating the full array of zeros and # setting the subtensor afterwards if data_format == 'bc01': if centered: input_arr = ifelse( T.eq(pad[0], 0), input_arr, T.concatenate( (T.zeros_like(input_arr[:, :, :pad[0]/2, :]), input_arr, T.zeros_like(input_arr[:, :, :pad[0] - pad[0]/2, :])), 2)) input_arr = ifelse( T.eq(pad[1], 0), input_arr, T.concatenate( (T.zeros_like(input_arr[:, :, :, :pad[1]/2]), input_arr, T.zeros_like(input_arr[:, :, :, :pad[1] - pad[1]/2])), 3)) else: input_arr = ifelse( T.eq(pad[0], 0), input_arr, T.concatenate((T.zeros_like(input_arr[:, :, :pad[0], :]), input_arr), 2)) input_arr = ifelse( T.eq(pad[1], 0), input_arr, T.concatenate((T.zeros_like(input_arr[:, :, :, :pad[1]]), input_arr), 3)) else: if centered: input_arr = ifelse( T.eq(pad[0], 0), input_arr, T.concatenate( (T.zeros_like(input_arr[:, :pad[0]/2, :, :]), input_arr, T.zeros_like(input_arr[:, :pad[0] - pad[0]/2, :, :])), 1)) input_arr = ifelse( T.eq(pad[1], 0), input_arr, T.concatenate( (T.zeros_like(input_arr[:, :, :pad[1]/2, :]), input_arr, T.zeros_like(input_arr[:, :, :pad[1] - pad[1]/2, :])), 2)) else: input_arr = ifelse( T.eq(pad[0], 0), input_arr, T.concatenate((T.zeros_like(input_arr[:, :pad[0], :, :]), input_arr), 1)) input_arr = ifelse( T.eq(pad[1], 0), input_arr, T.concatenate((T.zeros_like(input_arr[:, :, :pad[1], :]), input_arr), 2)) return input_arr, pad def zero_pad_shape(input_shape, patch_size, stride, data_format, only_pad=False): assert data_format in ['bc01', 'b01c'] patch_size = numpy.array(patch_size) stride = numpy.array(stride) if data_format == 'b01c': im_shape = numpy.array(input_shape[1:3]) else: im_shape = numpy.array(input_shape[2:]) pad = (im_shape - patch_size) % stride pad = (stride - pad) % stride if only_pad: out_shape = list(im_shape + pad) else: out_shape = list((im_shape - patch_size + pad) / stride + 1) if data_format == 'b01c': out_shape = [input_shape[0]] + out_shape + [input_shape[3]] else: out_shape = list(input_shape[:2]) + out_shape return list(out_shape) def get_equivalent_input_padding(layer, layers_args=[]): """Compute the equivalent padding in the input layer A function to compute the equivalent padding of a sequence of convolutional and pooling layers. It memorizes the padding of all the Layers up to the first InputLayer. It then computes what would be the equivalent padding in the Layer immediately before the chain of Layers that is being taken into account. """ # Initialize the DynamicPadding layers lasagne.layers.get_output(layer) # Loop through conv and pool to collect data all_layers = get_all_layers(layer) # while(not isinstance(layer, (InputLayer))): for layer in all_layers: # Note: stride is numerical, but pad *could* be symbolic try: pad, stride = (layer.pad, layer.stride) if isinstance(pad, int): pad = pad, pad if isinstance(stride, int): stride = stride, stride layers_args.append((pad, stride)) except(AttributeError): pass # Loop backward to compute the equivalent padding in the input # layer tot_pad = T.zeros(2) pad_factor = T.ones(2) while(layers_args): pad, stride = layers_args.pop() tot_pad += pad * pad_factor pad_factor *= stride return tot_pad ================================================ FILE: reseg.py ================================================ # Standard library imports import cPickle as pkl import collections import os import random from shutil import move, rmtree import sys import time # Related third party imports import lasagne from lasagne.layers import get_output import numpy as np from progressbar import ProgressBar import theano from theano import tensor as T from theano.compile.nanguardmode import NanGuardMode # Local application/library specific imports from helper_dataset import preprocess_dataset from get_info_model import print_params from layers import CropLayer, ReSegLayer from subprocess import check_output from utils import iterate_minibatches, save_with_retry, validate, VariableText # Datasets import # TODO these should go into preprocess/helper dataset/evaluate import camvid floatX = theano.config.floatX intX = 'uint8' debug = False nanguard = False datasets = {'camvid': (camvid.load_data, camvid.properties)} def get_dataset(name): return (datasets[name][0], datasets[name][1]) def buildReSeg(input_shape, input_var, n_layers, pheight, pwidth, dim_proj, nclasses, stack_sublayers, # upsampling out_upsampling, out_nfilters, out_filters_size, out_filters_stride, out_W_init=lasagne.init.GlorotUniform(), out_b_init=lasagne.init.Constant(0.), out_nonlinearity=lasagne.nonlinearities.rectify, # input ConvLayers in_nfilters=None, in_filters_size=(), in_filters_stride=(), in_W_init=lasagne.init.GlorotUniform(), in_b_init=lasagne.init.Constant(0.), in_nonlinearity=lasagne.nonlinearities.rectify, # common recurrent layer params RecurrentNet=lasagne.layers.GRULayer, nonlinearity=lasagne.nonlinearities.rectify, hid_init=lasagne.init.Constant(0.), grad_clipping=0, precompute_input=True, mask_input=None, # 1x1 Conv layer for dimensional reduction conv_dim_red=False, conv_dim_red_nonlinearity=lasagne.nonlinearities.identity, # GRU specific params gru_resetgate=lasagne.layers.Gate(W_cell=None), gru_updategate=lasagne.layers.Gate(W_cell=None), gru_hidden_update=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), gru_hid_init=lasagne.init.Constant(0.), # LSTM specific params lstm_ingate=lasagne.layers.Gate(), lstm_forgetgate=lasagne.layers.Gate(), lstm_cell=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), lstm_outgate=lasagne.layers.Gate(), # RNN specific params rnn_W_in_to_hid=lasagne.init.Uniform(), rnn_W_hid_to_hid=lasagne.init.Uniform(), rnn_b=lasagne.init.Constant(0.), # Special layer batch_norm=False ): '''Helper function to build a ReSeg network''' # Input is b01c print('Input shape: ' + str(input_shape)) l_in = lasagne.layers.InputLayer(shape=input_shape, input_var=input_var, name="input_layer") # Convert to bc01 (batchsize, ch, rows, cols) l_in = lasagne.layers.DimshuffleLayer(l_in, (0, 3, 1, 2)) # To know the upsampling ratio we compute what is the feature map # size at the end of the downsampling pathway for an hypotetical # initial size of 100 (we just need the ratio, so we don't care # about the actual size) hypotetical_fm_size = np.array((100.0, 100.0)) l_reseg = ReSegLayer(l_in, n_layers, pheight, pwidth, dim_proj, nclasses, stack_sublayers, # upsampling out_upsampling, out_nfilters, out_filters_size, out_filters_stride, out_W_init=out_W_init, out_b_init=out_b_init, out_nonlinearity=out_nonlinearity, hypotetical_fm_size=hypotetical_fm_size, # input ConvLayers in_nfilters=in_nfilters, in_filters_size=in_filters_size, in_filters_stride=in_filters_stride, in_W_init=in_W_init, in_b_init=in_b_init, in_nonlinearity=in_nonlinearity, # common recurrent layer params RecurrentNet=RecurrentNet, nonlinearity=nonlinearity, hid_init=hid_init, grad_clipping=grad_clipping, precompute_input=precompute_input, mask_input=mask_input, # 1x1 Conv layer for dimensional reduction conv_dim_red=conv_dim_red, conv_dim_red_nonlinearity=conv_dim_red_nonlinearity, # GRU specific params gru_resetgate=gru_resetgate, gru_updategate=gru_updategate, gru_hidden_update=gru_hidden_update, gru_hid_init=gru_hid_init, # LSTM specific params lstm_ingate=lstm_ingate, lstm_forgetgate=lstm_forgetgate, lstm_cell=lstm_cell, lstm_outgate=lstm_outgate, # RNN specific params rnn_W_in_to_hid=rnn_W_in_to_hid, rnn_W_hid_to_hid=rnn_W_hid_to_hid, rnn_b=rnn_b, # Special layers batch_norm=batch_norm, name='reseg') # Dynamic cropping target_size = get_output(l_in).shape[2:] crop = get_output(l_reseg).shape[2:] - target_size l_out = CropLayer(l_reseg, crop, centered=False) # channel = nclasses if 'linear' not in out_upsampling: l_out = lasagne.layers.Conv2DLayer( l_out, num_filters=nclasses, filter_size=(1, 1), stride=(1, 1), W=out_W_init, b=out_b_init, nonlinearity=None ) if batch_norm: l_out = lasagne.layers.batch_norm(l_out, axes='auto') # Go to b01c l_out = lasagne.layers.DimshuffleLayer( l_out, [0, 2, 3, 1], name='dimshuffle_before_softmax') # Reshape in 2D, last dimension is nclasses, where the softmax is applied l_out_shape = get_output(l_out).shape l_out = lasagne.layers.ReshapeLayer( l_out, (T.prod(l_out_shape[0:3]), l_out_shape[3]), name='reshape_before_softmax') l_out = lasagne.layers.NonlinearityLayer( l_out, nonlinearity=lasagne.nonlinearities.softmax, name="softmax_layer") return l_out def getFunctions(input_var, target_var, class_balance_w_var, l_pred, batch_norm=False, weight_decay=0., optimizer=lasagne.updates.adadelta, learning_rate=None, momentum=None, rho=None, beta1=None, beta2=None, epsilon=None, ): '''Helper function to build the training function ''' input_shape = input_var.shape # Compute BN params for prediction batch_norm_params = dict() if batch_norm: batch_norm_params.update( dict(batch_norm_update_averages=False)) batch_norm_params.update( dict(batch_norm_use_averages=True)) # Prediction function: # computes the deterministic distribution over the labels, i.e. we # disable the stochastic layers such as Dropout prediction = lasagne.layers.get_output(l_pred, deterministic=True, **batch_norm_params) f_pred = theano.function( [input_var], T.argmax(prediction, axis=1).reshape( (-1, input_shape[1], input_shape[2]))) # Compute the loss to be minimized during training batch_norm_params = dict() if batch_norm: batch_norm_params.update( dict(batch_norm_update_averages=True)) batch_norm_params.update( dict(batch_norm_use_averages=False)) prediction = lasagne.layers.get_output(l_pred, **batch_norm_params) loss = lasagne.objectives.categorical_crossentropy( prediction, target_var) loss *= class_balance_w_var loss = loss.reshape((-1, input_shape[1] * input_shape[2])) # Compute the cumulative loss (over the pixels) per minibatch loss = T.sum(loss, axis=1) # Compute the mean loss loss = T.mean(loss, axis=0) if weight_decay > 0: l2_penalty = lasagne.regularization.regularize_network_params( l_pred, lasagne.regularization.l2, tags={'regularizable': True}) loss += l2_penalty * weight_decay params = lasagne.layers.get_all_params(l_pred, trainable=True) opt_params = dict() if optimizer.__name__ == 'sgd': if learning_rate is None: raise TypeError("Learning rate can't be 'None' with SGD") opt_params = dict(learning_rate=learning_rate) elif (optimizer.__name__ == 'momentum' or optimizer.__name__ == 'nesterov_momentum'): if learning_rate is None: raise TypeError("Learning rate can't be 'None' " "with Momentum SGD or Nesterov Momentum") opt_params = dict( learning_rate=learning_rate, momentum=momentum ) elif optimizer.__name__ == 'adagrad': if learning_rate is not None: opt_params.update(dict(learning_rate=learning_rate)) if epsilon is not None: opt_params.update(dict(epsilon=epsilon)) elif (optimizer.__name__ == 'rmsprop' or optimizer.__name__ == 'adadelta'): if learning_rate is not None: opt_params.update(dict(learning_rate=learning_rate)) if rho is not None: opt_params.update(dict(rho=rho)) if epsilon is not None: opt_params.update(dict(epsilon=epsilon)) elif (optimizer.__name__ == 'adam' or optimizer.__name__ == 'adamax'): if learning_rate is not None: opt_params.update(dict(learning_rate=learning_rate)) if beta1 is not None: opt_params.update(dict(beta1=beta1)) if beta2 is not None: opt_params.update(dict(beta2=beta2)) if epsilon is not None: opt_params.update(dict(epsilon=epsilon)) else: raise NotImplementedError('Optimization method not implemented') updates = optimizer(loss, params, **opt_params) # Training function: # computes the training loss (with stochasticity, if any) and # updates the weights using the updates dictionary provided by the # optimization function f_train = theano.function([input_var, target_var, class_balance_w_var], loss, updates=updates) return f_pred, f_train def train(saveto='model.npz', tmp_saveto=None, # Input Conv layers in_nfilters=None, # None = no input convolution in_filters_size=(), in_filters_stride=(), in_W_init=lasagne.init.GlorotUniform(), in_b_init=lasagne.init.Constant(0.), in_nonlinearity=lasagne.nonlinearities.rectify, # RNNs layers dim_proj=[32, 32], pwidth=2, pheight=2, stack_sublayers=(True, True), RecurrentNet=lasagne.layers.GRULayer, nonlinearity=lasagne.nonlinearities.rectify, hid_init=lasagne.init.Constant(0.), grad_clipping=0, precompute_input=True, mask_input=None, # 1x1 Conv layer for dimensional reduction conv_dim_red=False, conv_dim_red_nonlinearity=lasagne.nonlinearities.identity, # GRU specific params gru_resetgate=lasagne.layers.Gate(W_cell=None), gru_updategate=lasagne.layers.Gate(W_cell=None), gru_hidden_update=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), gru_hid_init=lasagne.init.Constant(0.), # LSTM specific params lstm_ingate=lasagne.layers.Gate(), lstm_forgetgate=lasagne.layers.Gate(), lstm_cell=lasagne.layers.Gate( W_cell=None, nonlinearity=lasagne.nonlinearities.tanh), lstm_outgate=lasagne.layers.Gate(), # RNN specific params rnn_W_in_to_hid=lasagne.init.Uniform(), rnn_W_hid_to_hid=lasagne.init.Uniform(), rnn_b=lasagne.init.Constant(0.), # Output upsampling layers out_upsampling='grad', out_nfilters=None, # The last number should be the num of classes out_filters_size=(1, 1), out_filters_stride=None, out_W_init=lasagne.init.GlorotUniform(), out_b_init=lasagne.init.Constant(0.), out_nonlinearity=lasagne.nonlinearities.rectify, # Prediction, Softmax intermediate_pred=None, class_balance=None, # Special layers batch_norm=False, use_dropout=False, dropout_rate=0.5, use_dropout_x=False, dropout_x_rate=0.8, # Optimization method optimizer=lasagne.updates.adadelta, learning_rate=None, momentum=None, rho=None, beta1=None, beta2=None, epsilon=None, weight_decay=0., # l2 reg weight_noise=0., # Early stopping patience=500, # Num updates with no improvement before early stop max_epochs=5000, min_epochs=100, # Sampling and validation params validFreq=1000, saveFreq=1000, # Parameters pickle frequency n_save=-1, # If n_save is a list of indexes, the corresponding # elements of each split are saved. If n_save is an # integer, n_save random elements for each split are # saved. If n_save is -1, all the dataset is saved valid_wait=0, # Batch params batch_size=8, valid_batch_size=1, shuffle=True, # Dataset dataset='horses', color_space='RGB', color=True, use_depth=None, resize_images=True, resize_size=-1, # Pre-processing preprocess_type=None, patch_size=(9, 9), max_patches=1e5, # Data augmentation do_random_flip=False, do_random_shift=False, do_random_invert_color=False, shift_pixels=2, reload_=False ): # Set options and history_acc # ---------------------------- start = time.time() # we use time.time() to know the *real-world* time bestparams = {} rng = np.random.RandomState(0xbeef) saveto = [tmp_saveto, saveto] if tmp_saveto else [saveto] if type(pwidth) != list: pwidth = [pwidth] * len(dim_proj) if type(pheight) != list: pheight = [pheight] * len(dim_proj) # TODO Intermediate pred should probably have length nlayer - 1, # i.e., we don't need to enforce the last one to be True # TODO We are not using it for now # if intermediate_pred is None: # intermediate_pred = [[False] * (len(dim_proj) - 1)] + [[False, True]] # if not unroll(intermediate_pred)[-1]: # raise ValueError('The last value of intermediate_pred should be True') if not resize_images and valid_batch_size != 1: raise ValueError('When images are not resized valid_batch_size' 'should be 1') color = color if color else False nchannels = 3 if color else 1 mode = None if nanguard: mode = NanGuardMode(nan_is_error=True, inf_is_error=True, big_is_error=True) options = locals().copy() # Repositories hash options['recseg_version'] = check_output('git rev-parse HEAD', shell=True)[:-1] options['lasagne_version'] = lasagne.__version__ options['theano_version'] = theano.__version__ # options['trng'] = [el[0].get_value() for el in trng.state_updates] options['history_acc'] = np.array([]) options['history_conf_matrix'] = np.array([]) options['history_iou_index'] = np.array([]) options['eidx'] = 0 options['uidx'] = 0 # Reload # ------ if reload_: for s in saveto[::-1]: try: with open('%s.pkl' % s, 'rb') as f: options_reloaded = pkl.load(f) for k, v in options.iteritems(): if k in ['trng', 'history_acc', 'history_conf_matrix', 'history_iou_index']: continue if k not in options_reloaded: print('{} was not present in the options ' 'file'.format(k)) options_reloaded[k] = v options = options_reloaded print('Option file loaded: {}'.format(s)) break except IOError: continue saveto = options['saveto'] # Input Conv layers in_nfilters = options['in_nfilters'] in_filters_size = options['in_filters_size'] in_filters_stride = options['in_filters_stride'] in_W_init = options['in_W_init'] in_b_init = options['in_b_init'] in_nonlinearity = options['in_nonlinearity'] # RNNs layers dim_proj = options['dim_proj'] pwidth = options['pwidth'] pheight = options['pheight'] stack_sublayers = options['stack_sublayers'] RecurrentNet = options['RecurrentNet'] nonlinearity = options['nonlinearity'] hid_init = options['hid_init'] grad_clipping = options['grad_clipping'] precompute_input = options['precompute_input'] mask_input = options['mask_input'] # 1x1 Conv layer for dimensional reduction conv_dim_red = options['conv_dim_red'] conv_dim_red_nonlinearity = options['conv_dim_red_nonlinearity'] # GRU specific params gru_resetgate = options['gru_resetgate'] gru_updategate = options['gru_updategate'] gru_hidden_update = options['gru_hidden_update'] gru_hid_init = options['gru_hid_init'] # LSTM specific params lstm_ingate = options['lstm_ingate'] lstm_forgetgate = options['lstm_forgetgate'] lstm_cell = options['lstm_cell'] lstm_outgate = options['lstm_outgate'] # RNN specific params rnn_W_in_to_hid = options['rnn_W_in_to_hid'] rnn_W_hid_to_hid = options['rnn_W_hid_to_hid'] rnn_b = options['rnn_b'] # Output upsampling layers out_upsampling = options['out_upsampling'] out_nfilters = options['out_nfilters'] out_filters_size = options['out_filters_size'] out_filters_stride = options['out_filters_stride'] out_W_init = options['out_W_init'] out_b_init = options['out_b_init'] out_nonlinearity = options['out_nonlinearity'] # Prediction, Softmax intermediate_pred = options['intermediate_pred'] class_balance = options['class_balance'] valid_wait = options['valid_wait'] # Special layers batch_norm = options['batch_norm'] use_dropout = options['use_dropout'] dropout_rate = options['dropout_rate'] use_dropout_x = options['use_dropout_x'] dropout_x_rate = options['dropout_x_rate'] # Optimization method optimizer = options['optimizer'] learning_rate = options['learning_rate'] momentum = options['momentum'] rho = options['rho'] beta1 = options['beta1'] beta2 = options['beta2'] epsilon = options['epsilon'] weight_decay = options['weight_decay'] weight_noise = options['weight_noise'] # Batch params batch_size = options['batch_size'] valid_batch_size = options['valid_batch_size'] shuffle = options['shuffle'] # Dataset dataset = options['dataset'] color_space = options['color_space'] color = options['color'] use_depth = options['use_depth'] resize_images = options['resize_images'] resize_size = options['resize_size'] # Pre-processing preprocess_type = options['preprocess_type'] patch_size = options['patch_size'] max_patches = options['max_patches'] # Data augmentation do_random_flip = options['do_random_flip'] do_random_shift = options['do_random_shift'] do_random_invert_color = options['do_random_invert_color'] shift_pixels = options['shift_pixels'] # Save state from options rng = options['rng'] # trng = options['trng'] --> to be reloaded after building the model history_acc = options['history_acc'].tolist() history_conf_matrix = options['history_conf_matrix'].tolist() history_iou_index = options['history_iou_index'].tolist() print_params(options) n_layers = len(dim_proj) assert class_balance in [None, 'median_freq_cost', 'natural_freq_cost', 'priors_correction'], ( 'The balance class method is not implemented') assert (preprocess_type in [None, 'f-whiten', 'conv-zca', 'sub-lcn', 'subdiv-lcn', 'gcn', 'local_mean_sub']), ( "The preprocessing method choosen is not implemented") # Load data # --------- print("Loading data ...") load_data, properties = get_dataset(dataset) train, valid, test, mean, std, filenames, fullmasks = load_data( resize_images=resize_images, resize_size=resize_size, color=color, color_space=color_space, rng=rng, use_depth=use_depth, with_filenames=True, with_fullmasks=True) has_void_class = properties()['has_void_class'] if not color: if mean.ndim == 3: mean = np.expand_dims(mean, axis=3) if std.ndim == 3: std = np.expand_dims(std, axis=3) # Preprocess each image separately usually with LCN in order not to lose # time at each epoch # Default: input is float btw 0 and 1 # If we use vgg convnet the input should be 0:255 input_to_float = False if type(in_nfilters) == str else True train, valid, test = preprocess_dataset(train, valid, test, input_to_float, preprocess_type, patch_size, max_patches) # Compute the indexes of the images to be saved if isinstance(n_save, collections.Iterable): samples_ids = np.array(n_save) elif n_save != -1: samples_ids = [ random.sample(range(len(s)), min(len(s), n_save)) for s in [train[0], valid[0], test[0]]] else: samples_ids = [range(len(s)) for s in [train[0], valid[0], test[0]]] options['samples_ids'] = samples_ids # Retrieve basic size informations and split train variables x_train, y_train = train if len(x_train) == 0: raise RuntimeError("Dataset not found") filenames_train, filenames_valid, filenames_test = filenames cheight, cwidth, cchannels = x_train[0].shape nclasses = max([np.max(el) for el in y_train]) + 1 print '# of classes:', nclasses # Remove the segmentation samples dir to make sure we don't mix samples # from different experiments seg_path = os.path.join('segmentations', dataset, saveto[0].split('/')[-1][:-4]) try: rmtree(seg_path) except OSError: pass # Class balancing # --------------- # TODO: check if it works... w_freq = 1 if class_balance in ['median_freq_cost', 'rare_freq_cost']: u_train, c_train = np.unique(y_train, return_counts=True) priors = c_train.astype(theano.config.floatX) / train[1].size # the denominator is computed by summing the total number # of pixels of the images where the class is present # so it should be even more balanced px_count = np.zeros(u_train.shape) for tt in y_train: u_tt = np.unique(tt) px_t = tt.size for uu in u_tt: px_count[uu] += px_t priors = c_train.astype(theano.config.floatX) / px_count if class_balance == 'median_freq_cost': w_freq = np.median(priors) / priors elif class_balance == 'rare_freq_cost': w_freq = 1 / (nclasses * priors) print "Class balance weights", w_freq assert len(priors) == nclasses, ("Number of computed priors are " "different from number of classes") if validFreq == -1: validFreq = len(x_train)/batch_size if saveFreq == -1: saveFreq = len(x_train)/batch_size # Model compilation # ----------------- print("Building model ...") input_shape = (None, cheight, cwidth, cchannels) input_var = T.tensor4('inputs') target_var = T.ivector('targets') class_balance_w_var = T.vector('class_balance_w_var') # Set the RandomStream to assure repeatability lasagne.random.set_rng(rng) # Tag test values if debug: print "DEBUG MODE: loading tag.test_value ..." load_data, properties = get_dataset(dataset) train, _, _, _, _ = load_data( resize_images=resize_images, resize_size=resize_size, color=color, color_space=color_space, rng=rng) x_tag = (train[0][0:batch_size]).astype(floatX) y_tag = (train[1][0:batch_size]).astype(intX) # TODO Move preprocessing in a separate function if x_tag.ndim == 1: x_tag = x_tag[0] y_tag = y_tag[0] if x_tag.ndim == 3: x_tag = np.expand_dims(x_tag, 0) y_tag = np.expand_dims(y_tag, 0) input_var.tag.test_value = x_tag target_var.tag.test_value = y_tag.flatten() class_balance_w_var.tag.test_value = np.ones( np.prod(x_tag.shape[:3])).astype(floatX) theano.config.compute_test_value = 'warn' # Build the model l_out = buildReSeg(input_shape, input_var, n_layers, pheight, pwidth, dim_proj, nclasses, stack_sublayers, # upsampling out_upsampling, out_nfilters, out_filters_size, out_filters_stride, out_W_init=out_W_init, out_b_init=out_b_init, out_nonlinearity=out_nonlinearity, # input ConvLayers in_nfilters=in_nfilters, in_filters_size=in_filters_size, in_filters_stride=in_filters_stride, in_W_init=in_W_init, in_b_init=in_b_init, in_nonlinearity=in_nonlinearity, # common recurrent layer params RecurrentNet=RecurrentNet, nonlinearity=nonlinearity, hid_init=hid_init, grad_clipping=grad_clipping, precompute_input=precompute_input, mask_input=mask_input, # 1x1 Conv layer for dimensional reduction conv_dim_red=conv_dim_red, conv_dim_red_nonlinearity=conv_dim_red_nonlinearity, # GRU specific params gru_resetgate=gru_resetgate, gru_updategate=gru_updategate, gru_hidden_update=gru_hidden_update, gru_hid_init=gru_hid_init, # LSTM specific params lstm_ingate=lstm_ingate, lstm_forgetgate=lstm_forgetgate, lstm_cell=lstm_cell, lstm_outgate=lstm_outgate, # RNN specific params rnn_W_in_to_hid=rnn_W_in_to_hid, rnn_W_hid_to_hid=rnn_W_hid_to_hid, rnn_b=rnn_b, # special layers batch_norm=batch_norm) f_pred, f_train = getFunctions(input_var, target_var, class_balance_w_var, l_out, weight_decay, optimizer=optimizer, learning_rate=learning_rate, momentum=momentum, rho=rho, beta1=beta1, beta2=beta2, epsilon=epsilon) # Reload the list of the value parameters # TODO Check if the saved params are CudaNDArrays or not, so that we # don't need a GPU to reload the model (I'll do it when you are # done) if reload_: for s in saveto[::-1]: try: with np.load('%s' % s) as f: vparams = [f['arr_%d' % i] for i in range(len(f.files))] lastparams, bestparams = vparams # for i, v in enumerate(options['trng']): # trng.state_updates[i][0].set_value(v) print('Model file loaded: {}'.format(s)) lasagne.layers.set_all_param_values(l_out, bestparams) break except IOError: continue # Main loop # --------- print("Starting training...") uidx = options['uidx'] patience_counter = 0 estop = False save = False epochs_wid = VariableText( 'Epoch %(epoch)d/' + str(max_epochs) + ' Up %(up)d', {'epoch': 0, 'up': 0}) metrics_wid = VariableText( 'Cost %(cost)f, DD %(DD)f, UD %(UD)f %(shape)s', {'cost': 0, 'DD': 0, 'UD': 0, 'shape': 0}) widgets = [ '', epochs_wid, ' ', metrics_wid] pbar = ProgressBar(widgets=widgets, maxval=len(x_train), redirect_stdout=True).start() # Epochs loop for eidx in range(options['uidx'], max_epochs): nsamples = 0 epoch_cost = 0 start_time = time.time() # Minibatches loop for i, minibatch in enumerate(iterate_minibatches(x_train, y_train, batch_size, rng=rng, shuffle=shuffle)): inputs, targets, _ = minibatch st = time.time() nsamples += len(inputs) uidx += 1 # otherwise the normalization has been done before the preprocess # if preprocess_type is None: # inputs = inputs.astype(floatX) targets = targets.astype(intX) targets_flat = targets.flatten() dd = time.time() - st st = time.time() # Class balance class_balance_w = np.ones(np.prod(inputs.shape[:3])).astype(floatX) if class_balance in ['median_freq_cost', 'rare_freq_cost']: class_balance_w = w_freq[targets_flat].astype(floatX) # Compute cost cost = f_train(inputs.astype(floatX), targets_flat, class_balance_w) ud = time.time() - st if np.isnan(cost): raise RuntimeError('NaN detected') if np.isinf(cost): raise RuntimeError('Inf detected') # if np.mod(uidx, dispFreq) == 0: # print('Epoch {}, Up {}, Cost {:.3f}, DD {:.3f}, UD ' + # '{:.5f} {}').format(eidx, uidx, float(cost), dd, ud, # input_shape) epochs_wid.update_mapping({'epoch': eidx, 'up': uidx}) metrics_wid.update_mapping( {'cost': float(cost), 'DD': dd, 'UD': ud, 'shape': input_shape}) pbar.update(min(i*batch_size + 1, len(x_train))) def validate_model(): (train_global_acc, train_conf_matrix, train_mean_class_acc, train_iou_index, train_mean_iou_index) = validate(f_pred, train, valid_batch_size, has_void_class, preprocess_type, nclasses, samples_ids=samples_ids[0], filenames=filenames_train, folder_dataset='train', dataset=dataset, saveto=saveto[0]) (valid_global_acc, valid_conf_matrix, valid_mean_class_acc, valid_iou_index, valid_mean_iou_index) = validate(f_pred, valid, valid_batch_size, has_void_class, preprocess_type, nclasses, samples_ids=samples_ids[1], filenames=filenames_valid, folder_dataset='valid', dataset=dataset, saveto=saveto[0]) (test_global_acc, test_conf_matrix, test_mean_class_acc, test_iou_index, test_mean_iou_index) = validate(f_pred, test, valid_batch_size, has_void_class, preprocess_type, nclasses, samples_ids=samples_ids[2], filenames=filenames_test, folder_dataset='test', dataset=dataset, saveto=saveto[0]) print("") print("Global Accuracies:") print('Train {:.5f} Valid {:.5f} Test {:.5f}'.format( train_global_acc, valid_global_acc, test_global_acc)) print('Mean Class Accuracy - Train {:.5f} Valid {:.5f} ' 'Test {:.5f}'.format(train_mean_class_acc, valid_mean_class_acc, test_mean_class_acc)) print('Mean Class iou - Train {:.5f} Valid {:.5f} ' 'Test {:.5f}'.format(train_mean_iou_index, valid_mean_iou_index, test_mean_iou_index)) print("") history_acc.append([train_global_acc, train_mean_class_acc, train_mean_iou_index, valid_global_acc, valid_mean_class_acc, valid_mean_iou_index, test_global_acc, test_mean_class_acc, test_mean_iou_index]) history_conf_matrix.append([train_conf_matrix, valid_conf_matrix, test_conf_matrix]) history_iou_index.append([train_iou_index, valid_iou_index, test_iou_index]) options['history_acc'] = np.array(history_acc) options['history_conf_matrix'] = np.array(history_conf_matrix) options['history_iou_index'] = np.array(history_iou_index) return valid_mean_iou_index, test_mean_iou_index # Check predictions' accuracy if np.mod(uidx, validFreq) == 0: if valid_wait == 0: (valid_mean_iou_index, test_mean_iou_index) = validate_model() # Did we improve *validation* mean IOU accuracy? if (len(valid) > 0 and (len(history_acc) == 0 or valid_mean_iou_index >= np.array(history_acc)[:, 5].max())): # TODO check if CUDA variables! bestparams = lasagne.layers.get_all_param_values(l_out) patience_counter = 0 save = True # Save model params # Early stop if patience is over if (eidx > min_epochs): patience_counter += 1 if patience_counter == patience / validFreq: print 'Early Stop!' estop = True else: valid_wait -= 1 # Save model parameters if save or np.mod(uidx, saveFreq) == 0: save_time = time.time() lastparams = lasagne.layers.get_all_param_values(l_out) vparams = [lastparams, bestparams] # Retry if filesystem is busy save_with_retry(saveto[0], vparams) save = False pkl.dump(options, open('%s.pkl' % saveto[0], 'wb')) print 'Saved parameters and options in {} in {:.3f}s'.format( saveto[0], time.time() - save_time) epoch_cost += cost # exit minibatches loop if estop: break # exit epochs loop if estop: break print("Epoch {} of {} took {:.3f}s with overall cost {:.3f}".format( eidx + 1, max_epochs, time.time() - start_time, epoch_cost)) pbar.finish() max_valid_idx = np.argmax(np.array(history_acc)[:, 5]) best = history_acc[max_valid_idx] (train_global_acc, train_mean_class_acc, train_mean_iou_index, valid_global_acc, valid_mean_class_acc, valid_mean_iou_index, test_global_acc, test_mean_class_acc, test_mean_iou_index) = best print("") print("Global Accuracies:") print('Best: Train {:.5f} Valid {:.5f} Test {:.5f}'.format( train_global_acc, valid_global_acc, test_global_acc)) print('Best: Mean Class Accuracy - Train {:.5f} Valid {:.5f} ' 'Test {:.5f}'.format(train_mean_class_acc, valid_mean_class_acc, test_mean_class_acc)) print('Best: Mean Class iou - Train {:.5f} Valid {:.5f} ' 'Test {:.5f}'.format(train_mean_iou_index, valid_mean_iou_index, test_mean_iou_index)) print("") if len(saveto) != 1: print("Moving temporary model files to {}".format(saveto[1])) dirname = os.path.dirname(saveto[1]) if not os.path.exists(dirname): os.makedirs(dirname) move(saveto[0], saveto[1]) move(saveto[0] + '.pkl', saveto[1] + '.pkl') end = time.time() m, s = divmod(end - start, 60) h, m = divmod(m, 60) print("Total time elapsed: %d:%02d:%02d" % (h, m, s)) return best def show_seg(dataset_name, n_exp, dataset_set, mode='sequential', id=-1): """ :param model_filename: model_recseg_namedataset1.npz :param dataset_set: 'train', 'valid','test' :param mode: 'random', 'sequential', 'filename', 'id' :param id: 'filename' or 'index' :return: """ # load options model_filename = 'model_recseg_' + dataset_name + n_exp + ".npz" try: options = pkl.load(open( os.path.expanduser( os.path.join(dataset_name + "_models", model_filename + '.pkl')), 'rb')) saveto = options['saveto'][1] except IOError: pass try: options = pkl.load(open( os.path.expanduser( os.path.join("tmp", model_filename + '.pkl')), 'rb')) saveto = options['saveto'][0] except IOError: pass if len(options) == 0: print "Error file not found" exit() n_save = options['n_save'] n_save = -1 # Input Conv layers in_nfilters = options['in_nfilters'] in_filters_size = options['in_filters_size'] in_filters_stride = options['in_filters_stride'] in_W_init = options['in_W_init'] in_b_init = options['in_b_init'] in_nonlinearity = options['in_nonlinearity'] # RNNs layers dim_proj = options['dim_proj'] pwidth = options['pwidth'] pheight = options['pheight'] stack_sublayers = options['stack_sublayers'] RecurrentNet = options['RecurrentNet'] nonlinearity = options['nonlinearity'] hid_init = options['hid_init'] grad_clipping = options['grad_clipping'] precompute_input = options['precompute_input'] mask_input = options['mask_input'] # 1x1 Conv layer for dimensional reduction conv_dim_red = options.get('conv_dim_red', None) conv_dim_red_nonlinearity = options.get('conv_dim_red_nonlinearity', None) # GRU specific params gru_resetgate = options['gru_resetgate'] gru_updategate = options['gru_updategate'] gru_hidden_update = options['gru_hidden_update'] gru_hid_init = options['gru_hid_init'] # LSTM specific params lstm_ingate = options['lstm_ingate'] lstm_forgetgate = options['lstm_forgetgate'] lstm_cell = options['lstm_cell'] lstm_outgate = options['lstm_outgate'] # RNN specific params rnn_W_in_to_hid = options['rnn_W_in_to_hid'] rnn_W_hid_to_hid = options['rnn_W_hid_to_hid'] rnn_b = options['rnn_b'] # Output upsampling layers out_upsampling = options['out_upsampling'] out_nfilters = options['out_nfilters'] out_filters_size = options['out_filters_size'] out_filters_stride = options['out_filters_stride'] out_W_init = options['out_W_init'] out_b_init = options['out_b_init'] out_nonlinearity = options['out_nonlinearity'] # Prediction, Softmax class_balance = options['class_balance'] # Special layers batch_norm = options['batch_norm'] valid_batch_size = options['valid_batch_size'] # Dataset dataset = options['dataset'] color_space = options['color_space'] color = options['color'] use_depth = options.get('use_depth', None) resize_images = options['resize_images'] resize_size = options['resize_size'] # Pre-processing preprocess_type = options['preprocess_type'] patch_size = options['patch_size'] max_patches = options['max_patches'] # Save state from options rng = options['rng'] # trng = options['trng'] --> to be reloaded after building the model print_params(options) n_layers = len(dim_proj) assert class_balance in [None, 'median_freq_cost', 'natural_freq_cost', 'priors_correction'], ( 'The balance class method is not implemented') assert (preprocess_type in [None, 'f-whiten', 'conv-zca', 'sub-lcn', 'subdiv-lcn', 'gcn', 'local_mean_sub']), ( "The preprocessing method choosen is not implemented") # Load data # --------- print("Loading data ...") load_data, properties = get_dataset(dataset) train, valid, test, mean, std, filenames, fullmasks = load_data( resize_images=resize_images, resize_size=resize_size, color=color, color_space=color_space, rng=rng, use_depth=use_depth, with_filenames=True, with_fullmasks=True) has_void_class = properties()['has_void_class'] if not color: if mean.ndim == 3: mean = np.expand_dims(mean, axis=3) if std.ndim == 3: std = np.expand_dims(std, axis=3) # Preprocess each image separately usually with LCN in order not to lose # time at each epoch # Default: input is float btw 0 and 1 # If we use vgg convnet the input should be 0:255 input_to_float = False if type(in_nfilters) == str else True train, valid, test = preprocess_dataset(train, valid, test, input_to_float, preprocess_type, patch_size, max_patches) # Compute the indexes of the images to be saved if isinstance(n_save, collections.Iterable): samples_ids = np.array(n_save) elif n_save != -1: samples_ids = [ random.sample(range(len(s)), min(len(s), n_save)) for s in [train[0], valid[0], test[0]]] else: samples_ids = [range(len(s)) for s in [train[0], valid[0], test[0]]] options['samples_ids'] = samples_ids # Retrieve basic size informations and split train variables x_train, y_train = train if len(x_train) == 0: raise RuntimeError("Dataset not found") filenames_train, filenames_valid, filenames_test = filenames cheight, cwidth, cchannels = x_train[0].shape nclasses = max([np.max(el) for el in y_train]) + 1 print '# of classes:', nclasses # Remove the segmentation samples dir to make sure we don't mix samples # from different experiments seg_path = os.path.join('segmentations', dataset, saveto.split('/')[-1][:-4]) # Class balancing # --------------- w_freq = 1 if class_balance in ['median_freq_cost', 'rare_freq_cost']: # Get labels ids and number of pixels per label u_train, c_train = np.unique(y_train, return_counts=True) # The denominator is computed by summing the total number # of pixels of the images where the class is present px_count = np.zeros(u_train.shape) for tt in y_train: u_tt = np.unique(tt) px_t = tt.size for uu in u_tt: px_count[uu] += px_t priors = c_train.astype(theano.config.floatX) / px_count if class_balance == 'median_freq_cost': w_freq = np.median(priors) / priors # we don't want to give more importance to the void class if has_void_class: w_freq[-1] = 0 elif class_balance == 'rare_freq_cost': w_freq = 1 / (nclasses * priors) print "Class balance weights", w_freq assert len(priors) == nclasses, ("Number of computed priors are " "different from number of classes") try: rmtree(seg_path) except OSError: pass if dataset_set == 'train': data = train samples_ids = samples_ids[0] filenames = filenames_train elif dataset_set == 'valid': data = valid samples_ids = samples_ids[1] filenames = filenames_valid else: data = test samples_ids = samples_ids[2] filenames = filenames_test input_shape = (None, cheight, cwidth, cchannels) input_var = T.tensor4('inputs') l_out = buildReSeg(input_shape, input_var, n_layers, pheight, pwidth, dim_proj, nclasses, stack_sublayers, # upsampling out_upsampling, out_nfilters, out_filters_size, out_filters_stride, out_W_init=out_W_init, out_b_init=out_b_init, out_nonlinearity=out_nonlinearity, # input ConvLayers in_nfilters=in_nfilters, in_filters_size=in_filters_size, in_filters_stride=in_filters_stride, in_W_init=in_W_init, in_b_init=in_b_init, in_nonlinearity=in_nonlinearity, # common recurrent layer params RecurrentNet=RecurrentNet, nonlinearity=nonlinearity, hid_init=hid_init, grad_clipping=grad_clipping, precompute_input=precompute_input, mask_input=mask_input, # 1x1 Conv layer for dimensional reduction conv_dim_red=conv_dim_red, conv_dim_red_nonlinearity=conv_dim_red_nonlinearity, # GRU specific params gru_resetgate=gru_resetgate, gru_updategate=gru_updategate, gru_hidden_update=gru_hidden_update, gru_hid_init=gru_hid_init, # LSTM specific params lstm_ingate=lstm_ingate, lstm_forgetgate=lstm_forgetgate, lstm_cell=lstm_cell, lstm_outgate=lstm_outgate, # RNN specific params rnn_W_in_to_hid=rnn_W_in_to_hid, rnn_W_hid_to_hid=rnn_W_hid_to_hid, rnn_b=rnn_b, # special layers batch_norm=batch_norm) # load best params print("Loading parameter best model ...") with np.load(saveto) as f: bestparams_val = [f['arr_%d' % i] for i in range(len(f.files))] lasagne.layers.set_all_param_values(l_out, bestparams_val[1]) input_shape = input_var.shape # Compute BN params for prediction batch_norm_params = dict() if batch_norm: batch_norm_params.update( dict(batch_norm_update_averages=False)) batch_norm_params.update( dict(batch_norm_use_averages=True)) print("Building model ...") # Model compilation # ----------------- # computes the deterministic distribution over the labels, i.e. we # disable the stochastic layers such as Dropout prediction = lasagne.layers.get_output(l_out, deterministic=True, **batch_norm_params) f_pred = theano.function( [input_var], T.argmax(prediction, axis=1).reshape( (-1, input_shape[1], input_shape[2]))) # compute prediction on the dataset or on the image that we specified (test_global_acc, test_conf_matrix, test_mean_class_acc, test_iou_index, test_mean_iou_index) = validate(f_pred, data, valid_batch_size, has_void_class, preprocess_type, nclasses, samples_ids=samples_ids, filenames=filenames, folder_dataset=dataset_set, dataset=dataset, saveto=saveto[0]) print("") print("Global Accuracies :") print('Test ', test_global_acc) print("") print("Class Accuracies :") print('Test ', test_mean_class_acc) print("") print("Mean Intersection Over Union :") print('Test ', test_mean_iou_index) print("") if __name__ == '__main__': if len(sys.argv) >= 3: dataset_name = sys.argv[1] n_exp = sys.argv[2] else: print "Usage: dataset_name n_exp, e.g. python reseg.py camvid 1" sys.exit() if len(sys.argv) > 3: if sys.argv[3] in ['train', 'valid', 'test']: dataset_set = sys.argv[3] else: print "Usage: choose one between 'train', 'valid', 'test'" sys.exit() else: dataset_set = 'test' if len(sys.argv) > 4: if sys.argv[4] in ['random', 'sequential', 'filename', 'id']: mode = sys.argv[4] if mode in ['filename', 'id']: if len(sys.argv) < 6: print "Insert a correct filename or id!" sys.exit() else: id = sys.argv[5] else: id = -1 else: print "Usage: mode can be 'random', 'sequential', 'filename', 'id'" sys.exit() else: mode = 'sequential' show_seg(dataset_name, n_exp, dataset_set) ================================================ FILE: utils.py ================================================ from collections import OrderedDict import os import matplotlib from matplotlib import cm, pyplot import numpy as np from progressbar import Bar, FormatLabel, Percentage, ProgressBar, Timer from progressbar.widgets import FormatWidgetMixin, WidthWidgetMixin from retrying import retry from skimage import img_as_ubyte from sklearn.metrics import confusion_matrix from skimage.color import label2rgb, gray2rgb from skimage.io import imsave import theano from config_datasets import colormap_datasets floatX = theano.config.floatX def iterate_minibatches(inputs, targets, batchsize, rng=None, shuffle=False): '''Batch iterator This is just a simple helper function iterating over training data in mini-batches of a particular size, optionally in random order. It assumes data is available as numpy arrays. For big datasets, you could load numpy arrays as memory-mapped files (np.load(..., mmap_mode='r')), or write your own custom data iteration function. For small datasets, you can also copy them to GPU at once for slightly improved performance. This would involve several changes in the main program, though, and is not demonstrated here. ''' assert len(inputs) == len(targets) if shuffle: if rng is None: raise Exception("A Numpy RandomState instance is needed!") indices = np.arange(len(inputs)) rng.shuffle(indices) for start_idx in range(0, len(inputs) - batchsize + 1, batchsize): if shuffle: excerpt = indices[start_idx:start_idx + batchsize] else: excerpt = slice(start_idx, start_idx + batchsize) yield inputs[excerpt], targets[excerpt], excerpt def save_image(outpath, img): import errno try: os.makedirs(os.path.dirname(outpath)) except OSError as e: if e.errno != errno.EEXIST: raise e pass imsave(outpath, img_as_ubyte(img)) def validate(f_pred, data, batchsize, has_void, preprocess_type=None, nclasses=2, samples_ids=[], dataset='camvid', saveto='test_lasagne', mean=None, std=None, fullmasks=None, filenames=None, folder_dataset='pred'): """Validate the model Returns ------- The function returns the following performance indexes computed on the input dataset: * Global Pixel Accuracy * Confusion Matrix * Mean Class Accuracy (Mean of the diagonal of Norm Conf Matrix) * Intersection Over Union Indexes for each class * Intersection Over Union Index """ # check if the dataset is empty if len(data) == 0 or len(samples_ids) == 0: return 0., [], 0., [], 0. seg_path = os.path.join('segmentations', dataset, saveto.split('/')[-1][:-4]) try: colormap = colormap_datasets[dataset] except KeyError: color_bins = np.linspace(0, 1, nclasses) norm_bins = matplotlib.colors.Normalize(vmin=0, vmax=1) m = cm.ScalarMappable(norm=norm_bins, cmap=pyplot.get_cmap('Pastel2')) colormap = m.to_rgba(color_bins)[:, :3] inputs, targets = data conf_matrix = np.zeros([nclasses, nclasses]).astype('float32') # Progressbar n_imgs = inputs.shape[0] bar_widgets = [ folder_dataset + ':', FormatLabel('%(value)d/' + str(n_imgs)), ' ', Bar(marker='#'), ' ', Percentage(), ' ', Timer()] pbar = ProgressBar(widgets=bar_widgets, maxval=n_imgs) for i, minibatch in enumerate(iterate_minibatches(inputs, targets, batchsize, shuffle=False)): mini_x, mini_y, mini_slice = minibatch # VGG needs 0:255 int inputs #if preprocess_type is None: # mini_x = img_as_float(mini_x) mini_f = filenames[mini_slice] preds = f_pred(mini_x.astype(floatX)) # just for visualization if np.max(mini_x) > 1: mini_x = (mini_x / 255.).astype(floatX) # Compute the confusion matrix for each image cf_m = confusion_matrix(mini_y.flatten(), preds.flatten(), range(0, nclasses)) conf_matrix += cf_m # Save samples if len(samples_ids) > 0: for pred, x, y, f in zip(preds, mini_x, mini_y, mini_f): if i in samples_ids: # Fix hdf5 stores string into an ndarray if isinstance(f, np.ndarray) and len(f) == 1: f = f[0] # Do not use pgm as an extension f = f.replace(".pgm", ".png") # Handle RGB-D or grey_img + disparity if x.shape[-1] in (1, 2): x = gray2rgb(x[:, :, 0]) elif x.shape[-1] == 4: x = x[:, :, :-1] # Save Image + GT + prediction im_name = os.path.basename(f) pred_rgb = label2rgb(pred, colors=colormap) y_rgb = label2rgb(y, colors=colormap) im_save = np.concatenate((x, y_rgb, pred_rgb), axis=1) outpath = os.path.join(seg_path, folder_dataset, im_name) save_image(outpath, im_save) pbar.update(min(i*batchsize + 1, n_imgs)) pbar.update(n_imgs) # always get to 100% pbar.finish() # Compute per class metrics per_class_TP = np.diagonal(conf_matrix).astype(floatX) per_class_FP = conf_matrix.sum(axis=0) - per_class_TP per_class_FN = conf_matrix.sum(axis=1) - per_class_TP # Compute global accuracy n_pixels = np.sum(conf_matrix) if has_void: n_pixels -= np.sum(conf_matrix[-1, :]) global_acc = per_class_TP[:-1].sum() / float(n_pixels) else: global_acc = per_class_TP.sum() / float(n_pixels) # Class Accuracy class_acc = per_class_TP / (per_class_FN + per_class_TP) class_acc = np.nan_to_num(class_acc) mean_class_acc = (np.mean(class_acc[:-1]) if has_void else np.mean(class_acc)) # Class Intersection over Union iou_index = per_class_TP / (per_class_TP + per_class_FP + per_class_FN) iou_index = np.nan_to_num(iou_index) mean_iou_index = (np.mean(iou_index[:-1]) if has_void else np.mean(iou_index)) return global_acc, conf_matrix, mean_class_acc, iou_index, mean_iou_index def zipp(vparams, params): """Copy values from one dictionary to another. It will copy all the values from the first dictionary to the second dictionary. Parameters ---------- vparams : dict The dictionary to read the parameters from params : The dictionary to write the parameters to """ for kk, vv in vparams.iteritems(): params[kk].set_value(vv) def unzip(zipped, prefix=None): """Return a dict of values out of a dict of theano variables If a prefix is provided it will attach the prefix to the name of the keys in the dictionary Parameters ---------- zipped : dict The dictionary of theano variables prefix : string, optional A prefix to be added to the keys of dictionary """ prefix = '' if prefix is None else prefix + '_' new_params = OrderedDict() for kk, vv in zipped.iteritems(): new_params[prefix + kk] = vv.get_value() return new_params def unroll(deep_list): """ Unroll a deep list into a shallow list Parameters ---------- deep_list : list or tuple An annidated list of lists and/or tuples. Must not be empty. Note ---- The list comprehension is equivalent to: ``` if type(deep_list) in [list, tuple] and len(deep_list): if len(deep_list) == 1: return unroll(deep_list[0]) else: return unroll(deep_list[0]) + unroll(deep_list[1:]) else: return [deep_list] ``` """ return ((unroll(deep_list[0]) if len(deep_list) == 1 else unroll(deep_list[0]) + unroll(deep_list[1:])) if type(deep_list) in [list, tuple] and len(deep_list) else [deep_list]) def retry_if_io_error(exception): """Return True if IOError. Return True if we should retry (in this case when it's an IOError), False otherwise. """ print "Filesystem error, retrying in 2 seconds..." return isinstance(exception, IOError) @retry(stop_max_attempt_number=10, wait_fixed=2000, retry_on_exception=retry_if_io_error) def save_with_retry(saveto, args): if not os.path.exists(os.path.dirname(saveto)): os.makedirs(os.path.dirname(saveto)) np.savez(saveto, *args) def ceildiv(a, b): """Division rounded up Parameters ---------- a : number The numerator b : number The denominator Reference --------- http://stackoverflow.com/questions/14822184/is-there-a-ceiling-equivalent\ -of-operator-in-python """ return -(-a // b) def to_float(l): """Converts an iterable in a list of floats Parameters ---------- l : iterable The iterable to be converted to float """ return [float(el) for el in l] def to_int(l): """Converts an iterable in a list of ints Parameters ---------- l : iterable The iterable to be converted to float """ return [int(el) for el in l] class VariableText(FormatWidgetMixin, WidthWidgetMixin): mapping = {} def __init__(self, format, mapping=mapping, **kwargs): self.format = format self.mapping = mapping FormatWidgetMixin.__init__(self, format=format, **kwargs) WidthWidgetMixin.__init__(self, **kwargs) def update_str(self, new_format): self.format = new_format def update_mapping(self, new_mapping): self.mapping.update(new_mapping) def __call__(self, progress, data): return FormatWidgetMixin.__call__(self, progress, self.mapping, self.format) ================================================ FILE: vgg16.py ================================================ # VGG-16, 16-layer model from the paper: # "Very Deep Convolutional Networks for Large-Scale Image Recognition" # Original source: https://gist.github.com/ksimonyan/211839e770f7b538e2d8 # License: non-commercial use only # Download pretrained weights from: # https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/vgg16.pkl from collections import OrderedDict import numpy try: import cPickle as pickle except: import pickle import lasagne import lasagne.layers from lasagne.layers import (InputLayer, DenseLayer, NonlinearityLayer, ConcatLayer) from lasagne.nonlinearities import softmax from padded import PaddedConv2DLayer from padded import PaddedPool2DLayer import theano class Vgg16Layer(lasagne.layers.Layer): def __init__(self, l_in=InputLayer((None, 3, 224, 224)), get_layer='prob', padded=True, trainable=False, regularizable=False, name='vgg'): super(Vgg16Layer, self).__init__(l_in, name) self.l_in = l_in self.get_layer = get_layer self.padded = padded self.trainable = trainable self.regularizable = regularizable if padded: ConvLayer = PaddedConv2DLayer PoolLayer = PaddedPool2DLayer else: try: ConvLayer = lasagne.layers.dnn.Conv2DDNNLayer except AttributeError: ConvLayer = lasagne.layers.Conv2DLayer PoolLayer = lasagne.layers.Pool2DLayer net = OrderedDict() net['input'] = l_in net['bgr'] = RGBtoBGRLayer(net['input']) net['conv1_1'] = ConvLayer( net['bgr'], 64, 3, pad=1, flip_filters=False) net['conv1_2'] = ConvLayer( net['conv1_1'], 64, 3, pad=1, flip_filters=False) net['pool1'] = PoolLayer( net['conv1_2'], 2) net['conv2_1'] = ConvLayer( net['pool1'], 128, 3, pad=1, flip_filters=False) net['conv2_2'] = ConvLayer( net['conv2_1'], 128, 3, pad=1, flip_filters=False) net['pool2'] = PoolLayer( net['conv2_2'], 2) net['conv3_1'] = ConvLayer( net['pool2'], 256, 3, pad=1, flip_filters=False) net['conv3_2'] = ConvLayer( net['conv3_1'], 256, 3, pad=1, flip_filters=False) net['conv3_3'] = ConvLayer( net['conv3_2'], 256, 3, pad=1, flip_filters=False) net['pool3'] = PoolLayer( net['conv3_3'], 2) net['conv4_1'] = ConvLayer( net['pool3'], 512, 3, pad=1, flip_filters=False) net['conv4_2'] = ConvLayer( net['conv4_1'], 512, 3, pad=1, flip_filters=False) net['conv4_3'] = ConvLayer( net['conv4_2'], 512, 3, pad=1, flip_filters=False) net['pool4'] = PoolLayer( net['conv4_3'], 2) net['conv5_1'] = ConvLayer( net['pool4'], 512, 3, pad=1, flip_filters=False) net['conv5_2'] = ConvLayer( net['conv5_1'], 512, 3, pad=1, flip_filters=False) net['conv5_3'] = ConvLayer( net['conv5_2'], 512, 3, pad=1, flip_filters=False) net['pool5'] = PoolLayer( net['conv5_3'], 2) if 'fc' in get_layer or get_layer == 'prob': net['fc6'] = DenseLayer(net['pool5'], num_units=4096) net['fc7'] = DenseLayer(net['fc6'], num_units=4096) net['fc8'] = DenseLayer(net['fc7'], num_units=1000, nonlinearity=None) net['prob'] = NonlinearityLayer(net['fc8'], softmax) self.concat_sublayers = [] if 'concat' in get_layer: n_pool = get_layer[6:] get_layer = 'pool' + str(n_pool) l_concat = net['conv1_1'] for i in range(int(n_pool)): l_conv = net['conv' + str(i+1) + '_1'] l_pool = net['pool' + str(i+1)] l_new = ConvLayer( l_concat, l_conv.num_filters, 2, pad=0, stride=2, flip_filters=True, name='vgg16_skipconnection_conv_' + str(i+1)) self.concat_sublayers.append(l_new) l_concat = ConcatLayer( (l_pool, l_new), axis=1, name='vgg16_skipconnection_concat_' + str(i)) self.concat_sublayers.append(l_concat) out_layer = l_concat else: out_layer = net[get_layer] reached = False # Collect garbage for el in net.iteritems(): if reached: del(net[el[0]]) if el[0] == get_layer: reached = True self.sublayers = net # Set names to layers for name in net.keys(): if not net[name].name: net[name].name = 'vgg16_' + name # Reload weights nparams = len(lasagne.layers.get_all_params(net.values())) with open('w_vgg16.pkl', 'rb') as f: # Note: in python3 use the pickle.load parameter # `encoding='latin-1'` vgg16_w = pickle.load(f)['param values'] lasagne.layers.set_all_param_values(net.values(), vgg16_w[:nparams]) # Do not train or regularize vgg if not trainable or not regularizable: all_layers = net.values() for vgg_layer in all_layers: if 'concat' not in vgg_layer.name: layer_params = vgg_layer.get_params() for p in layer_params: if not regularizable: try: vgg_layer.params[p].remove('regularizable') except KeyError: pass if not trainable: try: vgg_layer.params[p].remove('trainable') except KeyError: pass # save the vgg sublayers self.out_layer = out_layer # HACK LASAGNE # This will set `self.input_layer`, which is needed by Lasagne to find # the layers with the get_all_layers() helper function in the # case of a layer with sublayers if isinstance(self.out_layer, tuple): self.input_layer = None else: self.input_layer = self.out_layer def get_output_for(self, input_var, **kwargs): # HACK LASAGNE # This is needed, jointly with the previous hack, to ensure that # this layer behaves as its last sublayer (namely, # self.input_layer) return input_var def get_output_shape_for(self, input_shape): c_input_shape = input_shape # iterate through vgg for name, layer in self.sublayers.items()[1:]: output_shape = layer.get_output_shape_for(input_shape) input_shape = output_shape # iterate through the parallel network if any for layer in self.concat_sublayers: if isinstance(layer, ConcatLayer): c_input_shape = (c_input_shape, c_input_shape) output_shape = layer.get_output_shape_for(c_input_shape) c_input_shape = output_shape return output_shape class RGBtoBGRLayer(lasagne.layers.Layer): def __init__(self, l_in, bgr_mean=numpy.array([103.939, 116.779, 123.68]), data_format='bc01', **kwargs): """A Layer to normalize and convert images from RGB to BGR This layer converts images from RGB to BGR to adapt to Caffe that uses OpenCV, which uses BGR. It also subtracts the per-pixel mean. Parameters ---------- l_in : :class:``lasagne.layers.Layer`` The incoming layer, typically an :class:``lasagne.layers.InputLayer`` bgr_mean : iterable of 3 ints The mean of each channel. By default, the ImageNet mean values are used. data_format : str The format of l_in, either `b01c` (batch, rows, cols, channels) or `bc01` (batch, channels, rows, cols) """ super(RGBtoBGRLayer, self).__init__(l_in, **kwargs) assert data_format in ['bc01', 'b01c'] self.l_in = l_in floatX = theano.config.floatX self.bgr_mean = bgr_mean.astype(floatX) self.data_format = data_format def get_output_for(self, input_im, **kwargs): if self.data_format == 'bc01': input_im = input_im[:, ::-1, :, :] input_im -= self.bgr_mean[:, numpy.newaxis, numpy.newaxis] else: input_im = input_im[:, :, :, ::-1] input_im -= self.bgr_mean return input_im