master c5d603a69243 cached
16 files
94.5 KB
24.4k tokens
58 symbols
1 requests
Download .txt
Repository: zhengyang-wang/3D-Unet--Tensorflow
Branch: master
Commit: c5d603a69243
Files: 16
Total size: 94.5 KB

Directory structure:
gitextract_1ntfa_iy/

├── .gitattributes
├── LICENSE
├── README.md
├── configure.py
├── evaluation.py
├── generate_tfrecord.py
├── input_fn.py
├── main.py
├── model.py
├── network.py
├── utils/
│   ├── DiceRatio.py
│   ├── HausdorffDistance.py
│   ├── __init__.py
│   ├── attention.py
│   └── basic_ops.py
└── visualize.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# Non-local U-Nets for Biomedical Image Segmentation

This repository provides the experimental code for our paper "Non-local U-Nets for Biomedical Image Segmentation" accepted by AAAI-20.

This repository includes an (re-)implementation, using updated Tensorflow APIs, of [3D Unet](https://github.com/zhengyang-wang/Unet_3D) for isointense infant brain image segmentation. Besides, we implement our proposed global aggregation blocks, which modify self-attention layers for 3D Unet. The user can optionally insert the blocks to the standard 3D Unet.

For users who wants to use the standard 3D Unet, you need to modify network.py by removing line 62-67 and 72-79. Do not use "_att_decoding_block_layer" in "_build_network". Should you have any question, open an issue and I will respond.

Created by [Zhengyang Wang](http://people.tamu.edu/~zhengyang.wang/) and [Shuiwang Ji](http://people.tamu.edu/~sji/index.html) at Texas A&M University.

## Update
**11/10/2019**:

Our paper "Non-local U-Nets for Biomedical Image Segmentation" has been accepted by AAAI-20!

**10/01/2018**:
1. The code now works when we have subjects of different spatial sizes.

2. During training, validation and prediction, you only need to change the configures in configure.py. In the old version, you have to change configures correspondingly in several files like main.py, utils/input_fn.py, etc.

## Publication

The paper is available at [https://www.aaai.org/Papers/AAAI/2020GB/AAAI-WangZ.5933.pdf](https://www.aaai.org/Papers/AAAI/2020GB/AAAI-WangZ.5933.pdf).

If using this code , please cite our paper.
```
@inproceedings{wang2020non,
  title={Non-local U-Nets for Biomedical Image Segmentation},
  author={Wang, Zhengyang and Zou, Na and Shen, Dinggang and Ji, Shuiwang},
  booktitle={Proceedings of the AAAI Conference on Artificial Intelligence},
  year={2020}
}
```

## Dataset

The dataset is from UNC and used as the training dataset in [iSeg-2017](http://iseg2017.web.unc.edu/). Basically, it is composed of multi-modality isointense infant brain MR images (3D) of 10 subjects. Each subject has two 3D images (modalities), T1WI and T2WI, with a manually created 3D segmentation label.

It is an important step in brain development study to perform automatic segmentation of infant brain magnetic resonance (MR) images into white matter (WM), grey matter (GM) and cerebrospinal fluid (CSF) regions. This task is especially challenging in the isointense stage (approximately 6-8 months of age) when WM and GM exhibit similar levels of intensities in MR images.

## Results

Here provides a glance at the effect of our proposed model. The baseline is [3-D Fully Convolutional Networks for Multimodal Isointense Infant Brain Image Segmentation](https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8287819).

**Visualization of the segmentation results on the 10th subject by our proposed model and the baseline model**:
![model](./results/sample_results.png)

**Comparison of training processes between our proposed model and the baseline model**:
![model](./results/training_curve.png)

## System requirement

#### Programming language

Python 3.5+

#### Python Packages

tensorflow-gpu 1.7 - 1.10, numpy, scipy

## Configure the network

All network hyperparameters are configured in main.py.

#### Training

raw_data_dir:the directory where the raw data is stored

data_dir: the directory where the input data is stored

num_training_subs: the number of subjects used for training

train_epochs: the number of epochs to use for training

epochs_per_eval: the number of training epochs to run between evaluations

batch_size: the number of examples processed in each training batch

learning_rate: learning rate

weight_decay: weight decay rate

num_parallel_calls: The number of records that are processed in parallel during input processing. This can be optimized per data set but for generally homogeneous data sets, should be approximately the number of available CPU cores.

model_dir: the directory where the model will be stored

#### Validation

patch_size: spatial size of patches

overlap_step: overlap step size when performing testing

validation_id: 1-10, which subject is used for validation

checkpoint_num: which checkpoint is used for validation

save_dir: the directory where the prediction is stored

raw_data_dir: the directory where the raw data is stored

#### Network architecture

network_depth: the network depth

num_classes: the number of classes

num_filters: number of filters for initial_conv

## Training and Evaluation

#### Preprocess data

Before training, we preprocess data into tfrecords format, which is optimized for Tensorflow. A good example of how to preprocess data and use tfrecords files as inputs can be found in generate_tfrecord.py and input_fn.py.

#### Start training

After configure configure.py, we can start to train by running
```
python main.py
```

#### Training process visualization

We employ tensorboard to visualize the training process.
```
tensorboard --logdir=model_dir/
```

#### Testing and prediction

If you want to do testing, first make predictions by running
```
python main.py --option='predict'
```

Then, if you have access to labels, setup evaluation.py and run
```
python evaluation.py
```

You may also visualize the results. setup visualize.py and run
```
python visualize.py
```


================================================
FILE: configure.py
================================================
import tensorflow as tf


"""This script defines hyperparameters.
"""

def configure():
	flags = tf.app.flags

	# training
	flags.DEFINE_string('raw_data_dir', '/data/zhengyang/InfantBrain/RawData',
			'the directory where the raw data is stored')
	flags.DEFINE_string('data_dir', '/data/zhengyang/InfantBrain/tfrecords_full',
			'the directory where the input data is stored')
	flags.DEFINE_integer('num_training_subs', 9,
			'the number of subjects used for training')
	flags.DEFINE_integer('train_epochs', 100000,
			'the number of epochs to use for training')
	flags.DEFINE_integer('epochs_per_eval', 5000,
			'the number of training epochs to run between evaluations')
	flags.DEFINE_integer('batch_size', 5,
			'the number of examples processed in each training batch')
	flags.DEFINE_float('learning_rate', 1e-3, 'learning rate')
	flags.DEFINE_float('weight_decay', 2e-6, 'weight decay rate')
	flags.DEFINE_integer('num_parallel_calls', 5,
			'The number of records that are processed in parallel \
			during input processing. This can be optimized per data set but \
			for generally homogeneous data sets, should be approximately the \
			number of available CPU cores.')
	flags.DEFINE_string('model_dir', './model-10',
			'the directory where the model will be stored')

	# validation / prediction
	flags.DEFINE_integer('patch_size', 32, 'spatial size of patches')
	flags.DEFINE_integer('overlap_step', 8,
			'overlap step size when performing validation/prediction')
	flags.DEFINE_integer('validation_id', 10,
			'1-10 or -1, which subject is used for validation')
	flags.DEFINE_integer('prediction_id', 11,
			'1-23, which subject is used for prediction')
	flags.DEFINE_integer('checkpoint_num', 153000,
			'which checkpoint is used for validation/prediction')
	flags.DEFINE_string('save_dir', './results',
			'the directory where the prediction is stored')

	# network
	flags.DEFINE_integer('network_depth', 3, 'the network depth')
	flags.DEFINE_integer('num_classes', 4, 'the number of classes')
	flags.DEFINE_integer('num_filters', 32,
			 'number of filters for initial_conv')
	
	flags.FLAGS.__dict__['__parsed'] = False
	return flags.FLAGS


conf = configure()

================================================
FILE: evaluation.py
================================================
import os
import numpy as np
from utils import dice_ratio, ModHausdorffDist
from generate_tfrecord import load_subject


"""Perform evaluation in terms of dice ratio and 3D MHD.
"""


################################################################################
# Arguments
################################################################################
RAW_DATA_DIR = '/data/zhengyang/InfantBrain/RawData'
LABEL_DIR = '/data/zhengyang/InfantBrain/tfrecords_full'
PRED_DIR = './results'
PRED_ID = 10 # 1-10
PATCH_SIZE = 32
CHECKPOINT_NUM = 153000
OVERLAP_STEPSIZE = 8


################################################################################
# Functions
################################################################################
def one_hot(label):
	'''Convert label (d,h,w) to one-hot label (d,h,w,num_class).
	'''

	num_class = np.max(label) + 1
	return np.eye(num_class)[label]


def MHD_3D(pred, label):
	'''Compute 3D MHD for a single class.
	
	Args:
		pred: An array of size [Depth, Height, Width], with only 0 or 1 values
		label: An array of size [Depth, Height, Width], with only 0 or 1 values

	Returns:
		3D MHD for a single class
	'''

	D, H, W = label.shape

	pred_d = np.array([pred[:, i, j] for i in range(H) for j in range(W)])
	pred_h = np.array([pred[i, :, j] for i in range(D) for j in range(W)])
	pred_w = np.array([pred[i, j, :] for i in range(D) for j in range(H)])

	label_d = np.array([label[:, i, j] for i in range(H) for j in range(W)])
	label_h = np.array([label[i, :, j] for i in range(D) for j in range(W)])
	label_w = np.array([label[i, j, :] for i in range(D) for j in range(H)])

	MHD_d = ModHausdorffDist(pred_d, label_d)[0]
	MHD_h = ModHausdorffDist(pred_h, label_h)[0]
	MHD_w = ModHausdorffDist(pred_w, label_w)[0]

	ret = np.mean([MHD_d, MHD_h, MHD_w])

	print('--->MHD d:', MHD_d)
	print('--->MHD h:', MHD_h)
	print('--->MHD w:', MHD_w)
	# print('--->avg:', ret)

	return ret


def Evaluate(label_dir, pred_dir, pred_id, patch_size, checkpoint_num,
		overlap_step):
	print('Perform evaluation for subject-%d:' % pred_id)

	print('Loading label...')
	label_file = os.path.join(label_dir, 'subject-%d-label.npy' % pred_id)
	assert os.path.isfile(label_file), \
		('Run generate_tfrecord.py to generate the label file.')
	label = np.load(label_file)
	print('Check label: ', label.shape, np.max(label))

	print('Loading predition...')
	pred_file = os.path.join(pred_dir, 
				'preds-%d-sub-%d-overlap-%d-patch-%d.npy' % \
				(checkpoint_num, pred_id, overlap_step, patch_size))
	assert os.path.isfile(pred_file), \
		('Run main.py --option=predict to generate the prediction results.')
	pred = np.load(pred_file)
	print('Check pred: ', pred.shape, np.max(pred))

	print('Extract pred and label for each class...')
	label_one_hot = one_hot(label)
	pred_one_hot = one_hot(pred)
	print('Check shape: ', label_one_hot.shape, pred_one_hot.shape)

	# Separate each class. 0 corresponds to the background class (ignore).
	csf_pred = pred_one_hot[:,:,:,1]
	csf_label = label_one_hot[:,:,:,1]

	gm_pred = pred_one_hot[:,:,:,2]
	gm_label = label_one_hot[:,:,:,2]

	wm_pred = pred_one_hot[:,:,:,3]
	wm_label = label_one_hot[:,:,:,3]

	# evaluate dice ratio
	print('Evaluate dice ratio...')
	csf_dr = dice_ratio(csf_pred, csf_label)
	print('--->CSF Dice Ratio:', csf_dr)
	gm_dr = dice_ratio(gm_pred, gm_label)
	print('--->GM Dice Ratio:', gm_dr)
	wm_dr = dice_ratio(wm_pred, wm_label)
	print('--->WM Dice Ratio:', wm_dr)
	print('--->avg:', np.mean([csf_dr, gm_dr, wm_dr]))

	# # evaluate MHD
	# print('Evaluate 3D MHD (---SLOW---)...')
	# csf_mhd = MHD_3D(csf_pred, csf_label)
	# print('--->CSF MHD:', csf_mhd)
	# gm_mhd = MHD_3D(gm_pred, gm_label)
	# print('--->GM MHD:', gm_mhd)
	# wm_mhd = MHD_3D(wm_pred, wm_label)
	# print('--->WM MHD:', wm_mhd)
	# print('--->avg:', np.mean([csf_mhd, gm_mhd, wm_mhd]))

	print('Done.')

if __name__ == '__main__':
	Evaluate(
		label_dir=LABEL_DIR,
		pred_dir=PRED_DIR,
		pred_id=PRED_ID,
		patch_size=PATCH_SIZE,
		checkpoint_num=CHECKPOINT_NUM,
		overlap_step=OVERLAP_STEPSIZE)

================================================
FILE: generate_tfrecord.py
================================================
import os
import sys
import tensorflow as tf
import nibabel as nib
import numpy as np
from configure import conf


"""Generate TFRecord Files.
"""

################################################################################
# Basic Functions
################################################################################
def _float_feature(value):
	return tf.train.Feature(float_list=tf.train.FloatList(value=value))


def _bytes_feature(value):
	return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))


def _int64_feature(value):
	return tf.train.Feature(int64_list=tf.train.Int64List(value=value))


def cut_edge(data):
	'''Cuts zero edge for a 3D image.

	Args:
		data: A 3D image, [Depth, Height, Width, 1].

	Returns:
		original_shape: [Depth, Height, Width]
		cut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e]
	'''

	D, H, W, _ = data.shape
	D_s, D_e = 0, D-1
	H_s, H_e = 0, H-1
	W_s, W_e = 0, W-1

	while D_s < D:
		if data[D_s].sum() != 0:
			break
		D_s += 1
	while D_e > D_s:
		if data[D_e].sum() != 0:
			break
		D_e -= 1
	while H_s < H:
		if data[:,H_s].sum() != 0:
			break
		H_s += 1
	while H_e > H_s:
		if data[:,H_e].sum() != 0:
			break
		H_e -= 1
	while W_s < W:
		if data[:,:,W_s].sum() != 0:
			break
		W_s += 1
	while W_e > W_s:
		if data[:,:,W_e].sum() != 0:
			break
		W_e -= 1
	
	original_shape = [D, H, W]
	cut_size = [int(D_s), int(D_e+1), int(H_s), int(H_e+1), int(W_s), int(W_e+1)]
	return (original_shape, cut_size)

def convert_labels(labels):
	'''Converts 0:background / 10:CSF / 150:GM / 250:WM to 0/1/2/3. SLOW!
	'''

	D, H, W, C = labels.shape

	for d in range(D):
		for h in range(H):
			for w in range(W):
				if labels[d,h,w,0] == 10:
					labels[d,h,w,0] = 1
				elif labels[d,h,w,0] == 150:
					labels[d,h,w,0] = 2
				elif labels[d,h,w,0] == 250:
					labels[d,h,w,0] = 3


def load_subject(raw_data_dir, subject_id):
	'''Load subject data.

	Args:
		subject_id: [1-23]

	Returns:
		[T1, T2, label]
	'''

	subject_name = 'subject-%d-' % subject_id

	f1 = os.path.join(raw_data_dir, subject_name+'T1.hdr')
	f2 = os.path.join(raw_data_dir, subject_name+'T2.hdr')

	img_T1 = nib.load(f1)
	img_T2 = nib.load(f2)

	inputs_T1 = img_T1.get_data()
	inputs_T2 = img_T2.get_data()
	
	if subject_id < 11:
		fl = os.path.join(raw_data_dir, subject_name+'label.hdr')
		img_label = nib.load(fl)
		inputs_label = img_label.get_data()
	else:
		inputs_label = None

	return [inputs_T1, inputs_T2, inputs_label]
		

def prepare_validation(cutted_image, patch_size, overlap_stepsize):
	"""Determine patches for validation."""

	patch_ids = []

	D, H, W, _ = cutted_image.shape

	drange = list(range(0, D-patch_size+1, overlap_stepsize))
	hrange = list(range(0, H-patch_size+1, overlap_stepsize))
	wrange = list(range(0, W-patch_size+1, overlap_stepsize))

	if (D-patch_size) % overlap_stepsize != 0:
		drange.append(D-patch_size)
	if (H-patch_size) % overlap_stepsize != 0:
		hrange.append(H-patch_size)
	if (W-patch_size) % overlap_stepsize != 0:
		wrange.append(W-patch_size)

	for d in drange:
		for h in hrange:
			for w in wrange:
				patch_ids.append((d, h, w))

	return patch_ids

################################################################################
# TFRecord Generation Functions
################################################################################

def write_training_examples(T1, T2, label, original_shape, cut_size, output_file):
	"""Create a training tfrecord file.
	
	Args:
		T1: T1 image. [Depth, Height, Width, 1].
		T2: T2 image. [Depth, Height, Width, 1].
		label: Label. [Depth, Height, Width, 1].
		original_shape: A list of three integers [D, H, W].
		cut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e].
		output_file: The file name for the tfrecord file.
	"""

	writer = tf.python_io.TFRecordWriter(output_file)

	example = tf.train.Example(features=tf.train.Features(
		feature={
			'T1': _bytes_feature([T1[:,:,:,0].tostring()]), #int16
			'T2': _bytes_feature([T2[:,:,:,0].tostring()]), #int16
			'label': _bytes_feature([label[:,:,:,0].tostring()]), #uint8
			'original_shape': _int64_feature(original_shape),
			'cut_size': _int64_feature(cut_size)
		}
	))

	writer.write(example.SerializeToString())

	writer.close()


def write_validation_examples(T1, T2, label, patch_size, cut_size, overlap_stepsize, output_file):
	"""Create a validation tfrecord file.
	
	Args:
		T1: T1 image. [Depth, Height, Width, 1].
		T2: T2 image. [Depth, Height, Width, 1].
		label: Label. [Depth, Height, Width, 1].
		patch_size: An integer.
		cut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e].
		overlap_stepsize: An integer.
		output_file: The file name for the tfrecord file.
	"""

	T1 = T1[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
	T2 = T2[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
	label = label[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]

	patch_ids = prepare_validation(T1, patch_size, overlap_stepsize)
	print ('Number of patches:', len(patch_ids))

	writer = tf.python_io.TFRecordWriter(output_file)

	for i in range(len(patch_ids)):

		(d, h, w) = patch_ids[i]

		_T1 = T1[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]
		_T2 = T2[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]
		_label = label[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]

		example = tf.train.Example(features=tf.train.Features(
			feature={
				'T1': _bytes_feature([_T1[:,:,:,0].tostring()]), #int16
				'T2': _bytes_feature([_T2[:,:,:,0].tostring()]), #int16
				'label': _bytes_feature([_label[:,:,:,0].tostring()]), #uint8
			}
		))

		writer.write(example.SerializeToString())

	writer.close()


def write_prediction_examples(T1, T2, patch_size, cut_size, overlap_stepsize, output_file):
	"""Create a testing tfrecord file.
	
	Args:
		T1: T1 image. [Depth, Height, Width, 1].
		T2: T2 image. [Depth, Height, Width, 1].
		patch_size: An integer.
		cut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e].
		overlap_stepsize: An integer.
		output_file: The file name for the tfrecord file.
	"""

	T1 = T1[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
	T2 = T2[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]

	patch_ids = prepare_validation(T1, patch_size, overlap_stepsize)
	print ('Number of patches:', len(patch_ids))

	writer = tf.python_io.TFRecordWriter(output_file)

	for i in range(len(patch_ids)):

		(d, h, w) = patch_ids[i]

		_T1 = T1[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]
		_T2 = T2[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]

		example = tf.train.Example(features=tf.train.Features(
			feature={
				'T1': _bytes_feature([_T1[:,:,:,0].tostring()]), #int16
				'T2': _bytes_feature([_T2[:,:,:,0].tostring()]), #int16
			}
		))

		writer.write(example.SerializeToString())

	writer.close()


def generate_files(raw_data_dir, output_path, valid_id, pred_id, patch_size, overlap_stepsize):
	"""Create tfrecord files."""
	if valid_id not in range(1, 11) and valid_id != -1:
		print('The valid_id should be in [1,10] or -1.')
		sys.exit(-1)

	if not os.path.exists(output_path):
		os.makedirs(output_path)

	for i in range(1, 24):
		print('---Process subject %d:---' % i)

		subject_name = 'subject-%d' % i
		train_filename = os.path.join(output_path, subject_name+'.tfrecords')

		pred_subject_name = 'subject-%d-pred-%d-patch-%d' % (pred_id, overlap_stepsize, patch_size)
		pred_filename = os.path.join(output_path, pred_subject_name+'.tfrecords')

		valid_subject_name = 'subject-%d-valid-%d-patch-%d' % (valid_id, overlap_stepsize, patch_size)
		valid_filename = os.path.join(output_path, valid_subject_name+'.tfrecords')

		# save converted label for fast evaluation
		converted_label_filename = 'subject-%d-label.npy' % valid_id
		converted_label_filename = os.path.join(output_path, converted_label_filename)
		
		if (i < 11 and not os.path.isfile(train_filename)) or \
			(i == pred_id and not os.path.isfile(pred_filename)) or \
			(i == valid_id and (not os.path.isfile(valid_filename) or \
				not os.path.isfile(converted_label_filename))):
			print('Loading data...')
			[_T1, _T2, _label] = load_subject(raw_data_dir, i)

			if _label is not None:
				print('Converting label...')
				convert_labels(_label)
				print('Check label: ', np.max(_label))

			(original_shape, cut_size) = cut_edge(_T1)
			print('Check original_shape: ', original_shape)
			print('Check cut_size: ', cut_size)

		if not os.path.isfile(train_filename) and i < 11:
			print('Create the training file:')
			write_training_examples(_T1, _T2, _label, original_shape, cut_size, train_filename)

		if i == valid_id:
			if not os.path.isfile(valid_filename):
				print('Create the validation file:')
				write_validation_examples(_T1, _T2, _label, patch_size, cut_size, overlap_stepsize, valid_filename)

			if not os.path.isfile(converted_label_filename):
				print('Create the converted label file:')
				np.save(converted_label_filename, _label[:,:,:,0])

		if i == pred_id:
			if not os.path.isfile(pred_filename):
				print('Create the prediction file:')
				write_prediction_examples(_T1, _T2, patch_size, cut_size, overlap_stepsize, pred_filename)

		print('---Done.---')


if __name__ == '__main__':
	generate_files(
		conf.raw_data_dir,
		conf.data_dir,
		conf.validation_id,
		conf.prediction_id,
		conf.patch_size,
		conf.overlap_step)


================================================
FILE: input_fn.py
================================================
import tensorflow as tf
import os
from configure import conf

"""This script defines the input interface.
"""


################################################################################
# Functions
################################################################################
def get_filenames(data_dir, mode, valid_id, pred_id, overlap_step, patch_size):
	"""Returns a list of filenames."""

	if mode == 'train':
		train_files = [
			os.path.join(data_dir, 'subject-%d.tfrecords' % i)
			for i in range(1, 11)
			if i != valid_id
		]
		for f in train_files:
			assert os.path.isfile(f), \
				('Run generate_tfrecord.py to generate training files.')
		return train_files
	elif mode == 'valid':
		valid_file = os.path.join(data_dir, 
			'subject-%d-valid-%d-patch-%d.tfrecords' % (valid_id, overlap_step, patch_size))
		assert os.path.isfile(valid_file), \
			('Run generate_tfrecord.py to generate the validation file.')
		return [valid_file]
	elif mode == 'pred':
		pred_file = os.path.join(data_dir,
			'subject-%d-pred-%d-patch-%d.tfrecords' % (pred_id, overlap_step, patch_size))
		assert os.path.isfile(pred_file), \
			('Run generate_tfrecord.py to generate the prediction file.')
		return [pred_file]


def decode_train(serialized_example):
	"""Parses training data from the given `serialized_example`."""

	features = tf.parse_single_example(
					serialized_example,
					features={
						'T1':tf.FixedLenFeature([],tf.string),
						'T2':tf.FixedLenFeature([], tf.string),
						'label':tf.FixedLenFeature([],tf.string),
						'original_shape':tf.FixedLenFeature(3, tf.int64),
						'cut_size':tf.FixedLenFeature(6, tf.int64)
					})

	img_shape = features['original_shape']
	cut_size = features['cut_size']

	# Convert from a scalar string tensor
	image_T1 = tf.decode_raw(features['T1'], tf.int16)
	image_T1 = tf.reshape(image_T1, img_shape)
	image_T2 = tf.decode_raw(features['T2'], tf.int16)
	image_T2 = tf.reshape(image_T2, img_shape)
	label = tf.decode_raw(features['label'], tf.uint8)
	label = tf.reshape(label, img_shape)

	# Convert dtype.
	image_T1 = tf.cast(image_T1, tf.float32)
	image_T2 = tf.cast(image_T2, tf.float32)
	label = tf.cast(label, tf.float32)

	return image_T1, image_T2, label, cut_size


def decode_valid(serialized_example):
	"""Parses validation data from the given `serialized_example`."""

	features = tf.parse_single_example(
					serialized_example,
					features={
						'T1':tf.FixedLenFeature([],tf.string),
						'T2':tf.FixedLenFeature([], tf.string),
						'label':tf.FixedLenFeature([],tf.string)
					})

	patch_shape = [conf.patch_size, conf.patch_size, conf.patch_size]

	# Convert from a scalar string tensor
	image_T1 = tf.decode_raw(features['T1'], tf.int16)
	image_T1 = tf.reshape(image_T1, patch_shape)
	image_T2 = tf.decode_raw(features['T2'], tf.int16)
	image_T2 = tf.reshape(image_T2, patch_shape)
	label = tf.decode_raw(features['label'], tf.uint8)
	label = tf.reshape(label, patch_shape)

	# Convert dtype.
	image_T1 = tf.cast(image_T1, tf.float32)
	image_T2 = tf.cast(image_T2, tf.float32)

	return image_T1, image_T2, label


def decode_pred(serialized_example):
	"""Parses prediction data from the given `serialized_example`."""

	features = tf.parse_single_example(
					serialized_example,
					features={
						'T1':tf.FixedLenFeature([],tf.string),
						'T2':tf.FixedLenFeature([], tf.string)
					})

	patch_shape = [conf.patch_size, conf.patch_size, conf.patch_size]

	# Convert from a scalar string tensor
	image_T1 = tf.decode_raw(features['T1'], tf.int16)
	image_T1 = tf.reshape(image_T1, patch_shape)
	image_T2 = tf.decode_raw(features['T2'], tf.int16)
	image_T2 = tf.reshape(image_T2, patch_shape)

	# Convert dtype.
	image_T1 = tf.cast(image_T1, tf.float32)
	image_T2 = tf.cast(image_T2, tf.float32)
	label = tf.zeros(image_T1.shape) # pseudo label

	return image_T1, image_T2, label


def crop_image(image_T1, image_T2, label, cut_size):
	"""Crop training data."""

	data = tf.stack([image_T1, image_T2, label], axis=-1)

	# Randomly crop a [patch_size, patch_size, patch_size] section of the image.
	image = tf.random_crop(
				data[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :],
				[conf.patch_size, conf.patch_size, conf.patch_size, 3])

	[image_T1, image_T2, label] = tf.unstack(image, 3, axis=-1)

	return image_T1, image_T2, label


def normalize_image(image_T1, image_T2, label):
	"""Normalize data."""

	# Subtract off the mean and divide by the variance of the pixels.
	image_T1 = tf.image.per_image_standardization(image_T1)
	image_T2 = tf.image.per_image_standardization(image_T2)

	features = tf.stack([image_T1, image_T2], axis=-1)

	label = tf.cast(label, tf.int32)
	
	return features, label


def input_function(data_dir, mode, patch_size, batch_size, buffer_size, valid_id,
						pred_id, overlap_step, num_epochs=1, num_parallel_calls=1):
	"""Input function.

	Args:
		data_dir: The directory containing the input data.
		mode: A string in ['train', 'valid', 'pred'].
		patch_size: An integer.
		batch_size: The number of samples per batch.
		buffer_size: The buffer size to use when shuffling records. A larger
			value results in better randomness, but smaller values reduce startup
			time and use less memory.
		valid_id: The ID of the validation subject.
		pred_id: The ID of the prediction subject.
		overlap_step: An integer.
		num_epochs: The number of epochs to repeat the dataset.
		num_parallel_calls: The number of records that are processed in parallel.
			This can be optimized per data set but for generally homogeneous data
			sets, should be approximately the number of available CPU cores.

	Returns:
		Dataset of (features, labels) pairs ready for iteration.
	"""

	with tf.name_scope('input'):
		# Generate a Dataset with raw records.
		filenames = get_filenames(data_dir, mode, valid_id, pred_id, overlap_step, patch_size)
		dataset = tf.data.TFRecordDataset(filenames)

		# We prefetch a batch at a time, This can help smooth out the time taken to
		# load input files as we go through shuffling and processing.
		dataset = dataset.prefetch(buffer_size=batch_size)

		if mode == 'train':
			# Shuffle the records. Note that we shuffle before repeating to ensure
			# that the shuffling respects epoch boundaries.
			dataset = dataset.shuffle(buffer_size=buffer_size)

		# If we are training over multiple epochs before evaluating, repeat the
		# dataset for the appropriate number of epochs.
		dataset = dataset.repeat(num_epochs)

		if mode == 'train':
			dataset = dataset.map(decode_train, num_parallel_calls=num_parallel_calls)
			dataset = dataset.map(crop_image, num_parallel_calls=num_parallel_calls)
		elif mode == 'valid':
			dataset = dataset.map(decode_valid, num_parallel_calls=num_parallel_calls)
		elif mode == 'pred':
			dataset = dataset.map(decode_pred, num_parallel_calls=num_parallel_calls)

		dataset = dataset.map(normalize_image, num_parallel_calls=num_parallel_calls)

		dataset = dataset.batch(batch_size)

		# Operations between the final prefetch and the get_next call to the iterator
		# will happen synchronously during run time. We prefetch here again to
		# background all of the above processing work and keep it out of the
		# critical training path.
		dataset = dataset.prefetch(1)

		iterator = dataset.make_one_shot_iterator()
		features, label = iterator.get_next()

		return features, label


================================================
FILE: main.py
================================================
import argparse
import os
import tensorflow as tf
from model import Model
from configure import conf


"""This script defines hyperparameters.
"""


def main(_):
	parser = argparse.ArgumentParser()
	parser.add_argument('--option', dest='option', type=str, default='train',
						help='actions: train or predict')
	args = parser.parse_args()

	if args.option not in ['train', 'predict']:
		print('invalid option: ', args.option)
		print("Please input a option: train or predict")
	else:
		model = Model(conf)
		getattr(model, args.option)()


if __name__ == '__main__':
	# Choose which gpu or cpu to use
	os.environ['CUDA_VISIBLE_DEVICES'] = '5'
	tf.logging.set_verbosity(tf.logging.INFO)
	tf.app.run()


================================================
FILE: model.py
================================================
import tensorflow as tf
import os
import sys
import numpy as np

from network import Network
from input_fn import input_function
from generate_tfrecord import cut_edge, prepare_validation, load_subject


"""This script trains or evaluates the model.
"""


class Model(object):

	def __init__(self, conf):
		self.conf = conf


	def _model_fn(self, features, labels, mode):
		"""Initializes the Model representing the model layers
		and uses that model to build the necessary EstimatorSpecs for
		the `mode` in question. For training, this means building losses,
		the optimizer, and the train op that get passed into the EstimatorSpec.
		For evaluation and prediction, the EstimatorSpec is returned without
		a train op, but with the necessary parameters for the given mode.

		Args:
			features: tensor representing input images
			labels: tensor representing class labels for all input images
			mode: current estimator mode; should be one of
				`tf.estimator.ModeKeys.TRAIN`, `EVALUATE`, `PREDICT`

		Returns:
			ModelFnOps
		"""
		net = Network(self.conf)
		logits = net(features, mode == tf.estimator.ModeKeys.TRAIN)

		predictions = {
			'classes': tf.argmax(logits, axis=-1),
			'probabilities': tf.nn.softmax(logits, name='softmax_tensor')
		}

		if mode == tf.estimator.ModeKeys.PREDICT:
			return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

		# Calculate loss, which includes softmax cross entropy and L2 regularization.
		cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
											labels=labels, logits=logits))

		# Create a tensor named cross_entropy for logging purposes.
		tf.identity(cross_entropy, name='cross_entropy')
		tf.summary.scalar('cross_entropy', cross_entropy)

		# Add weight decay to the loss.
		loss = cross_entropy + self.conf.weight_decay * tf.add_n(
				[tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'kernel' in v.name])

		if mode == tf.estimator.ModeKeys.TRAIN:
			global_step = tf.train.get_or_create_global_step()
			
			# Learning rate.
			# initial_learning_rate = self.conf.learning_rate
			# Multiply the learning rate by 0.1 at 100, 150, and 200 epochs.
			# boundaries = [int(batches_per_epoch * epoch) for epoch in [150, 200]]
			# vals = [initial_learning_rate * decay for decay in [1, 0.25, 0.25*0.25]]
			# learning_rate = tf.train.piecewise_constant(global_step, boundaries, vals)

			# Create a tensor named learning_rate for logging purposes
			# tf.identity(learning_rate, name='learning_rate')
			# tf.summary.scalar('learning_rate', learning_rate)

			# optimizer = tf.train.MomentumOptimizer(
			# 				learning_rate=learning_rate,
			# 				momentum=self.conf.momentum)

			optimizer = tf.train.AdamOptimizer(learning_rate=self.conf.learning_rate)

			# Batch norm requires update ops to be added as a dependency to train_op
			update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
			with tf.control_dependencies(update_ops):
				train_op = optimizer.minimize(loss, global_step)
		else:
			train_op = None

		accuracy = tf.metrics.accuracy(labels, predictions['classes'])
		metrics = {'accuracy': accuracy}

		# Create a tensor named train_accuracy for logging purposes
		tf.identity(accuracy[1], name='train_accuracy')
		tf.summary.scalar('train_accuracy', accuracy[1])

		return tf.estimator.EstimatorSpec(
				mode=mode,
				predictions=predictions,
				loss=loss,
				train_op=train_op,
				eval_metric_ops=metrics)


	def train(self):
		# Using the Winograd non-fused algorithms provides a small performance boost.
		os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'

		save_checkpoints_steps = self.conf.epochs_per_eval * \
						self.conf.num_training_subs // self.conf.batch_size
		run_config = tf.estimator.RunConfig().replace(
						save_checkpoints_steps=save_checkpoints_steps,
						keep_checkpoint_max=0)

		classifier = tf.estimator.Estimator(
						model_fn=self._model_fn,
						model_dir=self.conf.model_dir,
						config=run_config)

		for _ in range(self.conf.train_epochs // self.conf.epochs_per_eval):
			tensors_to_log = {
				# 'learning_rate': 'learning_rate',
				'cross_entropy': 'cross_entropy',
				'train_accuracy': 'train_accuracy'
			}

			logging_hook = tf.train.LoggingTensorHook(
								tensors=tensors_to_log, every_n_iter=100)

			print('Starting a training cycle.')

			def input_fn_train():
				return input_function(
							data_dir=self.conf.data_dir,
							mode='train',
							patch_size=self.conf.patch_size,
							batch_size=self.conf.batch_size,
							buffer_size=self.conf.num_training_subs,
							valid_id=self.conf.validation_id,
							pred_id=-1, # not used
							overlap_step=-1, # not used
							num_epochs=self.conf.epochs_per_eval,
							num_parallel_calls=self.conf.num_parallel_calls)

			classifier.train(input_fn=input_fn_train, hooks=[logging_hook])

			if self.conf.validation_id != -1:
				print('Starting to evaluate.')

				def input_fn_eval():
					return input_function(
								data_dir=self.conf.data_dir,
								mode='valid',
								patch_size=self.conf.patch_size,
								batch_size=self.conf.batch_size,
								buffer_size=-1, # not used
								valid_id=self.conf.validation_id,
								pred_id=-1, # not used
								overlap_step=self.conf.overlap_step,
								num_epochs=1,
								num_parallel_calls=self.conf.num_parallel_calls)

				classifier.evaluate(input_fn=input_fn_eval)


	def predict(self):
		# Using the Winograd non-fused algorithms provides a small performance boost.
		os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'

		print('Perform prediction for subject-%d:' % self.conf.prediction_id)

		print('Loading data...')
		[T1, _, _] = load_subject(self.conf.raw_data_dir, self.conf.prediction_id)

		(_, cut_size) = cut_edge(T1)
		print('Check cut_size: ',cut_size)

		cutted_T1 = T1[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
		patch_ids = prepare_validation(cutted_T1, self.conf.patch_size, self.conf.overlap_step)
		num_patches = len(patch_ids)
		print ('Number of patches:', num_patches)

		print('Initialize...')
		classifier = tf.estimator.Estimator(
						model_fn=self._model_fn,
						model_dir=self.conf.model_dir)

		def input_fn_predict():
			return input_function(
						data_dir=self.conf.data_dir,
						mode='pred',
						patch_size=self.conf.patch_size,
						batch_size=self.conf.batch_size,
						buffer_size=-1, # not used
						valid_id=-1, # not used
						pred_id=self.conf.prediction_id,
						overlap_step=self.conf.overlap_step,
						num_epochs=1,
						num_parallel_calls=self.conf.num_parallel_calls)

		checkpoint_file = os.path.join(self.conf.model_dir, 
							'model.ckpt-'+str(self.conf.checkpoint_num))

		preds = classifier.predict(
					input_fn=input_fn_predict,
					checkpoint_path=checkpoint_file)

		print('Starting to predict.')

		predictions = {}
		for i, pred in enumerate(preds):
			location = patch_ids[i]
			print('Step {:d}/{:d} processing results for ({:d},{:d},{:d})'.format(
						i+1, num_patches, location[0], location[1], location[2]),
						end='\r',
						flush=True)
			logits = pred['probabilities']
			for j in range(self.conf.patch_size):
				for k in range(self.conf.patch_size):
					for l in range(self.conf.patch_size):
						key = (location[0]+j, location[1]+k, location[2]+l)
						if key not in predictions.keys():
							predictions[key] = []
						predictions[key].append(logits[j, k, l, :])

		print('Averaging results...')

		results = np.zeros((T1.shape[0], T1.shape[1], T1.shape[2], self.conf.num_classes),
							dtype=np.float32)
		print(results.shape)
		for key in predictions.keys():
			results[cut_size[0]+key[0],	cut_size[2]+key[1], cut_size[4]+key[2]] = \
						np.mean(predictions[key], axis=0)
		results = np.argmax(results, axis=-1)

		print('Saving results...')

		if not os.path.exists(self.conf.save_dir):
			os.makedirs(self.conf.save_dir)
		save_filename = 'preds-' + str(self.conf.checkpoint_num) + \
						'-sub-' + str(self.conf.prediction_id) + \
						'-overlap-' + str(self.conf.overlap_step) + \
						'-patch-' + str(self.conf.patch_size) + '.npy'
		save_file = os.path.join(self.conf.save_dir, save_filename)
		np.save(save_file, results)

		print('Done.')

		os._exit(0)


================================================
FILE: network.py
================================================
import tensorflow as tf

from utils import Deconv3D, Conv3D, BN_ReLU, Dilated_Conv3D, multihead_attention_3d


"""This script defines the network.
"""


class Network(object):

	def __init__(self, conf):
		# configure
		self.num_classes = conf.num_classes
		self.num_filters = conf.num_filters
		self.block_sizes = [1] * conf.network_depth
		self.block_strides = [1] + [2] * (conf.network_depth - 1)


	def __call__(self, inputs, training):
		"""Add operations to classify a batch of input images.

		Args:
			inputs: A Tensor representing a batch of input images.
			training: A boolean. Set to True to add operations required only when
				training the classifier.

		Returns:
			A logits Tensor with shape [<batch_size>, self.num_classes].
		"""

		return self._build_network(inputs, training)


	################################################################################
	# Composite blocks building the network
	################################################################################
	def _build_network(self, inputs, training):
		"""Build the network.
		"""

		inputs = Conv3D(
					inputs=inputs,
					filters=self.num_filters,
					kernel_size=3,
					strides=1)
		inputs = tf.identity(inputs, 'initial_conv')

		skip_inputs = []
		for i, num_blocks in enumerate(self.block_sizes):
			# print(i, num_blocks)
			num_filters = self.num_filters * (2**i)
			inputs = self._encoding_block_layer(
						inputs=inputs, filters=num_filters,
						block_fn=self._residual_block, blocks=num_blocks,
						strides=self.block_strides[i], training=training,
						name='encode_block_layer{}'.format(i+1))
			skip_inputs.append(inputs)
			# print(inputs.shape)
		# print(len(skip_inputs))
		
		inputs = BN_ReLU(inputs, training)
		num_filters = self.num_filters * (2**(len(self.block_sizes)-1))
		# print(num_filters)
		inputs = multihead_attention_3d(
					inputs, num_filters, num_filters, num_filters, 2, training, layer_type='SAME')
		inputs += skip_inputs[-1]

		for i, num_blocks in reversed(list(enumerate(self.block_sizes[1:]))):
			# print(i, num_blocks)
			num_filters = self.num_filters * (2**i)
			if i == len(self.block_sizes) - 2:
				inputs = self._att_decoding_block_layer(
						inputs=inputs, skip_inputs=skip_inputs[i],
						filters=num_filters, block_fn=self._residual_block,
						blocks=1, strides=self.block_strides[i+1],
						training=training,
						name='decode_block_layer{}'.format(len(self.block_sizes)-i-1))
			else:
				inputs = self._decoding_block_layer(
						inputs=inputs, skip_inputs=skip_inputs[i],
						filters=num_filters, block_fn=self._residual_block,
						blocks=1, strides=self.block_strides[i+1],
						training=training,
						name='decode_block_layer{}'.format(len(self.block_sizes)-i-1))
			# print(inputs.shape)

		inputs = self._output_block_layer(inputs=inputs, training=training)
		# print(inputs.shape)

		return inputs


	################################################################################
	# Composite blocks building the network
	################################################################################
	def _output_block_layer(self, inputs, training):

		inputs = BN_ReLU(inputs, training)

		inputs = tf.layers.dropout(inputs, rate=0.5, training=training)
		
		inputs = Conv3D(
					inputs=inputs,
					filters=self.num_classes,
					kernel_size=1,
					strides=1,
					use_bias=True)

		return tf.identity(inputs, 'output')


	def _encoding_block_layer(self, inputs, filters, block_fn,
								blocks, strides, training, name):
		"""Creates one layer of encoding blocks for the model.

		Args:
			inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
			filters: The number of filters for the first convolution of the layer.
			block_fn: The block to use within the model.
			blocks: The number of blocks contained in the layer.
			strides: The stride to use for the first convolution of the layer. If
				greater than 1, this layer will ultimately downsample the input.
			training: Either True or False, whether we are currently training the
				model. Needed for batch norm.
			name: A string name for the tensor output of the block layer.

		Returns:
			The output tensor of the block layer.
		"""

		def projection_shortcut(inputs):
			return Conv3D(
					inputs=inputs,
					filters=filters,
					kernel_size=1,
					strides=strides)

		# Only the first block per block_layer uses projection_shortcut and strides
		inputs = block_fn(inputs, filters, training, projection_shortcut, strides)

		for _ in range(1, blocks):
			inputs = block_fn(inputs, filters, training, None, 1)

		return tf.identity(inputs, name)


	def _att_decoding_block_layer(self, inputs, skip_inputs, filters,
								block_fn, blocks, strides, training, name):
		"""Creates one layer of decoding blocks for the model.

		Args:
			inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
			skip_inputs: A tensor of size [batch, depth_in, height_in, width_in, filters].
			filters: The number of filters for the first convolution of the layer.
			block_fn: The block to use within the model.
			blocks: The number of blocks contained in the layer.
			strides: The stride to use for the first convolution of the layer. If
				greater than 1, this layer will ultimately downsample the input.
			training: Either True or False, whether we are currently training the
				model. Needed for batch norm.
			name: A string name for the tensor output of the block layer.

		Returns:
			The output tensor of the block layer.
		"""

		def projection_shortcut(inputs):
			return Deconv3D(
					inputs=inputs,
					filters=filters,
					kernel_size=3,
					strides=strides)

		inputs = self._attention_block(
					inputs, filters, training, projection_shortcut, strides)

		inputs = inputs + skip_inputs

		for _ in range(0, blocks):
			inputs = block_fn(inputs, filters, training, None, 1)

		return tf.identity(inputs, name)


	def _decoding_block_layer(self, inputs, skip_inputs, filters,
								block_fn, blocks, strides, training, name):
		"""Creates one layer of decoding blocks for the model.

		Args:
			inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
			skip_inputs: A tensor of size [batch, depth_in, height_in, width_in, filters].
			filters: The number of filters for the first convolution of the layer.
			block_fn: The block to use within the model.
			blocks: The number of blocks contained in the layer.
			strides: The stride to use for the first convolution of the layer. If
				greater than 1, this layer will ultimately downsample the input.
			training: Either True or False, whether we are currently training the
				model. Needed for batch norm.
			name: A string name for the tensor output of the block layer.

		Returns:
			The output tensor of the block layer.
		"""

		inputs = Deconv3D(
					inputs=inputs,
					filters=filters,
					kernel_size=3,
					strides=strides)

		inputs = inputs + skip_inputs

		for _ in range(0, blocks):
			inputs = block_fn(inputs, filters, training, None, 1)

		return tf.identity(inputs, name)


	################################################################################
	# Basic blocks building the network
	################################################################################
	def _residual_block(self, inputs, filters, training,
							projection_shortcut, strides):
		"""Standard building block for residual networks with BN before convolutions.

		Args:
			inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
			filters: The number of filters for the convolutions.
			training: A Boolean for whether the model is in training or inference
				mode. Needed for batch normalization.
			projection_shortcut: The function to use for projection shortcuts
				(typically a 1x1 convolution when downsampling the input).
			strides: The block's stride. If greater than 1, this block will ultimately
				downsample the input.

		Returns:
			The output tensor of the block.
		"""

		shortcut = inputs
		inputs = BN_ReLU(inputs, training)

		# The projection shortcut should come after the first batch norm and ReLU
		# since it performs a 1x1 convolution.
		if projection_shortcut is not None:
			shortcut = projection_shortcut(inputs)

		inputs = Conv3D(
					inputs=inputs,
					filters=filters,
					kernel_size=3,
					strides=strides)

		inputs = BN_ReLU(inputs, training)

		inputs = Conv3D(
					inputs=inputs,
					filters=filters,
					kernel_size=3,
					strides=1)

		return inputs + shortcut


	def _attention_block(self, inputs, filters, training,
							projection_shortcut, strides):
		"""Attentional building block for residual networks with BN before convolutions.

		Args:
			inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
			filters: The number of filters for the convolutions.
			training: A Boolean for whether the model is in training or inference
				mode. Needed for batch normalization.
			projection_shortcut: The function to use for projection shortcuts
				(typically a 1x1 convolution when downsampling the input).
			strides: The block's stride. If greater than 1, this block will ultimately
				downsample the input.

		Returns:
			The output tensor of the block.
		"""

		shortcut = inputs
		inputs = BN_ReLU(inputs, training)

		# The projection shortcut should come after the first batch norm and ReLU
		# since it performs a 1x1 convolution.
		if projection_shortcut is not None:
			shortcut = projection_shortcut(inputs)

		if strides != 1:
			layer_type = 'UP'
		else:
			layer_type = 'SAME'

		inputs = multihead_attention_3d(
					inputs, filters, filters, filters, 1, training, layer_type)

		return inputs + shortcut


================================================
FILE: utils/DiceRatio.py
================================================
import numpy as np

def dice_ratio(pred, label):
    '''Note: pred & label should only contain 0 or 1.
    '''
    
    return np.sum(pred[label==1])*2.0 / (np.sum(pred) + np.sum(label))

================================================
FILE: utils/HausdorffDistance.py
================================================
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 16 23:56:41 2014

@author: Edward
"""
import numpy as np
from numpy.core.umath_tests import inner1d
# A = np.array([[1,2],[3,4],[5,6],[7,8]])
# B = np.array([[2,3],[4,5],[6,7],[8,9],[10,11]])


# Hausdorff Distance
def HausdorffDist(A,B):
    # Hausdorf Distance: Compute the Hausdorff distance between two point
    # clouds.
    # Let A and B be subsets of metric space (Z,dZ),
    # The Hausdorff distance between A and B, denoted by dH(A,B),
    # is defined by:
    # dH(A,B) = max(h(A,B),h(B,A)),
    # where h(A,B) = max(min(d(a,b))
    # and d(a,b) is a L2 norm
    # dist_H = hausdorff(A,B)
    # A: First point sets (MxN, with M observations in N dimension)
    # B: Second point sets (MxN, with M observations in N dimension)
    # ** A and B may have different number of rows, but must have the same
    # number of columns.
    #
    # Edward DongBo Cui; Stanford University; 06/17/2014

    # Find pairwise distance
    D_mat = np.sqrt(inner1d(A,A)[np.newaxis].T + inner1d(B,B)-2*(np.dot(A,B.T)))
    # Find DH
    dH = np.max(np.array([np.max(np.min(D_mat,axis=0)),np.max(np.min(D_mat,axis=1))]))
    return(dH)

def ModHausdorffDist(A,B):
    #This function computes the Modified Hausdorff Distance (MHD) which is
    #proven to function better than the directed HD as per Dubuisson et al.
    #in the following work:
    #
    #M. P. Dubuisson and A. K. Jain. A Modified Hausdorff distance for object
    #matching. In ICPR94, pages A:566-568, Jerusalem, Israel, 1994.
    #http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=576361
    #
    #The function computed the forward and reverse distances and outputs the
    #maximum/minimum of both.
    #Optionally, the function can return forward and reverse distance.
    #
    #Format for calling function:
    #
    #[MHD,FHD,RHD] = ModHausdorffDist(A,B);
    #
    #where
    #MHD = Modified Hausdorff Distance.
    #FHD = Forward Hausdorff Distance: minimum distance from all points of B
    #      to a point in A, averaged for all A
    #RHD = Reverse Hausdorff Distance: minimum distance from all points of A
    #      to a point in B, averaged for all B
    #A -> Point set 1, [row as observations, and col as dimensions]
    #B -> Point set 2, [row as observations, and col as dimensions]
    #
    #No. of samples of each point set may be different but the dimension of
    #the points must be the same.
    #
    #Edward DongBo Cui Stanford University; 06/17/2014

    # Find pairwise distance
    D_mat = np.sqrt(inner1d(A,A)[np.newaxis].T + inner1d(B,B)-2*(np.dot(A,B.T)))
    # Calculating the forward HD: mean(min(each col))
    FHD = np.mean(np.min(D_mat,axis=1))
    # Calculating the reverse HD: mean(min(each row))
    RHD = np.mean(np.min(D_mat,axis=0))
    # Calculating mhd
    MHD = np.max(np.array([FHD, RHD]))
    return(MHD, FHD, RHD)

================================================
FILE: utils/__init__.py
================================================
from .basic_ops import Pool3d, Deconv3D, Conv3D, Dilated_Conv3D, BN_ReLU
from .DiceRatio import dice_ratio
from .HausdorffDistance import ModHausdorffDist
from .attention import multihead_attention_3d

================================================
FILE: utils/attention.py
================================================
import tensorflow as tf
from .basic_ops import *


"""This script defines 3D different multi-head attention layers.
"""


def multihead_attention_3d(inputs, total_key_filters, total_value_filters,
							output_filters, num_heads, training, layer_type='SAME',
							name=None):
	"""3d Multihead scaled-dot-product attention with input/output transformations.
	
	Args:
		inputs: a Tensor with shape [batch, d, h, w, channels]
		total_key_filters: an integer. Note that queries have the same number 
			of channels as keys
		total_value_filters: an integer
		output_depth: an integer
		num_heads: an integer dividing total_key_filters and total_value_filters
		layer_type: a string, type of this layer -- SAME, DOWN, UP
		name: an optional string

	Returns:
		A Tensor of shape [batch, _d, _h, _w, output_filters]
	
	Raises:
		ValueError: if the total_key_filters or total_value_filters are not divisible
			by the number of attention heads.
	"""

	if total_key_filters % num_heads != 0:
		raise ValueError("Key depth (%d) must be divisible by the number of "
						"attention heads (%d)." % (total_key_filters, num_heads))
	if total_value_filters % num_heads != 0:
		raise ValueError("Value depth (%d) must be divisible by the number of "
						"attention heads (%d)." % (total_value_filters, num_heads))
	if layer_type not in ['SAME', 'DOWN', 'UP']:
		raise ValueError("Layer type (%s) must be one of SAME, "
						"DOWN, UP." % (layer_type))

	with tf.variable_scope(
			name,
			default_name="multihead_attention_3d",
			values=[inputs]):

		# produce q, k, v
		q, k, v = compute_qkv_3d(inputs, total_key_filters,
						total_value_filters, layer_type)

		# after splitting, shape is [batch, heads, d, h, w, channels / heads]
		q = split_heads_3d(q, num_heads)
		k = split_heads_3d(k, num_heads)
		v = split_heads_3d(v, num_heads)

		# normalize
		key_filters_per_head = total_key_filters // num_heads
		q *= key_filters_per_head**-0.5

		# attention
		x = global_attention_3d(q, k, v, training)
		
		x = combine_heads_3d(x)
		x = Conv3D(x, output_filters, 1, 1, use_bias=True)

		return x


def compute_qkv_3d(inputs, total_key_filters, total_value_filters, layer_type):
	"""Computes query, key and value.

	Args:
		inputs: a Tensor with shape [batch, d, h, w, channels]
		total_key_filters: an integer
		total_value_filters: and integer
		layer_type: String, type of this layer -- SAME, DOWN, UP
	
	Returns:
		q: [batch, _d, _h, _w, total_key_filters] tensor
		k: [batch, h, w, total_key_filters] tensor
		v: [batch, h, w, total_value_filters] tensor
	"""

	# linear transformation for q
	if layer_type == 'SAME':
		q = Conv3D(inputs, total_key_filters, 1, 1, use_bias=True)
	elif layer_type == 'DOWN':
		q = Conv3D(inputs, total_key_filters, 3, 2, use_bias=True)
	elif layer_type == 'UP':
		q = Deconv3D(inputs, total_key_filters, 3, 2, use_bias=True)

	# linear transformation for k
	k = Conv3D(inputs, total_key_filters, 1, 1, use_bias=True)

	# linear transformation for k
	v = Conv3D(inputs, total_value_filters, 1, 1, use_bias=True)

	return q, k, v


def split_heads_3d(x, num_heads):
	"""Split channels (last dimension) into multiple heads (becomes dimension 1).
	
	Args:
		x: a Tensor with shape [batch, d, h, w, channels]
		num_heads: an integer
	
	Returns:
		a Tensor with shape [batch, num_heads, d, h, w, channels / num_heads]
	"""

	return tf.transpose(split_last_dimension(x, num_heads), [0, 4, 1, 2, 3, 5])


def split_last_dimension(x, n):
	"""Reshape x so that the last dimension becomes two dimensions.
	The first of these two dimensions is n.

	Args:
		x: a Tensor with shape [..., m]
		n: an integer.

	Returns:
		a Tensor with shape [..., n, m/n]
	"""

	old_shape = x.get_shape().dims
	last = old_shape[-1]
	new_shape = old_shape[:-1] + [n] + [last // n if last else None]
	
	ret = tf.reshape(x, tf.concat([tf.shape(x)[:-1], [n, -1]], 0))
	ret.set_shape(new_shape)
	
	return ret


def global_attention_3d(q, k, v, training, name=None):
	"""global self-attention.
	Args:
		q: a Tensor with shape [batch, heads, _d, _h, _w, channels_k]
		k: a Tensor with shape [batch, heads, d, h, w, channels_k]
		v: a Tensor with shape [batch, heads, d, h, w, channels_v]
		name: an optional string
	Returns:
		a Tensor of shape [batch, heads, _d, _h, _w, channels_v]
	"""
	with tf.variable_scope(
			name,
			default_name="global_attention_3d",
			values=[q, k, v]):

		new_shape = tf.concat([tf.shape(q)[0:-1], [v.shape[-1].value]], 0)

		# flatten q,k,v
		q_new = flatten_3d(q)
		k_new = flatten_3d(k)
		v_new = flatten_3d(v)

		# attention
		output = dot_product_attention(q_new, k_new, v_new, bias=None,
					training=training, dropout_rate=0.5, name="global_3d")

		# putting the representations back in the right place
		output = scatter_3d(output, new_shape)

		return output


def reshape_range(tensor, i, j, shape):
	"""Reshapes a tensor between dimensions i and j."""

	target_shape = tf.concat(
			[tf.shape(tensor)[:i], shape, tf.shape(tensor)[j:]],
			axis=0)

	return tf.reshape(tensor, target_shape)


def flatten_3d(x):
	"""flatten x."""

	x_shape = tf.shape(x)
	# [batch, heads, length, channels], length = d*h*w
	x = reshape_range(x, 2, 5, [tf.reduce_prod(x_shape[2:5])])

	return x


def scatter_3d(x, shape):
	"""scatter x."""

	x = tf.reshape(x, shape)

	return x


def dot_product_attention(q, k, v, bias, training, dropout_rate=0.0, name=None):
	"""Dot-product attention.

	Args:
		q: a Tensor with shape [batch, heads, length_q, channels_k]
		k: a Tensor with shape [batch, heads, length_kv, channels_k]
		v: a Tensor with shape [batch, heads, length_kv, channels_v]
		bias: bias Tensor
		dropout_rate: a floating point number
		name: an optional string

	Returns:
		A Tensor with shape [batch, heads, length_q, channels_v]
	"""

	with tf.variable_scope(
			name,
			default_name="dot_product_attention",
			values=[q, k, v]):

		# [batch, num_heads, length_q, length_kv]
		logits = tf.matmul(q, k, transpose_b=True)

		if bias is not None:
			logits += bias

		weights = tf.nn.softmax(logits, name="attention_weights")

		# dropping out the attention links for each of the heads
		weights = tf.layers.dropout(weights, dropout_rate, training)

		return tf.matmul(weights, v)


def combine_heads_3d(x):
	"""Inverse of split_heads_3d.

	Args:
		x: a Tensor with shape [batch, num_heads, d, h, w, channels / num_heads]

	Returns:
		a Tensor with shape [batch, d, h, w, channels]
	"""

	return combine_last_two_dimensions(tf.transpose(x, [0, 2, 3, 4, 1, 5]))


def combine_last_two_dimensions(x):
	"""Reshape x so that the last two dimension become one.

	Args:
		x: a Tensor with shape [..., a, b]

	Returns:
		a Tensor with shape [..., a*b]
	"""

	old_shape = x.get_shape().dims
	a, b = old_shape[-2:]
	new_shape = old_shape[:-2] + [a * b if a and b else None]

	ret = tf.reshape(x, tf.concat([tf.shape(x)[:-2], [-1]], 0))
	ret.set_shape(new_shape)

	return ret


================================================
FILE: utils/basic_ops.py
================================================
import tensorflow as tf


"""This script defines basic operations.
"""



################################################################################
# Basic operations building the network
################################################################################
def Pool3d(inputs, kernel_size, strides):
	"""Performs 3D max pooling."""

	return tf.layers.max_pooling3d(
			inputs=inputs,
			pool_size=kernel_size,
			strides=strides,
			padding='same')


def Deconv3D(inputs, filters, kernel_size, strides, use_bias=False):
	"""Performs 3D deconvolution without bias and activation function."""

	return tf.layers.conv3d_transpose(
			inputs=inputs,
			filters=filters,
			kernel_size=kernel_size,
			strides=strides,
			padding='same',
			use_bias=use_bias,
			kernel_initializer=tf.truncated_normal_initializer())


def Conv3D(inputs, filters, kernel_size, strides, use_bias=False):
	"""Performs 3D convolution without bias and activation function."""

	return tf.layers.conv3d(
			inputs=inputs,
			filters=filters,
			kernel_size=kernel_size,
			strides=strides,
			padding='same',
			use_bias=use_bias,
			kernel_initializer=tf.truncated_normal_initializer())


def Dilated_Conv3D(inputs, filters, kernel_size, dilation_rate, use_bias=False):
	"""Performs 3D dilated convolution without bias and activation function."""

	return tf.layers.conv3d(
			inputs=inputs,
			filters=filters,
			kernel_size=kernel_size,
			strides=1,
			dilation_rate=dilation_rate,
			padding='same',
			use_bias=use_bias,
			kernel_initializer=tf.truncated_normal_initializer())


def BN_ReLU(inputs, training):
	"""Performs a batch normalization followed by a ReLU6."""

	# We set fused=True for a significant performance boost. See
	# https://www.tensorflow.org/performance/performance_guide#common_fused_ops
	inputs = tf.layers.batch_normalization(
				inputs=inputs,
				axis=-1,
				momentum=0.997,
				epsilon=1e-5,
				center=True,
				scale=True,
				training=training, 
				fused=True)

	return tf.nn.relu6(inputs)


================================================
FILE: visualize.py
================================================
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt


"""Visualize results by slices.
"""


################################################################################
# Arguments
################################################################################
RAW_DATA_DIR = '/data/zhengyang/InfantBrain/RawData'
LABEL_DIR = '/data/zhengyang/InfantBrain/tfrecords_full'
PRED_DIR = './results'
PRED_ID = 10 # 1-10
PATCH_SIZE = 32
CHECKPOINT_NUM = 153000
OVERLAP_STEPSIZE = 8
SLICE_DEPTH = 150


################################################################################
# Functions
################################################################################
def Visualize(label_dir, pred_dir, pred_id, patch_size, checkpoint_num,
		overlap_step, slice_depth):
	print('Perform visualization for subject-%d:' % pred_id)

	print('Loading label...')
	label_file = os.path.join(label_dir, 'subject-%d-label.npy' % pred_id)
	assert os.path.isfile(label_file), \
		('Run generate_tfrecord.py to generate the label file.')
	label = np.load(label_file)
	print('Check label: ', label.shape, np.max(label))

	print('Loading predition...')
	pred_file = os.path.join(pred_dir, 
				'preds-%d-sub-%d-overlap-%d-patch-%d.npy' % \
				(checkpoint_num, pred_id, overlap_step, patch_size))
	assert os.path.isfile(pred_file), \
		('Run main.py --option=predict to generate the prediction results.')
	pred = np.load(pred_file)
	print('Check pred: ', pred.shape, np.max(pred))

	pred_show = pred[:, :, slice_depth]
	label_show = label[:, :, slice_depth]

	fig = plt.figure()
	fig.suptitle('Compare the %d-th slice.' % slice_depth, fontsize=14)

	a = fig.add_subplot(1,2,1)
	imgplot = plt.imshow(label_show)
	a.set_title('Groud Truth')

	a = fig.add_subplot(1,2,2)
	imgplot = plt.imshow(pred_show)
	a.set_title('Prediction')

	plt.savefig('visualization-%d-sub-%d-overlap-%d' % \
			(checkpoint_num, pred_id, overlap_step))

if __name__ == '__main__':
	Visualize(
		label_dir=LABEL_DIR,
		pred_dir=PRED_DIR,
		pred_id=PRED_ID,
		patch_size=PATCH_SIZE,
		checkpoint_num=CHECKPOINT_NUM,
		overlap_step=OVERLAP_STEPSIZE,
		slice_depth=SLICE_DEPTH)
Download .txt
gitextract_1ntfa_iy/

├── .gitattributes
├── LICENSE
├── README.md
├── configure.py
├── evaluation.py
├── generate_tfrecord.py
├── input_fn.py
├── main.py
├── model.py
├── network.py
├── utils/
│   ├── DiceRatio.py
│   ├── HausdorffDistance.py
│   ├── __init__.py
│   ├── attention.py
│   └── basic_ops.py
└── visualize.py
Download .txt
SYMBOL INDEX (58 symbols across 12 files)

FILE: configure.py
  function configure (line 7) | def configure():

FILE: evaluation.py
  function one_hot (line 26) | def one_hot(label):
  function MHD_3D (line 34) | def MHD_3D(pred, label):
  function Evaluate (line 69) | def Evaluate(label_dir, pred_dir, pred_id, patch_size, checkpoint_num,

FILE: generate_tfrecord.py
  function _float_feature (line 15) | def _float_feature(value):
  function _bytes_feature (line 19) | def _bytes_feature(value):
  function _int64_feature (line 23) | def _int64_feature(value):
  function cut_edge (line 27) | def cut_edge(data):
  function convert_labels (line 72) | def convert_labels(labels):
  function load_subject (line 89) | def load_subject(raw_data_dir, subject_id):
  function prepare_validation (line 120) | def prepare_validation(cutted_image, patch_size, overlap_stepsize):
  function write_training_examples (line 149) | def write_training_examples(T1, T2, label, original_shape, cut_size, out...
  function write_validation_examples (line 178) | def write_validation_examples(T1, T2, label, patch_size, cut_size, overl...
  function write_prediction_examples (line 221) | def write_prediction_examples(T1, T2, patch_size, cut_size, overlap_step...
  function generate_files (line 260) | def generate_files(raw_data_dir, output_path, valid_id, pred_id, patch_s...

FILE: input_fn.py
  function get_filenames (line 12) | def get_filenames(data_dir, mode, valid_id, pred_id, overlap_step, patch...
  function decode_train (line 39) | def decode_train(serialized_example):
  function decode_valid (line 71) | def decode_valid(serialized_example):
  function decode_pred (line 99) | def decode_pred(serialized_example):
  function crop_image (line 125) | def crop_image(image_T1, image_T2, label, cut_size):
  function normalize_image (line 140) | def normalize_image(image_T1, image_T2, label):
  function input_function (line 154) | def input_function(data_dir, mode, patch_size, batch_size, buffer_size, ...

FILE: main.py
  function main (line 12) | def main(_):

FILE: model.py
  class Model (line 15) | class Model(object):
    method __init__ (line 17) | def __init__(self, conf):
    method _model_fn (line 21) | def _model_fn(self, features, labels, mode):
    method train (line 103) | def train(self):
    method predict (line 164) | def predict(self):

FILE: network.py
  class Network (line 10) | class Network(object):
    method __init__ (line 12) | def __init__(self, conf):
    method __call__ (line 20) | def __call__(self, inputs, training):
    method _build_network (line 38) | def _build_network(self, inputs, training):
    method _output_block_layer (line 97) | def _output_block_layer(self, inputs, training):
    method _encoding_block_layer (line 113) | def _encoding_block_layer(self, inputs, filters, block_fn,
    method _att_decoding_block_layer (line 148) | def _att_decoding_block_layer(self, inputs, skip_inputs, filters,
    method _decoding_block_layer (line 186) | def _decoding_block_layer(self, inputs, skip_inputs, filters,
    method _residual_block (line 223) | def _residual_block(self, inputs, filters, training,
    method _attention_block (line 266) | def _attention_block(self, inputs, filters, training,

FILE: utils/DiceRatio.py
  function dice_ratio (line 3) | def dice_ratio(pred, label):

FILE: utils/HausdorffDistance.py
  function HausdorffDist (line 14) | def HausdorffDist(A,B):
  function ModHausdorffDist (line 37) | def ModHausdorffDist(A,B):

FILE: utils/attention.py
  function multihead_attention_3d (line 9) | def multihead_attention_3d(inputs, total_key_filters, total_value_filters,
  function compute_qkv_3d (line 69) | def compute_qkv_3d(inputs, total_key_filters, total_value_filters, layer...
  function split_heads_3d (line 101) | def split_heads_3d(x, num_heads):
  function split_last_dimension (line 115) | def split_last_dimension(x, n):
  function global_attention_3d (line 137) | def global_attention_3d(q, k, v, training, name=None):
  function reshape_range (line 169) | def reshape_range(tensor, i, j, shape):
  function flatten_3d (line 179) | def flatten_3d(x):
  function scatter_3d (line 189) | def scatter_3d(x, shape):
  function dot_product_attention (line 197) | def dot_product_attention(q, k, v, bias, training, dropout_rate=0.0, nam...
  function combine_heads_3d (line 231) | def combine_heads_3d(x):
  function combine_last_two_dimensions (line 244) | def combine_last_two_dimensions(x):

FILE: utils/basic_ops.py
  function Pool3d (line 12) | def Pool3d(inputs, kernel_size, strides):
  function Deconv3D (line 22) | def Deconv3D(inputs, filters, kernel_size, strides, use_bias=False):
  function Conv3D (line 35) | def Conv3D(inputs, filters, kernel_size, strides, use_bias=False):
  function Dilated_Conv3D (line 48) | def Dilated_Conv3D(inputs, filters, kernel_size, dilation_rate, use_bias...
  function BN_ReLU (line 62) | def BN_ReLU(inputs, training):

FILE: visualize.py
  function Visualize (line 28) | def Visualize(label_dir, pred_dir, pred_id, patch_size, checkpoint_num,
Condensed preview — 16 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (103K chars).
[
  {
    "path": ".gitattributes",
    "chars": 66,
    "preview": "# Auto detect text files and perform LF normalization\n* text=auto\n"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 5355,
    "preview": "# Non-local U-Nets for Biomedical Image Segmentation\n\nThis repository provides the experimental code for our paper \"Non-"
  },
  {
    "path": "configure.py",
    "chars": 2175,
    "preview": "import tensorflow as tf\n\n\n\"\"\"This script defines hyperparameters.\n\"\"\"\n\ndef configure():\n\tflags = tf.app.flags\n\n\t# traini"
  },
  {
    "path": "evaluation.py",
    "chars": 4058,
    "preview": "import os\nimport numpy as np\nfrom utils import dice_ratio, ModHausdorffDist\nfrom generate_tfrecord import load_subject\n\n"
  },
  {
    "path": "generate_tfrecord.py",
    "chars": 9553,
    "preview": "import os\nimport sys\nimport tensorflow as tf\nimport nibabel as nib\nimport numpy as np\nfrom configure import conf\n\n\n\"\"\"Ge"
  },
  {
    "path": "input_fn.py",
    "chars": 7392,
    "preview": "import tensorflow as tf\nimport os\nfrom configure import conf\n\n\"\"\"This script defines the input interface.\n\"\"\"\n\n\n########"
  },
  {
    "path": "main.py",
    "chars": 702,
    "preview": "import argparse\nimport os\nimport tensorflow as tf\nfrom model import Model\nfrom configure import conf\n\n\n\"\"\"This script de"
  },
  {
    "path": "model.py",
    "chars": 8221,
    "preview": "import tensorflow as tf\nimport os\nimport sys\nimport numpy as np\n\nfrom network import Network\nfrom input_fn import input_"
  },
  {
    "path": "network.py",
    "chars": 9708,
    "preview": "import tensorflow as tf\n\nfrom utils import Deconv3D, Conv3D, BN_ReLU, Dilated_Conv3D, multihead_attention_3d\n\n\n\"\"\"This s"
  },
  {
    "path": "utils/DiceRatio.py",
    "chars": 186,
    "preview": "import numpy as np\n\ndef dice_ratio(pred, label):\n    '''Note: pred & label should only contain 0 or 1.\n    '''\n    \n    "
  },
  {
    "path": "utils/HausdorffDistance.py",
    "chars": 2875,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 16 23:56:41 2014\n\n@author: Edward\n\"\"\"\nimport numpy as np\nfrom numpy.core."
  },
  {
    "path": "utils/__init__.py",
    "chars": 200,
    "preview": "from .basic_ops import Pool3d, Deconv3D, Conv3D, Dilated_Conv3D, BN_ReLU\nfrom .DiceRatio import dice_ratio\nfrom .Hausdor"
  },
  {
    "path": "utils/attention.py",
    "chars": 6896,
    "preview": "import tensorflow as tf\nfrom .basic_ops import *\n\n\n\"\"\"This script defines 3D different multi-head attention layers.\n\"\"\"\n"
  },
  {
    "path": "utils/basic_ops.py",
    "chars": 2021,
    "preview": "import tensorflow as tf\n\n\n\"\"\"This script defines basic operations.\n\"\"\"\n\n\n\n##############################################"
  },
  {
    "path": "visualize.py",
    "chars": 2187,
    "preview": "import os\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\n\"\"\"Visualize resu"
  }
]

About this extraction

This page contains the full source code of the zhengyang-wang/3D-Unet--Tensorflow GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 16 files (94.5 KB), approximately 24.4k tokens, and a symbol index with 58 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!