├── Dockerfile ├── LICENSE ├── README.md ├── dice_loss.py ├── eval.py ├── hubconf.py ├── models ├── __init__.py └── utransformer │ ├── U_Transformer.py │ └── __init__.py ├── requirements.txt ├── test.py ├── train.py └── utils ├── __init__.py ├── base.py ├── data_vis.py ├── dataset.py ├── functional.py ├── losses.py ├── meter.py ├── metrics.py └── train.py /Dockerfile: -------------------------------------------------------------------------------- 1 | # Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch 2 | FROM nvcr.io/nvidia/pytorch:20.12-py3 3 | 4 | # Install linux packages 5 | RUN apt update && apt install -y screen libgl1-mesa-glx 6 | 7 | # Install python dependencies 8 | RUN pip install --upgrade pip 9 | COPY requirements.txt . 10 | RUN pip install -r requirements.txt 11 | RUN pip install gsutil 12 | 13 | # Create working directory 14 | WORKDIR /home/xray/segmentation_models.pytorch/ 15 | 16 | 17 | # Copy weights 18 | #RUN python3 -c "from models import *; \ 19 | #attempt_download('weights/yolov5s.pt'); \ 20 | #attempt_download('weights/yolov5m.pt'); \ 21 | #attempt_download('weights/yolov5l.pt')" 22 | 23 | 24 | # --------------------------------------------------- Extras Below --------------------------------------------------- 25 | 26 | # Build and Push 27 | # t=ultralytics/yolov5:latest && sudo docker build -t $t . && sudo docker push $t 28 | # for v in {300..303}; do t=ultralytics/coco:v$v && sudo docker build -t $t . && sudo docker push $t; done 29 | 30 | # Pull and Run 31 | # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t 32 | 33 | # Pull and Run with local directory access 34 | # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/coco:/usr/src/coco $t 35 | 36 | # Kill all 37 | # sudo docker kill $(sudo docker ps -q) 38 | 39 | # Kill all image-based 40 | # sudo docker kill $(sudo docker ps -a -q --filter ancestor=ultralytics/yolov5:latest) 41 | 42 | # Bash into running container 43 | # sudo docker container exec -it ba65811811ab bash 44 | 45 | # Bash into stopped container 46 | # sudo docker commit 092b16b25c5b usr/resume && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco --entrypoint=sh usr/resume 47 | 48 | # Send weights to GCP 49 | # python -c "from utils.general import *; strip_optimizer('runs/train/exp0_*/weights/best.pt', 'tmp.pt')" && gsutil cp tmp.pt gs://*.pt 50 | 51 | # Clean up 52 | # docker system prune -a --volumes 53 | -------------------------------------------------------------------------------- /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 | An unofficial implement of paper: U-Net Transformer: Self and Cross Attention for 2 | Medical Image Segmentation (arxiv:2103.06104) 3 | 4 | I am not the author of this paper, and there are still has serious bugs, please help me to improve. 5 | -------------------------------------------------------------------------------- /dice_loss.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch.autograd import Function 3 | 4 | 5 | class DiceCoeff(Function): 6 | """Dice coeff for individual examples""" 7 | 8 | def forward(self, input, target): 9 | self.save_for_backward(input, target) 10 | eps = 0.0001 11 | self.inter = torch.dot(input.view(-1), target.view(-1)) 12 | self.union = torch.sum(input) + torch.sum(target) + eps 13 | 14 | t = (2 * self.inter.float() + eps) / self.union.float() 15 | return t 16 | 17 | # This function has only a single output, so it gets only one gradient 18 | def backward(self, grad_output): 19 | 20 | input, target = self.saved_variables 21 | grad_input = grad_target = None 22 | 23 | if self.needs_input_grad[0]: 24 | grad_input = grad_output * 2 * (target * self.union - self.inter) \ 25 | / (self.union * self.union) 26 | if self.needs_input_grad[1]: 27 | grad_target = None 28 | 29 | return grad_input, grad_target 30 | 31 | 32 | def dice_coeff(input, target): 33 | """Dice coeff for batches""" 34 | if input.is_cuda: 35 | s = torch.FloatTensor(1).cuda().zero_() 36 | else: 37 | s = torch.FloatTensor(1).zero_() 38 | 39 | for i, c in enumerate(zip(input, target)): 40 | s = s + DiceCoeff().forward(c[0], c[1]) 41 | 42 | return s / (i + 1) 43 | -------------------------------------------------------------------------------- /eval.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | from tqdm import tqdm 4 | 5 | from dice_loss import dice_coeff 6 | 7 | 8 | def eval_net(net, loader, device): 9 | """Evaluation without the densecrf with the dice coefficient""" 10 | net.eval() 11 | mask_type = torch.float32 if net.n_classes == 1 else torch.long 12 | n_val = len(loader) # the number of batch 13 | tot = 0 14 | 15 | with tqdm(total=n_val, desc='Validation round', unit='batch', leave=False) as pbar: 16 | for batch in loader: 17 | imgs, true_masks = batch['image'], batch['mask'] 18 | imgs = imgs.to(device=device, dtype=torch.float32) 19 | true_masks = true_masks.to(device=device, dtype=mask_type) 20 | 21 | with torch.no_grad(): 22 | mask_pred = net(imgs) 23 | 24 | if net.n_classes > 1: 25 | tot += F.cross_entropy(mask_pred, true_masks).item() 26 | else: 27 | pred = torch.sigmoid(mask_pred) 28 | pred = (pred > 0.5).float() 29 | tot += dice_coeff(pred, true_masks).item() 30 | pbar.update() 31 | 32 | net.train() 33 | return tot / n_val 34 | -------------------------------------------------------------------------------- /hubconf.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from unet import UNet as _UNet 3 | 4 | def unet_carvana(pretrained=False): 5 | """ 6 | UNet model trained on the Carvana dataset ( https://www.kaggle.com/c/carvana-image-masking-challenge/data ). 7 | Set the scale to 1 (100%) when predicting. 8 | """ 9 | net = _UNet(n_channels=3, n_classes=1, bilinear=True) 10 | if pretrained: 11 | checkpoint = 'https://github.com/milesial/Pytorch-UNet/releases/download/v1.0/unet_carvana_scale1_epoch5.pth' 12 | net.load_state_dict(torch.hub.load_state_dict_from_url(checkpoint, progress=True)) 13 | 14 | return net 15 | 16 | -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | # from .unet import Unet 2 | from .ddrnet.DDRNet import DualResNet 3 | from .utransformer.U_Transformer import U_Transformer 4 | 5 | from typing import Optional 6 | import torch 7 | 8 | 9 | def create_model( 10 | arch: str, 11 | in_channels: int = 3, 12 | classes: int = 1, 13 | **kwargs, 14 | ) -> torch.nn.Module: 15 | """Models wrapper. Allows to create any model just with parametes 16 | 17 | """ 18 | 19 | archs = [DualResNet, U_Transformer] 20 | archs_dict = {a.__name__.lower(): a for a in archs} 21 | try: 22 | model_class = archs_dict[arch.lower()] 23 | except KeyError: 24 | raise KeyError( 25 | "Wrong architecture type `{}`. Avalibale options are: {}".format( 26 | arch, 27 | list(archs_dict.keys()), 28 | )) 29 | return model_class( 30 | in_channels=in_channels, 31 | classes=classes, 32 | **kwargs, 33 | ) 34 | -------------------------------------------------------------------------------- /models/utransformer/U_Transformer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | import torch.nn.functional as F 4 | import math 5 | import numpy as np 6 | 7 | 8 | class DoubleConv(nn.Module): 9 | """(convolution => [BN] => ReLU) * 2""" 10 | def __init__(self, in_channels, out_channels, mid_channels=None): 11 | super().__init__() 12 | if not mid_channels: 13 | mid_channels = out_channels 14 | self.double_conv = nn.Sequential( 15 | nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1), 16 | nn.BatchNorm2d(mid_channels), 17 | nn.ReLU(inplace=True), 18 | nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1), 19 | nn.BatchNorm2d(out_channels), 20 | nn.ReLU(inplace=True), 21 | ) 22 | 23 | def forward(self, x): 24 | return self.double_conv(x) 25 | 26 | 27 | class Down(nn.Module): 28 | """Downscaling with maxpool then double conv""" 29 | def __init__(self, in_channels, out_channels): 30 | super().__init__() 31 | self.maxpool_conv = nn.Sequential( 32 | nn.MaxPool2d(2), 33 | DoubleConv(in_channels, out_channels), 34 | ) 35 | 36 | def forward(self, x): 37 | return self.maxpool_conv(x) 38 | 39 | 40 | class Up(nn.Module): 41 | """Upscaling then double conv""" 42 | def __init__(self, in_channels, out_channels, bilinear=True): 43 | super().__init__() 44 | 45 | # if bilinear, use the normal convolutions to reduce the number of channels 46 | if bilinear: 47 | self.up = nn.Upsample(scale_factor=2, 48 | mode='bilinear', 49 | align_corners=True) 50 | self.conv = DoubleConv(in_channels, out_channels, in_channels // 2) 51 | else: 52 | self.up = nn.ConvTranspose2d( 53 | in_channels, 54 | in_channels // 2, 55 | kernel_size=2, 56 | stride=2, 57 | ) 58 | self.conv = DoubleConv(in_channels, out_channels) 59 | 60 | def forward(self, x1, x2): 61 | x1 = self.up(x1) 62 | # input is CHW 63 | diffY = x2.size()[2] - x1.size()[2] 64 | diffX = x2.size()[3] - x1.size()[3] 65 | 66 | x1 = F.pad( 67 | x1, 68 | [diffX // 2, diffX - diffX // 2, diffY // 2, diffY - diffY // 2]) 69 | # if you have padding issues, see 70 | # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a 71 | # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd 72 | x = torch.cat([x2, x1], dim=1) 73 | return self.conv(x) 74 | 75 | 76 | class OutConv(nn.Module): 77 | def __init__(self, in_channels, out_channels): 78 | super(OutConv, self).__init__() 79 | self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1) 80 | 81 | def forward(self, x): 82 | return self.conv(x) 83 | 84 | 85 | class MultiHeadDense(nn.Module): 86 | def __init__(self, d, bias=False): 87 | super(MultiHeadDense, self).__init__() 88 | self.weight = nn.Parameter(torch.Tensor(d, d)) 89 | if bias: 90 | raise NotImplementedError() 91 | self.bias = Parameter(torch.Tensor(d, d)) 92 | else: 93 | self.register_parameter('bias', None) 94 | self.reset_parameters() 95 | 96 | def reset_parameters(self) -> None: 97 | nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) 98 | if self.bias is not None: 99 | fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) 100 | bound = 1 / math.sqrt(fan_in) 101 | nn.init.uniform_(self.bias, -bound, bound) 102 | 103 | def forward(self, x): 104 | # x:[b, h*w, d] 105 | b, wh, d = x.size() 106 | x = torch.bmm(x, self.weight.repeat(b, 1, 1)) 107 | # x = F.linear(x, self.weight, self.bias) 108 | return x 109 | 110 | 111 | class MultiHeadAttention(nn.Module): 112 | def __init__(self): 113 | super(MultiHeadAttention, self).__init__() 114 | 115 | def positional_encoding_2d(self, d_model, height, width): 116 | """ 117 | reference: wzlxjtu/PositionalEncoding2D 118 | 119 | :param d_model: dimension of the model 120 | :param height: height of the positions 121 | :param width: width of the positions 122 | :return: d_model*height*width position matrix 123 | """ 124 | if d_model % 4 != 0: 125 | raise ValueError("Cannot use sin/cos positional encoding with " 126 | "odd dimension (got dim={:d})".format(d_model)) 127 | pe = torch.zeros(d_model, height, width) 128 | try: 129 | pe = pe.to(torch.device("cuda:0")) 130 | except RuntimeError: 131 | pass 132 | # Each dimension use half of d_model 133 | d_model = int(d_model / 2) 134 | div_term = torch.exp( 135 | torch.arange(0., d_model, 2) * -(math.log(10000.0) / d_model)) 136 | pos_w = torch.arange(0., width).unsqueeze(1) 137 | pos_h = torch.arange(0., height).unsqueeze(1) 138 | pe[0:d_model:2, :, :] = torch.sin(pos_w * div_term).transpose( 139 | 0, 1).unsqueeze(1).repeat(1, height, 1) 140 | pe[1:d_model:2, :, :] = torch.cos(pos_w * div_term).transpose( 141 | 0, 1).unsqueeze(1).repeat(1, height, 1) 142 | pe[d_model::2, :, :] = torch.sin(pos_h * div_term).transpose( 143 | 0, 1).unsqueeze(2).repeat(1, 1, width) 144 | pe[d_model + 1::2, :, :] = torch.cos(pos_h * div_term).transpose( 145 | 0, 1).unsqueeze(2).repeat(1, 1, width) 146 | return pe 147 | 148 | def forward(self, x): 149 | raise NotImplementedError() 150 | 151 | 152 | class PositionalEncoding2D(nn.Module): 153 | def __init__(self, channels): 154 | """ 155 | :param channels: The last dimension of the tensor you want to apply pos emb to. 156 | """ 157 | super(PositionalEncoding2D, self).__init__() 158 | channels = int(np.ceil(channels / 2)) 159 | self.channels = channels 160 | inv_freq = 1. / (10000 161 | **(torch.arange(0, channels, 2).float() / channels)) 162 | self.register_buffer('inv_freq', inv_freq) 163 | 164 | def forward(self, tensor): 165 | """ 166 | :param tensor: A 4d tensor of size (batch_size, x, y, ch) 167 | :return: Positional Encoding Matrix of size (batch_size, x, y, ch) 168 | """ 169 | if len(tensor.shape) != 4: 170 | raise RuntimeError("The input tensor has to be 4d!") 171 | batch_size, x, y, orig_ch = tensor.shape 172 | pos_x = torch.arange(x, 173 | device=tensor.device).type(self.inv_freq.type()) 174 | pos_y = torch.arange(y, 175 | device=tensor.device).type(self.inv_freq.type()) 176 | sin_inp_x = torch.einsum("i,j->ij", pos_x, self.inv_freq) 177 | sin_inp_y = torch.einsum("i,j->ij", pos_y, self.inv_freq) 178 | emb_x = torch.cat((sin_inp_x.sin(), sin_inp_x.cos()), 179 | dim=-1).unsqueeze(1) 180 | emb_y = torch.cat((sin_inp_y.sin(), sin_inp_y.cos()), dim=-1) 181 | emb = torch.zeros((x, y, self.channels * 2), 182 | device=tensor.device).type(tensor.type()) 183 | emb[:, :, :self.channels] = emb_x 184 | emb[:, :, self.channels:2 * self.channels] = emb_y 185 | 186 | return emb[None, :, :, :orig_ch].repeat(batch_size, 1, 1, 1) 187 | 188 | 189 | class PositionalEncodingPermute2D(nn.Module): 190 | def __init__(self, channels): 191 | """ 192 | Accepts (batchsize, ch, x, y) instead of (batchsize, x, y, ch) 193 | """ 194 | super(PositionalEncodingPermute2D, self).__init__() 195 | self.penc = PositionalEncoding2D(channels) 196 | 197 | def forward(self, tensor): 198 | tensor = tensor.permute(0, 2, 3, 1) 199 | enc = self.penc(tensor) 200 | return enc.permute(0, 3, 1, 2) 201 | 202 | 203 | class MultiHeadSelfAttention(MultiHeadAttention): 204 | def __init__(self, channel): 205 | super(MultiHeadSelfAttention, self).__init__() 206 | self.query = MultiHeadDense(channel, bias=False) 207 | self.key = MultiHeadDense(channel, bias=False) 208 | self.value = MultiHeadDense(channel, bias=False) 209 | self.softmax = nn.Softmax(dim=1) 210 | self.pe = PositionalEncodingPermute2D(channel) 211 | 212 | def forward(self, x): 213 | b, c, h, w = x.size() 214 | # pe = self.positional_encoding_2d(c, h, w) 215 | pe = self.pe(x) 216 | x = x + pe 217 | x = x.reshape(b, c, h * w).permute(0, 2, 1) #[b, h*w, d] 218 | Q = self.query(x) 219 | K = self.key(x) 220 | A = self.softmax(torch.bmm(Q, K.permute(0, 2, 1)) / 221 | math.sqrt(c)) #[b, h*w, h*w] 222 | V = self.value(x) 223 | x = torch.bmm(A, V).permute(0, 2, 1).reshape(b, c, h, w) 224 | return x 225 | 226 | 227 | class MultiHeadCrossAttention(MultiHeadAttention): 228 | def __init__(self, channelY, channelS): 229 | super(MultiHeadCrossAttention, self).__init__() 230 | self.Sconv = nn.Sequential( 231 | nn.MaxPool2d(2), nn.Conv2d(channelS, channelS, kernel_size=1), 232 | nn.BatchNorm2d(channelS), nn.ReLU(inplace=True)) 233 | self.Yconv = nn.Sequential( 234 | nn.Conv2d(channelY, channelS, kernel_size=1), 235 | nn.BatchNorm2d(channelS), nn.ReLU(inplace=True)) 236 | self.query = MultiHeadDense(channelS, bias=False) 237 | self.key = MultiHeadDense(channelS, bias=False) 238 | self.value = MultiHeadDense(channelS, bias=False) 239 | self.conv = nn.Sequential( 240 | nn.Conv2d(channelS, channelS, kernel_size=1), 241 | nn.BatchNorm2d(channelS), nn.ReLU(inplace=True), 242 | nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)) 243 | self.Yconv2 = nn.Sequential( 244 | nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True), 245 | nn.Conv2d(channelY, channelY, kernel_size=3, padding=1), 246 | nn.Conv2d(channelY, channelS, kernel_size=1), 247 | nn.BatchNorm2d(channelS), nn.ReLU(inplace=True)) 248 | self.softmax = nn.Softmax(dim=1) 249 | self.Spe = PositionalEncodingPermute2D(channelS) 250 | self.Ype = PositionalEncodingPermute2D(channelY) 251 | 252 | def forward(self, Y, S): 253 | Sb, Sc, Sh, Sw = S.size() 254 | Yb, Yc, Yh, Yw = Y.size() 255 | # Spe = self.positional_encoding_2d(Sc, Sh, Sw) 256 | Spe = self.Spe(S) 257 | S = S + Spe 258 | S1 = self.Sconv(S).reshape(Yb, Sc, Yh * Yw).permute(0, 2, 1) 259 | V = self.value(S1) 260 | # Ype = self.positional_encoding_2d(Yc, Yh, Yw) 261 | Ype = self.Ype(Y) 262 | Y = Y + Ype 263 | Y1 = self.Yconv(Y).reshape(Yb, Sc, Yh * Yw).permute(0, 2, 1) 264 | Y2 = self.Yconv2(Y) 265 | Q = self.query(Y1) 266 | K = self.key(Y1) 267 | A = self.softmax(torch.bmm(Q, K.permute(0, 2, 1)) / math.sqrt(Sc)) 268 | x = torch.bmm(A, V).permute(0, 2, 1).reshape(Yb, Sc, Yh, Yw) 269 | Z = self.conv(x) 270 | Z = Z * S 271 | Z = torch.cat([Z, Y2], dim=1) 272 | return Z 273 | 274 | 275 | class TransformerUp(nn.Module): 276 | def __init__(self, Ychannels, Schannels): 277 | super(TransformerUp, self).__init__() 278 | self.MHCA = MultiHeadCrossAttention(Ychannels, Schannels) 279 | self.conv = nn.Sequential( 280 | nn.Conv2d(Ychannels, 281 | Schannels, 282 | kernel_size=3, 283 | stride=1, 284 | padding=1, 285 | bias=True), nn.BatchNorm2d(Schannels), 286 | nn.ReLU(inplace=True), 287 | nn.Conv2d(Schannels, 288 | Schannels, 289 | kernel_size=3, 290 | stride=1, 291 | padding=1, 292 | bias=True), nn.BatchNorm2d(Schannels), 293 | nn.ReLU(inplace=True)) 294 | 295 | def forward(self, Y, S): 296 | x = self.MHCA(Y, S) 297 | x = self.conv(x) 298 | return x 299 | 300 | 301 | class U_Transformer(nn.Module): 302 | def __init__(self, in_channels, classes, bilinear=True): 303 | super(U_Transformer, self).__init__() 304 | self.in_channels = in_channels 305 | self.classes = classes 306 | self.bilinear = bilinear 307 | 308 | self.inc = DoubleConv(in_channels, 64) 309 | self.down1 = Down(64, 128) 310 | self.down2 = Down(128, 256) 311 | self.down3 = Down(256, 512) 312 | self.MHSA = MultiHeadSelfAttention(512) 313 | self.up1 = TransformerUp(512, 256) 314 | self.up2 = TransformerUp(256, 128) 315 | self.up3 = TransformerUp(128, 64) 316 | self.outc = OutConv(64, classes) 317 | 318 | def forward(self, x): 319 | x1 = self.inc(x) 320 | x2 = self.down1(x1) 321 | x3 = self.down2(x2) 322 | x4 = self.down3(x3) 323 | x4 = self.MHSA(x4) 324 | x = self.up1(x4, x3) 325 | x = self.up2(x, x2) 326 | x = self.up3(x, x1) 327 | logits = self.outc(x) 328 | return logits -------------------------------------------------------------------------------- /models/utransformer/__init__.py: -------------------------------------------------------------------------------- 1 | from .U_Transformer import U_Transformer -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | matplotlib 2 | numpy 3 | Pillow 4 | torch 5 | torchvision 6 | tensorboard 7 | future 8 | tqdm 9 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import logging 3 | import os 4 | import os.path as osp 5 | from glob import glob 6 | 7 | import numpy as np 8 | import pandas as pd 9 | import torch 10 | import torch.nn.functional as F 11 | from PIL import Image 12 | from torchvision import transforms 13 | 14 | from unet import * 15 | from utils.data_vis import plot_img_and_mask 16 | from utils.dataset import BasicDataset 17 | 18 | os.environ["CUDA_VISIBLE_DEVICES"] = "4" 19 | dir_img = osp.join("..", "unet_dataset", "images", "test") 20 | dir_mask = osp.join("..", "unet_dataset", "labels", "test") 21 | 22 | def predict_img(net, 23 | full_img, 24 | device, 25 | scale_factor=1, 26 | out_threshold=0.5): 27 | net.eval() 28 | 29 | img = torch.from_numpy(BasicDataset.preprocess(full_img, scale_factor)) 30 | 31 | img = img.unsqueeze(0) 32 | img = img.to(device=device, dtype=torch.float32) 33 | 34 | with torch.no_grad(): 35 | output = net(img) 36 | 37 | if net.n_classes > 1: 38 | probs = F.softmax(output, dim=1) 39 | else: 40 | probs = torch.sigmoid(output) 41 | 42 | probs = probs.squeeze(0) 43 | 44 | # tf = transforms.Compose( 45 | # [ 46 | # transforms.ToPILImage(), 47 | # transforms.Resize(full_img.size[1]), 48 | # transforms.ToTensor() 49 | # ] 50 | # ) 51 | 52 | # probs = tf(probs.cpu()) 53 | full_mask = probs.squeeze().cpu().numpy() 54 | 55 | return (full_mask > out_threshold) 56 | 57 | 58 | def get_args(): 59 | parser = argparse.ArgumentParser(description='Predict masks from input images', 60 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 61 | parser.add_argument('--model', '-m', default='MODEL.pth', 62 | metavar='FILE', 63 | help="Specify the file in which the model is stored") 64 | parser.add_argument('--viz', '-v', action='store_true', 65 | help="Visualize the images as they are processed", 66 | default=False) 67 | parser.add_argument('--mask-threshold', '-t', type=float, 68 | help="Minimum probability value to consider a mask pixel white", 69 | default=0.5) 70 | parser.add_argument('--scale', '-s', type=float, 71 | help="Scale factor for the input images", 72 | default=1) 73 | parser.add_argument('--model_type', type=str, default='unet', 74 | help="Model which choosed.") 75 | 76 | return parser.parse_args() 77 | 78 | 79 | def get_output_filenames(args): 80 | in_files = args.input 81 | out_files = [] 82 | 83 | if not args.output: 84 | for f in in_files: 85 | pathsplit = os.path.splitext(f) 86 | out_files.append("{}_OUT{}".format(pathsplit[0], pathsplit[1])) 87 | elif len(in_files) != len(args.output): 88 | logging.error("Input files and output files are not of the same length") 89 | raise SystemExit() 90 | else: 91 | out_files = args.output 92 | 93 | return out_files 94 | 95 | def caculate_dice(y_true, y_pred, threshold = 0.5, smooth = 0.000001): 96 | y_true = (y_true > 0.5).astype(np.int_) 97 | y_pred = (y_pred > 0.5).astype(np.int_) 98 | return (2. * np.sum(y_true * y_pred)) / (np.sum(y_true) + np.sum(y_pred) + smooth) 99 | 100 | def Evaluate(true_mask, pred_mask): 101 | """ 102 | Get the DICE/IOU between each predicted mask and each true mask. 103 | 104 | Inputs: 105 | masks_true : array-like 106 | A 2D array of shape (image_height, image_width) 107 | masks_pred : array-like 108 | A 2D array of shape (image_height, image_width) 109 | 110 | Returns: 111 | array-like 112 | A 2D array of shape (n_true_masks, n_predicted_masks), where 113 | the element at position (i, j) denotes the dice between the `i`th true 114 | mask and the `j`th predicted mask. 115 | """ 116 | assert true_mask.shape == pred_mask.shape, "Gt and pred must have same shape." 117 | height, width = true_mask.shape 118 | m_true = true_mask.copy().reshape(height * width).T 119 | m_pred = pred_mask.copy().reshape(height * width) 120 | TP = np.dot(m_pred, m_true) 121 | TN = np.dot(1 - m_pred, 1 - m_true) 122 | FP = np.dot(m_pred, 1 - m_true) 123 | FN = np.dot(1 - m_pred, m_true) 124 | dice = 2*TP/(2*TP+FP+FN) 125 | iou = TP/(TP+FP+FN) 126 | precision = TP/(TP+FP) 127 | recall = sensitivity = TP/(TP+FN) 128 | specificity = TN/(FP+TN) 129 | return dice, iou, precision, recall, specificity 130 | 131 | # def Evaluate(true_mask, pred_mask): 132 | # """ 133 | # Get the DICE/IOU between each predicted mask and each true mask. 134 | 135 | # Inputs: 136 | # masks_true : array-like 137 | # A 2D array of shape (image_height, image_width) 138 | # masks_pred : array-like 139 | # A 2D array of shape (image_height, image_width) 140 | 141 | # Returns: 142 | # array-like 143 | # A 2D array of shape (n_true_masks, n_predicted_masks), where 144 | # the element at position (i, j) denotes the dice between the `i`th true 145 | # mask and the `j`th predicted mask. 146 | # """ 147 | # assert true_mask.shape == pred_mask.shape, "Gt and pred must have same shape." 148 | # masks_true = true_mask[np.newaxis, ...] 149 | # masks_pred = pred_mask[np.newaxis, ...] 150 | # n_true_masks, height, width = masks_true.shape 151 | # n_pred_masks = masks_pred.shape[0] 152 | # m_true = masks_true.copy().reshape(n_true_masks, height * width).T 153 | # m_pred = masks_pred.copy().reshape(n_pred_masks, height * width) 154 | # numerator = np.dot(m_pred, m_true) 155 | # denominator = m_pred.sum(1).reshape(-1, 1) + m_true.sum(0).reshape(1, -1) 156 | # dice = 2*numerator / denominator 157 | # iou = numerator / (denominator - numerator) 158 | # sensitivity = numerator / m_true.sum(0).reshape(1, -1) 159 | # specificity = numerator / m_pred.sum(1).reshape(-1, 1) 160 | # return dice, iou, sensitivity, specificity 161 | 162 | def mask_to_image(mask): 163 | return Image.fromarray((mask * 255).astype(np.uint8)) 164 | 165 | 166 | if __name__ == "__main__": 167 | args = get_args() 168 | in_files = sorted(glob(osp.join(dir_img, "**", "*.npy"), recursive=True)) 169 | 170 | nets = { 171 | "unet": UNet, 172 | "inunet": InUNet, 173 | "attunet": AttU_Net, 174 | "inattunet": InAttU_Net, 175 | "att2uneta": Att2U_NetA, 176 | "att2unetb": Att2U_NetB, 177 | "att2unetc": Att2U_NetC, 178 | } 179 | try: 180 | net_type = nets[args.model_type.lower()] 181 | net = net_type(n_channels=1, n_classes=1, bilinear=True) 182 | except KeyError: 183 | os._exit(0) 184 | 185 | logging.info("Loading model {}".format(args.model)) 186 | 187 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 188 | logging.info(f'Using device {device}') 189 | net.to(device=device) 190 | net.load_state_dict(torch.load(args.model, map_location=device)) 191 | 192 | logging.info("Model loaded !") 193 | 194 | n = len(in_files) 195 | test_res = [] 196 | print("main_id\t\t\t\tdice\t\t\tiou\t\t\tprecision\t\tsensitivity/recall\tspecificity") 197 | TN = TP = FP = FN = 0 198 | for i, fn in enumerate(in_files): 199 | main_id = osp.basename(fn).split(".")[0] 200 | logging.info("\nPredicting image {} ...".format(fn)) 201 | 202 | img = np.load(fn) 203 | 204 | pred_mask = predict_img(net=net, 205 | full_img=img, 206 | scale_factor=args.scale, 207 | out_threshold=args.mask_threshold, 208 | device=device).astype(np.int) 209 | true_mask = np.load(fn.replace("images", "labels")) 210 | dice, iou, precision, recall, specificity = Evaluate(true_mask, pred_mask) 211 | print(f"{i+1}/{n}-{main_id}:\t{dice}\t{iou}\t{precision}\t{recall}\t{specificity}") 212 | test_res.append((main_id, dice, iou, precision, recall, specificity)) 213 | if dice == 0: 214 | if pred_mask.sum() == 0 and true_mask.sum() != 0: 215 | FN += 1 216 | elif pred_mask.sum() != 0 and true_mask.sum() == 0: 217 | FP += 1 218 | elif pred_mask.sum() == 0 and true_mask.sum() == 0: 219 | TN += 1 220 | else: 221 | TP += 1 222 | if args.viz: 223 | logging.info("Visualizing results for image {}, close to continue ...".format(fn)) 224 | plot_img_and_mask(img, mask) 225 | 226 | test_res.sort(key = lambda x:x[0]) 227 | ids, dice, iou, precision, recall, specificity = zip(*test_res) 228 | dice_max = np.max(dice) 229 | dice_min = np.min(dice) 230 | dice_mean = np.mean(dice) 231 | dice_var = np.var(dice) 232 | print("dice_max: {}, dice_min: {}, dice_mean: {}, dice_var: {}".format(dice_max, dice_min, dice_mean, dice_var)) 233 | print(f"bump TP: {TP}, TN: {TN}, FP: {FP}, FN: {FN}") 234 | 235 | writer = pd.ExcelWriter(osp.join(osp.dirname(args.model), "test_res.xlsx")) 236 | 237 | res = { 238 | "id": ids, 239 | "dice": dice, 240 | "iou": iou, 241 | "precisions": precision, 242 | "sensitivity/recall": recall, 243 | "specificity": specificity, 244 | } 245 | res = pd.DataFrame(res) 246 | res.to_excel(writer, sheet_name="result", index=False) 247 | 248 | writer.close() 249 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | # %% 2 | import argparse 3 | import logging 4 | import os 5 | import os.path as osp 6 | import sys 7 | 8 | import numpy as np 9 | import torch 10 | import torch.nn as nn 11 | from torch import optim 12 | from torch.cuda import amp 13 | from torch.nn.modules import activation 14 | from torch.nn.modules.activation import Threshold 15 | from tqdm import tqdm 16 | 17 | from eval import eval_net 18 | 19 | from torch.utils.tensorboard import SummaryWriter 20 | from torch.utils.data import DataLoader, random_split 21 | from torch.utils.data.distributed import DistributedSampler 22 | import utils 23 | import models 24 | from utils.dataset import BasicDataset 25 | # %% 26 | logger = logging.getLogger(__name__) 27 | 28 | dir_img = osp.join("..", "unet_dataset", "images", "trainval") 29 | dir_mask = osp.join("..", "unet_dataset", "labels", "trainval") 30 | 31 | 32 | def is_parallel(model): 33 | return type(model) in (nn.parallel.DataParallel, 34 | nn.parallel.DistributedDataParallel) 35 | 36 | 37 | def get_args(): 38 | parser = argparse.ArgumentParser( 39 | description='Train the UNet on images and target masks', 40 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 41 | parser.add_argument('-e', 42 | '--epochs', 43 | metavar='E', 44 | type=int, 45 | default=5, 46 | help='Number of epochs', 47 | dest='epochs') 48 | parser.add_argument('-b', 49 | '--batch_size', 50 | metavar='B', 51 | type=int, 52 | nargs='?', 53 | default=1, 54 | help='Batch size', 55 | dest='batchsize') 56 | parser.add_argument('-l', 57 | '--learning_rate', 58 | metavar='LR', 59 | type=float, 60 | nargs='?', 61 | default=0.0001, 62 | help='Learning rate', 63 | dest='lr') 64 | parser.add_argument('-f', 65 | '--load', 66 | dest='load', 67 | type=str, 68 | default=False, 69 | help='Load model from a .pth file') 70 | parser.add_argument('-s', 71 | '--scale', 72 | dest='scale', 73 | type=float, 74 | default=0.5, 75 | help='Downscaling factor of the images') 76 | parser.add_argument('-v', 77 | '--validation', 78 | dest='val', 79 | type=float, 80 | default=0.1, 81 | help='Percent of the data \ 82 | that is used as validation (0-100)') 83 | parser.add_argument('-d', 84 | '--device', 85 | default='', 86 | help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 87 | parser.add_argument('--local_rank', 88 | type=int, 89 | default=-1, 90 | help='DDP parameter, do not modify') 91 | parser.add_argument('--model_type', 92 | type=str, 93 | default='unet', 94 | help="Model which choosed.") 95 | parser.add_argument('--split_seed', type=int, default=None, help='') 96 | return parser.parse_args() 97 | 98 | 99 | def select_device(device='', batch_size=None): 100 | # device = 'cpu' or '0' or '0,1,2,3' 101 | s = f'UNetHX torch {torch.__version__} ' 102 | cpu = device.lower() == 'cpu' 103 | if cpu: 104 | os.environ[ 105 | 'CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False 106 | elif device: # non-cpu device requested 107 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable 108 | assert torch.cuda.is_available( 109 | ), f'CUDA unavailable, invalid device {device} requested' # check availability 110 | 111 | cuda = not cpu and torch.cuda.is_available() 112 | if cuda: 113 | n = torch.cuda.device_count() 114 | if n > 1 and batch_size: # check that batch_size is compatible with device_count 115 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' 116 | space = ' ' * len(s) 117 | for i, d in enumerate(device.split(',') if device else range(n)): 118 | p = torch.cuda.get_device_properties(i) 119 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB 120 | else: 121 | s += 'CPU\n' 122 | 123 | logger.info(s) # skip a line 124 | return torch.device('cuda:0' if cuda else 'cpu') 125 | 126 | 127 | def train_net(model, 128 | device, 129 | epochs=5, 130 | batch_size=1, 131 | lr=0.001, 132 | val_percent=0.1, 133 | save_all_cp=True, 134 | dir_checkpoint='runs', 135 | split_seed=None): 136 | 137 | dataset = BasicDataset(dir_img, dir_mask) 138 | n_val = int(len(dataset) * 139 | val_percent) if val_percent < 1 else int(val_percent) 140 | n_train = len(dataset) - n_val 141 | if split_seed: 142 | train, val = random_split( 143 | dataset, [n_train, n_val], 144 | generator=torch.Generator().manual_seed(split_seed)) 145 | else: 146 | train, val = random_split(dataset, [n_train, n_val]) 147 | if type(model) == nn.parallel.DistributedDataParallel: 148 | train_loader = DataLoader(train, 149 | batch_size=batch_size, 150 | shuffle=False, 151 | num_workers=0, 152 | pin_memory=True, 153 | sampler=DistributedSampler(train)) 154 | val_loader = DataLoader(val, 155 | batch_size=batch_size, 156 | shuffle=False, 157 | num_workers=0, 158 | pin_memory=True, 159 | drop_last=True, 160 | sampler=DistributedSampler(val)) 161 | else: 162 | train_loader = DataLoader(train, 163 | batch_size=batch_size, 164 | shuffle=True, 165 | num_workers=8, 166 | pin_memory=True) 167 | val_loader = DataLoader(val, 168 | batch_size=batch_size, 169 | shuffle=False, 170 | num_workers=8, 171 | pin_memory=True, 172 | drop_last=True) 173 | 174 | logging.info(f'''Starting training: 175 | Epochs: {epochs} 176 | Batch size: {batch_size} 177 | Learning rate: {lr} 178 | Training size: {n_train} 179 | Validation size: {n_val} 180 | Checkpoints: {save_all_cp} 181 | Device: {device.type} 182 | ''') 183 | 184 | # loss = nn.BCEWithLogitsLoss() 185 | # loss.__name__ = 'BCEWithLogitLoss' 186 | # loss = nn.BCELoss() 187 | # loss.__name__ = 'BCELoss' 188 | loss = utils.losses.NoiseRobustDiceLoss(eps=1e-7, activation='sigmoid') 189 | metrics = [ 190 | utils.metrics.Dice(threshold=0.5, activation='sigmoid'), 191 | utils.metrics.Fscore(threshold=None, activation='sigmoid') 192 | ] 193 | optimizer = torch.optim.Adam([ 194 | dict(params=model.parameters(), lr=lr), 195 | ]) 196 | 197 | train_epoch = utils.train.TrainEpoch( 198 | model, 199 | loss=loss, 200 | metrics=metrics, 201 | optimizer=optimizer, 202 | device=device, 203 | verbose=True, 204 | ) 205 | valid_epoch = utils.train.ValidEpoch( 206 | model, 207 | loss=loss, 208 | metrics=metrics, 209 | device=device, 210 | verbose=True, 211 | ) 212 | 213 | max_score = 0 214 | os.makedirs(dir_checkpoint, exist_ok=True) 215 | for i in range(0, epochs): 216 | print('\nEpoch: {}'.format(i + 1)) 217 | train_logs = train_epoch.run(train_loader) 218 | valid_logs = valid_epoch.run(val_loader) 219 | 220 | # do something (save model, change lr, etc.) 221 | if max_score < valid_logs['dice_score']: 222 | max_score = valid_logs['dice_score'] 223 | torch.save(model, osp.join(dir_checkpoint, 'best_model.pt')) 224 | torch.save(model.state_dict(), 225 | osp.join(dir_checkpoint, 'best_model_dict.pth')) 226 | print('Model saved!') 227 | 228 | if save_all_cp: 229 | torch.save(model.state_dict(), 230 | osp.join(dir_checkpoint, f'CP_epoch{i + 1}.pth')) 231 | # writer = SummaryWriter(log_dir=dir_checkpoint) 232 | # global_step = 0 233 | 234 | # optimizer = optim.RMSprop(net.parameters(), 235 | # lr=lr, 236 | # weight_decay=1e-8, 237 | # momentum=0.9) 238 | # scheduler = optim.lr_scheduler.ReduceLROnPlateau( 239 | # optimizer, 'min' if net.n_classes > 1 else 'max', patience=2) 240 | # if net.n_classes > 1: 241 | # criterion = nn.CrossEntropyLoss() 242 | # else: 243 | # criterion = nn.BCEWithLogitsLoss() 244 | 245 | # for epoch in range(epochs): 246 | # net.train() 247 | 248 | # epoch_loss = 0 249 | # with tqdm(total=n_train, 250 | # desc=f'Epoch {epoch + 1}/{epochs}', 251 | # unit='img') as pbar: 252 | # for batch in train_loader: 253 | # imgs = batch['image'] 254 | # true_masks = batch['mask'] 255 | # assert imgs.shape[1] == net.n_channels, \ 256 | # f'Network has been defined with {net.n_channels} input channels, ' \ 257 | # f'but loaded images have {imgs.shape[1]} channels. Please check that ' \ 258 | # 'the images are loaded correctly.' 259 | 260 | # imgs = imgs.to(device=device, dtype=torch.float32) 261 | # mask_type = torch.float32 if net.n_classes == 1 else torch.long 262 | # true_masks = true_masks.to(device=device, dtype=mask_type) 263 | 264 | # masks_pred = net(imgs) 265 | # loss = criterion(masks_pred, true_masks) 266 | # epoch_loss += loss.item() 267 | # writer.add_scalar('Loss/train', loss.item(), global_step) 268 | 269 | # pbar.set_postfix(**{'loss (batch)': loss.item()}) 270 | 271 | # optimizer.zero_grad() 272 | # loss.backward() 273 | # # for name, param in net.named_parameters(): 274 | # # print(name, param.grad) 275 | # nn.utils.clip_grad_value_(net.parameters(), 0.1) 276 | # optimizer.step() 277 | 278 | # pbar.update(imgs.shape[0]) 279 | # global_step += 1 280 | # if global_step % (n_train // (10 * batch_size)) == 0: 281 | # for tag, value in net.named_parameters(): 282 | # try: 283 | # tag = tag.replace('.', '/') 284 | # writer.add_histogram('weights/' + tag, 285 | # value.data.cpu().numpy(), 286 | # global_step) 287 | # writer.add_histogram('grads/' + tag, 288 | # value.grad.data.cpu().numpy(), 289 | # global_step) 290 | # except AttributeError: 291 | # pass 292 | # val_score = eval_net(net, val_loader, device) 293 | # scheduler.step(val_score) 294 | # writer.add_scalar('learning_rate', 295 | # optimizer.param_groups[0]['lr'], 296 | # global_step) 297 | 298 | # if net.n_classes > 1: 299 | # logging.info( 300 | # 'Validation cross entropy: {}'.format(val_score)) 301 | # writer.add_scalar('Loss/test', val_score, global_step) 302 | # else: 303 | # logging.info( 304 | # 'Validation Dice Coeff: {}'.format(val_score)) 305 | # writer.add_scalar('Dice/test', val_score, global_step) 306 | 307 | # writer.add_images('images', imgs, global_step) 308 | # if net.n_classes == 1: 309 | # writer.add_images('masks/true', true_masks, 310 | # global_step) 311 | # writer.add_images('masks/pred', 312 | # torch.sigmoid(masks_pred) > 0.5, 313 | # global_step) 314 | 315 | # if save_cp: 316 | # try: 317 | # os.mkdir(dir_checkpoint) 318 | # logging.info('Created checkpoint directory') 319 | # except OSError: 320 | # pass 321 | # torch.save(net.state_dict(), 322 | # osp.join(dir_checkpoint, f'CP_epoch{epoch + 1}.pth')) 323 | # logging.info(f'Checkpoint {epoch + 1} saved !') 324 | 325 | # writer.close() 326 | 327 | 328 | if __name__ == '__main__': 329 | logging.basicConfig(level=logging.INFO, 330 | format='%(levelname)s: %(message)s') 331 | args = get_args() 332 | # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 333 | device = select_device(args.device, batch_size=args.batchsize) 334 | logging.info(f'Using device {device}') 335 | 336 | import socket 337 | from datetime import datetime 338 | current_time = datetime.now().strftime('%b%d_%H-%M-%S') 339 | comment = f'MT_{args.model_type}_SS_{args.split_seed}_LR_{args.lr}_BS_{args.batchsize}' 340 | dir_checkpoint = osp.join( 341 | ".", "checkpoints", 342 | f"{current_time}_{socket.gethostname()}_" + comment) 343 | # Change here to adapt to your data 344 | # n_channels=3 for RGB images 345 | # n_classes is the number of probabilities you want to get per pixel 346 | # - For 1 class and background, use n_classes=1 347 | # - For 2 classes, use n_classes=1 348 | # - For N > 2 classes, use n_classes=N 349 | nets = { 350 | # "unet": models.UNet, 351 | # "inunet": InUNet, 352 | # "attunet": AttU_Net, 353 | # "inattunet": InAttU_Net, 354 | # "att2uneta": Att2U_NetA, 355 | # "att2unetb": Att2U_NetB, 356 | # "att2unetc": Att2U_NetC, 357 | # "ecaunet": ECAU_Net, 358 | # "gsaunet": GsAUNet, 359 | # "utnet": U_Transformer, 360 | "ddrnet": models.DualResNet, 361 | "utrans": models.U_Transformer, 362 | } 363 | try: 364 | net_type = nets[args.model_type.lower()] 365 | net = net_type(in_channels=1, classes=1) 366 | except KeyError: 367 | os._exit(0) 368 | net.to(device=device) 369 | # net.apply(weight_init) 370 | 371 | cuda = device.type != 'cpu' 372 | # DP mode 373 | if cuda and args.local_rank == -1 and torch.cuda.device_count() > 1: 374 | print(f"DP Use multiple gpus: {args.device}") 375 | net = nn.DataParallel(net) 376 | # DDP mode 377 | if cuda and args.local_rank != -1 and torch.cuda.device_count() > 1: 378 | print(f"DDP Use multiple gpus: {args.device}") 379 | assert torch.cuda.device_count() > args.local_rank 380 | device = torch.device('cuda', args.local_rank) 381 | torch.distributed.init_process_group(backend="nccl") 382 | net = nn.parallel.DistributedDataParallel(net) 383 | net = net.to(device=device) 384 | 385 | net = net.module if is_parallel(net) else net 386 | net = net.to(device=device) 387 | # logging.info( 388 | # f'Network:\n' 389 | # f'\t{net.n_channels} input channels\n' 390 | # f'\t{net.n_classes} output channels (classes)\n' 391 | # f'\t{"Bilinear" if net.bilinear else "Transposed conv"} upscaling') 392 | 393 | if args.load: 394 | net.load_state_dict(torch.load(args.load, map_location=device)) 395 | logging.info(f'Model loaded from {args.load}') 396 | 397 | train_net(model=net, 398 | epochs=args.epochs, 399 | batch_size=args.batchsize, 400 | lr=args.lr, 401 | device=device, 402 | val_percent=args.val, 403 | dir_checkpoint=dir_checkpoint, 404 | split_seed=args.split_seed, 405 | save_all_cp=True) 406 | 407 | # %% 408 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | from . import train 2 | from . import losses 3 | from . import metrics 4 | from . import dataset -------------------------------------------------------------------------------- /utils/base.py: -------------------------------------------------------------------------------- 1 | import re 2 | import torch 3 | import torch.nn as nn 4 | 5 | 6 | class BaseObject(nn.Module): 7 | def __init__(self, name=None): 8 | super().__init__() 9 | self._name = name 10 | 11 | @property 12 | def __name__(self): 13 | if self._name is None: 14 | name = self.__class__.__name__ 15 | s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) 16 | return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() 17 | else: 18 | return self._name 19 | 20 | 21 | class Metric(BaseObject): 22 | pass 23 | 24 | 25 | class Loss(BaseObject): 26 | def __add__(self, other): 27 | if isinstance(other, Loss): 28 | return SumOfLosses(self, other) 29 | else: 30 | raise ValueError('Loss should be inherited from `Loss` class') 31 | 32 | def __radd__(self, other): 33 | return self.__add__(other) 34 | 35 | def __mul__(self, value): 36 | if isinstance(value, (int, float)): 37 | return MultipliedLoss(self, value) 38 | else: 39 | raise ValueError('Loss should be inherited from `BaseLoss` class') 40 | 41 | def __rmul__(self, other): 42 | return self.__mul__(other) 43 | 44 | 45 | class SumOfLosses(Loss): 46 | def __init__(self, l1, l2): 47 | name = '{} + {}'.format(l1.__name__, l2.__name__) 48 | super().__init__(name=name) 49 | self.l1 = l1 50 | self.l2 = l2 51 | 52 | def __call__(self, *inputs): 53 | return self.l1.forward(*inputs) + self.l2.forward(*inputs) 54 | 55 | 56 | # # class Loss(BaseObject): 57 | # # def __add__(self, *other): 58 | # # assert len(other) > 1 59 | # # if isinstance(other[0], Loss): 60 | # # res = SumOfLosses(self, other[0]) 61 | # # else: 62 | # # raise ValueError('Loss should be inherited from `Loss` class') 63 | # # for x in other[1:]: 64 | # # if isinstance(x, Loss): 65 | # # res += SumOfLosses(self, x) 66 | # # else: 67 | # # raise ValueError('Loss should be inherited from `Loss` class') 68 | # # return res 69 | 70 | # def __radd__(self, other): 71 | # return self.__add__(other) 72 | 73 | # def __mul__(self, value): 74 | # if isinstance(value, (int, float)): 75 | # return MultipliedLoss(self, value) 76 | # else: 77 | # raise ValueError('Loss should be inherited from `BaseLoss` class') 78 | 79 | # def __rmul__(self, other): 80 | # return self.__mul__(other) 81 | 82 | # class SumOfLosses(Loss): 83 | # def __init__(self, *losses): 84 | # name = "" 85 | # for loss in losses: 86 | # name += '{} + '.format(loss.__name__) 87 | # name = name[:-3] 88 | # super().__init__(name=name) 89 | # self.losses = losses 90 | 91 | # def __call__(self, *inputs): 92 | # assert len(self.losses) > 1 93 | # res = self.losses[0].forward(*inputs) 94 | # for loss in self.losses[1:]: 95 | # res += loss.forward(*inputs) 96 | # return res 97 | 98 | 99 | class MultipliedLoss(Loss): 100 | def __init__(self, loss, multiplier): 101 | 102 | # resolve name 103 | if len(loss.__name__.split('+')) > 1: 104 | name = '{} * ({})'.format(multiplier, loss.__name__) 105 | else: 106 | name = '{} * {}'.format(multiplier, loss.__name__) 107 | super().__init__(name=name) 108 | self.loss = loss 109 | self.multiplier = multiplier 110 | 111 | def __call__(self, *inputs): 112 | return self.multiplier * self.loss.forward(*inputs) 113 | -------------------------------------------------------------------------------- /utils/data_vis.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | 4 | def plot_img_and_mask(img, mask): 5 | classes = mask.shape[2] if len(mask.shape) > 2 else 1 6 | fig, ax = plt.subplots(1, classes + 1) 7 | ax[0].set_title('Input image') 8 | ax[0].imshow(img) 9 | if classes > 1: 10 | for i in range(classes): 11 | ax[i+1].set_title(f'Output mask (class {i+1})') 12 | ax[i+1].imshow(mask[:, :, i]) 13 | else: 14 | ax[1].set_title(f'Output mask') 15 | ax[1].imshow(mask) 16 | plt.xticks([]), plt.yticks([]) 17 | plt.show() 18 | -------------------------------------------------------------------------------- /utils/dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path as osp 3 | import numpy as np 4 | from glob import glob 5 | import torch 6 | from torch.utils.data import Dataset 7 | import logging 8 | from PIL import Image 9 | 10 | 11 | class BasicDataset(Dataset): 12 | def __init__(self, imgs_dir, masks_dir, mask_suffix=''): 13 | self.imgs_dir = imgs_dir 14 | self.masks_dir = masks_dir 15 | self.mask_suffix = mask_suffix 16 | 17 | self.ids = [ 18 | osp.splitext(file)[0] for file in os.listdir(imgs_dir) 19 | if not file.startswith('.') 20 | ] 21 | logging.info(f'Creating dataset with {len(self.ids)} examples') 22 | 23 | def __len__(self): 24 | return len(self.ids) 25 | 26 | @classmethod 27 | def preprocess(cls, img_nd): 28 | if len(img_nd.shape) == 2: 29 | img_nd = np.expand_dims(img_nd, axis=2) 30 | # img_nd = np.repeat(img_nd, 3, 2) # make 1 channel pic to 3 channels pic 31 | 32 | # HWC to CHW 33 | img_trans = img_nd.transpose((2, 0, 1)) 34 | 35 | if 255 >= img_trans.max() > 1 and img_trans.min() > 0: 36 | # Normally UINT8 pic 37 | img_trans = img_trans / 255.0 38 | elif 0 < img_trans.all() <= 1: 39 | # Normally FLOAT pic 40 | pass 41 | else: 42 | # DICOM pic 43 | pass 44 | 45 | return img_trans 46 | 47 | def __getitem__(self, i): 48 | idx = self.ids[i] 49 | # print( 50 | # self.masks_dir, 51 | # idx, 52 | # self.mask_suffix, #0.5 53 | # ) 54 | mask_file = glob( 55 | osp.join(self.masks_dir, idx + self.mask_suffix + '.*')) 56 | img_file = glob(osp.join(self.imgs_dir, idx + '.*')) 57 | 58 | assert len(mask_file) == 1, \ 59 | f'Either no mask or multiple masks found for the ID {idx}: {mask_file}' 60 | assert len(img_file) == 1, \ 61 | f'Either no image or multiple images found for the ID {idx}: {img_file}' 62 | mask = np.load(mask_file[0]) 63 | img = np.load(img_file[0]) 64 | 65 | assert img.size == mask.size, \ 66 | f'Image and mask {idx} should be the same size, but are {img.size} and {mask.size}' 67 | 68 | img = self.preprocess(img) 69 | mask = self.preprocess(mask) 70 | 71 | return torch.from_numpy(img).type( 72 | torch.FloatTensor), torch.from_numpy(mask).type(torch.FloatTensor) 73 | 74 | 75 | class CarvanaDataset(BasicDataset): 76 | def __init__(self, imgs_dir, masks_dir, scale=1): 77 | super().__init__(imgs_dir, masks_dir, scale, mask_suffix='_mask') 78 | -------------------------------------------------------------------------------- /utils/functional.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | def _take_channels(*xs, ignore_channels=None): 5 | if ignore_channels is None: 6 | return xs 7 | else: 8 | channels = [ 9 | channel for channel in range(xs[0].shape[1]) 10 | if channel not in ignore_channels 11 | ] 12 | xs = [ 13 | torch.index_select(x, 14 | dim=1, 15 | index=torch.tensor(channels).to(x.device)) 16 | for x in xs 17 | ] 18 | return xs 19 | 20 | 21 | def _threshold(x, threshold=None): 22 | if threshold is not None: 23 | return (x > threshold).type(x.dtype) 24 | else: 25 | return x 26 | 27 | 28 | def iou(pr, gt, eps=1e-7, threshold=None, ignore_channels=None): 29 | """Calculate Intersection over Union between ground truth and prediction 30 | Args: 31 | pr (torch.Tensor): predicted tensor 32 | gt (torch.Tensor): ground truth tensor 33 | eps (float): epsilon to avoid zero division 34 | threshold: threshold for outputs binarization 35 | Returns: 36 | float: IoU (Jaccard) score 37 | """ 38 | 39 | pr = _threshold(pr, threshold=threshold) 40 | pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels) 41 | 42 | intersection = torch.sum(gt * pr) 43 | union = torch.sum(gt) + torch.sum(pr) - intersection + eps 44 | return (intersection + eps) / union 45 | 46 | 47 | jaccard = iou 48 | 49 | 50 | def dice(pr, gt, eps=1e-7, threshold=None, ignore_channels=None): 51 | """Calculate Dice cofficient between ground truth and prediction 52 | Args: 53 | pr (torch.Tensor): predicted tensor 54 | gt (torch.Tensor): ground truth tensor 55 | eps (float): epsilon to avoid zero division 56 | threshold: threshold for outputs binarization 57 | Returns: 58 | float: dice score 59 | """ 60 | 61 | pr = _threshold(pr, threshold=threshold) 62 | pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels) 63 | 64 | intersection = torch.sum(gt * pr) 65 | union = torch.sum(gt) + torch.sum(pr) - intersection + eps 66 | return (2 * intersection + eps) / (union + intersection) 67 | 68 | 69 | def noise_robust_dice(pr, 70 | gt, 71 | eps=1e-7, 72 | gamma=1.5, 73 | threshold=None, 74 | ignore_channels=None): 75 | """Calculate Noise Robust Dice cofficient between ground truth and prediction 76 | Args: 77 | pr (torch.Tensor): predicted tensor 78 | gt (torch.Tensor): ground truth tensor 79 | eps (float): epsilon to avoid zero division 80 | gamma: scalar, [1.0, 2.0]. 81 | When γ = 2.0, LNR-Dice equals to the Dice loss LDice. 82 | When γ = 1.0, LNR-Dice becomes a weighted version of LMAE. 83 | threshold: threshold for outputs binarization 84 | Returns: 85 | float: dice score 86 | """ 87 | 88 | pr = _threshold(pr, threshold=threshold) 89 | pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels) 90 | 91 | intersection = torch.sum(torch.pow(torch.abs(pr - gt), gamma)) 92 | union = torch.sum(torch.square(gt)) + torch.sum(torch.square(pr)) + eps 93 | return 1 - intersection / union 94 | 95 | 96 | def tversky(pr, 97 | gt, 98 | eps=1e-7, 99 | alpha=0.5, 100 | beta=0.5, 101 | threshold=None, 102 | ignore_channels=None): 103 | """Calculate tversky cofficient between ground truth and prediction 104 | Args: 105 | pr (torch.Tensor): predicted tensor 106 | gt (torch.Tensor): ground truth tensor 107 | eps (float): epsilon to avoid zero division 108 | threshold: threshold for outputs binarization 109 | Returns: 110 | float: dice score 111 | """ 112 | 113 | pr = _threshold(pr, threshold=threshold) 114 | pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels) 115 | 116 | tp = torch.sum(gt * pr) 117 | fp = torch.sum(pr) - tp 118 | fn = torch.sum(gt) - tp 119 | 120 | tversky = (tp + eps) / (tp + alpha * fn + beta * fp + eps) 121 | return tversky 122 | 123 | 124 | def f_score(pr, gt, beta=1, eps=1e-7, threshold=None, ignore_channels=None): 125 | """Calculate F-score between ground truth and prediction 126 | Args: 127 | pr (torch.Tensor): predicted tensor 128 | gt (torch.Tensor): ground truth tensor 129 | beta (float): positive constant 130 | eps (float): epsilon to avoid zero division 131 | threshold: threshold for outputs binarization 132 | Returns: 133 | float: F score 134 | """ 135 | 136 | pr = _threshold(pr, threshold=threshold) 137 | pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels) 138 | 139 | tp = torch.sum(gt * pr) 140 | fp = torch.sum(pr) - tp 141 | fn = torch.sum(gt) - tp 142 | 143 | score = ((1 + beta ** 2) * tp + eps) \ 144 | / ((1 + beta ** 2) * tp + beta ** 2 * fn + fp + eps) 145 | 146 | return score 147 | 148 | 149 | def binary_cross_entropy(pr, 150 | gt, 151 | pos_weight=1, 152 | reduction='mean', 153 | threshold=None, 154 | ignore_channels=None): 155 | """Calculate binary cross entropy between ground truth and prediction 156 | Args: 157 | pr (torch.Tensor): predicted tensor 158 | gt (torch.Tensor): ground truth tensor 159 | threshold: threshold for outputs binarization 160 | Returns: 161 | float: binary cross entropy 162 | """ 163 | 164 | pr = _threshold(pr, threshold=threshold) 165 | pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels) 166 | 167 | bce = pos_weight * gt * torch.log(pr) + (1 - gt) * torch.log(1 - pr) 168 | if reduction == 'mean': 169 | bce = bce.mean() 170 | elif reduction == 'sum': 171 | bce = bce.sum() 172 | return bce 173 | 174 | 175 | def accuracy(pr, gt, threshold=0.5, ignore_channels=None): 176 | """Calculate accuracy score between ground truth and prediction 177 | Args: 178 | pr (torch.Tensor): predicted tensor 179 | gt (torch.Tensor): ground truth tensor 180 | eps (float): epsilon to avoid zero division 181 | threshold: threshold for outputs binarization 182 | Returns: 183 | float: precision score 184 | """ 185 | pr = _threshold(pr, threshold=threshold) 186 | pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels) 187 | 188 | tp = torch.sum(gt == pr, dtype=pr.dtype) 189 | score = tp / gt.view(-1).shape[0] 190 | return score 191 | 192 | 193 | def precision(pr, gt, eps=1e-7, threshold=None, ignore_channels=None): 194 | """Calculate precision score between ground truth and prediction 195 | Args: 196 | pr (torch.Tensor): predicted tensor 197 | gt (torch.Tensor): ground truth tensor 198 | eps (float): epsilon to avoid zero division 199 | threshold: threshold for outputs binarization 200 | Returns: 201 | float: precision score 202 | """ 203 | 204 | pr = _threshold(pr, threshold=threshold) 205 | pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels) 206 | 207 | tp = torch.sum(gt * pr) 208 | fp = torch.sum(pr) - tp 209 | 210 | score = (tp + eps) / (tp + fp + eps) 211 | 212 | return score 213 | 214 | 215 | def recall(pr, gt, eps=1e-7, threshold=None, ignore_channels=None): 216 | """Calculate Recall between ground truth and prediction 217 | Args: 218 | pr (torch.Tensor): A list of predicted elements 219 | gt (torch.Tensor): A list of elements that are to be predicted 220 | eps (float): epsilon to avoid zero division 221 | threshold: threshold for outputs binarization 222 | Returns: 223 | float: recall score 224 | """ 225 | 226 | pr = _threshold(pr, threshold=threshold) 227 | pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels) 228 | 229 | tp = torch.sum(gt * pr) 230 | fn = torch.sum(gt) - tp 231 | 232 | score = (tp + eps) / (tp + fn + eps) 233 | 234 | return score 235 | -------------------------------------------------------------------------------- /utils/losses.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch 3 | 4 | from . import base 5 | from . import functional as F 6 | from .metrics import Activation 7 | 8 | 9 | class JaccardLoss(base.Loss): 10 | def __init__(self, 11 | eps=1., 12 | activation=None, 13 | ignore_channels=None, 14 | **kwargs): 15 | super().__init__(**kwargs) 16 | self.eps = eps 17 | self.activation = Activation(activation) 18 | self.ignore_channels = ignore_channels 19 | 20 | def forward(self, y_pr, y_gt): 21 | y_pr = self.activation(y_pr) 22 | return 1 - F.jaccard( 23 | y_pr, 24 | y_gt, 25 | eps=self.eps, 26 | threshold=None, 27 | ignore_channels=self.ignore_channels, 28 | ) 29 | 30 | 31 | class DiceLoss(base.Loss): 32 | def __init__(self, 33 | eps=1., 34 | activation=None, 35 | ignore_channels=None, 36 | **kwargs): 37 | super().__init__(**kwargs) 38 | self.eps = eps 39 | self.activation = Activation(activation) 40 | self.ignore_channels = ignore_channels 41 | 42 | def forward(self, y_pr, y_gt): 43 | y_pr = self.activation(y_pr) 44 | return 1 - F.dice( 45 | y_pr, 46 | y_gt, 47 | eps=self.eps, 48 | threshold=None, 49 | ignore_channels=self.ignore_channels, 50 | ) 51 | 52 | 53 | class NoiseRobustDiceLoss(base.Loss): 54 | def __init__(self, 55 | eps=1., 56 | activation=None, 57 | gamma=1.5, 58 | ignore_channels=None, 59 | **kwargs): 60 | super().__init__(**kwargs) 61 | self.eps = eps 62 | self.activation = Activation(activation) 63 | self.gamma = gamma 64 | self.ignore_channels = ignore_channels 65 | 66 | def forward(self, y_pr, y_gt): 67 | y_pr = self.activation(y_pr) 68 | return 1 - F.noise_robust_dice( 69 | y_pr, 70 | y_gt, 71 | eps=self.eps, 72 | threshold=None, 73 | gamma=self.gamma, 74 | ignore_channels=self.ignore_channels, 75 | ) 76 | 77 | 78 | class TverskyLoss(base.Loss): 79 | def __init__(self, 80 | eps=1., 81 | activation=None, 82 | alpha=0.5, 83 | beta=0.5, 84 | ignore_channles=None, 85 | **kwargs): 86 | super().__init__(**kwargs) 87 | self.eps = eps 88 | self.activation = Activation(activation) 89 | self.alpha = alpha 90 | self.beta = beta 91 | self.ignore_channels = ignore_channles 92 | 93 | def forward(self, y_pr, y_gt): 94 | return 1 - F.tversky( 95 | y_pr, 96 | y_gt, 97 | eps=self.eps, 98 | threshold=None, 99 | alpha=self.alpha, 100 | beta=self.beta, 101 | ignore_channels=self.ignore_channels, 102 | ) 103 | 104 | 105 | class FLoss(base.Loss): 106 | def __init__(self, 107 | eps=1., 108 | beta=1., 109 | activation=None, 110 | ignore_channels=None, 111 | **kwargs): 112 | super().__init__(**kwargs) 113 | self.eps = eps 114 | self.beta = beta 115 | self.activation = Activation(activation) 116 | self.ignore_channels = ignore_channels 117 | 118 | def forward(self, y_pr, y_gt): 119 | y_pr = self.activation(y_pr) 120 | return 1 - F.f_score( 121 | y_pr, 122 | y_gt, 123 | eps=self.eps, 124 | beta=self.beta, 125 | threshold=None, 126 | ignore_channels=self.ignore_channels, 127 | ) 128 | 129 | 130 | class L1Loss(nn.L1Loss, base.Loss): 131 | pass 132 | 133 | 134 | class MSELoss(nn.MSELoss, base.Loss): 135 | pass 136 | 137 | 138 | class CrossEntropyLoss(nn.CrossEntropyLoss, base.Loss): 139 | pass 140 | 141 | 142 | class NLLLoss(nn.NLLLoss, base.Loss): 143 | pass 144 | 145 | 146 | class BCELoss(nn.BCELoss, base.Loss): 147 | pass 148 | 149 | 150 | class BCEWithLogitsLoss(nn.BCEWithLogitsLoss, base.Loss): 151 | pass 152 | -------------------------------------------------------------------------------- /utils/meter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | class Meter(object): 5 | '''Meters provide a way to keep track of important statistics in an online manner. 6 | This class is abstract, but provides a standard interface for all meters to follow. 7 | ''' 8 | 9 | def reset(self): 10 | '''Resets the meter to default settings.''' 11 | pass 12 | 13 | def add(self, value): 14 | '''Log a new value to the meter 15 | Args: 16 | value: Next result to include. 17 | ''' 18 | pass 19 | 20 | def value(self): 21 | '''Get the value of the meter in the current state.''' 22 | pass 23 | 24 | 25 | class AverageValueMeter(Meter): 26 | def __init__(self): 27 | super(AverageValueMeter, self).__init__() 28 | self.reset() 29 | self.val = 0 30 | 31 | def add(self, value, n=1): 32 | self.val = value 33 | self.sum += value 34 | self.var += value * value 35 | self.n += n 36 | 37 | if self.n == 0: 38 | self.mean, self.std = np.nan, np.nan 39 | elif self.n == 1: 40 | self.mean = 0.0 + self.sum # This is to force a copy in torch/numpy 41 | self.std = np.inf 42 | self.mean_old = self.mean 43 | self.m_s = 0.0 44 | else: 45 | self.mean = self.mean_old + (value - n * self.mean_old) / float(self.n) 46 | self.m_s += (value - self.mean_old) * (value - self.mean) 47 | self.mean_old = self.mean 48 | self.std = np.sqrt(self.m_s / (self.n - 1.0)) 49 | 50 | def value(self): 51 | return self.mean, self.std 52 | 53 | def reset(self): 54 | self.n = 0 55 | self.sum = 0.0 56 | self.var = 0.0 57 | self.val = 0.0 58 | self.mean = np.nan 59 | self.mean_old = 0.0 60 | self.m_s = 0.0 61 | self.std = np.nan 62 | -------------------------------------------------------------------------------- /utils/metrics.py: -------------------------------------------------------------------------------- 1 | from . import base 2 | from . import functional as F 3 | from torch import nn 4 | 5 | 6 | class Activation(nn.Module): 7 | def __init__(self, name, **params): 8 | 9 | super().__init__() 10 | 11 | if name is None or name == 'identity': 12 | self.activation = nn.Identity(**params) 13 | elif name == 'sigmoid': 14 | self.activation = nn.Sigmoid() 15 | elif name == 'softmax2d': 16 | self.activation = nn.Softmax(dim=1, **params) 17 | elif name == 'softmax': 18 | self.activation = nn.Softmax(**params) 19 | elif name == 'logsoftmax': 20 | self.activation = nn.LogSoftmax(**params) 21 | elif name == 'tanh': 22 | self.activation = nn.Tanh() 23 | elif name == 'argmax': 24 | self.activation = ArgMax(**params) 25 | elif name == 'argmax2d': 26 | self.activation = ArgMax(dim=1, **params) 27 | elif callable(name): 28 | self.activation = name(**params) 29 | else: 30 | raise ValueError( 31 | 'Activation should be callable/sigmoid/softmax/logsoftmax/tanh/None; got {}' 32 | .format(name)) 33 | 34 | def forward(self, x): 35 | return self.activation(x) 36 | 37 | 38 | class IoU(base.Metric): 39 | __name__ = 'iou_score' 40 | 41 | def __init__(self, 42 | eps=1e-7, 43 | threshold=0.5, 44 | activation=None, 45 | ignore_channels=None, 46 | **kwargs): 47 | super().__init__(**kwargs) 48 | self.eps = eps 49 | self.threshold = threshold 50 | self.activation = Activation(activation) 51 | self.ignore_channels = ignore_channels 52 | 53 | def forward(self, y_pr, y_gt): 54 | y_pr = self.activation(y_pr) 55 | return F.iou( 56 | y_pr, 57 | y_gt, 58 | eps=self.eps, 59 | threshold=self.threshold, 60 | ignore_channels=self.ignore_channels, 61 | ) 62 | 63 | 64 | class Dice(base.Metric): 65 | __name__ = 'dice_score' 66 | 67 | def __init__(self, 68 | eps=1e-7, 69 | threshold=0.5, 70 | activation=None, 71 | ignore_channels=None, 72 | **kwargs): 73 | super().__init__(**kwargs) 74 | self.eps = eps 75 | self.threshold = threshold 76 | self.activation = Activation(activation) 77 | self.ignore_channels = ignore_channels 78 | 79 | def forward(self, y_pr, y_gt): 80 | y_pr = self.activation(y_pr) 81 | return F.dice( 82 | y_pr, 83 | y_gt, 84 | eps=self.eps, 85 | threshold=self.threshold, 86 | ignore_channels=self.ignore_channels, 87 | ) 88 | 89 | 90 | class Fscore(base.Metric): 91 | __name__ = 'f_score' 92 | 93 | def __init__(self, 94 | beta=1, 95 | eps=1e-7, 96 | threshold=0.5, 97 | activation=None, 98 | ignore_channels=None, 99 | **kwargs): 100 | super().__init__(**kwargs) 101 | self.eps = eps 102 | self.beta = beta 103 | self.threshold = threshold 104 | self.activation = Activation(activation) 105 | self.ignore_channels = ignore_channels 106 | 107 | def forward(self, y_pr, y_gt): 108 | y_pr = self.activation(y_pr) 109 | return F.f_score( 110 | y_pr, 111 | y_gt, 112 | eps=self.eps, 113 | beta=self.beta, 114 | threshold=self.threshold, 115 | ignore_channels=self.ignore_channels, 116 | ) 117 | 118 | 119 | class Accuracy(base.Metric): 120 | def __init__(self, 121 | threshold=0.5, 122 | activation=None, 123 | ignore_channels=None, 124 | **kwargs): 125 | super().__init__(**kwargs) 126 | self.threshold = threshold 127 | self.activation = Activation(activation) 128 | self.ignore_channels = ignore_channels 129 | 130 | def forward(self, y_pr, y_gt): 131 | y_pr = self.activation(y_pr) 132 | return F.accuracy( 133 | y_pr, 134 | y_gt, 135 | threshold=self.threshold, 136 | ignore_channels=self.ignore_channels, 137 | ) 138 | 139 | 140 | class Recall(base.Metric): 141 | def __init__(self, 142 | eps=1e-7, 143 | threshold=0.5, 144 | activation=None, 145 | ignore_channels=None, 146 | **kwargs): 147 | super().__init__(**kwargs) 148 | self.eps = eps 149 | self.threshold = threshold 150 | self.activation = Activation(activation) 151 | self.ignore_channels = ignore_channels 152 | 153 | def forward(self, y_pr, y_gt): 154 | y_pr = self.activation(y_pr) 155 | return F.recall( 156 | y_pr, 157 | y_gt, 158 | eps=self.eps, 159 | threshold=self.threshold, 160 | ignore_channels=self.ignore_channels, 161 | ) 162 | 163 | 164 | class Precision(base.Metric): 165 | def __init__(self, 166 | eps=1e-7, 167 | threshold=0.5, 168 | activation=None, 169 | ignore_channels=None, 170 | **kwargs): 171 | super().__init__(**kwargs) 172 | self.eps = eps 173 | self.threshold = threshold 174 | self.activation = Activation(activation) 175 | self.ignore_channels = ignore_channels 176 | 177 | def forward(self, y_pr, y_gt): 178 | y_pr = self.activation(y_pr) 179 | return F.precision( 180 | y_pr, 181 | y_gt, 182 | eps=self.eps, 183 | threshold=self.threshold, 184 | ignore_channels=self.ignore_channels, 185 | ) 186 | -------------------------------------------------------------------------------- /utils/train.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import torch 3 | from tqdm import tqdm as tqdm 4 | from .meter import AverageValueMeter 5 | 6 | 7 | class Epoch: 8 | def __init__(self, 9 | model, 10 | loss, 11 | metrics, 12 | stage_name, 13 | device='cpu', 14 | verbose=True): 15 | self.model = model 16 | self.loss = loss 17 | self.metrics = metrics 18 | self.stage_name = stage_name 19 | self.verbose = verbose 20 | self.device = device 21 | 22 | self._to_device() 23 | 24 | def _to_device(self): 25 | self.model.to(self.device) 26 | self.loss.to(self.device) 27 | for metric in self.metrics: 28 | metric.to(self.device) 29 | 30 | def _format_logs(self, logs): 31 | str_logs = ['{} - {:.4}'.format(k, v) for k, v in logs.items()] 32 | s = ', '.join(str_logs) 33 | return s 34 | 35 | def batch_update(self, x, y): 36 | raise NotImplementedError 37 | 38 | def on_epoch_start(self): 39 | pass 40 | 41 | def run(self, dataloader): 42 | 43 | self.on_epoch_start() 44 | 45 | logs = {} 46 | loss_meter = AverageValueMeter() 47 | metrics_meters = { 48 | metric.__name__: AverageValueMeter() 49 | for metric in self.metrics 50 | } 51 | 52 | with tqdm(dataloader, 53 | desc=self.stage_name, 54 | file=sys.stdout, 55 | disable=not (self.verbose)) as iterator: 56 | for x, y in iterator: 57 | x, y = x.to(self.device), y.to(self.device) 58 | loss, y_pred = self.batch_update(x, y) 59 | 60 | # update loss logs 61 | loss_value = loss.cpu().detach().numpy() 62 | loss_meter.add(loss_value) 63 | loss_logs = {self.loss.__name__: loss_meter.mean} 64 | logs.update(loss_logs) 65 | 66 | # update metrics logs 67 | for metric_fn in self.metrics: 68 | metric_value = metric_fn(y_pred, y).cpu().detach().numpy() 69 | metrics_meters[metric_fn.__name__].add(metric_value) 70 | metrics_logs = {k: v.mean for k, v in metrics_meters.items()} 71 | logs.update(metrics_logs) 72 | 73 | if self.verbose: 74 | s = self._format_logs(logs) 75 | iterator.set_postfix_str(s) 76 | 77 | return logs 78 | 79 | 80 | class TrainEpoch(Epoch): 81 | def __init__(self, 82 | model, 83 | loss, 84 | metrics, 85 | optimizer, 86 | device='cpu', 87 | verbose=True): 88 | super().__init__( 89 | model=model, 90 | loss=loss, 91 | metrics=metrics, 92 | stage_name='train', 93 | device=device, 94 | verbose=verbose, 95 | ) 96 | self.optimizer = optimizer 97 | 98 | def on_epoch_start(self): 99 | self.model.train() 100 | 101 | def batch_update(self, x, y): 102 | self.optimizer.zero_grad() 103 | prediction = self.model.forward(x) 104 | loss = self.loss(prediction, y) 105 | loss.backward() 106 | self.optimizer.step() 107 | return loss, prediction 108 | 109 | 110 | class ValidEpoch(Epoch): 111 | def __init__(self, model, loss, metrics, device='cpu', verbose=True): 112 | super().__init__( 113 | model=model, 114 | loss=loss, 115 | metrics=metrics, 116 | stage_name='valid', 117 | device=device, 118 | verbose=verbose, 119 | ) 120 | 121 | def on_epoch_start(self): 122 | self.model.eval() 123 | 124 | def batch_update(self, x, y): 125 | with torch.no_grad(): 126 | prediction = self.model.forward(x) 127 | loss = self.loss(prediction, y) 128 | return loss, prediction 129 | 130 | 131 | class TestEpoch(ValidEpoch): 132 | def __init__(self, model, loss, metrics, device='cpu', verbose=True): 133 | super().__init__( 134 | model=model, 135 | loss=loss, 136 | metrics=metrics, 137 | stage_name='test', 138 | device=device, 139 | verbose=verbose, 140 | ) 141 | 142 | def run(self, dataloader): 143 | 144 | self.on_epoch_start() 145 | 146 | logs = {} 147 | loss_meter = AverageValueMeter() 148 | metrics_meters = { 149 | metric.__name__: AverageValueMeter() 150 | for metric in self.metrics 151 | } 152 | TP = FTP = FP = FN = TN = 0 153 | 154 | with tqdm(dataloader, 155 | desc=self.stage_name, 156 | file=sys.stdout, 157 | disable=not (self.verbose)) as iterator: 158 | for x, y in iterator: 159 | x, y = x.to(self.device), y.to(self.device) 160 | loss, y_pred = self.batch_update(x, y) 161 | 162 | # update loss logs 163 | loss_value = loss.cpu().detach().numpy() 164 | loss_meter.add(loss_value) 165 | loss_logs = {self.loss.__name__: loss_meter.mean} 166 | logs.update(loss_logs) 167 | 168 | # update metrics logs 169 | for metric_fn in self.metrics: 170 | metric_value = metric_fn(y_pred, y).cpu().detach().numpy() 171 | metrics_meters[metric_fn.__name__].add(metric_value) 172 | metrics_logs = {k: v.mean for k, v in metrics_meters.items()} 173 | logs.update(metrics_logs) 174 | 175 | # update metrics logs 176 | if torch.sum(y) > 0 and torch.sum(y_pred) > 0: 177 | if torch.sum(y * y_pred) > 0: 178 | TP += 1 179 | else: 180 | FTP += 1 181 | elif torch.sum(y) > 0 and torch.sum(y_pred) == 0: 182 | FN += 1 183 | elif torch.sum(y) == 0 and torch.sum(y_pred) > 0: 184 | FP += 1 185 | elif torch.sum(y) == 0 and torch.sum(y_pred) == 0: 186 | TN += 1 187 | ACC = (TP + TN) / (TP + TN + FP + FN + FTP) 188 | bump_metrics_logs = { 189 | "TP": TP, 190 | "FTP": FTP, 191 | "FN": FN, 192 | "FP": FP, 193 | "TN": TN, 194 | "ACC": ACC, 195 | } 196 | logs.update(bump_metrics_logs) 197 | 198 | if self.verbose: 199 | s = self._format_logs(logs) 200 | iterator.set_postfix_str(s) 201 | 202 | return logs --------------------------------------------------------------------------------