├── .DS_Store
├── .gitattributes
├── LICENSE
├── README.md
├── configure.py
├── evaluation.py
├── generate_tfrecord.py
├── input_fn.py
├── main.py
├── model.py
├── network.py
├── results
├── sample_results.png
└── training_curve.png
├── utils
├── .DS_Store
├── DiceRatio.py
├── HausdorffDistance.py
├── __init__.py
├── attention.py
└── basic_ops.py
└── visualize.py
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhengyang-wang/3D-Unet--Tensorflow/c5d603a69243a69dd6d89edefdf1ba249640450b/.DS_Store
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Non-local U-Nets for Biomedical Image Segmentation
2 |
3 | This repository provides the experimental code for our paper "Non-local U-Nets for Biomedical Image Segmentation" accepted by AAAI-20.
4 |
5 | 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.
6 |
7 | 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.
8 |
9 | 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.
10 |
11 | ## Update
12 | **11/10/2019**:
13 |
14 | Our paper "Non-local U-Nets for Biomedical Image Segmentation" has been accepted by AAAI-20!
15 |
16 | **10/01/2018**:
17 | 1. The code now works when we have subjects of different spatial sizes.
18 |
19 | 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.
20 |
21 | ## Publication
22 |
23 | 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).
24 |
25 | If using this code , please cite our paper.
26 | ```
27 | @inproceedings{wang2020non,
28 | title={Non-local U-Nets for Biomedical Image Segmentation},
29 | author={Wang, Zhengyang and Zou, Na and Shen, Dinggang and Ji, Shuiwang},
30 | booktitle={Proceedings of the AAAI Conference on Artificial Intelligence},
31 | year={2020}
32 | }
33 | ```
34 |
35 | ## Dataset
36 |
37 | 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.
38 |
39 | 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.
40 |
41 | ## Results
42 |
43 | 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).
44 |
45 | **Visualization of the segmentation results on the 10th subject by our proposed model and the baseline model**:
46 | 
47 |
48 | **Comparison of training processes between our proposed model and the baseline model**:
49 | 
50 |
51 | ## System requirement
52 |
53 | #### Programming language
54 |
55 | Python 3.5+
56 |
57 | #### Python Packages
58 |
59 | tensorflow-gpu 1.7 - 1.10, numpy, scipy
60 |
61 | ## Configure the network
62 |
63 | All network hyperparameters are configured in main.py.
64 |
65 | #### Training
66 |
67 | raw_data_dir:the directory where the raw data is stored
68 |
69 | data_dir: the directory where the input data is stored
70 |
71 | num_training_subs: the number of subjects used for training
72 |
73 | train_epochs: the number of epochs to use for training
74 |
75 | epochs_per_eval: the number of training epochs to run between evaluations
76 |
77 | batch_size: the number of examples processed in each training batch
78 |
79 | learning_rate: learning rate
80 |
81 | weight_decay: weight decay rate
82 |
83 | 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.
84 |
85 | model_dir: the directory where the model will be stored
86 |
87 | #### Validation
88 |
89 | patch_size: spatial size of patches
90 |
91 | overlap_step: overlap step size when performing testing
92 |
93 | validation_id: 1-10, which subject is used for validation
94 |
95 | checkpoint_num: which checkpoint is used for validation
96 |
97 | save_dir: the directory where the prediction is stored
98 |
99 | raw_data_dir: the directory where the raw data is stored
100 |
101 | #### Network architecture
102 |
103 | network_depth: the network depth
104 |
105 | num_classes: the number of classes
106 |
107 | num_filters: number of filters for initial_conv
108 |
109 | ## Training and Evaluation
110 |
111 | #### Preprocess data
112 |
113 | 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.
114 |
115 | #### Start training
116 |
117 | After configure configure.py, we can start to train by running
118 | ```
119 | python main.py
120 | ```
121 |
122 | #### Training process visualization
123 |
124 | We employ tensorboard to visualize the training process.
125 | ```
126 | tensorboard --logdir=model_dir/
127 | ```
128 |
129 | #### Testing and prediction
130 |
131 | If you want to do testing, first make predictions by running
132 | ```
133 | python main.py --option='predict'
134 | ```
135 |
136 | Then, if you have access to labels, setup evaluation.py and run
137 | ```
138 | python evaluation.py
139 | ```
140 |
141 | You may also visualize the results. setup visualize.py and run
142 | ```
143 | python visualize.py
144 | ```
145 |
--------------------------------------------------------------------------------
/configure.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 |
3 |
4 | """This script defines hyperparameters.
5 | """
6 |
7 | def configure():
8 | flags = tf.app.flags
9 |
10 | # training
11 | flags.DEFINE_string('raw_data_dir', '/data/zhengyang/InfantBrain/RawData',
12 | 'the directory where the raw data is stored')
13 | flags.DEFINE_string('data_dir', '/data/zhengyang/InfantBrain/tfrecords_full',
14 | 'the directory where the input data is stored')
15 | flags.DEFINE_integer('num_training_subs', 9,
16 | 'the number of subjects used for training')
17 | flags.DEFINE_integer('train_epochs', 100000,
18 | 'the number of epochs to use for training')
19 | flags.DEFINE_integer('epochs_per_eval', 5000,
20 | 'the number of training epochs to run between evaluations')
21 | flags.DEFINE_integer('batch_size', 5,
22 | 'the number of examples processed in each training batch')
23 | flags.DEFINE_float('learning_rate', 1e-3, 'learning rate')
24 | flags.DEFINE_float('weight_decay', 2e-6, 'weight decay rate')
25 | flags.DEFINE_integer('num_parallel_calls', 5,
26 | 'The number of records that are processed in parallel \
27 | during input processing. This can be optimized per data set but \
28 | for generally homogeneous data sets, should be approximately the \
29 | number of available CPU cores.')
30 | flags.DEFINE_string('model_dir', './model-10',
31 | 'the directory where the model will be stored')
32 |
33 | # validation / prediction
34 | flags.DEFINE_integer('patch_size', 32, 'spatial size of patches')
35 | flags.DEFINE_integer('overlap_step', 8,
36 | 'overlap step size when performing validation/prediction')
37 | flags.DEFINE_integer('validation_id', 10,
38 | '1-10 or -1, which subject is used for validation')
39 | flags.DEFINE_integer('prediction_id', 11,
40 | '1-23, which subject is used for prediction')
41 | flags.DEFINE_integer('checkpoint_num', 153000,
42 | 'which checkpoint is used for validation/prediction')
43 | flags.DEFINE_string('save_dir', './results',
44 | 'the directory where the prediction is stored')
45 |
46 | # network
47 | flags.DEFINE_integer('network_depth', 3, 'the network depth')
48 | flags.DEFINE_integer('num_classes', 4, 'the number of classes')
49 | flags.DEFINE_integer('num_filters', 32,
50 | 'number of filters for initial_conv')
51 |
52 | flags.FLAGS.__dict__['__parsed'] = False
53 | return flags.FLAGS
54 |
55 |
56 | conf = configure()
--------------------------------------------------------------------------------
/evaluation.py:
--------------------------------------------------------------------------------
1 | import os
2 | import numpy as np
3 | from utils import dice_ratio, ModHausdorffDist
4 | from generate_tfrecord import load_subject
5 |
6 |
7 | """Perform evaluation in terms of dice ratio and 3D MHD.
8 | """
9 |
10 |
11 | ################################################################################
12 | # Arguments
13 | ################################################################################
14 | RAW_DATA_DIR = '/data/zhengyang/InfantBrain/RawData'
15 | LABEL_DIR = '/data/zhengyang/InfantBrain/tfrecords_full'
16 | PRED_DIR = './results'
17 | PRED_ID = 10 # 1-10
18 | PATCH_SIZE = 32
19 | CHECKPOINT_NUM = 153000
20 | OVERLAP_STEPSIZE = 8
21 |
22 |
23 | ################################################################################
24 | # Functions
25 | ################################################################################
26 | def one_hot(label):
27 | '''Convert label (d,h,w) to one-hot label (d,h,w,num_class).
28 | '''
29 |
30 | num_class = np.max(label) + 1
31 | return np.eye(num_class)[label]
32 |
33 |
34 | def MHD_3D(pred, label):
35 | '''Compute 3D MHD for a single class.
36 |
37 | Args:
38 | pred: An array of size [Depth, Height, Width], with only 0 or 1 values
39 | label: An array of size [Depth, Height, Width], with only 0 or 1 values
40 |
41 | Returns:
42 | 3D MHD for a single class
43 | '''
44 |
45 | D, H, W = label.shape
46 |
47 | pred_d = np.array([pred[:, i, j] for i in range(H) for j in range(W)])
48 | pred_h = np.array([pred[i, :, j] for i in range(D) for j in range(W)])
49 | pred_w = np.array([pred[i, j, :] for i in range(D) for j in range(H)])
50 |
51 | label_d = np.array([label[:, i, j] for i in range(H) for j in range(W)])
52 | label_h = np.array([label[i, :, j] for i in range(D) for j in range(W)])
53 | label_w = np.array([label[i, j, :] for i in range(D) for j in range(H)])
54 |
55 | MHD_d = ModHausdorffDist(pred_d, label_d)[0]
56 | MHD_h = ModHausdorffDist(pred_h, label_h)[0]
57 | MHD_w = ModHausdorffDist(pred_w, label_w)[0]
58 |
59 | ret = np.mean([MHD_d, MHD_h, MHD_w])
60 |
61 | print('--->MHD d:', MHD_d)
62 | print('--->MHD h:', MHD_h)
63 | print('--->MHD w:', MHD_w)
64 | # print('--->avg:', ret)
65 |
66 | return ret
67 |
68 |
69 | def Evaluate(label_dir, pred_dir, pred_id, patch_size, checkpoint_num,
70 | overlap_step):
71 | print('Perform evaluation for subject-%d:' % pred_id)
72 |
73 | print('Loading label...')
74 | label_file = os.path.join(label_dir, 'subject-%d-label.npy' % pred_id)
75 | assert os.path.isfile(label_file), \
76 | ('Run generate_tfrecord.py to generate the label file.')
77 | label = np.load(label_file)
78 | print('Check label: ', label.shape, np.max(label))
79 |
80 | print('Loading predition...')
81 | pred_file = os.path.join(pred_dir,
82 | 'preds-%d-sub-%d-overlap-%d-patch-%d.npy' % \
83 | (checkpoint_num, pred_id, overlap_step, patch_size))
84 | assert os.path.isfile(pred_file), \
85 | ('Run main.py --option=predict to generate the prediction results.')
86 | pred = np.load(pred_file)
87 | print('Check pred: ', pred.shape, np.max(pred))
88 |
89 | print('Extract pred and label for each class...')
90 | label_one_hot = one_hot(label)
91 | pred_one_hot = one_hot(pred)
92 | print('Check shape: ', label_one_hot.shape, pred_one_hot.shape)
93 |
94 | # Separate each class. 0 corresponds to the background class (ignore).
95 | csf_pred = pred_one_hot[:,:,:,1]
96 | csf_label = label_one_hot[:,:,:,1]
97 |
98 | gm_pred = pred_one_hot[:,:,:,2]
99 | gm_label = label_one_hot[:,:,:,2]
100 |
101 | wm_pred = pred_one_hot[:,:,:,3]
102 | wm_label = label_one_hot[:,:,:,3]
103 |
104 | # evaluate dice ratio
105 | print('Evaluate dice ratio...')
106 | csf_dr = dice_ratio(csf_pred, csf_label)
107 | print('--->CSF Dice Ratio:', csf_dr)
108 | gm_dr = dice_ratio(gm_pred, gm_label)
109 | print('--->GM Dice Ratio:', gm_dr)
110 | wm_dr = dice_ratio(wm_pred, wm_label)
111 | print('--->WM Dice Ratio:', wm_dr)
112 | print('--->avg:', np.mean([csf_dr, gm_dr, wm_dr]))
113 |
114 | # # evaluate MHD
115 | # print('Evaluate 3D MHD (---SLOW---)...')
116 | # csf_mhd = MHD_3D(csf_pred, csf_label)
117 | # print('--->CSF MHD:', csf_mhd)
118 | # gm_mhd = MHD_3D(gm_pred, gm_label)
119 | # print('--->GM MHD:', gm_mhd)
120 | # wm_mhd = MHD_3D(wm_pred, wm_label)
121 | # print('--->WM MHD:', wm_mhd)
122 | # print('--->avg:', np.mean([csf_mhd, gm_mhd, wm_mhd]))
123 |
124 | print('Done.')
125 |
126 | if __name__ == '__main__':
127 | Evaluate(
128 | label_dir=LABEL_DIR,
129 | pred_dir=PRED_DIR,
130 | pred_id=PRED_ID,
131 | patch_size=PATCH_SIZE,
132 | checkpoint_num=CHECKPOINT_NUM,
133 | overlap_step=OVERLAP_STEPSIZE)
--------------------------------------------------------------------------------
/generate_tfrecord.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import tensorflow as tf
4 | import nibabel as nib
5 | import numpy as np
6 | from configure import conf
7 |
8 |
9 | """Generate TFRecord Files.
10 | """
11 |
12 | ################################################################################
13 | # Basic Functions
14 | ################################################################################
15 | def _float_feature(value):
16 | return tf.train.Feature(float_list=tf.train.FloatList(value=value))
17 |
18 |
19 | def _bytes_feature(value):
20 | return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
21 |
22 |
23 | def _int64_feature(value):
24 | return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
25 |
26 |
27 | def cut_edge(data):
28 | '''Cuts zero edge for a 3D image.
29 |
30 | Args:
31 | data: A 3D image, [Depth, Height, Width, 1].
32 |
33 | Returns:
34 | original_shape: [Depth, Height, Width]
35 | cut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e]
36 | '''
37 |
38 | D, H, W, _ = data.shape
39 | D_s, D_e = 0, D-1
40 | H_s, H_e = 0, H-1
41 | W_s, W_e = 0, W-1
42 |
43 | while D_s < D:
44 | if data[D_s].sum() != 0:
45 | break
46 | D_s += 1
47 | while D_e > D_s:
48 | if data[D_e].sum() != 0:
49 | break
50 | D_e -= 1
51 | while H_s < H:
52 | if data[:,H_s].sum() != 0:
53 | break
54 | H_s += 1
55 | while H_e > H_s:
56 | if data[:,H_e].sum() != 0:
57 | break
58 | H_e -= 1
59 | while W_s < W:
60 | if data[:,:,W_s].sum() != 0:
61 | break
62 | W_s += 1
63 | while W_e > W_s:
64 | if data[:,:,W_e].sum() != 0:
65 | break
66 | W_e -= 1
67 |
68 | original_shape = [D, H, W]
69 | cut_size = [int(D_s), int(D_e+1), int(H_s), int(H_e+1), int(W_s), int(W_e+1)]
70 | return (original_shape, cut_size)
71 |
72 | def convert_labels(labels):
73 | '''Converts 0:background / 10:CSF / 150:GM / 250:WM to 0/1/2/3. SLOW!
74 | '''
75 |
76 | D, H, W, C = labels.shape
77 |
78 | for d in range(D):
79 | for h in range(H):
80 | for w in range(W):
81 | if labels[d,h,w,0] == 10:
82 | labels[d,h,w,0] = 1
83 | elif labels[d,h,w,0] == 150:
84 | labels[d,h,w,0] = 2
85 | elif labels[d,h,w,0] == 250:
86 | labels[d,h,w,0] = 3
87 |
88 |
89 | def load_subject(raw_data_dir, subject_id):
90 | '''Load subject data.
91 |
92 | Args:
93 | subject_id: [1-23]
94 |
95 | Returns:
96 | [T1, T2, label]
97 | '''
98 |
99 | subject_name = 'subject-%d-' % subject_id
100 |
101 | f1 = os.path.join(raw_data_dir, subject_name+'T1.hdr')
102 | f2 = os.path.join(raw_data_dir, subject_name+'T2.hdr')
103 |
104 | img_T1 = nib.load(f1)
105 | img_T2 = nib.load(f2)
106 |
107 | inputs_T1 = img_T1.get_data()
108 | inputs_T2 = img_T2.get_data()
109 |
110 | if subject_id < 11:
111 | fl = os.path.join(raw_data_dir, subject_name+'label.hdr')
112 | img_label = nib.load(fl)
113 | inputs_label = img_label.get_data()
114 | else:
115 | inputs_label = None
116 |
117 | return [inputs_T1, inputs_T2, inputs_label]
118 |
119 |
120 | def prepare_validation(cutted_image, patch_size, overlap_stepsize):
121 | """Determine patches for validation."""
122 |
123 | patch_ids = []
124 |
125 | D, H, W, _ = cutted_image.shape
126 |
127 | drange = list(range(0, D-patch_size+1, overlap_stepsize))
128 | hrange = list(range(0, H-patch_size+1, overlap_stepsize))
129 | wrange = list(range(0, W-patch_size+1, overlap_stepsize))
130 |
131 | if (D-patch_size) % overlap_stepsize != 0:
132 | drange.append(D-patch_size)
133 | if (H-patch_size) % overlap_stepsize != 0:
134 | hrange.append(H-patch_size)
135 | if (W-patch_size) % overlap_stepsize != 0:
136 | wrange.append(W-patch_size)
137 |
138 | for d in drange:
139 | for h in hrange:
140 | for w in wrange:
141 | patch_ids.append((d, h, w))
142 |
143 | return patch_ids
144 |
145 | ################################################################################
146 | # TFRecord Generation Functions
147 | ################################################################################
148 |
149 | def write_training_examples(T1, T2, label, original_shape, cut_size, output_file):
150 | """Create a training tfrecord file.
151 |
152 | Args:
153 | T1: T1 image. [Depth, Height, Width, 1].
154 | T2: T2 image. [Depth, Height, Width, 1].
155 | label: Label. [Depth, Height, Width, 1].
156 | original_shape: A list of three integers [D, H, W].
157 | cut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e].
158 | output_file: The file name for the tfrecord file.
159 | """
160 |
161 | writer = tf.python_io.TFRecordWriter(output_file)
162 |
163 | example = tf.train.Example(features=tf.train.Features(
164 | feature={
165 | 'T1': _bytes_feature([T1[:,:,:,0].tostring()]), #int16
166 | 'T2': _bytes_feature([T2[:,:,:,0].tostring()]), #int16
167 | 'label': _bytes_feature([label[:,:,:,0].tostring()]), #uint8
168 | 'original_shape': _int64_feature(original_shape),
169 | 'cut_size': _int64_feature(cut_size)
170 | }
171 | ))
172 |
173 | writer.write(example.SerializeToString())
174 |
175 | writer.close()
176 |
177 |
178 | def write_validation_examples(T1, T2, label, patch_size, cut_size, overlap_stepsize, output_file):
179 | """Create a validation tfrecord file.
180 |
181 | Args:
182 | T1: T1 image. [Depth, Height, Width, 1].
183 | T2: T2 image. [Depth, Height, Width, 1].
184 | label: Label. [Depth, Height, Width, 1].
185 | patch_size: An integer.
186 | cut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e].
187 | overlap_stepsize: An integer.
188 | output_file: The file name for the tfrecord file.
189 | """
190 |
191 | T1 = T1[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
192 | T2 = T2[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
193 | label = label[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
194 |
195 | patch_ids = prepare_validation(T1, patch_size, overlap_stepsize)
196 | print ('Number of patches:', len(patch_ids))
197 |
198 | writer = tf.python_io.TFRecordWriter(output_file)
199 |
200 | for i in range(len(patch_ids)):
201 |
202 | (d, h, w) = patch_ids[i]
203 |
204 | _T1 = T1[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]
205 | _T2 = T2[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]
206 | _label = label[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]
207 |
208 | example = tf.train.Example(features=tf.train.Features(
209 | feature={
210 | 'T1': _bytes_feature([_T1[:,:,:,0].tostring()]), #int16
211 | 'T2': _bytes_feature([_T2[:,:,:,0].tostring()]), #int16
212 | 'label': _bytes_feature([_label[:,:,:,0].tostring()]), #uint8
213 | }
214 | ))
215 |
216 | writer.write(example.SerializeToString())
217 |
218 | writer.close()
219 |
220 |
221 | def write_prediction_examples(T1, T2, patch_size, cut_size, overlap_stepsize, output_file):
222 | """Create a testing tfrecord file.
223 |
224 | Args:
225 | T1: T1 image. [Depth, Height, Width, 1].
226 | T2: T2 image. [Depth, Height, Width, 1].
227 | patch_size: An integer.
228 | cut_size: A list of six integers [Depth_s, Depth_e, Height_s, Height_e, Width_s, Width_e].
229 | overlap_stepsize: An integer.
230 | output_file: The file name for the tfrecord file.
231 | """
232 |
233 | T1 = T1[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
234 | T2 = T2[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
235 |
236 | patch_ids = prepare_validation(T1, patch_size, overlap_stepsize)
237 | print ('Number of patches:', len(patch_ids))
238 |
239 | writer = tf.python_io.TFRecordWriter(output_file)
240 |
241 | for i in range(len(patch_ids)):
242 |
243 | (d, h, w) = patch_ids[i]
244 |
245 | _T1 = T1[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]
246 | _T2 = T2[d:d+patch_size, h:h+patch_size, w:w+patch_size, :]
247 |
248 | example = tf.train.Example(features=tf.train.Features(
249 | feature={
250 | 'T1': _bytes_feature([_T1[:,:,:,0].tostring()]), #int16
251 | 'T2': _bytes_feature([_T2[:,:,:,0].tostring()]), #int16
252 | }
253 | ))
254 |
255 | writer.write(example.SerializeToString())
256 |
257 | writer.close()
258 |
259 |
260 | def generate_files(raw_data_dir, output_path, valid_id, pred_id, patch_size, overlap_stepsize):
261 | """Create tfrecord files."""
262 | if valid_id not in range(1, 11) and valid_id != -1:
263 | print('The valid_id should be in [1,10] or -1.')
264 | sys.exit(-1)
265 |
266 | if not os.path.exists(output_path):
267 | os.makedirs(output_path)
268 |
269 | for i in range(1, 24):
270 | print('---Process subject %d:---' % i)
271 |
272 | subject_name = 'subject-%d' % i
273 | train_filename = os.path.join(output_path, subject_name+'.tfrecords')
274 |
275 | pred_subject_name = 'subject-%d-pred-%d-patch-%d' % (pred_id, overlap_stepsize, patch_size)
276 | pred_filename = os.path.join(output_path, pred_subject_name+'.tfrecords')
277 |
278 | valid_subject_name = 'subject-%d-valid-%d-patch-%d' % (valid_id, overlap_stepsize, patch_size)
279 | valid_filename = os.path.join(output_path, valid_subject_name+'.tfrecords')
280 |
281 | # save converted label for fast evaluation
282 | converted_label_filename = 'subject-%d-label.npy' % valid_id
283 | converted_label_filename = os.path.join(output_path, converted_label_filename)
284 |
285 | if (i < 11 and not os.path.isfile(train_filename)) or \
286 | (i == pred_id and not os.path.isfile(pred_filename)) or \
287 | (i == valid_id and (not os.path.isfile(valid_filename) or \
288 | not os.path.isfile(converted_label_filename))):
289 | print('Loading data...')
290 | [_T1, _T2, _label] = load_subject(raw_data_dir, i)
291 |
292 | if _label is not None:
293 | print('Converting label...')
294 | convert_labels(_label)
295 | print('Check label: ', np.max(_label))
296 |
297 | (original_shape, cut_size) = cut_edge(_T1)
298 | print('Check original_shape: ', original_shape)
299 | print('Check cut_size: ', cut_size)
300 |
301 | if not os.path.isfile(train_filename) and i < 11:
302 | print('Create the training file:')
303 | write_training_examples(_T1, _T2, _label, original_shape, cut_size, train_filename)
304 |
305 | if i == valid_id:
306 | if not os.path.isfile(valid_filename):
307 | print('Create the validation file:')
308 | write_validation_examples(_T1, _T2, _label, patch_size, cut_size, overlap_stepsize, valid_filename)
309 |
310 | if not os.path.isfile(converted_label_filename):
311 | print('Create the converted label file:')
312 | np.save(converted_label_filename, _label[:,:,:,0])
313 |
314 | if i == pred_id:
315 | if not os.path.isfile(pred_filename):
316 | print('Create the prediction file:')
317 | write_prediction_examples(_T1, _T2, patch_size, cut_size, overlap_stepsize, pred_filename)
318 |
319 | print('---Done.---')
320 |
321 |
322 | if __name__ == '__main__':
323 | generate_files(
324 | conf.raw_data_dir,
325 | conf.data_dir,
326 | conf.validation_id,
327 | conf.prediction_id,
328 | conf.patch_size,
329 | conf.overlap_step)
330 |
--------------------------------------------------------------------------------
/input_fn.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | import os
3 | from configure import conf
4 |
5 | """This script defines the input interface.
6 | """
7 |
8 |
9 | ################################################################################
10 | # Functions
11 | ################################################################################
12 | def get_filenames(data_dir, mode, valid_id, pred_id, overlap_step, patch_size):
13 | """Returns a list of filenames."""
14 |
15 | if mode == 'train':
16 | train_files = [
17 | os.path.join(data_dir, 'subject-%d.tfrecords' % i)
18 | for i in range(1, 11)
19 | if i != valid_id
20 | ]
21 | for f in train_files:
22 | assert os.path.isfile(f), \
23 | ('Run generate_tfrecord.py to generate training files.')
24 | return train_files
25 | elif mode == 'valid':
26 | valid_file = os.path.join(data_dir,
27 | 'subject-%d-valid-%d-patch-%d.tfrecords' % (valid_id, overlap_step, patch_size))
28 | assert os.path.isfile(valid_file), \
29 | ('Run generate_tfrecord.py to generate the validation file.')
30 | return [valid_file]
31 | elif mode == 'pred':
32 | pred_file = os.path.join(data_dir,
33 | 'subject-%d-pred-%d-patch-%d.tfrecords' % (pred_id, overlap_step, patch_size))
34 | assert os.path.isfile(pred_file), \
35 | ('Run generate_tfrecord.py to generate the prediction file.')
36 | return [pred_file]
37 |
38 |
39 | def decode_train(serialized_example):
40 | """Parses training data from the given `serialized_example`."""
41 |
42 | features = tf.parse_single_example(
43 | serialized_example,
44 | features={
45 | 'T1':tf.FixedLenFeature([],tf.string),
46 | 'T2':tf.FixedLenFeature([], tf.string),
47 | 'label':tf.FixedLenFeature([],tf.string),
48 | 'original_shape':tf.FixedLenFeature(3, tf.int64),
49 | 'cut_size':tf.FixedLenFeature(6, tf.int64)
50 | })
51 |
52 | img_shape = features['original_shape']
53 | cut_size = features['cut_size']
54 |
55 | # Convert from a scalar string tensor
56 | image_T1 = tf.decode_raw(features['T1'], tf.int16)
57 | image_T1 = tf.reshape(image_T1, img_shape)
58 | image_T2 = tf.decode_raw(features['T2'], tf.int16)
59 | image_T2 = tf.reshape(image_T2, img_shape)
60 | label = tf.decode_raw(features['label'], tf.uint8)
61 | label = tf.reshape(label, img_shape)
62 |
63 | # Convert dtype.
64 | image_T1 = tf.cast(image_T1, tf.float32)
65 | image_T2 = tf.cast(image_T2, tf.float32)
66 | label = tf.cast(label, tf.float32)
67 |
68 | return image_T1, image_T2, label, cut_size
69 |
70 |
71 | def decode_valid(serialized_example):
72 | """Parses validation data from the given `serialized_example`."""
73 |
74 | features = tf.parse_single_example(
75 | serialized_example,
76 | features={
77 | 'T1':tf.FixedLenFeature([],tf.string),
78 | 'T2':tf.FixedLenFeature([], tf.string),
79 | 'label':tf.FixedLenFeature([],tf.string)
80 | })
81 |
82 | patch_shape = [conf.patch_size, conf.patch_size, conf.patch_size]
83 |
84 | # Convert from a scalar string tensor
85 | image_T1 = tf.decode_raw(features['T1'], tf.int16)
86 | image_T1 = tf.reshape(image_T1, patch_shape)
87 | image_T2 = tf.decode_raw(features['T2'], tf.int16)
88 | image_T2 = tf.reshape(image_T2, patch_shape)
89 | label = tf.decode_raw(features['label'], tf.uint8)
90 | label = tf.reshape(label, patch_shape)
91 |
92 | # Convert dtype.
93 | image_T1 = tf.cast(image_T1, tf.float32)
94 | image_T2 = tf.cast(image_T2, tf.float32)
95 |
96 | return image_T1, image_T2, label
97 |
98 |
99 | def decode_pred(serialized_example):
100 | """Parses prediction data from the given `serialized_example`."""
101 |
102 | features = tf.parse_single_example(
103 | serialized_example,
104 | features={
105 | 'T1':tf.FixedLenFeature([],tf.string),
106 | 'T2':tf.FixedLenFeature([], tf.string)
107 | })
108 |
109 | patch_shape = [conf.patch_size, conf.patch_size, conf.patch_size]
110 |
111 | # Convert from a scalar string tensor
112 | image_T1 = tf.decode_raw(features['T1'], tf.int16)
113 | image_T1 = tf.reshape(image_T1, patch_shape)
114 | image_T2 = tf.decode_raw(features['T2'], tf.int16)
115 | image_T2 = tf.reshape(image_T2, patch_shape)
116 |
117 | # Convert dtype.
118 | image_T1 = tf.cast(image_T1, tf.float32)
119 | image_T2 = tf.cast(image_T2, tf.float32)
120 | label = tf.zeros(image_T1.shape) # pseudo label
121 |
122 | return image_T1, image_T2, label
123 |
124 |
125 | def crop_image(image_T1, image_T2, label, cut_size):
126 | """Crop training data."""
127 |
128 | data = tf.stack([image_T1, image_T2, label], axis=-1)
129 |
130 | # Randomly crop a [patch_size, patch_size, patch_size] section of the image.
131 | image = tf.random_crop(
132 | data[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :],
133 | [conf.patch_size, conf.patch_size, conf.patch_size, 3])
134 |
135 | [image_T1, image_T2, label] = tf.unstack(image, 3, axis=-1)
136 |
137 | return image_T1, image_T2, label
138 |
139 |
140 | def normalize_image(image_T1, image_T2, label):
141 | """Normalize data."""
142 |
143 | # Subtract off the mean and divide by the variance of the pixels.
144 | image_T1 = tf.image.per_image_standardization(image_T1)
145 | image_T2 = tf.image.per_image_standardization(image_T2)
146 |
147 | features = tf.stack([image_T1, image_T2], axis=-1)
148 |
149 | label = tf.cast(label, tf.int32)
150 |
151 | return features, label
152 |
153 |
154 | def input_function(data_dir, mode, patch_size, batch_size, buffer_size, valid_id,
155 | pred_id, overlap_step, num_epochs=1, num_parallel_calls=1):
156 | """Input function.
157 |
158 | Args:
159 | data_dir: The directory containing the input data.
160 | mode: A string in ['train', 'valid', 'pred'].
161 | patch_size: An integer.
162 | batch_size: The number of samples per batch.
163 | buffer_size: The buffer size to use when shuffling records. A larger
164 | value results in better randomness, but smaller values reduce startup
165 | time and use less memory.
166 | valid_id: The ID of the validation subject.
167 | pred_id: The ID of the prediction subject.
168 | overlap_step: An integer.
169 | num_epochs: The number of epochs to repeat the dataset.
170 | num_parallel_calls: The number of records that are processed in parallel.
171 | This can be optimized per data set but for generally homogeneous data
172 | sets, should be approximately the number of available CPU cores.
173 |
174 | Returns:
175 | Dataset of (features, labels) pairs ready for iteration.
176 | """
177 |
178 | with tf.name_scope('input'):
179 | # Generate a Dataset with raw records.
180 | filenames = get_filenames(data_dir, mode, valid_id, pred_id, overlap_step, patch_size)
181 | dataset = tf.data.TFRecordDataset(filenames)
182 |
183 | # We prefetch a batch at a time, This can help smooth out the time taken to
184 | # load input files as we go through shuffling and processing.
185 | dataset = dataset.prefetch(buffer_size=batch_size)
186 |
187 | if mode == 'train':
188 | # Shuffle the records. Note that we shuffle before repeating to ensure
189 | # that the shuffling respects epoch boundaries.
190 | dataset = dataset.shuffle(buffer_size=buffer_size)
191 |
192 | # If we are training over multiple epochs before evaluating, repeat the
193 | # dataset for the appropriate number of epochs.
194 | dataset = dataset.repeat(num_epochs)
195 |
196 | if mode == 'train':
197 | dataset = dataset.map(decode_train, num_parallel_calls=num_parallel_calls)
198 | dataset = dataset.map(crop_image, num_parallel_calls=num_parallel_calls)
199 | elif mode == 'valid':
200 | dataset = dataset.map(decode_valid, num_parallel_calls=num_parallel_calls)
201 | elif mode == 'pred':
202 | dataset = dataset.map(decode_pred, num_parallel_calls=num_parallel_calls)
203 |
204 | dataset = dataset.map(normalize_image, num_parallel_calls=num_parallel_calls)
205 |
206 | dataset = dataset.batch(batch_size)
207 |
208 | # Operations between the final prefetch and the get_next call to the iterator
209 | # will happen synchronously during run time. We prefetch here again to
210 | # background all of the above processing work and keep it out of the
211 | # critical training path.
212 | dataset = dataset.prefetch(1)
213 |
214 | iterator = dataset.make_one_shot_iterator()
215 | features, label = iterator.get_next()
216 |
217 | return features, label
218 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import os
3 | import tensorflow as tf
4 | from model import Model
5 | from configure import conf
6 |
7 |
8 | """This script defines hyperparameters.
9 | """
10 |
11 |
12 | def main(_):
13 | parser = argparse.ArgumentParser()
14 | parser.add_argument('--option', dest='option', type=str, default='train',
15 | help='actions: train or predict')
16 | args = parser.parse_args()
17 |
18 | if args.option not in ['train', 'predict']:
19 | print('invalid option: ', args.option)
20 | print("Please input a option: train or predict")
21 | else:
22 | model = Model(conf)
23 | getattr(model, args.option)()
24 |
25 |
26 | if __name__ == '__main__':
27 | # Choose which gpu or cpu to use
28 | os.environ['CUDA_VISIBLE_DEVICES'] = '5'
29 | tf.logging.set_verbosity(tf.logging.INFO)
30 | tf.app.run()
31 |
--------------------------------------------------------------------------------
/model.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | import os
3 | import sys
4 | import numpy as np
5 |
6 | from network import Network
7 | from input_fn import input_function
8 | from generate_tfrecord import cut_edge, prepare_validation, load_subject
9 |
10 |
11 | """This script trains or evaluates the model.
12 | """
13 |
14 |
15 | class Model(object):
16 |
17 | def __init__(self, conf):
18 | self.conf = conf
19 |
20 |
21 | def _model_fn(self, features, labels, mode):
22 | """Initializes the Model representing the model layers
23 | and uses that model to build the necessary EstimatorSpecs for
24 | the `mode` in question. For training, this means building losses,
25 | the optimizer, and the train op that get passed into the EstimatorSpec.
26 | For evaluation and prediction, the EstimatorSpec is returned without
27 | a train op, but with the necessary parameters for the given mode.
28 |
29 | Args:
30 | features: tensor representing input images
31 | labels: tensor representing class labels for all input images
32 | mode: current estimator mode; should be one of
33 | `tf.estimator.ModeKeys.TRAIN`, `EVALUATE`, `PREDICT`
34 |
35 | Returns:
36 | ModelFnOps
37 | """
38 | net = Network(self.conf)
39 | logits = net(features, mode == tf.estimator.ModeKeys.TRAIN)
40 |
41 | predictions = {
42 | 'classes': tf.argmax(logits, axis=-1),
43 | 'probabilities': tf.nn.softmax(logits, name='softmax_tensor')
44 | }
45 |
46 | if mode == tf.estimator.ModeKeys.PREDICT:
47 | return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
48 |
49 | # Calculate loss, which includes softmax cross entropy and L2 regularization.
50 | cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
51 | labels=labels, logits=logits))
52 |
53 | # Create a tensor named cross_entropy for logging purposes.
54 | tf.identity(cross_entropy, name='cross_entropy')
55 | tf.summary.scalar('cross_entropy', cross_entropy)
56 |
57 | # Add weight decay to the loss.
58 | loss = cross_entropy + self.conf.weight_decay * tf.add_n(
59 | [tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'kernel' in v.name])
60 |
61 | if mode == tf.estimator.ModeKeys.TRAIN:
62 | global_step = tf.train.get_or_create_global_step()
63 |
64 | # Learning rate.
65 | # initial_learning_rate = self.conf.learning_rate
66 | # Multiply the learning rate by 0.1 at 100, 150, and 200 epochs.
67 | # boundaries = [int(batches_per_epoch * epoch) for epoch in [150, 200]]
68 | # vals = [initial_learning_rate * decay for decay in [1, 0.25, 0.25*0.25]]
69 | # learning_rate = tf.train.piecewise_constant(global_step, boundaries, vals)
70 |
71 | # Create a tensor named learning_rate for logging purposes
72 | # tf.identity(learning_rate, name='learning_rate')
73 | # tf.summary.scalar('learning_rate', learning_rate)
74 |
75 | # optimizer = tf.train.MomentumOptimizer(
76 | # learning_rate=learning_rate,
77 | # momentum=self.conf.momentum)
78 |
79 | optimizer = tf.train.AdamOptimizer(learning_rate=self.conf.learning_rate)
80 |
81 | # Batch norm requires update ops to be added as a dependency to train_op
82 | update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
83 | with tf.control_dependencies(update_ops):
84 | train_op = optimizer.minimize(loss, global_step)
85 | else:
86 | train_op = None
87 |
88 | accuracy = tf.metrics.accuracy(labels, predictions['classes'])
89 | metrics = {'accuracy': accuracy}
90 |
91 | # Create a tensor named train_accuracy for logging purposes
92 | tf.identity(accuracy[1], name='train_accuracy')
93 | tf.summary.scalar('train_accuracy', accuracy[1])
94 |
95 | return tf.estimator.EstimatorSpec(
96 | mode=mode,
97 | predictions=predictions,
98 | loss=loss,
99 | train_op=train_op,
100 | eval_metric_ops=metrics)
101 |
102 |
103 | def train(self):
104 | # Using the Winograd non-fused algorithms provides a small performance boost.
105 | os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'
106 |
107 | save_checkpoints_steps = self.conf.epochs_per_eval * \
108 | self.conf.num_training_subs // self.conf.batch_size
109 | run_config = tf.estimator.RunConfig().replace(
110 | save_checkpoints_steps=save_checkpoints_steps,
111 | keep_checkpoint_max=0)
112 |
113 | classifier = tf.estimator.Estimator(
114 | model_fn=self._model_fn,
115 | model_dir=self.conf.model_dir,
116 | config=run_config)
117 |
118 | for _ in range(self.conf.train_epochs // self.conf.epochs_per_eval):
119 | tensors_to_log = {
120 | # 'learning_rate': 'learning_rate',
121 | 'cross_entropy': 'cross_entropy',
122 | 'train_accuracy': 'train_accuracy'
123 | }
124 |
125 | logging_hook = tf.train.LoggingTensorHook(
126 | tensors=tensors_to_log, every_n_iter=100)
127 |
128 | print('Starting a training cycle.')
129 |
130 | def input_fn_train():
131 | return input_function(
132 | data_dir=self.conf.data_dir,
133 | mode='train',
134 | patch_size=self.conf.patch_size,
135 | batch_size=self.conf.batch_size,
136 | buffer_size=self.conf.num_training_subs,
137 | valid_id=self.conf.validation_id,
138 | pred_id=-1, # not used
139 | overlap_step=-1, # not used
140 | num_epochs=self.conf.epochs_per_eval,
141 | num_parallel_calls=self.conf.num_parallel_calls)
142 |
143 | classifier.train(input_fn=input_fn_train, hooks=[logging_hook])
144 |
145 | if self.conf.validation_id != -1:
146 | print('Starting to evaluate.')
147 |
148 | def input_fn_eval():
149 | return input_function(
150 | data_dir=self.conf.data_dir,
151 | mode='valid',
152 | patch_size=self.conf.patch_size,
153 | batch_size=self.conf.batch_size,
154 | buffer_size=-1, # not used
155 | valid_id=self.conf.validation_id,
156 | pred_id=-1, # not used
157 | overlap_step=self.conf.overlap_step,
158 | num_epochs=1,
159 | num_parallel_calls=self.conf.num_parallel_calls)
160 |
161 | classifier.evaluate(input_fn=input_fn_eval)
162 |
163 |
164 | def predict(self):
165 | # Using the Winograd non-fused algorithms provides a small performance boost.
166 | os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'
167 |
168 | print('Perform prediction for subject-%d:' % self.conf.prediction_id)
169 |
170 | print('Loading data...')
171 | [T1, _, _] = load_subject(self.conf.raw_data_dir, self.conf.prediction_id)
172 |
173 | (_, cut_size) = cut_edge(T1)
174 | print('Check cut_size: ',cut_size)
175 |
176 | cutted_T1 = T1[cut_size[0]:cut_size[1], cut_size[2]:cut_size[3], cut_size[4]:cut_size[5], :]
177 | patch_ids = prepare_validation(cutted_T1, self.conf.patch_size, self.conf.overlap_step)
178 | num_patches = len(patch_ids)
179 | print ('Number of patches:', num_patches)
180 |
181 | print('Initialize...')
182 | classifier = tf.estimator.Estimator(
183 | model_fn=self._model_fn,
184 | model_dir=self.conf.model_dir)
185 |
186 | def input_fn_predict():
187 | return input_function(
188 | data_dir=self.conf.data_dir,
189 | mode='pred',
190 | patch_size=self.conf.patch_size,
191 | batch_size=self.conf.batch_size,
192 | buffer_size=-1, # not used
193 | valid_id=-1, # not used
194 | pred_id=self.conf.prediction_id,
195 | overlap_step=self.conf.overlap_step,
196 | num_epochs=1,
197 | num_parallel_calls=self.conf.num_parallel_calls)
198 |
199 | checkpoint_file = os.path.join(self.conf.model_dir,
200 | 'model.ckpt-'+str(self.conf.checkpoint_num))
201 |
202 | preds = classifier.predict(
203 | input_fn=input_fn_predict,
204 | checkpoint_path=checkpoint_file)
205 |
206 | print('Starting to predict.')
207 |
208 | predictions = {}
209 | for i, pred in enumerate(preds):
210 | location = patch_ids[i]
211 | print('Step {:d}/{:d} processing results for ({:d},{:d},{:d})'.format(
212 | i+1, num_patches, location[0], location[1], location[2]),
213 | end='\r',
214 | flush=True)
215 | logits = pred['probabilities']
216 | for j in range(self.conf.patch_size):
217 | for k in range(self.conf.patch_size):
218 | for l in range(self.conf.patch_size):
219 | key = (location[0]+j, location[1]+k, location[2]+l)
220 | if key not in predictions.keys():
221 | predictions[key] = []
222 | predictions[key].append(logits[j, k, l, :])
223 |
224 | print('Averaging results...')
225 |
226 | results = np.zeros((T1.shape[0], T1.shape[1], T1.shape[2], self.conf.num_classes),
227 | dtype=np.float32)
228 | print(results.shape)
229 | for key in predictions.keys():
230 | results[cut_size[0]+key[0], cut_size[2]+key[1], cut_size[4]+key[2]] = \
231 | np.mean(predictions[key], axis=0)
232 | results = np.argmax(results, axis=-1)
233 |
234 | print('Saving results...')
235 |
236 | if not os.path.exists(self.conf.save_dir):
237 | os.makedirs(self.conf.save_dir)
238 | save_filename = 'preds-' + str(self.conf.checkpoint_num) + \
239 | '-sub-' + str(self.conf.prediction_id) + \
240 | '-overlap-' + str(self.conf.overlap_step) + \
241 | '-patch-' + str(self.conf.patch_size) + '.npy'
242 | save_file = os.path.join(self.conf.save_dir, save_filename)
243 | np.save(save_file, results)
244 |
245 | print('Done.')
246 |
247 | os._exit(0)
248 |
--------------------------------------------------------------------------------
/network.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 |
3 | from utils import Deconv3D, Conv3D, BN_ReLU, Dilated_Conv3D, multihead_attention_3d
4 |
5 |
6 | """This script defines the network.
7 | """
8 |
9 |
10 | class Network(object):
11 |
12 | def __init__(self, conf):
13 | # configure
14 | self.num_classes = conf.num_classes
15 | self.num_filters = conf.num_filters
16 | self.block_sizes = [1] * conf.network_depth
17 | self.block_strides = [1] + [2] * (conf.network_depth - 1)
18 |
19 |
20 | def __call__(self, inputs, training):
21 | """Add operations to classify a batch of input images.
22 |
23 | Args:
24 | inputs: A Tensor representing a batch of input images.
25 | training: A boolean. Set to True to add operations required only when
26 | training the classifier.
27 |
28 | Returns:
29 | A logits Tensor with shape [, self.num_classes].
30 | """
31 |
32 | return self._build_network(inputs, training)
33 |
34 |
35 | ################################################################################
36 | # Composite blocks building the network
37 | ################################################################################
38 | def _build_network(self, inputs, training):
39 | """Build the network.
40 | """
41 |
42 | inputs = Conv3D(
43 | inputs=inputs,
44 | filters=self.num_filters,
45 | kernel_size=3,
46 | strides=1)
47 | inputs = tf.identity(inputs, 'initial_conv')
48 |
49 | skip_inputs = []
50 | for i, num_blocks in enumerate(self.block_sizes):
51 | # print(i, num_blocks)
52 | num_filters = self.num_filters * (2**i)
53 | inputs = self._encoding_block_layer(
54 | inputs=inputs, filters=num_filters,
55 | block_fn=self._residual_block, blocks=num_blocks,
56 | strides=self.block_strides[i], training=training,
57 | name='encode_block_layer{}'.format(i+1))
58 | skip_inputs.append(inputs)
59 | # print(inputs.shape)
60 | # print(len(skip_inputs))
61 |
62 | inputs = BN_ReLU(inputs, training)
63 | num_filters = self.num_filters * (2**(len(self.block_sizes)-1))
64 | # print(num_filters)
65 | inputs = multihead_attention_3d(
66 | inputs, num_filters, num_filters, num_filters, 2, training, layer_type='SAME')
67 | inputs += skip_inputs[-1]
68 |
69 | for i, num_blocks in reversed(list(enumerate(self.block_sizes[1:]))):
70 | # print(i, num_blocks)
71 | num_filters = self.num_filters * (2**i)
72 | if i == len(self.block_sizes) - 2:
73 | inputs = self._att_decoding_block_layer(
74 | inputs=inputs, skip_inputs=skip_inputs[i],
75 | filters=num_filters, block_fn=self._residual_block,
76 | blocks=1, strides=self.block_strides[i+1],
77 | training=training,
78 | name='decode_block_layer{}'.format(len(self.block_sizes)-i-1))
79 | else:
80 | inputs = self._decoding_block_layer(
81 | inputs=inputs, skip_inputs=skip_inputs[i],
82 | filters=num_filters, block_fn=self._residual_block,
83 | blocks=1, strides=self.block_strides[i+1],
84 | training=training,
85 | name='decode_block_layer{}'.format(len(self.block_sizes)-i-1))
86 | # print(inputs.shape)
87 |
88 | inputs = self._output_block_layer(inputs=inputs, training=training)
89 | # print(inputs.shape)
90 |
91 | return inputs
92 |
93 |
94 | ################################################################################
95 | # Composite blocks building the network
96 | ################################################################################
97 | def _output_block_layer(self, inputs, training):
98 |
99 | inputs = BN_ReLU(inputs, training)
100 |
101 | inputs = tf.layers.dropout(inputs, rate=0.5, training=training)
102 |
103 | inputs = Conv3D(
104 | inputs=inputs,
105 | filters=self.num_classes,
106 | kernel_size=1,
107 | strides=1,
108 | use_bias=True)
109 |
110 | return tf.identity(inputs, 'output')
111 |
112 |
113 | def _encoding_block_layer(self, inputs, filters, block_fn,
114 | blocks, strides, training, name):
115 | """Creates one layer of encoding blocks for the model.
116 |
117 | Args:
118 | inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
119 | filters: The number of filters for the first convolution of the layer.
120 | block_fn: The block to use within the model.
121 | blocks: The number of blocks contained in the layer.
122 | strides: The stride to use for the first convolution of the layer. If
123 | greater than 1, this layer will ultimately downsample the input.
124 | training: Either True or False, whether we are currently training the
125 | model. Needed for batch norm.
126 | name: A string name for the tensor output of the block layer.
127 |
128 | Returns:
129 | The output tensor of the block layer.
130 | """
131 |
132 | def projection_shortcut(inputs):
133 | return Conv3D(
134 | inputs=inputs,
135 | filters=filters,
136 | kernel_size=1,
137 | strides=strides)
138 |
139 | # Only the first block per block_layer uses projection_shortcut and strides
140 | inputs = block_fn(inputs, filters, training, projection_shortcut, strides)
141 |
142 | for _ in range(1, blocks):
143 | inputs = block_fn(inputs, filters, training, None, 1)
144 |
145 | return tf.identity(inputs, name)
146 |
147 |
148 | def _att_decoding_block_layer(self, inputs, skip_inputs, filters,
149 | block_fn, blocks, strides, training, name):
150 | """Creates one layer of decoding blocks for the model.
151 |
152 | Args:
153 | inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
154 | skip_inputs: A tensor of size [batch, depth_in, height_in, width_in, filters].
155 | filters: The number of filters for the first convolution of the layer.
156 | block_fn: The block to use within the model.
157 | blocks: The number of blocks contained in the layer.
158 | strides: The stride to use for the first convolution of the layer. If
159 | greater than 1, this layer will ultimately downsample the input.
160 | training: Either True or False, whether we are currently training the
161 | model. Needed for batch norm.
162 | name: A string name for the tensor output of the block layer.
163 |
164 | Returns:
165 | The output tensor of the block layer.
166 | """
167 |
168 | def projection_shortcut(inputs):
169 | return Deconv3D(
170 | inputs=inputs,
171 | filters=filters,
172 | kernel_size=3,
173 | strides=strides)
174 |
175 | inputs = self._attention_block(
176 | inputs, filters, training, projection_shortcut, strides)
177 |
178 | inputs = inputs + skip_inputs
179 |
180 | for _ in range(0, blocks):
181 | inputs = block_fn(inputs, filters, training, None, 1)
182 |
183 | return tf.identity(inputs, name)
184 |
185 |
186 | def _decoding_block_layer(self, inputs, skip_inputs, filters,
187 | block_fn, blocks, strides, training, name):
188 | """Creates one layer of decoding blocks for the model.
189 |
190 | Args:
191 | inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
192 | skip_inputs: A tensor of size [batch, depth_in, height_in, width_in, filters].
193 | filters: The number of filters for the first convolution of the layer.
194 | block_fn: The block to use within the model.
195 | blocks: The number of blocks contained in the layer.
196 | strides: The stride to use for the first convolution of the layer. If
197 | greater than 1, this layer will ultimately downsample the input.
198 | training: Either True or False, whether we are currently training the
199 | model. Needed for batch norm.
200 | name: A string name for the tensor output of the block layer.
201 |
202 | Returns:
203 | The output tensor of the block layer.
204 | """
205 |
206 | inputs = Deconv3D(
207 | inputs=inputs,
208 | filters=filters,
209 | kernel_size=3,
210 | strides=strides)
211 |
212 | inputs = inputs + skip_inputs
213 |
214 | for _ in range(0, blocks):
215 | inputs = block_fn(inputs, filters, training, None, 1)
216 |
217 | return tf.identity(inputs, name)
218 |
219 |
220 | ################################################################################
221 | # Basic blocks building the network
222 | ################################################################################
223 | def _residual_block(self, inputs, filters, training,
224 | projection_shortcut, strides):
225 | """Standard building block for residual networks with BN before convolutions.
226 |
227 | Args:
228 | inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
229 | filters: The number of filters for the convolutions.
230 | training: A Boolean for whether the model is in training or inference
231 | mode. Needed for batch normalization.
232 | projection_shortcut: The function to use for projection shortcuts
233 | (typically a 1x1 convolution when downsampling the input).
234 | strides: The block's stride. If greater than 1, this block will ultimately
235 | downsample the input.
236 |
237 | Returns:
238 | The output tensor of the block.
239 | """
240 |
241 | shortcut = inputs
242 | inputs = BN_ReLU(inputs, training)
243 |
244 | # The projection shortcut should come after the first batch norm and ReLU
245 | # since it performs a 1x1 convolution.
246 | if projection_shortcut is not None:
247 | shortcut = projection_shortcut(inputs)
248 |
249 | inputs = Conv3D(
250 | inputs=inputs,
251 | filters=filters,
252 | kernel_size=3,
253 | strides=strides)
254 |
255 | inputs = BN_ReLU(inputs, training)
256 |
257 | inputs = Conv3D(
258 | inputs=inputs,
259 | filters=filters,
260 | kernel_size=3,
261 | strides=1)
262 |
263 | return inputs + shortcut
264 |
265 |
266 | def _attention_block(self, inputs, filters, training,
267 | projection_shortcut, strides):
268 | """Attentional building block for residual networks with BN before convolutions.
269 |
270 | Args:
271 | inputs: A tensor of size [batch, depth_in, height_in, width_in, channels].
272 | filters: The number of filters for the convolutions.
273 | training: A Boolean for whether the model is in training or inference
274 | mode. Needed for batch normalization.
275 | projection_shortcut: The function to use for projection shortcuts
276 | (typically a 1x1 convolution when downsampling the input).
277 | strides: The block's stride. If greater than 1, this block will ultimately
278 | downsample the input.
279 |
280 | Returns:
281 | The output tensor of the block.
282 | """
283 |
284 | shortcut = inputs
285 | inputs = BN_ReLU(inputs, training)
286 |
287 | # The projection shortcut should come after the first batch norm and ReLU
288 | # since it performs a 1x1 convolution.
289 | if projection_shortcut is not None:
290 | shortcut = projection_shortcut(inputs)
291 |
292 | if strides != 1:
293 | layer_type = 'UP'
294 | else:
295 | layer_type = 'SAME'
296 |
297 | inputs = multihead_attention_3d(
298 | inputs, filters, filters, filters, 1, training, layer_type)
299 |
300 | return inputs + shortcut
301 |
--------------------------------------------------------------------------------
/results/sample_results.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhengyang-wang/3D-Unet--Tensorflow/c5d603a69243a69dd6d89edefdf1ba249640450b/results/sample_results.png
--------------------------------------------------------------------------------
/results/training_curve.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhengyang-wang/3D-Unet--Tensorflow/c5d603a69243a69dd6d89edefdf1ba249640450b/results/training_curve.png
--------------------------------------------------------------------------------
/utils/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhengyang-wang/3D-Unet--Tensorflow/c5d603a69243a69dd6d89edefdf1ba249640450b/utils/.DS_Store
--------------------------------------------------------------------------------
/utils/DiceRatio.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def dice_ratio(pred, label):
4 | '''Note: pred & label should only contain 0 or 1.
5 | '''
6 |
7 | return np.sum(pred[label==1])*2.0 / (np.sum(pred) + np.sum(label))
--------------------------------------------------------------------------------
/utils/HausdorffDistance.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Mon Jun 16 23:56:41 2014
4 |
5 | @author: Edward
6 | """
7 | import numpy as np
8 | from numpy.core.umath_tests import inner1d
9 | # A = np.array([[1,2],[3,4],[5,6],[7,8]])
10 | # B = np.array([[2,3],[4,5],[6,7],[8,9],[10,11]])
11 |
12 |
13 | # Hausdorff Distance
14 | def HausdorffDist(A,B):
15 | # Hausdorf Distance: Compute the Hausdorff distance between two point
16 | # clouds.
17 | # Let A and B be subsets of metric space (Z,dZ),
18 | # The Hausdorff distance between A and B, denoted by dH(A,B),
19 | # is defined by:
20 | # dH(A,B) = max(h(A,B),h(B,A)),
21 | # where h(A,B) = max(min(d(a,b))
22 | # and d(a,b) is a L2 norm
23 | # dist_H = hausdorff(A,B)
24 | # A: First point sets (MxN, with M observations in N dimension)
25 | # B: Second point sets (MxN, with M observations in N dimension)
26 | # ** A and B may have different number of rows, but must have the same
27 | # number of columns.
28 | #
29 | # Edward DongBo Cui; Stanford University; 06/17/2014
30 |
31 | # Find pairwise distance
32 | D_mat = np.sqrt(inner1d(A,A)[np.newaxis].T + inner1d(B,B)-2*(np.dot(A,B.T)))
33 | # Find DH
34 | dH = np.max(np.array([np.max(np.min(D_mat,axis=0)),np.max(np.min(D_mat,axis=1))]))
35 | return(dH)
36 |
37 | def ModHausdorffDist(A,B):
38 | #This function computes the Modified Hausdorff Distance (MHD) which is
39 | #proven to function better than the directed HD as per Dubuisson et al.
40 | #in the following work:
41 | #
42 | #M. P. Dubuisson and A. K. Jain. A Modified Hausdorff distance for object
43 | #matching. In ICPR94, pages A:566-568, Jerusalem, Israel, 1994.
44 | #http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=576361
45 | #
46 | #The function computed the forward and reverse distances and outputs the
47 | #maximum/minimum of both.
48 | #Optionally, the function can return forward and reverse distance.
49 | #
50 | #Format for calling function:
51 | #
52 | #[MHD,FHD,RHD] = ModHausdorffDist(A,B);
53 | #
54 | #where
55 | #MHD = Modified Hausdorff Distance.
56 | #FHD = Forward Hausdorff Distance: minimum distance from all points of B
57 | # to a point in A, averaged for all A
58 | #RHD = Reverse Hausdorff Distance: minimum distance from all points of A
59 | # to a point in B, averaged for all B
60 | #A -> Point set 1, [row as observations, and col as dimensions]
61 | #B -> Point set 2, [row as observations, and col as dimensions]
62 | #
63 | #No. of samples of each point set may be different but the dimension of
64 | #the points must be the same.
65 | #
66 | #Edward DongBo Cui Stanford University; 06/17/2014
67 |
68 | # Find pairwise distance
69 | D_mat = np.sqrt(inner1d(A,A)[np.newaxis].T + inner1d(B,B)-2*(np.dot(A,B.T)))
70 | # Calculating the forward HD: mean(min(each col))
71 | FHD = np.mean(np.min(D_mat,axis=1))
72 | # Calculating the reverse HD: mean(min(each row))
73 | RHD = np.mean(np.min(D_mat,axis=0))
74 | # Calculating mhd
75 | MHD = np.max(np.array([FHD, RHD]))
76 | return(MHD, FHD, RHD)
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
1 | from .basic_ops import Pool3d, Deconv3D, Conv3D, Dilated_Conv3D, BN_ReLU
2 | from .DiceRatio import dice_ratio
3 | from .HausdorffDistance import ModHausdorffDist
4 | from .attention import multihead_attention_3d
--------------------------------------------------------------------------------
/utils/attention.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | from .basic_ops import *
3 |
4 |
5 | """This script defines 3D different multi-head attention layers.
6 | """
7 |
8 |
9 | def multihead_attention_3d(inputs, total_key_filters, total_value_filters,
10 | output_filters, num_heads, training, layer_type='SAME',
11 | name=None):
12 | """3d Multihead scaled-dot-product attention with input/output transformations.
13 |
14 | Args:
15 | inputs: a Tensor with shape [batch, d, h, w, channels]
16 | total_key_filters: an integer. Note that queries have the same number
17 | of channels as keys
18 | total_value_filters: an integer
19 | output_depth: an integer
20 | num_heads: an integer dividing total_key_filters and total_value_filters
21 | layer_type: a string, type of this layer -- SAME, DOWN, UP
22 | name: an optional string
23 |
24 | Returns:
25 | A Tensor of shape [batch, _d, _h, _w, output_filters]
26 |
27 | Raises:
28 | ValueError: if the total_key_filters or total_value_filters are not divisible
29 | by the number of attention heads.
30 | """
31 |
32 | if total_key_filters % num_heads != 0:
33 | raise ValueError("Key depth (%d) must be divisible by the number of "
34 | "attention heads (%d)." % (total_key_filters, num_heads))
35 | if total_value_filters % num_heads != 0:
36 | raise ValueError("Value depth (%d) must be divisible by the number of "
37 | "attention heads (%d)." % (total_value_filters, num_heads))
38 | if layer_type not in ['SAME', 'DOWN', 'UP']:
39 | raise ValueError("Layer type (%s) must be one of SAME, "
40 | "DOWN, UP." % (layer_type))
41 |
42 | with tf.variable_scope(
43 | name,
44 | default_name="multihead_attention_3d",
45 | values=[inputs]):
46 |
47 | # produce q, k, v
48 | q, k, v = compute_qkv_3d(inputs, total_key_filters,
49 | total_value_filters, layer_type)
50 |
51 | # after splitting, shape is [batch, heads, d, h, w, channels / heads]
52 | q = split_heads_3d(q, num_heads)
53 | k = split_heads_3d(k, num_heads)
54 | v = split_heads_3d(v, num_heads)
55 |
56 | # normalize
57 | key_filters_per_head = total_key_filters // num_heads
58 | q *= key_filters_per_head**-0.5
59 |
60 | # attention
61 | x = global_attention_3d(q, k, v, training)
62 |
63 | x = combine_heads_3d(x)
64 | x = Conv3D(x, output_filters, 1, 1, use_bias=True)
65 |
66 | return x
67 |
68 |
69 | def compute_qkv_3d(inputs, total_key_filters, total_value_filters, layer_type):
70 | """Computes query, key and value.
71 |
72 | Args:
73 | inputs: a Tensor with shape [batch, d, h, w, channels]
74 | total_key_filters: an integer
75 | total_value_filters: and integer
76 | layer_type: String, type of this layer -- SAME, DOWN, UP
77 |
78 | Returns:
79 | q: [batch, _d, _h, _w, total_key_filters] tensor
80 | k: [batch, h, w, total_key_filters] tensor
81 | v: [batch, h, w, total_value_filters] tensor
82 | """
83 |
84 | # linear transformation for q
85 | if layer_type == 'SAME':
86 | q = Conv3D(inputs, total_key_filters, 1, 1, use_bias=True)
87 | elif layer_type == 'DOWN':
88 | q = Conv3D(inputs, total_key_filters, 3, 2, use_bias=True)
89 | elif layer_type == 'UP':
90 | q = Deconv3D(inputs, total_key_filters, 3, 2, use_bias=True)
91 |
92 | # linear transformation for k
93 | k = Conv3D(inputs, total_key_filters, 1, 1, use_bias=True)
94 |
95 | # linear transformation for k
96 | v = Conv3D(inputs, total_value_filters, 1, 1, use_bias=True)
97 |
98 | return q, k, v
99 |
100 |
101 | def split_heads_3d(x, num_heads):
102 | """Split channels (last dimension) into multiple heads (becomes dimension 1).
103 |
104 | Args:
105 | x: a Tensor with shape [batch, d, h, w, channels]
106 | num_heads: an integer
107 |
108 | Returns:
109 | a Tensor with shape [batch, num_heads, d, h, w, channels / num_heads]
110 | """
111 |
112 | return tf.transpose(split_last_dimension(x, num_heads), [0, 4, 1, 2, 3, 5])
113 |
114 |
115 | def split_last_dimension(x, n):
116 | """Reshape x so that the last dimension becomes two dimensions.
117 | The first of these two dimensions is n.
118 |
119 | Args:
120 | x: a Tensor with shape [..., m]
121 | n: an integer.
122 |
123 | Returns:
124 | a Tensor with shape [..., n, m/n]
125 | """
126 |
127 | old_shape = x.get_shape().dims
128 | last = old_shape[-1]
129 | new_shape = old_shape[:-1] + [n] + [last // n if last else None]
130 |
131 | ret = tf.reshape(x, tf.concat([tf.shape(x)[:-1], [n, -1]], 0))
132 | ret.set_shape(new_shape)
133 |
134 | return ret
135 |
136 |
137 | def global_attention_3d(q, k, v, training, name=None):
138 | """global self-attention.
139 | Args:
140 | q: a Tensor with shape [batch, heads, _d, _h, _w, channels_k]
141 | k: a Tensor with shape [batch, heads, d, h, w, channels_k]
142 | v: a Tensor with shape [batch, heads, d, h, w, channels_v]
143 | name: an optional string
144 | Returns:
145 | a Tensor of shape [batch, heads, _d, _h, _w, channels_v]
146 | """
147 | with tf.variable_scope(
148 | name,
149 | default_name="global_attention_3d",
150 | values=[q, k, v]):
151 |
152 | new_shape = tf.concat([tf.shape(q)[0:-1], [v.shape[-1].value]], 0)
153 |
154 | # flatten q,k,v
155 | q_new = flatten_3d(q)
156 | k_new = flatten_3d(k)
157 | v_new = flatten_3d(v)
158 |
159 | # attention
160 | output = dot_product_attention(q_new, k_new, v_new, bias=None,
161 | training=training, dropout_rate=0.5, name="global_3d")
162 |
163 | # putting the representations back in the right place
164 | output = scatter_3d(output, new_shape)
165 |
166 | return output
167 |
168 |
169 | def reshape_range(tensor, i, j, shape):
170 | """Reshapes a tensor between dimensions i and j."""
171 |
172 | target_shape = tf.concat(
173 | [tf.shape(tensor)[:i], shape, tf.shape(tensor)[j:]],
174 | axis=0)
175 |
176 | return tf.reshape(tensor, target_shape)
177 |
178 |
179 | def flatten_3d(x):
180 | """flatten x."""
181 |
182 | x_shape = tf.shape(x)
183 | # [batch, heads, length, channels], length = d*h*w
184 | x = reshape_range(x, 2, 5, [tf.reduce_prod(x_shape[2:5])])
185 |
186 | return x
187 |
188 |
189 | def scatter_3d(x, shape):
190 | """scatter x."""
191 |
192 | x = tf.reshape(x, shape)
193 |
194 | return x
195 |
196 |
197 | def dot_product_attention(q, k, v, bias, training, dropout_rate=0.0, name=None):
198 | """Dot-product attention.
199 |
200 | Args:
201 | q: a Tensor with shape [batch, heads, length_q, channels_k]
202 | k: a Tensor with shape [batch, heads, length_kv, channels_k]
203 | v: a Tensor with shape [batch, heads, length_kv, channels_v]
204 | bias: bias Tensor
205 | dropout_rate: a floating point number
206 | name: an optional string
207 |
208 | Returns:
209 | A Tensor with shape [batch, heads, length_q, channels_v]
210 | """
211 |
212 | with tf.variable_scope(
213 | name,
214 | default_name="dot_product_attention",
215 | values=[q, k, v]):
216 |
217 | # [batch, num_heads, length_q, length_kv]
218 | logits = tf.matmul(q, k, transpose_b=True)
219 |
220 | if bias is not None:
221 | logits += bias
222 |
223 | weights = tf.nn.softmax(logits, name="attention_weights")
224 |
225 | # dropping out the attention links for each of the heads
226 | weights = tf.layers.dropout(weights, dropout_rate, training)
227 |
228 | return tf.matmul(weights, v)
229 |
230 |
231 | def combine_heads_3d(x):
232 | """Inverse of split_heads_3d.
233 |
234 | Args:
235 | x: a Tensor with shape [batch, num_heads, d, h, w, channels / num_heads]
236 |
237 | Returns:
238 | a Tensor with shape [batch, d, h, w, channels]
239 | """
240 |
241 | return combine_last_two_dimensions(tf.transpose(x, [0, 2, 3, 4, 1, 5]))
242 |
243 |
244 | def combine_last_two_dimensions(x):
245 | """Reshape x so that the last two dimension become one.
246 |
247 | Args:
248 | x: a Tensor with shape [..., a, b]
249 |
250 | Returns:
251 | a Tensor with shape [..., a*b]
252 | """
253 |
254 | old_shape = x.get_shape().dims
255 | a, b = old_shape[-2:]
256 | new_shape = old_shape[:-2] + [a * b if a and b else None]
257 |
258 | ret = tf.reshape(x, tf.concat([tf.shape(x)[:-2], [-1]], 0))
259 | ret.set_shape(new_shape)
260 |
261 | return ret
262 |
--------------------------------------------------------------------------------
/utils/basic_ops.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 |
3 |
4 | """This script defines basic operations.
5 | """
6 |
7 |
8 |
9 | ################################################################################
10 | # Basic operations building the network
11 | ################################################################################
12 | def Pool3d(inputs, kernel_size, strides):
13 | """Performs 3D max pooling."""
14 |
15 | return tf.layers.max_pooling3d(
16 | inputs=inputs,
17 | pool_size=kernel_size,
18 | strides=strides,
19 | padding='same')
20 |
21 |
22 | def Deconv3D(inputs, filters, kernel_size, strides, use_bias=False):
23 | """Performs 3D deconvolution without bias and activation function."""
24 |
25 | return tf.layers.conv3d_transpose(
26 | inputs=inputs,
27 | filters=filters,
28 | kernel_size=kernel_size,
29 | strides=strides,
30 | padding='same',
31 | use_bias=use_bias,
32 | kernel_initializer=tf.truncated_normal_initializer())
33 |
34 |
35 | def Conv3D(inputs, filters, kernel_size, strides, use_bias=False):
36 | """Performs 3D convolution without bias and activation function."""
37 |
38 | return tf.layers.conv3d(
39 | inputs=inputs,
40 | filters=filters,
41 | kernel_size=kernel_size,
42 | strides=strides,
43 | padding='same',
44 | use_bias=use_bias,
45 | kernel_initializer=tf.truncated_normal_initializer())
46 |
47 |
48 | def Dilated_Conv3D(inputs, filters, kernel_size, dilation_rate, use_bias=False):
49 | """Performs 3D dilated convolution without bias and activation function."""
50 |
51 | return tf.layers.conv3d(
52 | inputs=inputs,
53 | filters=filters,
54 | kernel_size=kernel_size,
55 | strides=1,
56 | dilation_rate=dilation_rate,
57 | padding='same',
58 | use_bias=use_bias,
59 | kernel_initializer=tf.truncated_normal_initializer())
60 |
61 |
62 | def BN_ReLU(inputs, training):
63 | """Performs a batch normalization followed by a ReLU6."""
64 |
65 | # We set fused=True for a significant performance boost. See
66 | # https://www.tensorflow.org/performance/performance_guide#common_fused_ops
67 | inputs = tf.layers.batch_normalization(
68 | inputs=inputs,
69 | axis=-1,
70 | momentum=0.997,
71 | epsilon=1e-5,
72 | center=True,
73 | scale=True,
74 | training=training,
75 | fused=True)
76 |
77 | return tf.nn.relu6(inputs)
78 |
--------------------------------------------------------------------------------
/visualize.py:
--------------------------------------------------------------------------------
1 | import os
2 | import numpy as np
3 | import matplotlib
4 | matplotlib.use('Agg')
5 | import matplotlib.pyplot as plt
6 |
7 |
8 | """Visualize results by slices.
9 | """
10 |
11 |
12 | ################################################################################
13 | # Arguments
14 | ################################################################################
15 | RAW_DATA_DIR = '/data/zhengyang/InfantBrain/RawData'
16 | LABEL_DIR = '/data/zhengyang/InfantBrain/tfrecords_full'
17 | PRED_DIR = './results'
18 | PRED_ID = 10 # 1-10
19 | PATCH_SIZE = 32
20 | CHECKPOINT_NUM = 153000
21 | OVERLAP_STEPSIZE = 8
22 | SLICE_DEPTH = 150
23 |
24 |
25 | ################################################################################
26 | # Functions
27 | ################################################################################
28 | def Visualize(label_dir, pred_dir, pred_id, patch_size, checkpoint_num,
29 | overlap_step, slice_depth):
30 | print('Perform visualization for subject-%d:' % pred_id)
31 |
32 | print('Loading label...')
33 | label_file = os.path.join(label_dir, 'subject-%d-label.npy' % pred_id)
34 | assert os.path.isfile(label_file), \
35 | ('Run generate_tfrecord.py to generate the label file.')
36 | label = np.load(label_file)
37 | print('Check label: ', label.shape, np.max(label))
38 |
39 | print('Loading predition...')
40 | pred_file = os.path.join(pred_dir,
41 | 'preds-%d-sub-%d-overlap-%d-patch-%d.npy' % \
42 | (checkpoint_num, pred_id, overlap_step, patch_size))
43 | assert os.path.isfile(pred_file), \
44 | ('Run main.py --option=predict to generate the prediction results.')
45 | pred = np.load(pred_file)
46 | print('Check pred: ', pred.shape, np.max(pred))
47 |
48 | pred_show = pred[:, :, slice_depth]
49 | label_show = label[:, :, slice_depth]
50 |
51 | fig = plt.figure()
52 | fig.suptitle('Compare the %d-th slice.' % slice_depth, fontsize=14)
53 |
54 | a = fig.add_subplot(1,2,1)
55 | imgplot = plt.imshow(label_show)
56 | a.set_title('Groud Truth')
57 |
58 | a = fig.add_subplot(1,2,2)
59 | imgplot = plt.imshow(pred_show)
60 | a.set_title('Prediction')
61 |
62 | plt.savefig('visualization-%d-sub-%d-overlap-%d' % \
63 | (checkpoint_num, pred_id, overlap_step))
64 |
65 | if __name__ == '__main__':
66 | Visualize(
67 | label_dir=LABEL_DIR,
68 | pred_dir=PRED_DIR,
69 | pred_id=PRED_ID,
70 | patch_size=PATCH_SIZE,
71 | checkpoint_num=CHECKPOINT_NUM,
72 | overlap_step=OVERLAP_STEPSIZE,
73 | slice_depth=SLICE_DEPTH)
--------------------------------------------------------------------------------