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