├── Data ├── datasets │ └── flowers │ │ └── allclasses.txt └── text.txt ├── LICENSE ├── README.md ├── Utils ├── image_processing.py ├── inception_score.py ├── ops.py └── plot_msssim.py ├── _config.yml ├── create_dataset.py ├── dataprep.py ├── decoder.py ├── encode_text.py ├── encoder.py ├── generate_images.py ├── inception_score.py ├── model.py ├── msssim.py ├── requirements.txt ├── skipthoughts.py ├── t_interpolation.py ├── train.py └── z_interpolation.py /Data/datasets/flowers/allclasses.txt: -------------------------------------------------------------------------------- 1 | class_00001 2 | class_00002 3 | class_00003 4 | class_00004 5 | class_00005 6 | class_00006 7 | class_00007 8 | class_00008 9 | class_00009 10 | class_00010 11 | class_00011 12 | class_00012 13 | class_00013 14 | class_00014 15 | class_00015 16 | class_00016 17 | class_00017 18 | class_00018 19 | class_00019 20 | class_00020 21 | class_00021 22 | class_00022 23 | class_00023 24 | class_00024 25 | class_00025 26 | class_00026 27 | class_00027 28 | class_00028 29 | class_00029 30 | class_00030 31 | class_00031 32 | class_00032 33 | class_00033 34 | class_00034 35 | class_00035 36 | class_00036 37 | class_00037 38 | class_00038 39 | class_00039 40 | class_00040 41 | class_00041 42 | class_00042 43 | class_00043 44 | class_00044 45 | class_00045 46 | class_00046 47 | class_00047 48 | class_00048 49 | class_00049 50 | class_00050 51 | class_00051 52 | class_00052 53 | class_00053 54 | class_00054 55 | class_00055 56 | class_00056 57 | class_00057 58 | class_00058 59 | class_00059 60 | class_00060 61 | class_00061 62 | class_00062 63 | class_00063 64 | class_00064 65 | class_00065 66 | class_00066 67 | class_00067 68 | class_00068 69 | class_00069 70 | class_00070 71 | class_00071 72 | class_00072 73 | class_00073 74 | class_00074 75 | class_00075 76 | class_00076 77 | class_00077 78 | class_00078 79 | class_00079 80 | class_00080 81 | class_00081 82 | class_00082 83 | class_00083 84 | class_00084 85 | class_00085 86 | class_00086 87 | class_00087 88 | class_00088 89 | class_00089 90 | class_00090 91 | class_00091 92 | class_00092 93 | class_00093 94 | class_00094 95 | class_00095 96 | class_00096 97 | class_00097 98 | class_00098 99 | class_00099 100 | class_00100 101 | class_00101 102 | class_00102 -------------------------------------------------------------------------------- /Data/text.txt: -------------------------------------------------------------------------------- 1 | a flower with red petals which are pointed 2 | many pointed petals 3 | A yellow flower -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | This is the Tensorflow implementation of TAC-GAN model presented in 2 | [https://arxiv.org/abs/1703.06412](https://arxiv.org/abs/1703.06412). 3 | 4 | Text Conditioned Auxiliary Classifier Generative Adversarial Network, 5 | (TAC-GAN) is a text to image Generative Adversarial Network (GAN) for 6 | synthesizing images from their text descriptions. TAC-GAN builds upon the 7 | [AC-GAN](https://arxiv.org/abs/1610.09585) by conditioning the generated images 8 | on a text description instead of on a class label. In the presented TAC-GAN 9 | model, the input vector of the Generative network is built based on a noise 10 | vector and another vector containing an embedded representation of the 11 | textual description. While the Discriminator is similar to that of 12 | the AC-GAN, it is also augmented to receive the text information as 13 | input before performing its classification. 14 | 15 | For embedding the textual descriptions of the images into vectors we used 16 | [skip-thought vectors](https://arxiv.org/abs/1506.06726) 17 | 18 | The following is the architecture of the TAC-GAN model 19 | 20 | 22 | 23 | # Prerequisites 24 | Some important dependencies are the following and the rest can be installed 25 | using the ```requirements.txt``` 26 | 1. Python 3.5 27 | 2. [Tensorflow 1.2.0](https://github.com/tensorflow/tensorflow) 28 | 4. [Theano 0.9.0](https://github.com/Theano/Theano) : for skip thought vectors 29 | 5. [scikit-learn](http://scikit-learn.org/stable/index.html) : for skip thought vectors 30 | 6. [NLTK 3.2.1](http://www.nltk.org/) : for skip thought vectors 31 | 32 | It is recommended to use a virtual environment for running this project and 33 | installing the required dependencies in it by using the 34 | [***requirements.txt***](https://github.com/dashayushman/TAC-GAN/blob/master/requirements.txt) file. 35 | 36 | The project has been tested on a Ubuntu 14.04 machine with an 12 GB NVIDIA 37 | Titen X GPU 38 | 39 | # 1. Setup and Run 40 | 41 | ## 1.1. Clone the Repository 42 | 43 | ``` 44 | git clone https://github.com/dashayushman/TAC-GAN.git 45 | cd TAC-GAN 46 | ``` 47 | 48 | ## 1.2. Download the Dataset 49 | 50 | The model presented in the paper was trained on the 51 | [flowers dataset](http://www.robots.ox.ac.uk/~vgg/data/flowers/102/ ). This 52 | To train the TAC-GAN on the flowers dataset, first, download the dataset by 53 | doing the following, 54 | 55 | 1. **Download the flower images** from 56 | [here](http://www.robots.ox.ac.uk/~vgg/data/flowers/102/102flowers.tgz). 57 | Extract the ```102flowers.tgz``` file and copy the extracted ```jpg``` folder 58 | to ```Data/datasets/flowers``` 59 | 60 | 2. **Download the captions** from 61 | [here](https://drive.google.com/file/d/0B0ywwgffWnLLcms2WWJQRFNSWXM/). 62 | Extract the downloaded file, copy the text_c10 folder and paste it in ``` 63 | Data/datasets/flowers``` directory 64 | 65 | 3. **Download the pretrained skip-thought vectors model** from 66 | [here](https://github.com/ryankiros/skip-thoughts#getting-started) and copy 67 | the downloaded files to ```Data/skipthoughts``` 68 | 69 | **NB:** *It is recommended to keep all the images in an SSD if available. This 70 | makes the batch loading and processing operation faster.* 71 | 72 | ## 1.3. Data Preprocessing 73 | Extract the skip-thought features for the captions and prepare the dataset 74 | for training by running the following script 75 | 76 | ``` 77 | python dataprep.py --data_dir=Data --dataset=flowers 78 | ``` 79 | 80 | This script will create a set of pickled files in the datet directory which 81 | will be used during training. The following are the available flags for data preparation: 82 | 83 | FLAG | VALUE TYPE | DEFAULT VALUE | DESCRIPTION 84 | --- | --- | --- | --- 85 | data_dir | str | Data | The data directory | 86 | dataset | str | flowers | Dataset to use. For Eg., "flowers" | 87 | 88 | ## 1.4. Training 89 | 90 | To train TAC-GAN with the default hyper parameters run the following script 91 | 92 | ``` 93 | python train.py --dataset="flowers" --model_name=TAC-GAN 94 | ``` 95 | 96 | While training, you can montor samples generated by the model in the ```Data/training/TAC_GAN/samples``` directory. Notice that a directory is created according to the ***"model_name"*** taht you provide. This directory contains all the data related to a particular experiment. This can also be considered as an ***"experiment name"*** too. 97 | 98 | The following flags can be set to change the hyperparameters of the network. 99 | 100 | FLAG | VALUE TYPE | DEFAULT VALUE | DESCRIPTION 101 | --- | --- | --- | --- 102 | z-dim | int | 100 | Number of dimensions of the Noise vector | 103 | t_dim | int | 256 | Number of dimensions for the latent representation of the text embedding. 104 | batch_size | int | 64 | Mini-Batch Size 105 | image_size | int | 128 | Batch size to use during training. 106 | gf_dim | int | 64 | Number of conv filters in the first layer of the generator. 107 | df_dim | int | 64 | Number of conv filters in the first layer of the discriminator. 108 | caption_vector_length | int | 4800 | Length of the caption vector embedding (vector generated using skip-thought vectors model). 109 | n_classes | int | 102 | Number of classes 110 | data_dir | String | Data | Data directory 111 | learning_rate | float | 0.0002 | Learning rate 112 | beta1 | float | 0.5 | Momentum for Adam Update 113 | epochs | int | 200 | Maximum number of epochs to train 114 | save_every | int | 30 | Save model and samples after this many number.of iterations 115 | resume_model | Boolean | False | To Load the pre-trained model 116 | data_set | String | flowers | Which dataset to use: "flowers" 117 | model_name | String | model_1 | Name of the model: Can be anything 118 | train | bool | True | This is True while training and false otherwise. Used for batch normalization 119 | 120 | We used the following script (hyper-parameters) in for the results that we show in our paper 121 | 122 | ``` 123 | python train.py --t_dim=100 --image_size=128 --data_set=flowers --model_name=TAC_GAN --train=True --resume_model=True --z_dim=100 --n_classes=102 --epochs=400 --save_every=20 --caption_vector_length=4800 --batch_size=128 124 | ``` 125 | 126 | ## 1.5. Monitoring 127 | 128 | While training, you can monitor the updates on the *terminal* as well as by using [*tensorboard*](https://www.tensorflow.org/get_started/summaries_and_tensorboard) 129 | 130 | ### 1.5.1 The Terminal: 131 | ![Terminal log](https://chalelele.files.wordpress.com/2017/06/terminal_log.png) 132 | 133 | ### 1.5.1 Tensorboard: 134 | 135 | You can use the following script to start tensorboard and visualize realtime changes: 136 | 137 | ``` 138 | tensorboard --logdir=Data/training/TAC_GAN/summaries 139 | ``` 140 | 141 | ![Tensorboard](https://chalelele.files.wordpress.com/2017/06/tb.png) 142 | 143 | # 2. Generating Images for the text in the dataset 144 | 145 | Once you have trained the model for certain epochs you can generate images for all the text descriptions in the dataset use the following script. This will create a synthetic dataset with images generated by the generator. 146 | 147 | ``` 148 | python train.py --data_set=flowers --epochs=100 --output_dir=Data/synthetic_dataset --checkpoints_dir=Data/training/TAC_GAN/checkpoints 149 | ``` 150 | 151 | Notice that the ***checkpoints*** directory is ls created automatically created inside the ***model*** directory after you run the training script. 152 | 153 | This script will create the following directory structure: 154 | 155 | ``` 156 | Data 157 | |__synthetic_dataset 158 | |___ds 159 | |___train 160 | |___val 161 | ``` 162 | 163 | the ***train*** directory will contain all the images generated from the text descriptions of the images in the training set and the same goes for the ***val*** directory. 164 | 165 | # 3. Generating Images from any Text 166 | 167 | To generate images from any text, do the following 168 | 169 | ## 3.1 Add Text Descriptions: 170 | 171 | Write your text descriptions in a file or use the example file ```Data/text.txt``` that we have provided in the Data directory. 172 | The text description file should contain one text description per line. For example, 173 | 174 | ``` 175 | a flower with red petals which are pointed 176 | many pointed petals 177 | A yellow flower 178 | ``` 179 | 180 | ## 3.2 Extract Skip-Thought Vectors: 181 | 182 | Run the following script for extracting the Skip-Thought vectors for the text descriptions 183 | 184 | ``` 185 | python encode_text.py --caption_file=Data/text.txt --data_dir=Data 186 | ``` 187 | 188 | This script will create a pickle file called ```Data/enc_text.pkl``` with features extracted from the text descriptions. 189 | 190 | ## 3.3 Generate Images: 191 | 192 | To generate images for the text descriptions, run the following script, 193 | 194 | ``` 195 | python generate_images.py --data_set=flowers --checkpoints_dir=Data/training/TAC_GAN/checkpoints --images_per_caption=30 --data_dir=Data 196 | ``` 197 | 198 | This will create a directory ```Data/images_generated_from_text/``` with a folder corresponding to every row of the ***text.txt*** file. Each of these folders will contain images for that text. 199 | 200 | The following are the parameters you need to set, in case you have used different parameters for training the model. 201 | 202 | FLAG | VALUE TYPE | DEFAULT VALUE | DESCRIPTION 203 | --- | --- | --- | --- 204 | z-dim | int | 100 | Number of dimensions of the Noise vector | 205 | t_dim | int | 256 | Number of dimensions for the latent representation of the text embedding. 206 | batch_size | int | 64 | Mini-Batch Size 207 | image_size | int | 128 | Batch size to use during training. 208 | gf_dim | int | 64 | Number of conv filters in the first layer of the generator. 209 | df_dim | int | 64 | Number of conv filters in the first layer of the discriminator. 210 | caption_vector_length | int | 4800 | Length of the caption vector embedding (vector generated using skip-thought vectors model). 211 | n_classes | int | 102 | Number of classes 212 | data_dir | String | Data | Data directory 213 | learning_rate | float | 0.0002 | Learning rate 214 | beta1 | float | 0.5 | Momentum for Adam Update 215 | images_per_caption | int | 30 | Maximum number of images that you want to generate for each of the text descriptions 216 | data_set | String | flowers | Which dataset to use: "flowers" 217 | checkpoints_dir | String | /tmp | Path to the checkpoints directory which will be used to generate the images 218 | 219 | # 4. Evaluation 220 | 221 | We have used two metrics for evaluating TAC-GAN, 222 | 223 | 1. [Inception-Scope](https://github.com/openai/improved-gan/tree/master/inception_score) 224 | 2. [MS-SSIM score](https://github.com/tensorflow/models/blob/master/compression/image_encoder/msssim.py) 225 | 226 | The links are from where we adapted the code for evaluating TAC-GAN. Before evaluating the model, generate a synthetic dataset by referring to [**Section 6**](#6-generating-images-for-text-in-the-dataset) 227 | 228 | ## 4.1 Inception Score 229 | 230 | To calculate the inception score, use the following script, 231 | 232 | ``` 233 | python inception_score.py --output_dir=Data/synthetic_dataset --data_dir=Data --n_images=30000 --image_size=128 234 | ``` 235 | 236 | This will create a collection of all the generated images in ```Data/synthetic_dataset/ds_inception``` and show the inception score on the terminal. 237 | 238 | The following are the set of available parameters/flags 239 | 240 | FLAG | VALUE TYPE | DEFAULT VALUE | DESCRIPTION 241 | --- | --- | --- | --- 242 | output_dir | str | Data/ds_inception | Directory to dump all the images for calculating the inception score | 243 | data_dir | str | Data/synthetic_dataset/ds | The root directory of the synthetic dataset | 244 | n_images | int | 30000 | Number of images to consider for calculating inception score | 245 | image_size | int | 128 | Size of the image to consider for calculating inception score | 246 | 247 | 248 | ## 4.2 MS-SSIM 249 | 250 | To calculate the MS-SSIM score, use the following script, 251 | 252 | ``` 253 | python inception_score.py --output_dir=Data --data_dir=Data --dataset=flowers --syn_dataset_dir=Data/synthetic_datset/ds 254 | ``` 255 | 256 | This will create a ```Data/msssim.tsv``` tab separated file. The data in this file is structured as follows 257 | 258 | ``` 259 | 260 | ``` 261 | 262 | Once you have generated the ***msssim.tsv*** file, you can use the following script to generate a figure to compare the MS-SSIM score of the images in the real dataset with the images in the synthetic dataset belonging to the same class, 263 | 264 | ``` 265 | python utility/plot_msssim.py --input_file=Data/msssim.tsv --output_file=Data/msssim 266 | ``` 267 | 268 | This will create ```Data/msssim.pdf```, which is the ***.pdf*** file of the generated figure. 269 | 270 | # 5. Generate Interpolated Images 271 | 272 | In our paper we show the effect of interpolating the noise and the text embedding vectors on the generated image. Images are randomply selected and their text descriptions are used to generate synthetic images. The following sub-sections will elaborate on how to do it and which scripts will help you in doing it. 273 | 274 | ## 5.1 Z (Noise) Interpolation 275 | 276 | For interpolating the noise vector and generating images, use the following scripts 277 | 278 | ``` 279 | python z_interpolation.py --output_dir=Data/synthetic_dataset --data_set=flowers --checkpoints_dir=Data/training/TAC_GAN/checkpoints --n_images=500 280 | ``` 281 | 282 | This will generate the interpolated images in ```Data/synthetic_dataset/z_interpolation/```. 283 | 284 | ## 5.1 T (Text Embedding) Interpolation 285 | 286 | For interpolating the text embedding vectors and generating images, use the following scripts 287 | 288 | ``` 289 | python t_interpolation.py --output_dir=Data/synthetic_dataset --data_set=flowers --checkpoints_dir=Data/training/TAC_GAN/checkpoints --n_images=500 290 | ``` 291 | 292 | This will generate the interpolated images in ```Data/synthetic_dataset/t_interpolation/```. 293 | 294 | ***NOTE:*** Both the above mentioned scripts have the same flags/arguments, which are the following, 295 | 296 | FLAG | VALUE TYPE | DEFAULT VALUE | DESCRIPTION 297 | --- | --- | --- | --- 298 | z-dim | int | 100 | Number of dimensions of the Noise vector | 299 | t_dim | int | 256 | Number of dimensions for the latent representation of the text embedding. 300 | batch_size | int | 64 | Mini-Batch Size 301 | image_size | int | 128 | Batch size to use during training. 302 | gf_dim | int | 64 | Number of conv filters in the first layer of the generator. 303 | df_dim | int | 64 | Number of conv filters in the first layer of the discriminator. 304 | caption_vector_length | int | 4800 | Length of the caption vector embedding (vector generated using skip-thought vectors model). 305 | n_classes | int | 102 | Number of classes 306 | data_dir | String | Data | Data directory 307 | learning_rate | float | 0.0002 | Learning rate 308 | beta1 | float | 0.5 | Momentum for Adam Update 309 | data_set | str | flowers | The dataset to use: "flowers" 310 | output_dir | String | Data/synthetic_dataset | The directory in which the t_interpolated images will be generated 311 | checkpoints_dir | String | /tmp | Path to the checkpoints directory which will be used to generate the images 312 | n_interp | int | 100 | The factor difference between each interpolation (Should ideally be a multiple of 10) 313 | n_images | int | 500 | Number of images to randomply sample for generating interpolation results 314 | 315 | # 6. References 316 | 317 | ### TAC-GAN 318 | 319 | If you find this code usefull, then please use the following BibTex to cite our work. 320 | 321 | ``` 322 | @article{dash2017tac, 323 | title={TAC-GAN-Text Conditioned Auxiliary Classifier Generative Adversarial Network}, 324 | author={Dash, Ayushman and Gamboa, John Cristian Borges and Ahmed, Sheraz and Afzal, Muhammad Zeshan and Liwicki, Marcus}, 325 | journal={arXiv preprint arXiv:1703.06412}, 326 | year={2017} 327 | } 328 | ``` 329 | 330 | ### Oxford-102 Flowers Dataset 331 | 332 | If you use the Oxford-102 Flowers Dataset, then please cite their work using the following BibTex. 333 | 334 | ``` 335 | @InProceedings{Nilsback08, 336 | author = "Nilsback, M-E. and Zisserman, A.", 337 | title = "Automated Flower Classification over a Large Number of Classes", 338 | booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing", 339 | year = "2008", 340 | month = "Dec" 341 | } 342 | ``` 343 | 344 | ### Skip-Thought 345 | 346 | If you use the Skip-Thought model in your work like us, then please cite their work using the following BibTex 347 | 348 | ``` 349 | @article{kiros2015skip, 350 | title={Skip-Thought Vectors}, 351 | author={Kiros, Ryan and Zhu, Yukun and Salakhutdinov, Ruslan and Zemel, Richard S and Torralba, Antonio and Urtasun, Raquel and Fidler, Sanja}, 352 | journal={arXiv preprint arXiv:1506.06726}, 353 | year={2015} 354 | } 355 | ``` 356 | 357 | ### Code 358 | 359 | We have referred to the [text-to-image](https://github.com/paarthneekhara/text-to-image) and [DCGAN-tensorflow](https://github.com/carpedm20/DCGAN-tensorflow) repositories for developing our code, and we are extremely thankful to them. 360 | -------------------------------------------------------------------------------- /Utils/image_processing.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import misc 3 | import random 4 | import skimage 5 | import skimage.io 6 | import skimage.transform 7 | import os 8 | 9 | def load_image_array_flowers(image_file, image_size): 10 | img = skimage.io.imread(image_file) 11 | # GRAYSCALE 12 | if len(img.shape) == 2: 13 | img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8') 14 | img_new[:,:,0] = img 15 | img_new[:,:,1] = img 16 | img_new[:,:,2] = img 17 | img = img_new 18 | 19 | img_resized = skimage.transform.resize(img, (image_size, image_size)) 20 | 21 | # FLIP HORIZONTAL WIRH A PROBABILITY 0.5 22 | if random.random() > 0.5: 23 | img_resized = np.fliplr(img_resized) 24 | 25 | 26 | return img_resized.astype('float32') 27 | 28 | def load_image_array(image_file, image_size, 29 | image_id, data_dir='Data/datasets/mscoco/train2014', 30 | mode='train'): 31 | img = None 32 | if os.path.exists(image_file): 33 | #print('found' + image_file) 34 | img = skimage.io.imread(image_file) 35 | else: 36 | print('notfound' + image_file) 37 | img = skimage.io.imread('http://mscoco.org/images/%d' % (image_id)) 38 | img_path = os.path.join(data_dir, 'COCO_%s2014_%.12d.jpg' % ( mode, 39 | image_id)) 40 | skimage.io.imsave(img_path, img) 41 | 42 | # GRAYSCALE 43 | if len(img.shape) == 2: 44 | img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8') 45 | img_new[:,:,0] = img 46 | img_new[:,:,1] = img 47 | img_new[:,:,2] = img 48 | img = img_new 49 | 50 | img_resized = skimage.transform.resize(img, (image_size, image_size)) 51 | 52 | # FLIP HORIZONTAL WIRH A PROBABILITY 0.5 53 | if random.random() > 0.5: 54 | img_resized = np.fliplr(img_resized) 55 | 56 | return img_resized.astype('float32') 57 | 58 | def load_image_inception(image_file, image_size=128): 59 | img = skimage.io.imread(image_file) 60 | # GRAYSCALE 61 | if len(img.shape) == 2: 62 | img_new = np.ndarray((img.shape[0], img.shape[1], 3), dtype='uint8') 63 | img_new[:, :, 0] = img 64 | img_new[:, :, 1] = img 65 | img_new[:, :, 2] = img 66 | img = img_new 67 | 68 | if image_size != 0: 69 | img = skimage.transform.resize(img, (image_size, image_size), mode='reflect') 70 | 71 | return img.astype('int32') 72 | 73 | if __name__ == '__main__': 74 | # TEST>>> 75 | arr = load_image_array('sample.jpg', 64) 76 | print(arr.mean()) 77 | # rev = np.fliplr(arr) 78 | misc.imsave( 'rev.jpg', arr) 79 | -------------------------------------------------------------------------------- /Utils/inception_score.py: -------------------------------------------------------------------------------- 1 | # Code derived from tensorflow/tensorflow/models/image/imagenet/classify_image.py 2 | from __future__ import absolute_import 3 | from __future__ import division 4 | from __future__ import print_function 5 | 6 | import os.path 7 | import sys 8 | import tarfile 9 | 10 | import numpy as np 11 | from six.moves import urllib 12 | import tensorflow as tf 13 | import glob 14 | import scipy.misc 15 | import math 16 | import sys 17 | 18 | MODEL_DIR = '/tmp/imagenet' 19 | DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' 20 | softmax = None 21 | 22 | # Call this function with list of images. Each of elements should be a 23 | # numpy array with values ranging from 0 to 255. 24 | def get_inception_score(images, splits=10): 25 | assert(type(images) == list) 26 | assert(type(images[0]) == np.ndarray) 27 | assert(len(images[0].shape) == 3) 28 | assert(np.max(images[0]) > 10) 29 | assert(np.min(images[0]) >= 0.0) 30 | inps = [] 31 | for img in images: 32 | img = img.astype(np.float32) 33 | inps.append(np.expand_dims(img, 0)) 34 | bs = 100 35 | with tf.Session() as sess: 36 | preds = [] 37 | n_batches = int(math.ceil(float(len(inps)) / float(bs))) 38 | for i in range(n_batches): 39 | sys.stdout.write(".") 40 | sys.stdout.flush() 41 | inp = inps[(i * bs):min((i + 1) * bs, len(inps))] 42 | inp = np.concatenate(inp, 0) 43 | pred = sess.run(softmax, {'ExpandDims:0': inp}) 44 | preds.append(pred) 45 | preds = np.concatenate(preds, 0) 46 | scores = [] 47 | for i in range(splits): 48 | part = preds[(i * preds.shape[0] // splits):((i + 1) * preds.shape[0] // splits), :] 49 | kl = part * (np.log(part) - np.log(np.expand_dims(np.mean(part, 0), 0))) 50 | kl = np.mean(np.sum(kl, 1)) 51 | scores.append(np.exp(kl)) 52 | return np.mean(scores), np.std(scores) 53 | 54 | # This function is called automatically. 55 | def _init_inception(): 56 | global softmax 57 | if not os.path.exists(MODEL_DIR): 58 | os.makedirs(MODEL_DIR) 59 | filename = DATA_URL.split('/')[-1] 60 | filepath = os.path.join(MODEL_DIR, filename) 61 | if not os.path.exists(filepath): 62 | def _progress(count, block_size, total_size): 63 | sys.stdout.write('\r>> Downloading %s %.1f%%' % ( 64 | filename, float(count * block_size) / float(total_size) * 100.0)) 65 | sys.stdout.flush() 66 | filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress) 67 | print() 68 | statinfo = os.stat(filepath) 69 | print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.') 70 | tarfile.open(filepath, 'r:gz').extractall(MODEL_DIR) 71 | with tf.gfile.FastGFile(os.path.join( 72 | MODEL_DIR, 'classify_image_graph_def.pb'), 'rb') as f: 73 | graph_def = tf.GraphDef() 74 | graph_def.ParseFromString(f.read()) 75 | _ = tf.import_graph_def(graph_def, name='') 76 | # Works with an arbitrary minibatch size. 77 | with tf.Session() as sess: 78 | pool3 = sess.graph.get_tensor_by_name('pool_3:0') 79 | ops = pool3.graph.get_operations() 80 | for op_idx, op in enumerate(ops): 81 | for o in op.outputs: 82 | shape = o.get_shape() 83 | shape = [s.value for s in shape] 84 | new_shape = [] 85 | for j, s in enumerate(shape): 86 | if s == 1 and j == 0: 87 | new_shape.append(None) 88 | else: 89 | new_shape.append(s) 90 | o._shape = tf.TensorShape(new_shape) 91 | w = sess.graph.get_operation_by_name("softmax/logits/MatMul").inputs[1] 92 | logits = tf.matmul(tf.squeeze(pool3), w) 93 | softmax = tf.nn.softmax(logits) 94 | 95 | if softmax is None: 96 | _init_inception() 97 | -------------------------------------------------------------------------------- /Utils/ops.py: -------------------------------------------------------------------------------- 1 | # RESUED CODE FROM https://github.com/carpedm20/DCGAN-tensorflow/blob/master/ops.py 2 | import math 3 | import numpy as np 4 | import tensorflow as tf 5 | 6 | from tensorflow.python.framework import ops 7 | 8 | 9 | class batch_norm(object): 10 | """Code modification of http://stackoverflow.com/a/33950177""" 11 | def __init__(self, epsilon=1e-5, momentum = 0.9, name="batch_norm"): 12 | with tf.variable_scope(name): 13 | self.epsilon = epsilon 14 | self.momentum = momentum 15 | 16 | self.ema = tf.train.ExponentialMovingAverage(decay=self.momentum) 17 | self.name = name 18 | 19 | def __call__(self, x, train=True): 20 | shape = x.get_shape().as_list() 21 | 22 | if train: 23 | with tf.variable_scope(self.name) as scope: 24 | self.beta = tf.get_variable("beta", [shape[-1]], 25 | initializer=tf.constant_initializer(0.)) 26 | self.gamma = tf.get_variable("gamma", [shape[-1]], 27 | initializer=tf.random_normal_initializer(1., 0.02)) 28 | 29 | try: 30 | batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], name='moments') 31 | except: 32 | batch_mean, batch_var = tf.nn.moments(x, [0, 1], name='moments') 33 | 34 | ema_apply_op = self.ema.apply([batch_mean, batch_var]) 35 | self.ema_mean, self.ema_var = self.ema.average(batch_mean), self.ema.average(batch_var) 36 | 37 | with tf.control_dependencies([ema_apply_op]): 38 | mean, var = tf.identity(batch_mean), tf.identity(batch_var) 39 | else: 40 | mean, var = self.ema_mean, self.ema_var 41 | 42 | normed = tf.nn.batch_norm_with_global_normalization( 43 | x, mean, var, self.beta, self.gamma, self.epsilon, scale_after_normalization=True) 44 | 45 | return normed 46 | 47 | 48 | 49 | def binary_cross_entropy(preds, targets, name=None): 50 | """Computes binary cross entropy given `preds`. 51 | 52 | For brevity, let `x = `, `z = targets`. The logistic loss is 53 | 54 | loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i])) 55 | 56 | Args: 57 | preds: A `Tensor` of type `float32` or `float64`. 58 | targets: A `Tensor` of the same type and shape as `preds`. 59 | """ 60 | eps = 1e-12 61 | with ops.op_scope([preds, targets], name, "bce_loss") as name: 62 | preds = ops.convert_to_tensor(preds, name="preds") 63 | targets = ops.convert_to_tensor(targets, name="targets") 64 | return tf.reduce_mean(-(targets * tf.log(preds + eps) + 65 | (1. - targets) * tf.log(1. - preds + eps))) 66 | 67 | def conv_cond_concat(x, y): 68 | """Concatenate conditioning vector on feature map axis.""" 69 | x_shapes = x.get_shape() 70 | y_shapes = y.get_shape() 71 | return tf.concat(3, [x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])]) 72 | 73 | def conv2d(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, 74 | name="conv2d"): 75 | with tf.variable_scope(name): 76 | #w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[-1], output_dim], initializer=tf.truncated_normal_initializer(stddev=stddev)) 77 | w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[-1], output_dim], initializer = tf.contrib.layers.xavier_initializer()) 78 | conv = tf.nn.conv2d(input_, w, strides=[1, d_h, d_w, 1], padding='SAME') 79 | 80 | biases = tf.get_variable('biases', [output_dim], initializer=tf.constant_initializer(0.0)) 81 | conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape()) 82 | 83 | return conv 84 | 85 | def deconv2d(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, 86 | name="deconv2d", with_w=False): 87 | with tf.variable_scope(name): 88 | # filter : [height, width, output_channels, in_channels] 89 | #w = tf.get_variable('w', [k_h, k_h, output_shape[-1], input_.get_shape()[-1]], initializer=tf.random_normal_initializer(stddev=stddev)) 90 | w = tf.get_variable('w', [k_h, k_h, output_shape[-1], input_.get_shape()[-1]], initializer = tf.contrib.layers.xavier_initializer()) 91 | try: 92 | deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape, 93 | strides=[1, d_h, d_w, 1]) 94 | 95 | # Support for verisons of TensorFlow before 0.7.0 96 | except AttributeError: 97 | deconv = tf.nn.deconv2d(input_, w, output_shape=output_shape, 98 | strides=[1, d_h, d_w, 1]) 99 | 100 | biases = tf.get_variable('biases', [output_shape[-1]], initializer=tf.constant_initializer(0.0)) 101 | deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape()) 102 | 103 | if with_w: 104 | return deconv, w, biases 105 | else: 106 | return deconv 107 | 108 | def lrelu(x, leak=0.2, name="lrelu"): 109 | return tf.maximum(x, leak*x) 110 | 111 | def linear(input_, output_size, scope=None, stddev=0.02, bias_start=0.0, 112 | with_w=False): 113 | shape = input_.get_shape().as_list() 114 | 115 | with tf.variable_scope(scope or "Linear"): 116 | #matrix = tf.get_variable("Matrix", [shape[1], output_size], tf.float32, 117 | # tf.random_normal_initializer(stddev=stddev)) 118 | matrix = tf.get_variable("Matrix", [shape[1], output_size], tf.float32, 119 | tf.contrib.layers.xavier_initializer()) 120 | bias = tf.get_variable("bias", [output_size], 121 | initializer=tf.constant_initializer(bias_start)) 122 | if with_w: 123 | return tf.matmul(input_, matrix) + bias, matrix, bias 124 | else: 125 | return tf.matmul(input_, matrix) + bias 126 | 127 | def attention(decoder_output, seq_outputs, output_size, time_steps, 128 | name="attention"): 129 | 130 | with tf.variable_scope(name): 131 | ui = [] 132 | w_1 = tf.get_variable("w1", [output_size, output_size], 133 | tf.float32, 134 | tf.contrib.layers.xavier_initializer()) 135 | w_2 = tf.get_variable("w2", [output_size, output_size], 136 | tf.float32, 137 | tf.contrib.layers.xavier_initializer()) 138 | v = tf.get_variable("v", [output_size, 1], 139 | tf.float32, 140 | tf.contrib.layers.xavier_initializer()) 141 | for seq_out in seq_outputs: 142 | ui.append(tf.matmul(tf.nn.tanh(tf.matmul(seq_out, w_1) + 143 | tf.matmul(decoder_output, w_2)), v)) 144 | 145 | return ui 146 | 147 | def get_gt(batch_size, classes, real=1, name="gt"): 148 | 149 | with tf.variable_scope(name, reuse=None): 150 | r_f = tf.get_variable("rf", [batch_size, 1], 151 | initializer = tf.constant_initializer( 152 | real)) 153 | gt = tf.concat(1, [r_f, classes], name = 'gt_concat_classes') 154 | return gt -------------------------------------------------------------------------------- /Utils/plot_msssim.py: -------------------------------------------------------------------------------- 1 | # Plots a .tsv file. This was a simple script used to generate 2 | # the graph of the MS-SSIM in the paper. 3 | 4 | import matplotlib.pyplot as plt 5 | import argparse 6 | 7 | parser = argparse.ArgumentParser() 8 | 9 | parser.add_argument('--input_file', type=str, default="Data/msssim.tsv", 10 | help='the .tsv file that contains the msssim scores ' 11 | 'generated by using msssim.py') 12 | 13 | parser.add_argument('--output_file', type=str, default="Data/msssim", 14 | help='The name of the output figure file that you ' 15 | 'want to generate.') 16 | 17 | args = parser.parse_args() 18 | 19 | def open_tsv(file_name): 20 | with open(file_name, 'r') as f: 21 | tsv = f.readlines() 22 | 23 | ret = [] 24 | for l in tsv: 25 | ret.append(l.split('\t')) 26 | 27 | print(ret) 28 | return ret 29 | 30 | tsv = open_tsv(args.tsv_file) 31 | 32 | x = [] 33 | y = [] 34 | for i in tsv: 35 | x.append(i[1]) 36 | y.append(i[4]) 37 | 38 | 39 | plt.scatter(x, y) 40 | plt.plot([0,1], [0,1]) 41 | plt.xlim(0, 1) 42 | plt.ylim(0, 1) 43 | plt.xlabel('training data MS-SSIM value') 44 | plt.ylabel('samples MS-SSIM value') 45 | 46 | output_file_name = args.output_file + '.pdf' 47 | plt.savefig(output_file_name, format='pdf') 48 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /create_dataset.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | import model 4 | import argparse 5 | import pickle 6 | from os.path import join 7 | import scipy.misc 8 | import random 9 | import os 10 | from Utils import image_processing 11 | 12 | 13 | def main(): 14 | parser = argparse.ArgumentParser() 15 | parser.add_argument('--z_dim', type=int, default=100, 16 | help='Noise dimension') 17 | 18 | parser.add_argument('--t_dim', type=int, default=256, 19 | help='Text feature dimension') 20 | 21 | parser.add_argument('--batch_size', type=int, default=64, 22 | help='Batch Size') 23 | 24 | parser.add_argument('--image_size', type=int, default=128, 25 | help='Image Size a, a x a') 26 | 27 | parser.add_argument('--gf_dim', type=int, default=64, 28 | help='Number of conv in the first layer gen.') 29 | 30 | parser.add_argument('--df_dim', type=int, default=64, 31 | help='Number of conv in the first layer discr.') 32 | 33 | parser.add_argument('--caption_vector_length', type=int, default=4800, 34 | help='Caption Vector Length') 35 | 36 | parser.add_argument('--n_classes', type=int, default=102, 37 | help='Number of classes/class labels') 38 | 39 | parser.add_argument('--data_dir', type=str, default="Data", 40 | help='Data Directory') 41 | 42 | parser.add_argument('--learning_rate', type=float, default=0.0002, 43 | help='Learning Rate') 44 | 45 | parser.add_argument('--beta1', type=float, default=0.5, 46 | help='Momentum for Adam Update') 47 | 48 | parser.add_argument('--epochs', type=int, default=200, 49 | help='Max number of epochs') 50 | 51 | parser.add_argument('--data_set', type=str, default="flowers", 52 | help='Dat set: flowers') 53 | 54 | parser.add_argument('--output_dir', type=str, default="Data/ds", 55 | help='The directory in which this dataset will be ' 56 | 'created') 57 | 58 | parser.add_argument('--checkpoints_dir', type=str, default="/tmp", 59 | help='Path to the checkpoints directory') 60 | 61 | args = parser.parse_args() 62 | 63 | model_stage_1_ds_tr, model_stage_1_ds_val, datasets_root_dir = \ 64 | prepare_dirs(args) 65 | 66 | loaded_data = load_training_data(datasets_root_dir, args.data_set, 67 | args.caption_vector_length, args.n_classes) 68 | 69 | model_options = { 70 | 'z_dim': args.z_dim, 71 | 't_dim': args.t_dim, 72 | 'batch_size': args.batch_size, 73 | 'image_size': args.image_size, 74 | 'gf_dim': args.gf_dim, 75 | 'df_dim': args.df_dim, 76 | 'caption_vector_length': args.caption_vector_length, 77 | 'n_classes': loaded_data['n_classes'] 78 | } 79 | 80 | gan = model.GAN(model_options) 81 | input_tensors, variables, loss, outputs, checks = gan.build_model() 82 | 83 | sess = tf.InteractiveSession() 84 | tf.initialize_all_variables().run() 85 | 86 | saver = tf.train.Saver(max_to_keep=10000) 87 | print('resuming model from checkpoint' + 88 | str(tf.train.latest_checkpoint(args.checkpoints_dir))) 89 | if tf.train.latest_checkpoint(args.checkpoints_dir) is not None: 90 | saver.restore(sess, tf.train.latest_checkpoint(args.checkpoints_dir)) 91 | print('Successfully loaded model from ') 92 | else: 93 | print('Could not load checkpoints') 94 | exit() 95 | 96 | print('Generating images for the captions in the training set at ' + 97 | model_stage_1_ds_tr) 98 | for i in range(args.epochs): 99 | batch_no = 0 100 | while batch_no * args.batch_size + args.batch_size < \ 101 | loaded_data['data_length']: 102 | 103 | real_images, wrong_images, caption_vectors, z_noise, image_files, \ 104 | real_classes, wrong_classes, image_caps, image_ids, \ 105 | image_caps_ids = get_training_batch(batch_no, args.batch_size, 106 | args.image_size, args.z_dim, datasets_root_dir, 107 | args.data_set, loaded_data) 108 | 109 | feed = { 110 | input_tensors['t_real_image'].name: real_images, 111 | input_tensors['t_wrong_image'].name: wrong_images, 112 | input_tensors['t_real_caption'].name: caption_vectors, 113 | input_tensors['t_z'].name: z_noise, 114 | input_tensors['t_real_classes'].name: real_classes, 115 | input_tensors['t_wrong_classes'].name: wrong_classes, 116 | input_tensors['t_training'].name: True 117 | } 118 | 119 | g_loss, gen = sess.run([loss['g_loss'], outputs['generator']], 120 | feed_dict=feed) 121 | 122 | print("LOSSES", g_loss, batch_no, i, 123 | len(loaded_data['image_list']) / args.batch_size) 124 | batch_no += 1 125 | save_distributed_image_batch(model_stage_1_ds_tr, gen, image_caps, 126 | image_ids, image_caps_ids) 127 | 128 | print('Finished generating images for the training set captions.\n\n') 129 | print('Generating images for the captions in the validation set at ' + 130 | model_stage_1_ds_val) 131 | for i in range(args.epochs): 132 | batch_no = 0 133 | while batch_no * args.batch_size + args.batch_size < \ 134 | loaded_data['val_data_len']: 135 | 136 | val_captions, val_image_files, val_image_caps, val_image_ids, \ 137 | val_image_caps_ids, val_z_noise = get_val_caps_batch(batch_no, 138 | args.batch_size, args.z_dim, loaded_data, args.data_set, 139 | datasets_root_dir) 140 | 141 | val_feed = { 142 | input_tensors['t_real_caption'].name: val_captions, 143 | input_tensors['t_z'].name: val_z_noise, 144 | input_tensors['t_training'].name: True 145 | } 146 | 147 | val_gen, val_attn_spn = sess.run( 148 | [outputs['generator'], checks['attn_span']], 149 | feed_dict=val_feed) 150 | 151 | print("LOSSES", batch_no, i, len( 152 | loaded_data['val_img_list']) / args.batch_size) 153 | batch_no += 1 154 | save_distributed_image_batch(model_stage_1_ds_val, val_gen, 155 | val_image_caps, 156 | val_image_ids, 157 | val_image_caps_ids, val_attn_spn) 158 | print('Finished generating images for the validation set captions.\n\n') 159 | 160 | def prepare_dirs(args): 161 | 162 | model_stage_1_ds_tr = join(args.output_dir, 'ds', 'train') 163 | if not os.path.exists(model_stage_1_ds_tr): 164 | os.makedirs(model_stage_1_ds_tr) 165 | 166 | model_stage_1_ds_val = join(args.output_dir, 'ds', 'val') 167 | if not os.path.exists(model_stage_1_ds_val): 168 | os.makedirs(model_stage_1_ds_val) 169 | 170 | datasets_root_dir = join(args.data_dir, 'datasets') 171 | 172 | return model_stage_1_ds_tr, model_stage_1_ds_val, datasets_root_dir 173 | 174 | 175 | def load_training_data(data_dir, data_set, caption_vector_length, n_classes): 176 | if data_set == 'flowers': 177 | flower_str_captions = pickle.load( 178 | open(join(data_dir, 'flowers', 'flowers_caps.pkl'), "rb")) 179 | 180 | img_classes = pickle.load( 181 | open(join(data_dir, 'flowers', 'flower_tc.pkl'), "rb")) 182 | 183 | flower_enc_captions = pickle.load( 184 | open(join(data_dir, 'flowers', 'flower_tv.pkl'), "rb")) 185 | # h1 = h5py.File(join(data_dir, 'flower_tc.hdf5')) 186 | tr_image_ids = pickle.load( 187 | open(join(data_dir, 'flowers', 'train_ids.pkl'), "rb")) 188 | val_image_ids = pickle.load( 189 | open(join(data_dir, 'flowers', 'val_ids.pkl'), "rb")) 190 | 191 | # n_classes = n_classes 192 | max_caps_len = caption_vector_length 193 | 194 | tr_n_imgs = len(tr_image_ids) 195 | val_n_imgs = len(val_image_ids) 196 | 197 | return { 198 | 'image_list': tr_image_ids, 199 | 'captions': flower_enc_captions, 200 | 'data_length': tr_n_imgs, 201 | 'classes': img_classes, 202 | 'n_classes': n_classes, 203 | 'max_caps_len': max_caps_len, 204 | 'val_img_list': val_image_ids, 205 | 'val_captions': flower_enc_captions, 206 | 'val_data_len': val_n_imgs, 207 | 'str_captions': flower_str_captions 208 | } 209 | 210 | else: 211 | raise Exception('Dataset not found') 212 | 213 | 214 | def save_distributed_image_batch(data_dir, generated_images, image_caps, 215 | image_ids, caps_ids): 216 | for i, (image_id, caps_id, image_cap) in enumerate(zip( image_ids, \ 217 | caps_ids, image_caps)): 218 | image_dir = join(data_dir, str(image_id), str(caps_id)) 219 | if not os.path.exists(image_dir): 220 | os.makedirs(image_dir) 221 | collection_dir = join(data_dir, 'collection') 222 | if not os.path.exists(collection_dir): 223 | os.makedirs(collection_dir) 224 | caps_dir = join(image_dir, "caps.txt") 225 | if not os.path.exists(caps_dir): 226 | with open(caps_dir, "w") as text_file: 227 | text_file.write(image_cap + "\n") 228 | 229 | fake_image_255 = (generated_images[i, :, :, :]) 230 | if i == 0: 231 | scipy.misc.imsave(join(collection_dir, '{}.jpg'.format(image_id)), 232 | fake_image_255) 233 | num_files = len(os.walk(image_dir).__next__()[2]) 234 | scipy.misc.imsave(join(image_dir, '{}.jpg'.format(num_files + 1)), 235 | fake_image_255) 236 | 237 | 238 | def get_training_batch(batch_no, batch_size, image_size, z_dim, data_dir, 239 | data_set, loaded_data=None): 240 | 241 | if data_set == 'flowers': 242 | real_images = np.zeros((batch_size, image_size, image_size, 3)) 243 | wrong_images = np.zeros((batch_size, image_size, image_size, 3)) 244 | captions = np.zeros((batch_size, loaded_data['max_caps_len'])) 245 | real_classes = np.zeros((batch_size, loaded_data['n_classes'])) 246 | wrong_classes = np.zeros((batch_size, loaded_data['n_classes'])) 247 | 248 | cnt = 0 249 | image_files, image_caps, image_ids, image_caps_ids = [], [], [], [] 250 | 251 | for i in range(batch_no * batch_size, 252 | batch_no * batch_size + batch_size): 253 | 254 | idx = i % len(loaded_data['image_list']) 255 | image_file = join(data_dir, 256 | 'flowers/jpg/' + loaded_data['image_list'][idx]) 257 | 258 | image_ids.append(loaded_data['image_list'][idx]) 259 | 260 | image_array = image_processing.load_image_array_flowers(image_file, 261 | image_size) 262 | real_images[cnt, :, :, :] = image_array 263 | 264 | # Improve this selection of wrong image 265 | wrong_image_id = random.randint(0, 266 | len(loaded_data['image_list']) - 1) 267 | wrong_image_file = join(data_dir, 268 | 'flowers/jpg/' + loaded_data['image_list'][ 269 | wrong_image_id]) 270 | wrong_image_array = image_processing.load_image_array_flowers( 271 | wrong_image_file, 272 | image_size) 273 | wrong_images[cnt, :, :, :] = wrong_image_array 274 | 275 | wrong_classes[cnt, :] = loaded_data['classes'][ 276 | loaded_data['image_list'][ 277 | wrong_image_id]][ 278 | 0:loaded_data['n_classes']] 279 | 280 | random_caption = random.randint(0, 4) 281 | image_caps_ids.append(random_caption) 282 | captions[cnt, :] = \ 283 | loaded_data['captions'][loaded_data['image_list'][idx]][ 284 | random_caption][0:loaded_data['max_caps_len']] 285 | 286 | real_classes[cnt, :] = \ 287 | loaded_data['classes'][loaded_data['image_list'][idx]][ 288 | 0:loaded_data['n_classes']] 289 | str_cap = loaded_data['str_captions'][loaded_data['image_list'] 290 | [idx]][random_caption] 291 | 292 | image_files.append(image_file) 293 | image_caps.append(str_cap) 294 | cnt += 1 295 | 296 | z_noise = np.random.uniform(-1, 1, [batch_size, z_dim]) 297 | return real_images, wrong_images, captions, z_noise, image_files, \ 298 | real_classes, wrong_classes, image_caps, image_ids, \ 299 | image_caps_ids 300 | else: 301 | raise Exception('Dataset not found') 302 | 303 | 304 | def get_val_caps_batch(batch_no, batch_size, z_dim, loaded_data, data_set, 305 | data_dir): 306 | 307 | if data_set == 'flowers': 308 | captions = np.zeros((batch_size, loaded_data['max_caps_len'])) 309 | batch_idx = range(batch_no * batch_size, 310 | batch_no * batch_size + batch_size) 311 | image_ids = np.take(loaded_data['val_img_list'], batch_idx) 312 | 313 | image_files = [] 314 | image_caps = [] 315 | image_caps_ids = [] 316 | 317 | for idx, image_id in enumerate(image_ids) : 318 | image_file = join(data_dir, 319 | 'flowers/jpg/' + image_id) 320 | random_caption = random.randint(0, 4) 321 | image_caps_ids.append(random_caption) 322 | captions[idx, :] = \ 323 | loaded_data['val_captions'][image_id][random_caption][ 324 | 0 :loaded_data['max_caps_len']] 325 | str_cap = loaded_data['str_captions'][image_id][random_caption] 326 | image_caps.append(loaded_data['str_captions'] 327 | [image_id][random_caption]) 328 | image_files.append(image_file) 329 | 330 | z_noise = np.random.uniform(-1, 1, [batch_size, z_dim]) 331 | return captions, image_files, image_caps, image_ids, image_caps_ids, \ 332 | z_noise 333 | 334 | 335 | if __name__ == '__main__': 336 | main() 337 | -------------------------------------------------------------------------------- /dataprep.py: -------------------------------------------------------------------------------- 1 | import os 2 | import argparse 3 | import skipthoughts 4 | import traceback 5 | import pickle 6 | import random 7 | 8 | import numpy as np 9 | 10 | from os.path import join 11 | 12 | def get_one_hot_targets(target_file_path): 13 | target = [] 14 | one_hot_targets = [] 15 | n_target = 0 16 | try : 17 | with open(target_file_path) as f : 18 | target = f.readlines() 19 | target = [t.strip('\n') for t in target] 20 | n_target = len(target) 21 | except IOError : 22 | print('Could not load the labels.txt file in the dataset. A ' 23 | 'dataset folder is expected in the "data/datasets" ' 24 | 'directory with the name that has been passed as an ' 25 | 'argument to this method. This directory should contain a ' 26 | 'file called labels.txt which contains a list of labels and ' 27 | 'corresponding folders for the labels with the same name as ' 28 | 'the labels.') 29 | traceback.print_stack() 30 | 31 | lbl_idxs = np.arange(n_target) 32 | one_hot_targets = np.zeros((n_target, n_target)) 33 | one_hot_targets[np.arange(n_target), lbl_idxs] = 1 34 | 35 | return target, one_hot_targets, n_target 36 | 37 | def one_hot_encode_str_lbl(lbl, target, one_hot_targets): 38 | ''' 39 | Encodes a string label into one-hot encoding 40 | 41 | Example: 42 | input: "window" 43 | output: [0 0 0 0 0 0 1 0 0 0 0 0] 44 | the length would depend on the number of classes in the dataset. The 45 | above is just a random example. 46 | 47 | :param lbl: The string label 48 | :return: one-hot encoding 49 | ''' 50 | idx = target.index(lbl) 51 | return one_hot_targets[idx] 52 | 53 | def save_caption_vectors_flowers(data_dir, dt_range=(1, 103)) : 54 | import time 55 | 56 | img_dir = join(data_dir, 'flowers/jpg') 57 | all_caps_dir = join(data_dir, 'flowers/all_captions.txt') 58 | target_file_path = os.path.join(data_dir, "flowers/allclasses.txt") 59 | caption_dir = join(data_dir, 'flowers/text_c10') 60 | image_files = [f for f in os.listdir(img_dir) if 'jpg' in f] 61 | print(image_files[300 :400]) 62 | image_captions = {} 63 | image_classes = {} 64 | class_dirs = [] 65 | class_names = [] 66 | img_ids = [] 67 | 68 | target, one_hot_targets, n_target = get_one_hot_targets(target_file_path) 69 | 70 | for i in range(dt_range[0], dt_range[1]) : 71 | class_dir_name = 'class_%.5d' % (i) 72 | class_dir = join(caption_dir, class_dir_name) 73 | class_names.append(class_dir_name) 74 | class_dirs.append(class_dir) 75 | onlyimgfiles = [f[0 :11] + ".jpg" for f in os.listdir(class_dir) 76 | if 'txt' in f] 77 | for img_file in onlyimgfiles: 78 | image_classes[img_file] = None 79 | 80 | for img_file in onlyimgfiles: 81 | image_captions[img_file] = [] 82 | 83 | for class_dir, class_name in zip(class_dirs, class_names) : 84 | caption_files = [f for f in os.listdir(class_dir) if 'txt' in f] 85 | for i, cap_file in enumerate(caption_files) : 86 | if i%50 == 0: 87 | print(str(i) + ' captions extracted from' + str(class_dir)) 88 | with open(join(class_dir, cap_file)) as f : 89 | str_captions = f.read() 90 | captions = str_captions.split('\n') 91 | img_file = cap_file[0 :11] + ".jpg" 92 | 93 | # 5 captions per image 94 | image_captions[img_file] += [cap for cap in captions if len(cap) > 0][0 :5] 95 | image_classes[img_file] = one_hot_encode_str_lbl(class_name, 96 | target, 97 | one_hot_targets) 98 | 99 | model = skipthoughts.load_model() 100 | encoded_captions = {} 101 | for i, img in enumerate(image_captions) : 102 | st = time.time() 103 | encoded_captions[img] = skipthoughts.encode(model, image_captions[img]) 104 | if i%20 == 0: 105 | print(i, len(image_captions), img) 106 | print("Seconds", time.time() - st) 107 | 108 | img_ids = list(image_captions.keys()) 109 | 110 | random.shuffle(img_ids) 111 | n_train_instances = int(len(img_ids) * 0.9) 112 | tr_image_ids = img_ids[0 :n_train_instances] 113 | val_image_ids = img_ids[n_train_instances : -1] 114 | 115 | pickle.dump(image_captions, 116 | open(os.path.join(data_dir, 'flowers', 'flowers_caps.pkl'), "wb")) 117 | 118 | pickle.dump(tr_image_ids, 119 | open(os.path.join(data_dir, 'flowers', 'train_ids.pkl'), "wb")) 120 | pickle.dump(val_image_ids, 121 | open(os.path.join(data_dir, 'flowers', 'val_ids.pkl'), "wb")) 122 | 123 | ec_pkl_path = (join(data_dir, 'flowers', 'flower_tv.pkl')) 124 | pickle.dump(encoded_captions, open(ec_pkl_path, "wb")) 125 | 126 | fc_pkl_path = (join(data_dir, 'flowers', 'flower_tc.pkl')) 127 | pickle.dump(image_classes, open(fc_pkl_path, "wb")) 128 | 129 | def main() : 130 | parser = argparse.ArgumentParser() 131 | parser.add_argument('--data_dir', type = str, default = 'Data', 132 | help = 'Data directory') 133 | parser.add_argument('--dataset', type=str, default='flowers', 134 | help='Dataset to use. For Eg., "flowers"') 135 | args = parser.parse_args() 136 | 137 | dataset_dir = join(args.data_dir, "datasets") 138 | if args.dataset == 'flowers': 139 | save_caption_vectors_flowers(dataset_dir) 140 | else: 141 | print('Preprocessor for this dataset is not available.') 142 | 143 | 144 | if __name__ == '__main__' : 145 | main() 146 | -------------------------------------------------------------------------------- /decoder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved. 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # ============================================================================== 16 | r"""Neural Network Image Compression Decoder. 17 | 18 | Decompress an image from the numpy's npz format generated by the encoder. 19 | 20 | Example usage: 21 | python decoder.py --input_codes=output_codes.pkl --iteration=15 \ 22 | --output_directory=/tmp/compression_output/ --model=residual_gru.pb 23 | """ 24 | import io 25 | import os 26 | 27 | import numpy as np 28 | import tensorflow as tf 29 | 30 | tf.flags.DEFINE_string('input_codes', None, 'Location of binary code file.') 31 | tf.flags.DEFINE_integer('iteration', -1, 'The max quality level of ' 32 | 'the images to output. Use -1 to infer from loaded ' 33 | ' codes.') 34 | tf.flags.DEFINE_string('output_directory', None, 'Directory to save decoded ' 35 | 'images.') 36 | tf.flags.DEFINE_string('model', None, 'Location of compression model.') 37 | 38 | FLAGS = tf.flags.FLAGS 39 | 40 | 41 | def get_input_tensor_names(): 42 | name_list = ['GruBinarizer/SignBinarizer/Sign:0'] 43 | for i in range(1, 16): 44 | name_list.append('GruBinarizer/SignBinarizer/Sign_{}:0'.format(i)) 45 | return name_list 46 | 47 | 48 | def get_output_tensor_names(): 49 | return ['loop_{0:02d}/add:0'.format(i) for i in range(0, 16)] 50 | 51 | 52 | def main(_): 53 | if (FLAGS.input_codes is None or FLAGS.output_directory is None or 54 | FLAGS.model is None): 55 | print('\nUsage: python decoder.py --input_codes=output_codes.pkl ' 56 | '--iteration=15 --output_directory=/tmp/compression_output/ ' 57 | '--model=residual_gru.pb\n\n') 58 | return 59 | 60 | if FLAGS.iteration < -1 or FLAGS.iteration > 15: 61 | print('\n--iteration must be between 0 and 15 inclusive, or -1 to infer ' 62 | 'from file.\n') 63 | return 64 | iteration = FLAGS.iteration 65 | 66 | if not tf.gfile.Exists(FLAGS.output_directory): 67 | tf.gfile.MkDir(FLAGS.output_directory) 68 | 69 | if not tf.gfile.Exists(FLAGS.input_codes): 70 | print('\nInput codes not found.\n') 71 | return 72 | 73 | contents = '' 74 | with tf.gfile.FastGFile(FLAGS.input_codes, 'r') as code_file: 75 | contents = code_file.read() 76 | loaded_codes = np.load(io.BytesIO(contents)) 77 | assert ['codes', 'shape'] not in loaded_codes.files 78 | loaded_shape = loaded_codes['shape'] 79 | loaded_array = loaded_codes['codes'] 80 | 81 | # Unpack and recover code shapes. 82 | unpacked_codes = np.reshape(np.unpackbits(loaded_array) 83 | [:np.prod(loaded_shape)], 84 | loaded_shape) 85 | 86 | numpy_int_codes = np.split(unpacked_codes, len(unpacked_codes)) 87 | if iteration == -1: 88 | iteration = len(unpacked_codes) - 1 89 | # Convert back to float and recover scale. 90 | numpy_codes = [np.squeeze(x.astype(np.float32), 0) * 2 - 1 for x in 91 | numpy_int_codes] 92 | 93 | with tf.Graph().as_default() as graph: 94 | # Load the inference model for decoding. 95 | with tf.gfile.FastGFile(FLAGS.model, 'rb') as model_file: 96 | graph_def = tf.GraphDef() 97 | graph_def.ParseFromString(model_file.read()) 98 | _ = tf.import_graph_def(graph_def, name='') 99 | 100 | # For encoding the tensors into PNGs. 101 | input_image = tf.placeholder(tf.uint8) 102 | encoded_image = tf.image.encode_png(input_image) 103 | 104 | input_tensors = [graph.get_tensor_by_name(name) for name in 105 | get_input_tensor_names()][0:iteration+1] 106 | outputs = [graph.get_tensor_by_name(name) for name in 107 | get_output_tensor_names()][0:iteration+1] 108 | 109 | feed_dict = {key: value for (key, value) in zip(input_tensors, 110 | numpy_codes)} 111 | 112 | with tf.Session(graph=graph) as sess: 113 | results = sess.run(outputs, feed_dict=feed_dict) 114 | 115 | for index, result in enumerate(results): 116 | img = np.uint8(np.clip(result + 0.5, 0, 255)) 117 | img = img.squeeze() 118 | png_img = sess.run(encoded_image, feed_dict={input_image: img}) 119 | 120 | with tf.gfile.FastGFile(os.path.join(FLAGS.output_directory, 121 | 'image_{0:02d}.png'.format(index)), 122 | 'w') as output_image: 123 | output_image.write(png_img) 124 | 125 | 126 | if __name__ == '__main__': 127 | tf.app.run() 128 | -------------------------------------------------------------------------------- /encode_text.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | import argparse 4 | import skipthoughts 5 | import sys 6 | 7 | def main(): 8 | parser = argparse.ArgumentParser() 9 | parser.add_argument('--caption_file', type=str, default='Data/text.txt', 10 | help='caption file') 11 | parser.add_argument('--data_dir', type=str, default='Data', 12 | help='Data Directory') 13 | 14 | args = parser.parse_args() 15 | 16 | model = skipthoughts.load_model() 17 | encoded_captions = {} 18 | file_path = os.path.join(args.caption_file) 19 | dump_path = os.path.join(args.data_dir, 'enc_text.pkl') 20 | with open(file_path) as f: 21 | str_captions = f.read() 22 | captions = str_captions.split('\n') 23 | print(captions) 24 | encoded_captions['features'] = skipthoughts.encode(model, captions) 25 | 26 | pickle.dump(encoded_captions, 27 | open(dump_path, "wb")) 28 | print('Finished extracting Skip-Thought vectors of the given text ' 29 | 'descriptions') 30 | 31 | if __name__ == '__main__': 32 | main() -------------------------------------------------------------------------------- /encoder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # ============================================================================== 17 | r"""Neural Network Image Compression Encoder. 18 | 19 | Compresses an image to a binarized numpy array. The image must be padded to a 20 | multiple of 32 pixels in height and width. 21 | 22 | Example usage: 23 | python encoder.py --input_image=/your/image/here.png \ 24 | --output_codes=output_codes.pkl --iteration=15 --model=residual_gru.pb 25 | """ 26 | import io 27 | import os 28 | 29 | import numpy as np 30 | import tensorflow as tf 31 | 32 | tf.flags.DEFINE_string('input_image', None, 'Location of input image. We rely ' 33 | 'on tf.image to decode the image, so only PNG and JPEG ' 34 | 'formats are currently supported.') 35 | tf.flags.DEFINE_integer('iteration', 15, 'Quality level for encoding image. ' 36 | 'Must be between 0 and 15 inclusive.') 37 | tf.flags.DEFINE_string('output_codes', None, 'File to save output encoding.') 38 | tf.flags.DEFINE_string('model', None, 'Location of compression model.') 39 | 40 | FLAGS = tf.flags.FLAGS 41 | 42 | 43 | def get_output_tensor_names(): 44 | name_list = ['GruBinarizer/SignBinarizer/Sign:0'] 45 | for i in range(1, 16): 46 | name_list.append('GruBinarizer/SignBinarizer/Sign_{}:0'.format(i)) 47 | return name_list 48 | 49 | 50 | def main(_): 51 | if (FLAGS.input_image is None or FLAGS.output_codes is None or 52 | FLAGS.model is None): 53 | print('\nUsage: python encoder.py --input_image=/your/image/here.png ' 54 | '--output_codes=output_codes.pkl --iteration=15 ' 55 | '--model=residual_gru.pb\n\n') 56 | return 57 | 58 | if FLAGS.iteration < 0 or FLAGS.iteration > 15: 59 | print('\n--iteration must be between 0 and 15 inclusive.\n') 60 | return 61 | 62 | with tf.gfile.FastGFile(FLAGS.input_image) as input_image: 63 | input_image_str = input_image.read() 64 | 65 | with tf.Graph().as_default() as graph: 66 | # Load the inference model for encoding. 67 | with tf.gfile.FastGFile(FLAGS.model, 'rb') as model_file: 68 | graph_def = tf.GraphDef() 69 | graph_def.ParseFromString(model_file.read()) 70 | _ = tf.import_graph_def(graph_def, name='') 71 | 72 | input_tensor = graph.get_tensor_by_name('Placeholder:0') 73 | outputs = [graph.get_tensor_by_name(name) for name in 74 | get_output_tensor_names()] 75 | 76 | input_image = tf.placeholder(tf.string) 77 | _, ext = os.path.splitext(FLAGS.input_image) 78 | if ext == '.png': 79 | decoded_image = tf.image.decode_png(input_image, channels=3) 80 | elif ext == '.jpeg' or ext == '.jpg': 81 | decoded_image = tf.image.decode_jpeg(input_image, channels=3) 82 | else: 83 | assert False, 'Unsupported file format {}'.format(ext) 84 | decoded_image = tf.expand_dims(decoded_image, 0) 85 | 86 | with tf.Session(graph=graph) as sess: 87 | img_array = sess.run(decoded_image, feed_dict={input_image: 88 | input_image_str}) 89 | results = sess.run(outputs, feed_dict={input_tensor: img_array}) 90 | 91 | results = results[0:FLAGS.iteration + 1] 92 | int_codes = np.asarray([x.astype(np.int8) for x in results]) 93 | 94 | # Convert int codes to binary. 95 | int_codes = (int_codes + 1)//2 96 | export = np.packbits(int_codes.reshape(-1)) 97 | 98 | output = io.BytesIO() 99 | np.savez_compressed(output, shape=int_codes.shape, codes=export) 100 | with tf.gfile.FastGFile(FLAGS.output_codes, 'w') as code_file: 101 | code_file.write(output.getvalue()) 102 | 103 | 104 | if __name__ == '__main__': 105 | tf.app.run() 106 | -------------------------------------------------------------------------------- /generate_images.py: -------------------------------------------------------------------------------- 1 | import model 2 | import argparse 3 | import pickle 4 | import scipy.misc 5 | import random 6 | import os 7 | 8 | import tensorflow as tf 9 | import numpy as np 10 | 11 | from os.path import join 12 | 13 | 14 | def main(): 15 | parser = argparse.ArgumentParser() 16 | parser.add_argument('--z_dim', type=int, default=100, 17 | help='Noise dimension') 18 | 19 | parser.add_argument('--t_dim', type=int, default=256, 20 | help='Text feature dimension') 21 | 22 | parser.add_argument('--batch_size', type=int, default=64, 23 | help='Batch Size') 24 | 25 | parser.add_argument('--image_size', type=int, default=128, 26 | help='Image Size a, a x a') 27 | 28 | parser.add_argument('--gf_dim', type=int, default=64, 29 | help='Number of conv in the first layer gen.') 30 | 31 | parser.add_argument('--df_dim', type=int, default=64, 32 | help='Number of conv in the first layer discr.') 33 | 34 | parser.add_argument('--caption_vector_length', type=int, default=4800, 35 | help='Caption Vector Length') 36 | 37 | parser.add_argument('--n_classes', type=int, default=102, 38 | help='Number of classes/class labels') 39 | 40 | parser.add_argument('--data_dir', type=str, default="Data", 41 | help='Data Directory') 42 | 43 | parser.add_argument('--learning_rate', type=float, default=0.0002, 44 | help='Learning Rate') 45 | 46 | parser.add_argument('--beta1', type=float, default=0.5, 47 | help='Momentum for Adam Update') 48 | 49 | parser.add_argument('--images_per_caption', type=int, default=30, 50 | help='The number of images that you want to generate ' 51 | 'per text description') 52 | 53 | parser.add_argument('--data_set', type=str, default="flowers", 54 | help='Dat set: MS-COCO, flowers') 55 | 56 | parser.add_argument('--checkpoints_dir', type=str, default="/tmp", 57 | help='Path to the checkpoints directory') 58 | 59 | 60 | args = parser.parse_args() 61 | 62 | datasets_root_dir = join(args.data_dir, 'datasets') 63 | 64 | loaded_data = load_training_data(datasets_root_dir, args.data_set, 65 | args.caption_vector_length, 66 | args.n_classes) 67 | model_options = { 68 | 'z_dim': args.z_dim, 69 | 't_dim': args.t_dim, 70 | 'batch_size': args.batch_size, 71 | 'image_size': args.image_size, 72 | 'gf_dim': args.gf_dim, 73 | 'df_dim': args.df_dim, 74 | 'caption_vector_length': args.caption_vector_length, 75 | 'n_classes': loaded_data['n_classes'] 76 | } 77 | 78 | gan = model.GAN(model_options) 79 | input_tensors, variables, loss, outputs, checks = gan.build_model() 80 | 81 | sess = tf.InteractiveSession() 82 | tf.initialize_all_variables().run() 83 | 84 | saver = tf.train.Saver(max_to_keep=10000) 85 | print('Trying to resume model from ' + 86 | str(tf.train.latest_checkpoint(args.checkpoints_dir))) 87 | if tf.train.latest_checkpoint(args.checkpoints_dir) is not None: 88 | saver.restore(sess, tf.train.latest_checkpoint(args.checkpoints_dir)) 89 | print('Successfully loaded model from ') 90 | else: 91 | print('Could not load checkpoints. Please provide a valid path to' 92 | ' your checkpoints directory') 93 | exit() 94 | 95 | print('Starting to generate images from text descriptions.') 96 | for sel_i, text_cap in enumerate(loaded_data['text_caps']['features']): 97 | 98 | print('Text idx: {}\nRaw Text: {}\n'.format(sel_i, text_cap)) 99 | captions_1, image_files_1, image_caps_1, image_ids_1,\ 100 | image_caps_ids_1 = get_caption_batch(loaded_data, datasets_root_dir, 101 | dataset=args.data_set, batch_size=args.batch_size) 102 | 103 | captions_1[args.batch_size-1, :] = text_cap 104 | 105 | for z_i in range(args.images_per_caption): 106 | z_noise = np.random.uniform(-1, 1, [args.batch_size, args.z_dim]) 107 | val_feed = { 108 | input_tensors['t_real_caption'].name: captions_1, 109 | input_tensors['t_z'].name: z_noise, 110 | input_tensors['t_training'].name: True 111 | } 112 | 113 | val_gen = sess.run( 114 | [outputs['generator']], 115 | feed_dict=val_feed) 116 | dump_dir = os.path.join(args.data_dir, 117 | 'images_generated_from_text') 118 | save_distributed_image_batch(dump_dir, val_gen, sel_i, z_i, 119 | args.batch_size) 120 | print('Finished generating images from text description') 121 | 122 | 123 | def load_training_data(data_dir, data_set, caption_vector_length, n_classes): 124 | if data_set == 'flowers': 125 | flower_str_captions = pickle.load( 126 | open(join(data_dir, 'flowers', 'flowers_caps.pkl'), "rb")) 127 | 128 | img_classes = pickle.load( 129 | open(join(data_dir, 'flowers', 'flower_tc.pkl'), "rb")) 130 | 131 | flower_enc_captions = pickle.load( 132 | open(join(data_dir, 'flowers', 'flower_tv.pkl'), "rb")) 133 | # h1 = h5py.File(join(data_dir, 'flower_tc.hdf5')) 134 | tr_image_ids = pickle.load( 135 | open(join(data_dir, 'flowers', 'train_ids.pkl'), "rb")) 136 | val_image_ids = pickle.load( 137 | open(join(data_dir, 'flowers', 'val_ids.pkl'), "rb")) 138 | caps_new = pickle.load( 139 | open(join('Data', 'enc_text.pkl'), "rb")) 140 | 141 | # n_classes = n_classes 142 | max_caps_len = caption_vector_length 143 | 144 | tr_n_imgs = len(tr_image_ids) 145 | val_n_imgs = len(val_image_ids) 146 | 147 | return { 148 | 'image_list': tr_image_ids, 149 | 'captions': flower_enc_captions, 150 | 'data_length': tr_n_imgs, 151 | 'classes': img_classes, 152 | 'n_classes': n_classes, 153 | 'max_caps_len': max_caps_len, 154 | 'val_img_list': val_image_ids, 155 | 'val_captions': flower_enc_captions, 156 | 'val_data_len': val_n_imgs, 157 | 'str_captions': flower_str_captions, 158 | 'text_caps': caps_new 159 | } 160 | 161 | else: 162 | raise Exception('This dataset has not been handeled yet. ' 163 | 'Contributions are welcome.') 164 | 165 | 166 | def save_distributed_image_batch(data_dir, generated_images, sel_i, z_i, 167 | batch_size=64): 168 | generated_images = np.squeeze(generated_images) 169 | folder_name = str(sel_i) 170 | image_dir = join(data_dir, folder_name) 171 | if not os.path.exists(image_dir): 172 | os.makedirs(image_dir) 173 | fake_image_255 = generated_images[batch_size-1] 174 | scipy.misc.imsave(join(image_dir, '{}.jpg'.format(z_i)), 175 | fake_image_255) 176 | 177 | 178 | def get_caption_batch(loaded_data, data_dir, dataset='flowers', batch_size=64): 179 | 180 | captions = np.zeros((batch_size, loaded_data['max_caps_len'])) 181 | batch_idx = np.random.randint(0, loaded_data['data_length'], 182 | size=batch_size) 183 | image_ids = np.take(loaded_data['image_list'], batch_idx) 184 | image_files = [] 185 | image_caps = [] 186 | image_caps_ids = [] 187 | for idx, image_id in enumerate(image_ids): 188 | image_file = join(data_dir, dataset, 'jpg' + image_id) 189 | random_caption = random.randint(0, 4) 190 | image_caps_ids.append(random_caption) 191 | captions[idx, :] = \ 192 | loaded_data['captions'][image_id][random_caption][ 193 | 0:loaded_data['max_caps_len']] 194 | 195 | image_caps.append(loaded_data['captions'] 196 | [image_id][random_caption]) 197 | image_files.append(image_file) 198 | 199 | return captions, image_files, image_caps, image_ids, image_caps_ids 200 | 201 | if __name__ == '__main__': 202 | main() -------------------------------------------------------------------------------- /inception_score.py: -------------------------------------------------------------------------------- 1 | import os 2 | import argparse 3 | import progressbar 4 | 5 | from shutil import copy 6 | from Utils import inception_score as ins 7 | from Utils import image_processing as ip 8 | 9 | 10 | 11 | def prepare_inception_data(o_dir, i_dir): 12 | if not os.path.exists(o_dir): 13 | os.makedirs(o_dir) 14 | cnt = 0 15 | bar = progressbar.ProgressBar(redirect_stdout=True, 16 | max_value=progressbar.UnknownLength) 17 | for root, subFolders, files in os.walk(i_dir): 18 | if files: 19 | for f in files: 20 | if 'jpg' in f: 21 | f_name = str(cnt) + '_ins.' + f.split('.')[-1] 22 | cnt += 1 23 | file_dir = os.path.join(root, f) 24 | dest_path = os.path.join(o_dir, f) 25 | dest_new_name = os.path.join(o_dir, f_name) 26 | copy(file_dir, o_dir) 27 | os.rename(dest_path, dest_new_name) 28 | bar.update(cnt) 29 | bar.finish() 30 | print('Total number of files: {}'.format(cnt)) 31 | 32 | def load_images(o_dir, i_dir, n_images=3000, size=128): 33 | prepare_inception_data(o_dir, i_dir) 34 | image_list = [] 35 | done = False 36 | cnt = 0 37 | bar = progressbar.ProgressBar(redirect_stdout=True, 38 | max_value=progressbar.UnknownLength) 39 | for root, dirs, files in os.walk(o_dir): 40 | if files: 41 | for f in files: 42 | cnt += 1 43 | file_dir = os.path.join(root, f) 44 | image_list.append(ip.load_image_inception(file_dir, 0)) 45 | bar.update(cnt) 46 | if len(image_list) == n_images: 47 | done = True 48 | break 49 | if done: 50 | break 51 | bar.finish() 52 | print('Finished Loading Files') 53 | return image_list 54 | 55 | 56 | if __name__ == '__main__': 57 | parser = argparse.ArgumentParser() 58 | 59 | parser.add_argument('--output_dir', type=str, default="Data/ds_inception", 60 | help='directory to dump all the images for ' 61 | 'calculating the inception score') 62 | 63 | parser.add_argument('--data_dir', type=str, 64 | default="Data/synthetic_dataset/ds", 65 | help='The root directory of the synthetic dataset') 66 | 67 | parser.add_argument('--n_images', type=int, default=30000, 68 | help='Number of images to consider for calculating ' 69 | 'inception score') 70 | 71 | parser.add_argument('--image_size', type=int, default=128, 72 | help='Size of the image to consider for calculating ' 73 | 'inception score') 74 | 75 | args = parser.parse_args() 76 | 77 | imgs_list = load_images(args.output_dir, args.data_dir, 78 | n_images=args.n_images, size=args.image_size) 79 | 80 | print('Extracting Inception Score') 81 | mean, std = ins.get_inception_score(imgs_list) 82 | print('Mean Inception Score: {}\nStandard Deviation: {}'.format(mean, std)) -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import tensorflow.contrib.slim as slim 3 | from Utils import ops 4 | 5 | 6 | class GAN : 7 | ''' 8 | OPTIONS 9 | z_dim : Noise dimension 100 10 | t_dim : Text feature dimension 256 11 | image_size : Image Dimension 64 12 | gf_dim : Number of conv in the first layer generator 64 13 | df_dim : Number of conv in the first layer discriminator 64 14 | gfc_dim : Dimension of gen untis for for fully connected layer 1024 15 | caption_vector_length : Caption Vector Length 2400 16 | batch_size : Batch Size 64 17 | ''' 18 | 19 | def __init__(self, options) : 20 | self.options = options 21 | 22 | def build_model(self) : 23 | 24 | print('Initializing placeholder') 25 | img_size = self.options['image_size'] 26 | t_real_image = tf.placeholder('float32', [self.options['batch_size'], 27 | img_size, img_size, 3], 28 | name = 'real_image') 29 | t_wrong_image = tf.placeholder('float32', [self.options['batch_size'], 30 | img_size, img_size, 3], 31 | name = 'wrong_image') 32 | 33 | t_real_caption = tf.placeholder('float32', [self.options['batch_size'], 34 | self.options['caption_vector_length']], 35 | name='real_captions') 36 | 37 | t_z = tf.placeholder('float32', [self.options['batch_size'], 38 | self.options['z_dim']], name='input_noise') 39 | 40 | t_real_classes = tf.placeholder('float32', [self.options['batch_size'], 41 | self.options['n_classes']], 42 | name='real_classes') 43 | 44 | t_wrong_classes = tf.placeholder('float32', [self.options['batch_size'], 45 | self.options['n_classes']], 46 | name='wrong_classes') 47 | 48 | t_training = tf.placeholder(tf.bool, name='training') 49 | 50 | print('Building the Generator') 51 | fake_image = self.generator(t_z, t_real_caption, 52 | t_training) 53 | 54 | print('Building the Discriminator') 55 | disc_real_image, disc_real_image_logits, disc_real_image_aux, \ 56 | disc_real_image_aux_logits = self.discriminator( 57 | t_real_image, t_real_caption, self.options['n_classes'], 58 | t_training) 59 | 60 | disc_wrong_image, disc_wrong_image_logits, disc_wrong_image_aux, \ 61 | disc_wrong_image_aux_logits = self.discriminator( 62 | t_wrong_image, t_real_caption, self.options['n_classes'], 63 | t_training, reuse = True) 64 | 65 | disc_fake_image, disc_fake_image_logits, disc_fake_image_aux, \ 66 | disc_fake_image_aux_logits = self.discriminator( 67 | fake_image, t_real_caption, self.options['n_classes'], 68 | t_training, reuse = True) 69 | 70 | d_right_predictions = tf.equal(tf.argmax(disc_real_image_aux, 1), 71 | tf.argmax(t_real_classes, 1)) 72 | d_right_accuracy = tf.reduce_mean(tf.cast(d_right_predictions, 73 | tf.float32)) 74 | 75 | d_wrong_predictions = tf.equal(tf.argmax(disc_wrong_image_aux, 1), 76 | tf.argmax(t_wrong_classes, 1)) 77 | d_wrong_accuracy = tf.reduce_mean(tf.cast(d_wrong_predictions, 78 | tf.float32)) 79 | 80 | d_fake_predictions = tf.equal(tf.argmax(disc_fake_image_aux_logits, 1), 81 | tf.argmax(t_real_classes, 1)) 82 | d_fake_accuracy = tf.reduce_mean(tf.cast(d_fake_predictions, 83 | tf.float32)) 84 | 85 | tf.get_variable_scope()._reuse = False 86 | 87 | print('Building the Loss Function') 88 | g_loss_1 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( 89 | logits=disc_fake_image_logits, 90 | labels=tf.ones_like(disc_fake_image))) 91 | 92 | g_loss_2 = tf.reduce_mean( 93 | tf.nn.sigmoid_cross_entropy_with_logits( 94 | logits=disc_fake_image_aux_logits, 95 | labels=t_real_classes)) 96 | 97 | d_loss1 = tf.reduce_mean( 98 | tf.nn.sigmoid_cross_entropy_with_logits( 99 | logits=disc_real_image_logits, 100 | labels=tf.ones_like(disc_real_image))) 101 | d_loss1_1 = tf.reduce_mean( 102 | tf.nn.sigmoid_cross_entropy_with_logits( 103 | logits=disc_real_image_aux_logits, 104 | labels=t_real_classes)) 105 | d_loss2 = tf.reduce_mean( 106 | tf.nn.sigmoid_cross_entropy_with_logits( 107 | logits=disc_wrong_image_logits, 108 | labels=tf.zeros_like(disc_wrong_image))) 109 | d_loss2_1 = tf.reduce_mean( 110 | tf.nn.sigmoid_cross_entropy_with_logits( 111 | logits=disc_wrong_image_aux_logits, 112 | labels=t_wrong_classes)) 113 | d_loss3 = tf.reduce_mean( 114 | tf.nn.sigmoid_cross_entropy_with_logits( 115 | logits=disc_fake_image_logits, 116 | labels=tf.zeros_like(disc_fake_image))) 117 | 118 | d_loss = d_loss1 + d_loss1_1 + d_loss2 + d_loss2_1 + d_loss3 + g_loss_2 119 | 120 | g_loss = g_loss_1 + g_loss_2 121 | 122 | t_vars = tf.trainable_variables() 123 | print('List of all variables') 124 | for v in t_vars: 125 | print(v.name) 126 | print(v) 127 | self.add_histogram_summary(v.name, v) 128 | 129 | self.add_tb_scalar_summaries(d_loss, g_loss, d_loss1, d_loss2, d_loss3, 130 | d_loss1_1, d_loss2_1, g_loss_1, g_loss_2, d_right_accuracy, 131 | d_wrong_accuracy, d_fake_accuracy) 132 | 133 | self.add_image_summary('Generated Images', fake_image, 134 | self.options['batch_size']) 135 | 136 | d_vars = [var for var in t_vars if 'd_' in var.name] 137 | g_vars = [var for var in t_vars if 'g_' in var.name] 138 | 139 | input_tensors = { 140 | 't_real_image' : t_real_image, 141 | 't_wrong_image' : t_wrong_image, 142 | 't_real_caption' : t_real_caption, 143 | 't_z' : t_z, 144 | 't_real_classes' : t_real_classes, 145 | 't_wrong_classes' : t_wrong_classes, 146 | 't_training' : t_training, 147 | 148 | } 149 | 150 | variables = { 151 | 'd_vars' : d_vars, 152 | 'g_vars' : g_vars 153 | } 154 | 155 | loss = { 156 | 'g_loss' : g_loss, 157 | 'd_loss' : d_loss 158 | } 159 | 160 | outputs = { 161 | 'generator' : fake_image 162 | } 163 | 164 | checks = { 165 | 'd_loss1': d_loss1, 166 | 'd_loss2': d_loss2, 167 | 'd_loss3': d_loss3, 168 | 'g_loss_1': g_loss_1, 169 | 'g_loss_2': g_loss_2, 170 | 'd_loss1_1': d_loss1_1, 171 | 'd_loss2_1': d_loss2_1, 172 | 'disc_real_image_logits': disc_real_image_logits, 173 | 'disc_wrong_image_logits': disc_wrong_image, 174 | 'disc_fake_image_logits': disc_fake_image_logits 175 | } 176 | 177 | return input_tensors, variables, loss, outputs, checks 178 | 179 | def add_tb_scalar_summaries(self, d_loss, g_loss, d_loss1, d_loss2, 180 | d_loss3, d_loss1_1, d_loss2_1, g_loss_1, 181 | g_loss_2, d_right_accuracy, 182 | d_wrong_accuracy, d_fake_accuracy): 183 | 184 | self.add_scalar_summary("D_Loss", d_loss) 185 | self.add_scalar_summary("G_Loss", g_loss) 186 | self.add_scalar_summary("D loss-1 [Real/Fake loss for real images]", 187 | d_loss1) 188 | self.add_scalar_summary("D loss-2 [Real/Fake loss for wrong images]", 189 | d_loss2) 190 | self.add_scalar_summary("D loss-3 [Real/Fake loss for fake images]", 191 | d_loss3) 192 | self.add_scalar_summary( 193 | "D loss-4 [Aux Classifier loss for real images]", d_loss1_1) 194 | self.add_scalar_summary( 195 | "D loss-5 [Aux Classifier loss for wrong images]", d_loss2_1) 196 | self.add_scalar_summary("G loss-1 [Real/Fake loss for fake images]", 197 | g_loss_1) 198 | self.add_scalar_summary( 199 | "G loss-2 [Aux Classifier loss for fake images]", g_loss_2) 200 | self.add_scalar_summary("Discriminator Real Image Accuracy", 201 | d_right_accuracy) 202 | self.add_scalar_summary("Discriminator Wrong Image Accuracy", 203 | d_wrong_accuracy) 204 | self.add_scalar_summary("Discriminator Fake Image Accuracy", 205 | d_fake_accuracy) 206 | 207 | def add_scalar_summary(self, name, var): 208 | with tf.name_scope('summaries'): 209 | tf.summary.scalar(name, var) 210 | 211 | def add_histogram_summary(self, name, var): 212 | with tf.name_scope('summaries'): 213 | tf.summary.histogram(name, var) 214 | 215 | def add_image_summary(self, name, var, max_outputs=1): 216 | with tf.name_scope('summaries'): 217 | tf.summary.image(name, var, max_outputs=max_outputs) 218 | 219 | # GENERATOR IMPLEMENTATION based on : 220 | # https://github.com/carpedm20/DCGAN-tensorflow/blob/master/model.py 221 | def generator(self, t_z, t_text_embedding, t_training): 222 | 223 | s = self.options['image_size'] 224 | s2, s4, s8, s16 = int(s / 2), int(s / 4), int(s / 8), int(s / 16) 225 | 226 | reduced_text_embedding = ops.lrelu( 227 | ops.linear(t_text_embedding, self.options['t_dim'], 'g_embedding')) 228 | z_concat = tf.concat([t_z, reduced_text_embedding], -1) 229 | z_ = ops.linear(z_concat, self.options['gf_dim'] * 8 * s16 * s16, 230 | 'g_h0_lin') 231 | h0 = tf.reshape(z_, [-1, s16, s16, self.options['gf_dim'] * 8]) 232 | h0 = tf.nn.relu(slim.batch_norm(h0, is_training = t_training, 233 | scope="g_bn0")) 234 | 235 | h1 = ops.deconv2d(h0, [self.options['batch_size'], s8, s8, 236 | self.options['gf_dim'] * 4], name = 'g_h1') 237 | h1 = tf.nn.relu(slim.batch_norm(h1, is_training = t_training, 238 | scope="g_bn1")) 239 | 240 | h2 = ops.deconv2d(h1, [self.options['batch_size'], s4, s4, 241 | self.options['gf_dim'] * 2], name = 'g_h2') 242 | h2 = tf.nn.relu(slim.batch_norm(h2, is_training = t_training, 243 | scope="g_bn2")) 244 | 245 | h3 = ops.deconv2d(h2, [self.options['batch_size'], s2, s2, 246 | self.options['gf_dim'] * 1], name = 'g_h3') 247 | h3 = tf.nn.relu(slim.batch_norm(h3, is_training = t_training, 248 | scope="g_bn3")) 249 | 250 | h4 = ops.deconv2d(h3, [self.options['batch_size'], s, s, 3], 251 | name = 'g_h4') 252 | return (tf.tanh(h4) / 2. + 0.5) 253 | 254 | 255 | # DISCRIMINATOR IMPLEMENTATION based on : 256 | # https://github.com/carpedm20/DCGAN-tensorflow/blob/master/model.py 257 | def discriminator(self, image, t_text_embedding, n_classes, t_training, 258 | reuse = False) : 259 | if reuse : 260 | tf.get_variable_scope().reuse_variables() 261 | 262 | h0 = ops.lrelu( 263 | ops.conv2d(image, self.options['df_dim'], name = 'd_h0_conv')) # 64 264 | 265 | h1 = ops.lrelu(slim.batch_norm(ops.conv2d(h0, 266 | self.options['df_dim'] * 2, 267 | name = 'd_h1_conv'), 268 | reuse=reuse, 269 | is_training = t_training, 270 | scope = 'd_bn1')) # 32 271 | 272 | h2 = ops.lrelu(slim.batch_norm(ops.conv2d(h1, 273 | self.options['df_dim'] * 4, 274 | name = 'd_h2_conv'), 275 | reuse=reuse, 276 | is_training = t_training, 277 | scope = 'd_bn2')) # 16 278 | h3 = ops.lrelu(slim.batch_norm(ops.conv2d(h2, 279 | self.options['df_dim'] * 8, 280 | name = 'd_h3_conv'), 281 | reuse=reuse, 282 | is_training = t_training, 283 | scope = 'd_bn3')) # 8 284 | h3_shape = h3.get_shape().as_list() 285 | # ADD TEXT EMBEDDING TO THE NETWORK 286 | reduced_text_embeddings = ops.lrelu(ops.linear(t_text_embedding, 287 | self.options['t_dim'], 288 | 'd_embedding')) 289 | reduced_text_embeddings = tf.expand_dims(reduced_text_embeddings, 1) 290 | reduced_text_embeddings = tf.expand_dims(reduced_text_embeddings, 2) 291 | tiled_embeddings = tf.tile(reduced_text_embeddings, 292 | [1, h3_shape[1], h3_shape[1], 1], 293 | name = 'tiled_embeddings') 294 | 295 | h3_concat = tf.concat([h3, tiled_embeddings], 3, name = 'h3_concat') 296 | h3_new = ops.lrelu(slim.batch_norm(ops.conv2d(h3_concat, 297 | self.options['df_dim'] * 8, 298 | 1, 1, 1, 1, 299 | name = 'd_h3_conv_new'), 300 | reuse=reuse, 301 | is_training = t_training, 302 | scope = 'd_bn4')) # 4 303 | 304 | h3_flat = tf.reshape(h3_new, [self.options['batch_size'], -1]) 305 | 306 | h4 = ops.linear(h3_flat, 1, 'd_h4_lin_rw') 307 | h4_aux = ops.linear(h3_flat, n_classes, 'd_h4_lin_ac') 308 | 309 | return tf.nn.sigmoid(h4), h4, tf.nn.sigmoid(h4_aux), h4_aux 310 | 311 | # This has not been used used yet but can be used 312 | def attention(self, decoder_output, seq_outputs, output_size, time_steps, 313 | reuse=False) : 314 | if reuse: 315 | tf.get_variable_scope().reuse_variables() 316 | ui = ops.attention(decoder_output, seq_outputs, output_size, 317 | time_steps, name = "g_a_attention") 318 | 319 | with tf.variable_scope('g_a_attention'): 320 | ui = tf.transpose(ui, [1, 0, 2]) 321 | ai = tf.nn.softmax(ui, dim=1) 322 | seq_outputs = tf.transpose(seq_outputs, [1, 0, 2]) 323 | d_dash = tf.reduce_sum(tf.mul(seq_outputs, ai), axis=1) 324 | return d_dash, ai 325 | -------------------------------------------------------------------------------- /msssim.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # ============================================================================== 17 | 18 | """Python implementation of MS-SSIM. 19 | 20 | Usage: 21 | 22 | python msssim.py --original_image=original.png --compared_image=distorted.png 23 | """ 24 | import os 25 | import argparse 26 | import sys 27 | 28 | import tensorflow as tf 29 | import numpy as np 30 | 31 | from skimage.transform import resize 32 | from scipy import signal 33 | from scipy.ndimage.filters import convolve 34 | 35 | 36 | def _FSpecialGauss(size, sigma): 37 | """Function to mimic the 'fspecial' gaussian MATLAB function.""" 38 | radius = size // 2 39 | offset = 0.0 40 | start, stop = -radius, radius + 1 41 | if size % 2 == 0: 42 | offset = 0.5 43 | stop -= 1 44 | x, y = np.mgrid[offset + start:stop, offset + start:stop] 45 | assert len(x) == size 46 | g = np.exp(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2))) 47 | return g / g.sum() 48 | 49 | 50 | def _SSIMForMultiScale(img1, img2, max_val=255, filter_size=11, 51 | filter_sigma=1.5, k1=0.01, k2=0.03): 52 | """Return the Structural Similarity Map between `img1` and `img2`. 53 | 54 | This function attempts to match the functionality of ssim_index_new.m by 55 | Zhou Wang: http://www.cns.nyu.edu/~lcv/ssim/msssim.zip 56 | 57 | Arguments: 58 | img1: Numpy array holding the first RGB image batch. 59 | img2: Numpy array holding the second RGB image batch. 60 | max_val: the dynamic range of the images (i.e., the difference between the 61 | maximum the and minimum allowed values). 62 | filter_size: Size of blur kernel to use (will be reduced for small 63 | images). 64 | filter_sigma: Standard deviation for Gaussian blur kernel (will be reduced 65 | for small images). 66 | k1: Constant used to maintain stability in the SSIM calculation (0.01 in 67 | the original paper). 68 | k2: Constant used to maintain stability in the SSIM calculation (0.03 in 69 | the original paper). 70 | 71 | Returns: 72 | Pair containing the mean SSIM and contrast sensitivity between `img1` and 73 | `img2`. 74 | 75 | Raises: 76 | RuntimeError: If input images don't have the same shape or don't have four 77 | dimensions: [batch_size, height, width, depth]. 78 | """ 79 | if img1.shape != img2.shape: 80 | raise RuntimeError('Input images must have the same shape (%s vs. %s).', 81 | img1.shape, img2.shape) 82 | if img1.ndim != 4: 83 | raise RuntimeError('Input images must have four dimensions, not %d', 84 | img1.ndim) 85 | 86 | img1 = img1.astype(np.float64) 87 | img2 = img2.astype(np.float64) 88 | _, height, width, _ = img1.shape 89 | 90 | # Filter size can't be larger than height or width of images. 91 | size = min(filter_size, height, width) 92 | 93 | # Scale down sigma if a smaller filter size is used. 94 | sigma = size * filter_sigma / filter_size if filter_size else 0 95 | 96 | if filter_size: 97 | window = np.reshape(_FSpecialGauss(size, sigma), (1, size, size, 1)) 98 | mu1 = signal.fftconvolve(img1, window, mode='valid') 99 | mu2 = signal.fftconvolve(img2, window, mode='valid') 100 | sigma11 = signal.fftconvolve(img1 * img1, window, mode='valid') 101 | sigma22 = signal.fftconvolve(img2 * img2, window, mode='valid') 102 | sigma12 = signal.fftconvolve(img1 * img2, window, mode='valid') 103 | else: 104 | # Empty blur kernel so no need to convolve. 105 | mu1, mu2 = img1, img2 106 | sigma11 = img1 * img1 107 | sigma22 = img2 * img2 108 | sigma12 = img1 * img2 109 | 110 | mu11 = mu1 * mu1 111 | mu22 = mu2 * mu2 112 | mu12 = mu1 * mu2 113 | sigma11 -= mu11 114 | sigma22 -= mu22 115 | sigma12 -= mu12 116 | 117 | # Calculate intermediate values used by both ssim and cs_map. 118 | c1 = (k1 * max_val) ** 2 119 | c2 = (k2 * max_val) ** 2 120 | v1 = 2.0 * sigma12 + c2 121 | v2 = sigma11 + sigma22 + c2 122 | ssim = np.mean((((2.0 * mu12 + c1) * v1) / ((mu11 + mu22 + c1) * v2))) 123 | cs = np.mean(v1 / v2) 124 | return ssim, cs 125 | 126 | 127 | def MultiScaleSSIM(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5, 128 | k1=0.01, k2=0.03, weights=None): 129 | """Return the MS-SSIM score between `img1` and `img2`. 130 | 131 | This function implements Multi-Scale Structural Similarity (MS-SSIM) Image 132 | Quality Assessment according to Zhou Wang's paper, "Multi-scale structural 133 | similarity for image quality assessment" (2003). 134 | Link: https://ece.uwaterloo.ca/~z70wang/publications/msssim.pdf 135 | 136 | Author's MATLAB implementation: 137 | http://www.cns.nyu.edu/~lcv/ssim/msssim.zip 138 | 139 | Arguments: 140 | img1: Numpy array holding the first RGB image batch. 141 | img2: Numpy array holding the second RGB image batch. 142 | max_val: the dynamic range of the images (i.e., the difference between the 143 | maximum the and minimum allowed values). 144 | filter_size: Size of blur kernel to use (will be reduced for small 145 | images). 146 | filter_sigma: Standard deviation for Gaussian blur kernel (will be reduced 147 | for small images). 148 | k1: Constant used to maintain stability in the SSIM calculation (0.01 in 149 | the original paper). 150 | k2: Constant used to maintain stability in the SSIM calculation (0.03 in 151 | the original paper). 152 | weights: List of weights for each level; if none, use five levels and the 153 | weights from the original paper. 154 | 155 | Returns: 156 | MS-SSIM score between `img1` and `img2`. 157 | 158 | Raises: 159 | RuntimeError: If input images don't have the same shape or don't have four 160 | dimensions: [batch_size, height, width, depth]. 161 | """ 162 | if img1.shape != img2.shape: 163 | raise RuntimeError('Input images must have the same shape (%s vs. %s).', 164 | img1.shape, img2.shape) 165 | if img1.ndim != 4: 166 | raise RuntimeError('Input images must have four dimensions, not %d', 167 | img1.ndim) 168 | 169 | # Note: default weights don't sum to 1.0 but do match the paper / matlab 170 | # code. 171 | weights = np.array(weights if weights else 172 | [0.0448, 0.2856, 0.3001, 0.2363, 0.1333]) 173 | levels = weights.size 174 | downsample_filter = np.ones((1, 2, 2, 1)) / 4.0 175 | im1, im2 = [x.astype(np.float64) for x in [img1, img2]] 176 | mssim = np.array([]) 177 | mcs = np.array([]) 178 | for _ in range(levels): 179 | ssim, cs = _SSIMForMultiScale( 180 | im1, im2, max_val=max_val, filter_size=filter_size, 181 | filter_sigma=filter_sigma, k1=k1, k2=k2) 182 | mssim = np.append(mssim, ssim) 183 | mcs = np.append(mcs, cs) 184 | filtered = [convolve(im, downsample_filter, mode='reflect') 185 | for im in [im1, im2]] 186 | im1, im2 = [x[:, ::2, ::2, :] for x in filtered] 187 | return (np.prod(mcs[0:levels - 1] ** weights[0:levels - 1]) * 188 | (mssim[levels - 1] ** weights[levels - 1])) 189 | 190 | 191 | def calculate_msssim(img_dir, gen_img_dir, caption_dir, output_dir): 192 | 193 | image_files = [f for f in os.listdir(img_dir) if 'jpg' in f] 194 | image_captions = {} 195 | image_classes = {} 196 | class_dirs = [] 197 | class_names = [] 198 | img_ids = [] 199 | class_dict = {} 200 | gen_class_dict = {} 201 | 202 | print('Initializing objects for calculating MS-SSIM') 203 | for i in range(1, 103): 204 | class_dir_name = 'class_%.5d' % (i) 205 | class_dir = os.path.join(caption_dir, class_dir_name) 206 | class_names.append(class_dir_name) 207 | class_dirs.append(class_dir) 208 | onlyimgfiles = [f[0:11] + ".jpg" for f in os.listdir(class_dir) 209 | if 'txt' in f] 210 | for img_file in onlyimgfiles: 211 | image_classes[img_file] = None 212 | 213 | for img_file in onlyimgfiles: 214 | image_captions[img_file] = [] 215 | 216 | for class_dir, class_name in zip(class_dirs, class_names): 217 | caption_files = [f for f in os.listdir(class_dir) if 'txt' in f] 218 | class_imgs = [] 219 | gen_class_imgs = [] 220 | for i, cap_file in enumerate(caption_files): 221 | if i % 50 == 0: 222 | print(str(i) + ' captions extracted from' + str(class_dir)) 223 | 224 | class_imgs.append(cap_file[0:11] + ".jpg") 225 | image1_tr_path = os.path.join(gen_img_dir, 'train', 226 | cap_file[0:11] + ".jpg") 227 | if os.path.exists(image1_tr_path): 228 | for root, subFolders, files in os.walk(image1_tr_path): 229 | if files: 230 | for f in files: 231 | if 'jpg' in f: 232 | gen_class_imgs.append(os.path.join(root, f)) 233 | 234 | class_dict[class_name] = class_imgs 235 | gen_class_dict[class_name] = gen_class_imgs 236 | with tf.Session() as sess: 237 | for class_name in class_dict.keys(): 238 | img_list = class_dict[class_name] 239 | gen_img_list = gen_class_dict[class_name] 240 | real_msssim = [] 241 | fake_msssim = [] 242 | print('calculating MS-SSIM for real images of class : ' + str( 243 | class_name)) 244 | for i in range(0, len(img_list)): 245 | for j in range(i, len(img_list)): 246 | if (i == j): 247 | continue 248 | image1_path = os.path.join(img_dir, img_list[i]) 249 | image2_path = os.path.join(img_dir, img_list[j]) 250 | with open(image1_path, 'rb') as image_file: 251 | img1_str = image_file.read() 252 | with open(image2_path, 'rb') as image_file: 253 | img2_str = image_file.read() 254 | input_img = tf.placeholder(tf.string) 255 | decoded_image = tf.expand_dims( 256 | tf.image.decode_png(input_img, channels=3), 0) 257 | 258 | img1 = np.squeeze(sess.run(decoded_image, 259 | feed_dict={input_img: img1_str})) 260 | img2 = np.squeeze(sess.run(decoded_image, 261 | feed_dict={input_img: img2_str})) 262 | img1 = resize(img1, (128, 128, 3), mode='reflect') 263 | img2 = resize(img2, (128, 128, 3), mode='reflect') 264 | 265 | img1 = np.expand_dims(img1, axis=0) 266 | img2 = np.expand_dims(img2, axis=0) 267 | 268 | real_msssim.append(MultiScaleSSIM(img1, img2, max_val=255)) 269 | 270 | for i in range(0, len(gen_img_list)): 271 | for j in range(i, len(gen_img_list)): 272 | if (i == j): 273 | continue 274 | image1_path = os.path.join('', gen_img_list[i]) 275 | image2_path = os.path.join('', gen_img_list[j]) 276 | with open(image1_path, 'rb') as image_file: 277 | img1_str = image_file.read() 278 | with open(image2_path, 'rb') as image_file: 279 | img2_str = image_file.read() 280 | input_img = tf.placeholder(tf.string) 281 | decoded_image = tf.expand_dims( 282 | tf.image.decode_png(input_img, channels=3), 0) 283 | # with tf.Session() as sess: 284 | img1 = sess.run(decoded_image, 285 | feed_dict={input_img: img1_str}) 286 | img2 = sess.run(decoded_image, 287 | feed_dict={input_img: img2_str}) 288 | fake_msssim.append(MultiScaleSSIM(img1, img2, max_val=255)) 289 | 290 | mean_real_msssim = np.mean(real_msssim) 291 | mean_fake_msssim = np.mean(fake_msssim) 292 | 293 | tsv_dir = os.path.join(output_dir, 'msssim') 294 | tsv_path = os.path.join(tsv_dir, 'msssim.tsv') 295 | if not os.path.exists(tsv_dir): 296 | os.makedirs(tsv_dir) 297 | 298 | if os.path.exists(tsv_path): 299 | os.remove(tsv_path) 300 | 301 | with open(tsv_path, 'a') as f: 302 | str_real_mean = "%.9f" % mean_real_msssim 303 | str_fake_mean = "%.9f" % mean_fake_msssim 304 | f.write( 305 | class_name + '\t' + str_real_mean + '\t' + str_fake_mean + 306 | '\n') 307 | 308 | 309 | if __name__ == '__main__': 310 | parser = argparse.ArgumentParser() 311 | 312 | parser.add_argument('--output_dir', type=str, default="Data/ms-ssim", 313 | help='directory to dump all the images for ' 314 | 'calculating inception score') 315 | 316 | parser.add_argument('--data_dir', type=str, default="Data", 317 | help='Root directory of the data') 318 | 319 | parser.add_argument('--dataset', type=str, default="flowers", 320 | help='The root directory of the synthetic dataset') 321 | 322 | parser.add_argument('--syn_dataset_dir', type=str, default="flowers", 323 | help='The root directory of the synthetic dataset') 324 | 325 | args = parser.parse_args() 326 | 327 | if args.dataset != 'flowers': 328 | print('Dataset Not Found') 329 | sys.exit() 330 | 331 | img_dir = os.path.join(args.data_dir, 'datasets', args.dataset, 'jpg') 332 | gen_img_dir = args.syn_dataset_dir 333 | caption_dir = os.path.join(args.data_dir, 'datasets', 'flowers', 334 | 'text_c10') 335 | 336 | calculate_msssim(img_dir, gen_img_dir, caption_dir, args.output_dir) 337 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | backports-abc==0.5 2 | backports.weakref==1.0rc1 3 | bleach==1.5.0 4 | cycler==0.10.0 5 | decorator==4.0.11 6 | entrypoints==0.2.3 7 | html5lib==0.9999999 8 | ipykernel==4.6.1 9 | ipython==6.1.0 10 | ipython-genutils==0.2.0 11 | ipywidgets==6.0.0 12 | jedi==0.10.2 13 | Jinja2==2.9.6 14 | jsonschema==2.6.0 15 | jupyter==1.0.0 16 | jupyter-client==5.1.0 17 | jupyter-console==5.1.0 18 | jupyter-core==4.3.0 19 | Markdown==2.2.0 20 | MarkupSafe==1.0 21 | matplotlib==2.0.2 22 | mistune==0.7.4 23 | mpmath==0.19 24 | nbconvert==5.2.1 25 | nbformat==4.3.0 26 | nose==1.3.7 27 | notebook==5.0.0 28 | numpy==1.13.0 29 | pandas==0.20.2 30 | pandocfilters==1.4.1 31 | pexpect==4.2.1 32 | pickleshare==0.7.4 33 | progressbar2==3.30.2 34 | prompt-toolkit==1.0.14 35 | protobuf==3.3.0 36 | ptyprocess==0.5.2 37 | Pygments==2.2.0 38 | pyparsing==2.2.0 39 | python-dateutil==2.6.0 40 | python-utils==2.1.0 41 | pytz==2017.2 42 | pyzmq==16.0.2 43 | qtconsole==4.3.0 44 | scipy==0.19.1 45 | simplegeneric==0.8.1 46 | six==1.10.0 47 | sympy==1.0 48 | tensorflow-gpu==1.2.0 49 | terminado==0.6 50 | testpath==0.3.1 51 | Theano==0.9.0 52 | tornado==4.5.1 53 | traitlets==4.3.2 54 | typing==3.6.1 55 | wcwidth==0.1.7 56 | Werkzeug==0.12.2 57 | widgetsnbextension==2.0.0 58 | -------------------------------------------------------------------------------- /skipthoughts.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Skip-thought vectors 3 | https://github.com/ryankiros/skip-thoughts 4 | ''' 5 | import os 6 | 7 | import theano 8 | import theano.tensor as tensor 9 | 10 | import _pickle as pkl 11 | import numpy 12 | import copy 13 | import nltk 14 | 15 | from collections import OrderedDict, defaultdict 16 | from scipy.linalg import norm 17 | from nltk.tokenize import word_tokenize 18 | 19 | profile = False 20 | 21 | #-----------------------------------------------------------------------------# 22 | # Specify model and table locations here 23 | #-----------------------------------------------------------------------------# 24 | path_to_models = 'Data/skipthoughts/' 25 | path_to_tables = 'Data/skipthoughts/' 26 | #-----------------------------------------------------------------------------# 27 | 28 | path_to_umodel = path_to_models + 'uni_skip.npz' 29 | path_to_bmodel = path_to_models + 'bi_skip.npz' 30 | 31 | 32 | def load_model(): 33 | """ 34 | Load the model with saved tables 35 | """ 36 | # Load model options 37 | print('Loading model parameters...') 38 | with open('%s.pkl'%path_to_umodel, 'rb') as f: 39 | uoptions = pkl.load(f) 40 | with open('%s.pkl'%path_to_bmodel, 'rb') as f: 41 | boptions = pkl.load(f) 42 | 43 | # Load parameters 44 | uparams = init_params(uoptions) 45 | uparams = load_params(path_to_umodel, uparams) 46 | utparams = init_tparams(uparams) 47 | bparams = init_params_bi(boptions) 48 | bparams = load_params(path_to_bmodel, bparams) 49 | btparams = init_tparams(bparams) 50 | 51 | # Extractor functions 52 | print('Compiling encoders...') 53 | embedding, x_mask, ctxw2v = build_encoder(utparams, uoptions) 54 | f_w2v = theano.function([embedding, x_mask], ctxw2v, name='f_w2v') 55 | embedding, x_mask, ctxw2v = build_encoder_bi(btparams, boptions) 56 | f_w2v2 = theano.function([embedding, x_mask], ctxw2v, name='f_w2v2') 57 | 58 | # Tables 59 | print('Loading tables...') 60 | utable, btable = load_tables() 61 | 62 | # Store everything we need in a dictionary 63 | print('Packing up...') 64 | model = {} 65 | model['uoptions'] = uoptions 66 | model['boptions'] = boptions 67 | model['utable'] = utable 68 | model['btable'] = btable 69 | model['f_w2v'] = f_w2v 70 | model['f_w2v2'] = f_w2v2 71 | 72 | return model 73 | 74 | 75 | def load_tables(): 76 | """ 77 | Load the tables 78 | """ 79 | words = [] 80 | utable = numpy.load(path_to_tables + 'utable.npy', encoding='bytes') 81 | btable = numpy.load(path_to_tables + 'btable.npy', encoding='bytes') 82 | f = open(path_to_tables + 'dictionary.txt', 'rb') 83 | for line in f: 84 | words.append(line.decode('utf-8').strip()) 85 | f.close() 86 | utable = OrderedDict(zip(words, utable)) 87 | btable = OrderedDict(zip(words, btable)) 88 | return utable, btable 89 | 90 | 91 | def encode(model, X, use_norm=True, verbose=True, batch_size=128, use_eos=False): 92 | """ 93 | Encode sentences in the list X. Each entry will return a vector 94 | """ 95 | # first, do preprocessing 96 | X = preprocess(X) 97 | 98 | # word dictionary and init 99 | d = defaultdict(lambda : 0) 100 | for w in model['utable'].keys(): 101 | d[w] = 1 102 | ufeatures = numpy.zeros((len(X), model['uoptions']['dim']), dtype='float32') 103 | bfeatures = numpy.zeros((len(X), 2 * model['boptions']['dim']), dtype='float32') 104 | 105 | # length dictionary 106 | ds = defaultdict(list) 107 | captions = [s.split() for s in X] 108 | for i,s in enumerate(captions): 109 | ds[len(s)].append(i) 110 | 111 | # Get features. This encodes by length, in order to avoid wasting computation 112 | for k in ds.keys(): 113 | if verbose: 114 | print(k) 115 | numbatches = len(ds[k]) / batch_size + 1 116 | for minibatch in range(int(numbatches)): 117 | caps = ds[k][int(minibatch)::int(numbatches)] 118 | 119 | if use_eos: 120 | uembedding = numpy.zeros((k+1, len(caps), model['uoptions']['dim_word']), dtype='float32') 121 | bembedding = numpy.zeros((k+1, len(caps), model['boptions']['dim_word']), dtype='float32') 122 | else: 123 | uembedding = numpy.zeros((k, len(caps), model['uoptions']['dim_word']), dtype='float32') 124 | bembedding = numpy.zeros((k, len(caps), model['boptions']['dim_word']), dtype='float32') 125 | for ind, c in enumerate(caps): 126 | caption = captions[c] 127 | for j in range(len(caption)): 128 | if d[caption[j]] > 0: 129 | uembedding[j,ind] = model['utable'][caption[j]] 130 | bembedding[j,ind] = model['btable'][caption[j]] 131 | else: 132 | uembedding[j,ind] = model['utable']['UNK'] 133 | bembedding[j,ind] = model['btable']['UNK'] 134 | if use_eos: 135 | uembedding[-1,ind] = model['utable'][''] 136 | bembedding[-1,ind] = model['btable'][''] 137 | if use_eos: 138 | uff = model['f_w2v'](uembedding, numpy.ones((len(caption)+1,len(caps)), dtype='float32')) 139 | bff = model['f_w2v2'](bembedding, numpy.ones((len(caption)+1,len(caps)), dtype='float32')) 140 | else: 141 | uff = model['f_w2v'](uembedding, numpy.ones((len(caption),len(caps)), dtype='float32')) 142 | bff = model['f_w2v2'](bembedding, numpy.ones((len(caption),len(caps)), dtype='float32')) 143 | if use_norm: 144 | for j in range(len(uff)): 145 | uff[j] /= norm(uff[j]) 146 | bff[j] /= norm(bff[j]) 147 | for ind, c in enumerate(caps): 148 | ufeatures[c] = uff[ind] 149 | bfeatures[c] = bff[ind] 150 | 151 | features = numpy.c_[ufeatures, bfeatures] 152 | return features 153 | 154 | 155 | def preprocess(text): 156 | """ 157 | Preprocess text for encoder 158 | """ 159 | X = [] 160 | sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') 161 | for t in text: 162 | sents = sent_detector.tokenize(t) 163 | result = '' 164 | for s in sents: 165 | tokens = word_tokenize(s) 166 | result += ' ' + ' '.join(tokens) 167 | X.append(result) 168 | return X 169 | 170 | 171 | def nn(model, text, vectors, query, k=5): 172 | """ 173 | Return the nearest neighbour sentences to query 174 | text: list of sentences 175 | vectors: the corresponding representations for text 176 | query: a string to search 177 | """ 178 | qf = encode(model, [query]) 179 | qf /= norm(qf) 180 | scores = numpy.dot(qf, vectors.T).flatten() 181 | sorted_args = numpy.argsort(scores)[::-1] 182 | sentences = [text[a] for a in sorted_args[:k]] 183 | print('QUERY: ' + query) 184 | print('NEAREST: ') 185 | for i, s in enumerate(sentences): 186 | print(s, sorted_args[i]) 187 | 188 | 189 | def word_features(table): 190 | """ 191 | Extract word features into a normalized matrix 192 | """ 193 | features = numpy.zeros((len(table), 620), dtype='float32') 194 | keys = table.keys() 195 | for i in range(len(table)): 196 | f = table[keys[i]] 197 | features[i] = f / norm(f) 198 | return features 199 | 200 | 201 | def nn_words(table, wordvecs, query, k=10): 202 | """ 203 | Get the nearest neighbour words 204 | """ 205 | keys = table.keys() 206 | qf = table[query] 207 | scores = numpy.dot(qf, wordvecs.T).flatten() 208 | sorted_args = numpy.argsort(scores)[::-1] 209 | words = [keys[a] for a in sorted_args[:k]] 210 | print('QUERY: ' + query) 211 | print('NEAREST: ') 212 | for i, w in enumerate(words): 213 | print(w) 214 | 215 | 216 | def _p(pp, name): 217 | """ 218 | make prefix-appended name 219 | """ 220 | return '%s_%s'%(pp, name) 221 | 222 | 223 | def init_tparams(params): 224 | """ 225 | initialize Theano shared variables according to the initial parameters 226 | """ 227 | tparams = OrderedDict() 228 | for kk, pp in params.items(): 229 | tparams[kk] = theano.shared(params[kk], name=kk) 230 | return tparams 231 | 232 | 233 | def load_params(path, params): 234 | """ 235 | load parameters 236 | """ 237 | pp = numpy.load(path) 238 | for kk, vv in params.items(): 239 | if kk not in pp: 240 | warnings.warn('%s is not in the archive'%kk) 241 | continue 242 | params[kk] = pp[kk] 243 | return params 244 | 245 | 246 | # layers: 'name': ('parameter initializer', 'feedforward') 247 | layers = {'gru': ('param_init_gru', 'gru_layer')} 248 | 249 | def get_layer(name): 250 | fns = layers[name] 251 | return (eval(fns[0]), eval(fns[1])) 252 | 253 | 254 | def init_params(options): 255 | """ 256 | initialize all parameters needed for the encoder 257 | """ 258 | params = OrderedDict() 259 | 260 | # embedding 261 | params['Wemb'] = norm_weight(options['n_words_src'], options['dim_word']) 262 | 263 | # encoder: GRU 264 | params = get_layer(options['encoder'])[0](options, params, prefix='encoder', 265 | nin=options['dim_word'], dim=options['dim']) 266 | return params 267 | 268 | 269 | def init_params_bi(options): 270 | """ 271 | initialize all paramters needed for bidirectional encoder 272 | """ 273 | params = OrderedDict() 274 | 275 | # embedding 276 | params['Wemb'] = norm_weight(options['n_words_src'], options['dim_word']) 277 | 278 | # encoder: GRU 279 | params = get_layer(options['encoder'])[0](options, params, prefix='encoder', 280 | nin=options['dim_word'], dim=options['dim']) 281 | params = get_layer(options['encoder'])[0](options, params, prefix='encoder_r', 282 | nin=options['dim_word'], dim=options['dim']) 283 | return params 284 | 285 | 286 | def build_encoder(tparams, options): 287 | """ 288 | build an encoder, given pre-computed word embeddings 289 | """ 290 | # word embedding (source) 291 | embedding = tensor.tensor3('embedding', dtype='float32') 292 | x_mask = tensor.matrix('x_mask', dtype='float32') 293 | 294 | # encoder 295 | proj = get_layer(options['encoder'])[1](tparams, embedding, options, 296 | prefix='encoder', 297 | mask=x_mask) 298 | ctx = proj[0][-1] 299 | 300 | return embedding, x_mask, ctx 301 | 302 | 303 | def build_encoder_bi(tparams, options): 304 | """ 305 | build bidirectional encoder, given pre-computed word embeddings 306 | """ 307 | # word embedding (source) 308 | embedding = tensor.tensor3('embedding', dtype='float32') 309 | embeddingr = embedding[::-1] 310 | x_mask = tensor.matrix('x_mask', dtype='float32') 311 | xr_mask = x_mask[::-1] 312 | 313 | # encoder 314 | proj = get_layer(options['encoder'])[1](tparams, embedding, options, 315 | prefix='encoder', 316 | mask=x_mask) 317 | projr = get_layer(options['encoder'])[1](tparams, embeddingr, options, 318 | prefix='encoder_r', 319 | mask=xr_mask) 320 | 321 | ctx = tensor.concatenate([proj[0][-1], projr[0][-1]], axis=1) 322 | 323 | return embedding, x_mask, ctx 324 | 325 | 326 | # some utilities 327 | def ortho_weight(ndim): 328 | W = numpy.random.randn(ndim, ndim) 329 | u, s, v = numpy.linalg.svd(W) 330 | return u.astype('float32') 331 | 332 | 333 | def norm_weight(nin,nout=None, scale=0.1, ortho=True): 334 | if nout == None: 335 | nout = nin 336 | if nout == nin and ortho: 337 | W = ortho_weight(nin) 338 | else: 339 | W = numpy.random.uniform(low=-scale, high=scale, size=(nin, nout)) 340 | return W.astype('float32') 341 | 342 | 343 | def param_init_gru(options, params, prefix='gru', nin=None, dim=None): 344 | """ 345 | parameter init for GRU 346 | """ 347 | if nin == None: 348 | nin = options['dim_proj'] 349 | if dim == None: 350 | dim = options['dim_proj'] 351 | W = numpy.concatenate([norm_weight(nin,dim), 352 | norm_weight(nin,dim)], axis=1) 353 | params[_p(prefix,'W')] = W 354 | params[_p(prefix,'b')] = numpy.zeros((2 * dim,)).astype('float32') 355 | U = numpy.concatenate([ortho_weight(dim), 356 | ortho_weight(dim)], axis=1) 357 | params[_p(prefix,'U')] = U 358 | 359 | Wx = norm_weight(nin, dim) 360 | params[_p(prefix,'Wx')] = Wx 361 | Ux = ortho_weight(dim) 362 | params[_p(prefix,'Ux')] = Ux 363 | params[_p(prefix,'bx')] = numpy.zeros((dim,)).astype('float32') 364 | 365 | return params 366 | 367 | 368 | def gru_layer(tparams, state_below, options, prefix='gru', mask=None, **kwargs): 369 | """ 370 | Forward pass through GRU layer 371 | """ 372 | nsteps = state_below.shape[0] 373 | if state_below.ndim == 3: 374 | n_samples = state_below.shape[1] 375 | else: 376 | n_samples = 1 377 | 378 | dim = tparams[_p(prefix,'Ux')].shape[1] 379 | 380 | if mask == None: 381 | mask = tensor.alloc(1., state_below.shape[0], 1) 382 | 383 | def _slice(_x, n, dim): 384 | if _x.ndim == 3: 385 | return _x[:, :, n*dim:(n+1)*dim] 386 | return _x[:, n*dim:(n+1)*dim] 387 | 388 | state_below_ = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + tparams[_p(prefix, 'b')] 389 | state_belowx = tensor.dot(state_below, tparams[_p(prefix, 'Wx')]) + tparams[_p(prefix, 'bx')] 390 | U = tparams[_p(prefix, 'U')] 391 | Ux = tparams[_p(prefix, 'Ux')] 392 | 393 | def _step_slice(m_, x_, xx_, h_, U, Ux): 394 | preact = tensor.dot(h_, U) 395 | preact += x_ 396 | 397 | r = tensor.nnet.sigmoid(_slice(preact, 0, dim)) 398 | u = tensor.nnet.sigmoid(_slice(preact, 1, dim)) 399 | 400 | preactx = tensor.dot(h_, Ux) 401 | preactx = preactx * r 402 | preactx = preactx + xx_ 403 | 404 | h = tensor.tanh(preactx) 405 | 406 | h = u * h_ + (1. - u) * h 407 | h = m_[:,None] * h + (1. - m_)[:,None] * h_ 408 | 409 | return h 410 | 411 | seqs = [mask, state_below_, state_belowx] 412 | _step = _step_slice 413 | 414 | rval, updates = theano.scan(_step, 415 | sequences=seqs, 416 | outputs_info = [tensor.alloc(0., n_samples, dim)], 417 | non_sequences = [tparams[_p(prefix, 'U')], 418 | tparams[_p(prefix, 'Ux')]], 419 | name=_p(prefix, '_layers'), 420 | n_steps=nsteps, 421 | profile=profile, 422 | strict=True) 423 | rval = [rval] 424 | return rval 425 | 426 | -------------------------------------------------------------------------------- /t_interpolation.py: -------------------------------------------------------------------------------- 1 | import model 2 | import argparse 3 | import pickle 4 | import scipy.misc 5 | import random 6 | import os 7 | import progressbar 8 | 9 | import tensorflow as tf 10 | import numpy as np 11 | 12 | from os.path import join 13 | 14 | 15 | def main(): 16 | parser = argparse.ArgumentParser() 17 | parser.add_argument('--z_dim', type=int, default=100, 18 | help='Noise dimension') 19 | 20 | parser.add_argument('--t_dim', type=int, default=256, 21 | help='Text feature dimension') 22 | 23 | parser.add_argument('--batch_size', type=int, default=64, 24 | help='Batch Size') 25 | 26 | parser.add_argument('--image_size', type=int, default=128, 27 | help='Image Size a, a x a') 28 | 29 | parser.add_argument('--gf_dim', type=int, default=64, 30 | help='Number of conv in the first layer gen.') 31 | 32 | parser.add_argument('--df_dim', type=int, default=64, 33 | help='Number of conv in the first layer discr.') 34 | 35 | parser.add_argument('--caption_vector_length', type=int, default=4800, 36 | help='Caption Vector Length') 37 | 38 | parser.add_argument('--n_classes', type=int, default=102, 39 | help='Number of classes/class labels') 40 | 41 | parser.add_argument('--data_dir', type=str, default="Data", 42 | help='Data Directory') 43 | 44 | parser.add_argument('--learning_rate', type=float, default=0.0002, 45 | help='Learning Rate') 46 | 47 | parser.add_argument('--beta1', type=float, default=0.5, 48 | help='Momentum for Adam Update') 49 | 50 | parser.add_argument('--data_set', type=str, default="flowers", 51 | help='Dats set: flowers') 52 | 53 | parser.add_argument('--output_dir', type=str, default="Data/synthetic_dataset", 54 | help='The directory in which the t_interpolated ' 55 | 'images will be generated') 56 | 57 | parser.add_argument('--checkpoints_dir', type=str, default="/tmp", 58 | help='Path to the checkpoints directory') 59 | 60 | parser.add_argument('--n_interp', type=int, default=100, 61 | help='The difference between each interpolation. ' 62 | 'Should ideally be a multiple of 10') 63 | 64 | parser.add_argument('--n_images', type=int, default=500, 65 | help='Number of images to randomply sample for ' 66 | 'generating interpolation results') 67 | 68 | args = parser.parse_args() 69 | 70 | datasets_root_dir = join(args.data_dir, 'datasets') 71 | 72 | loaded_data = load_training_data(datasets_root_dir, args.data_set, 73 | args.caption_vector_length, 74 | args.n_classes) 75 | model_options = { 76 | 'z_dim': args.z_dim, 77 | 't_dim': args.t_dim, 78 | 'batch_size': args.batch_size, 79 | 'image_size': args.image_size, 80 | 'gf_dim': args.gf_dim, 81 | 'df_dim': args.df_dim, 82 | 'caption_vector_length': args.caption_vector_length, 83 | 'n_classes': loaded_data['n_classes'] 84 | } 85 | 86 | gan = model.GAN(model_options) 87 | input_tensors, variables, loss, outputs, checks = gan.build_model() 88 | 89 | sess = tf.InteractiveSession() 90 | tf.initialize_all_variables().run() 91 | 92 | saver = tf.train.Saver(max_to_keep=10000) 93 | print('resuming model from checkpoint' + 94 | str(tf.train.latest_checkpoint(args.checkpoints_dir))) 95 | if tf.train.latest_checkpoint(args.checkpoints_dir) is not None: 96 | saver.restore(sess, tf.train.latest_checkpoint(args.checkpoints_dir)) 97 | print('Successfully loaded model') 98 | else: 99 | print('Could not load checkpoints') 100 | exit() 101 | 102 | random.shuffle(loaded_data['image_list']) 103 | selected_images = loaded_data['image_list'][:args.n_images] 104 | cap_id = [np.random.randint(0, 4) for cap_i in range(len(selected_images))] 105 | 106 | print('Generating Images by interpolating the text features and z') 107 | bar = progressbar.ProgressBar(redirect_stdout=True, 108 | max_value=args.n_images) 109 | 110 | for sel_i, (sel_img, sel_cap) in enumerate(zip(selected_images, cap_id)): 111 | for sel_j in range(sel_i, len(cap_id)): 112 | print(str(sel_i) + '\t->\t' + str(sel_j)) 113 | if sel_i == sel_j: 114 | continue 115 | sel_img_2 = selected_images[sel_j] 116 | sel_cap_2 = cap_id[sel_j] 117 | 118 | captions_1, image_files_1, image_caps_1, image_ids_1, \ 119 | image_caps_ids_1 = get_images_z_intr(sel_img, sel_cap, 120 | loaded_data, datasets_root_dir) 121 | 122 | captions_2, image_files_2, image_caps_2, image_ids_2, \ 123 | image_caps_ids_2 = get_images_z_intr(sel_img_2, sel_cap_2, 124 | loaded_data, datasets_root_dir) 125 | 126 | z_noise_1 = np.random.uniform(-1, 1, [args.batch_size, args.z_dim]) 127 | z_noise_2 = np.random.uniform(-1, 1, [args.batch_size, args.z_dim]) 128 | intr_z_list = get_interp_vec(z_noise_1, z_noise_2, args.z_dim, 129 | args.n_interp, args.batch_size) 130 | 131 | intr_t_list = get_interp_vec(captions_1, captions_2, 132 | args.caption_vector_length, 133 | args.n_interp, args.batch_size) 134 | 135 | for z_i, z_noise in enumerate(intr_z_list): 136 | for t_i, captions in enumerate(intr_t_list): 137 | val_feed = { 138 | input_tensors['t_real_caption'].name: captions, 139 | input_tensors['t_z'].name: z_noise, 140 | input_tensors['t_training'].name: True 141 | } 142 | val_gen = sess.run([outputs['generator']], 143 | feed_dict=val_feed) 144 | 145 | save_distributed_image_batch(args.output_dir, val_gen, 146 | sel_i, sel_j, z_i, t_i, sel_img, sel_cap, 147 | sel_img_2, sel_cap_2, args.batch_size) 148 | bar.update(sel_i) 149 | bar.finish() 150 | print('Finished generating interpolated images') 151 | 152 | def load_training_data(data_dir, data_set, caption_vector_length, n_classes): 153 | if data_set == 'flowers': 154 | flower_str_captions = pickle.load( 155 | open(join(data_dir, 'flowers', 'flowers_caps.pkl'), "rb")) 156 | 157 | img_classes = pickle.load( 158 | open(join(data_dir, 'flowers', 'flower_tc.pkl'), "rb")) 159 | 160 | flower_enc_captions = pickle.load( 161 | open(join(data_dir, 'flowers', 'flower_tv.pkl'), "rb")) 162 | # h1 = h5py.File(join(data_dir, 'flower_tc.hdf5')) 163 | tr_image_ids = pickle.load( 164 | open(join(data_dir, 'flowers', 'train_ids.pkl'), "rb")) 165 | val_image_ids = pickle.load( 166 | open(join(data_dir, 'flowers', 'val_ids.pkl'), "rb")) 167 | 168 | # n_classes = n_classes 169 | max_caps_len = caption_vector_length 170 | 171 | tr_n_imgs = len(tr_image_ids) 172 | val_n_imgs = len(val_image_ids) 173 | 174 | return { 175 | 'image_list': tr_image_ids, 176 | 'captions': flower_enc_captions, 177 | 'data_length': tr_n_imgs, 178 | 'classes': img_classes, 179 | 'n_classes': n_classes, 180 | 'max_caps_len': max_caps_len, 181 | 'val_img_list': val_image_ids, 182 | 'val_captions': flower_enc_captions, 183 | 'val_data_len': val_n_imgs, 184 | 'str_captions': flower_str_captions 185 | } 186 | 187 | else: 188 | raise Exception('Dataset Not Found') 189 | 190 | 191 | def save_distributed_image_batch(data_dir, generated_images, sel_i, sel_2, z_i, 192 | t_i, sel_img, sel_cap, sel_img_2, sel_cap_2, 193 | batch_size): 194 | 195 | generated_images = np.squeeze(generated_images) 196 | folder_name = str(sel_i) + '_' + str(sel_2) 197 | 198 | image_dir = join(data_dir, 't_interpolation', folder_name, str(z_i)) 199 | if not os.path.exists(image_dir): 200 | os.makedirs(image_dir) 201 | 202 | meta_path = os.path.join(image_dir, "meta.txt") 203 | with open(meta_path, "w") as text_file: 204 | text_file.write(str(sel_img) + "\t" + str(sel_cap) + 205 | str(sel_img_2) + "\t" + str(sel_cap_2)) 206 | fake_image_255 = (generated_images[batch_size-1]) 207 | scipy.misc.imsave(join(image_dir, '{}.jpg'.format(t_i)), 208 | fake_image_255) 209 | 210 | 211 | def get_images_z_intr(sel_img, sel_cap, loaded_data, data_dir, batch_size=64): 212 | 213 | captions = np.zeros((batch_size, loaded_data['max_caps_len'])) 214 | batch_idx = np.random.randint(0, loaded_data['data_length'], 215 | size=batch_size - 1) 216 | image_ids = np.take(loaded_data['image_list'], batch_idx) 217 | image_files = [] 218 | image_caps = [] 219 | image_caps_ids = [] 220 | for idx, image_id in enumerate(image_ids): 221 | image_file = join(data_dir, 222 | 'flowers/jpg/' + image_id) 223 | random_caption = random.randint(0, 4) 224 | image_caps_ids.append(random_caption) 225 | captions[idx, :] = \ 226 | loaded_data['captions'][image_id][random_caption][ 227 | 0:loaded_data['max_caps_len']] 228 | str_cap = loaded_data['str_captions'][image_id][random_caption] 229 | image_caps.append(loaded_data['captions'] 230 | [image_id][random_caption]) 231 | image_files.append(image_file) 232 | if idx == batch_size-2: 233 | idx = idx + 1 234 | image_id = sel_img 235 | image_file = join(data_dir, 236 | 'flowers/jpg/' + sel_img) 237 | random_caption = sel_cap 238 | image_caps_ids.append(random_caption) 239 | captions[idx, :] = \ 240 | loaded_data['captions'][image_id][random_caption][ 241 | 0:loaded_data['max_caps_len']] 242 | str_cap = loaded_data['str_captions'][image_id][random_caption] 243 | image_caps.append(loaded_data['str_captions'] 244 | [image_id][random_caption]) 245 | image_files.append(image_file) 246 | break 247 | 248 | return captions, image_files, image_caps, image_ids, image_caps_ids 249 | 250 | 251 | def get_interp_vec(vec_1, vec_2, dim, n_interp, batch_size): 252 | 253 | intrip_list = [] 254 | bals = np.arange(0, 1, 1 / n_interp) 255 | for bal in bals: 256 | left = np.full((batch_size, dim), bal) 257 | right = np.full((batch_size, dim), 1.0 - bal) 258 | intrip_vec = np.multiply(vec_1, left) + np.multiply(vec_2, right) 259 | intrip_list.append(intrip_vec) 260 | return intrip_list 261 | 262 | if __name__ == '__main__': 263 | main() 264 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import model 2 | import argparse 3 | import pickle 4 | import scipy.misc 5 | import random 6 | import os 7 | import shutil 8 | 9 | import tensorflow as tf 10 | import numpy as np 11 | 12 | from os.path import join 13 | from Utils import image_processing 14 | 15 | def main(): 16 | parser = argparse.ArgumentParser() 17 | parser.add_argument('--z_dim', type=int, default=100, 18 | help='Noise dimension') 19 | 20 | parser.add_argument('--t_dim', type=int, default=256, 21 | help='Text feature dimension') 22 | 23 | parser.add_argument('--batch_size', type=int, default=64, 24 | help='Batch Size') 25 | 26 | parser.add_argument('--image_size', type=int, default=128, 27 | help='Image Size a, a x a') 28 | 29 | parser.add_argument('--gf_dim', type=int, default=64, 30 | help='Number of conv in the first layer gen.') 31 | 32 | parser.add_argument('--df_dim', type=int, default=64, 33 | help='Number of conv in the first layer discr.') 34 | 35 | parser.add_argument('--caption_vector_length', type=int, default=4800, 36 | help='Caption Vector Length') 37 | 38 | parser.add_argument('--n_classes', type = int, default = 102, 39 | help = 'Number of classes/class labels') 40 | 41 | parser.add_argument('--data_dir', type=str, default="Data", 42 | help='Data Directory') 43 | 44 | parser.add_argument('--learning_rate', type=float, default=0.0002, 45 | help='Learning Rate') 46 | 47 | parser.add_argument('--beta1', type=float, default=0.5, 48 | help='Momentum for Adam Update') 49 | 50 | parser.add_argument('--epochs', type=int, default=200, 51 | help='Max number of epochs') 52 | 53 | parser.add_argument('--save_every', type=int, default=30, 54 | help='Save Model/Samples every x iterations over ' 55 | 'batches') 56 | 57 | parser.add_argument('--resume_model', type=bool, default=False, 58 | help='Pre-Trained Model load or not') 59 | 60 | parser.add_argument('--data_set', type=str, default="flowers", 61 | help='Dat set: MS-COCO, flowers') 62 | 63 | parser.add_argument('--model_name', type=str, default="TAC_GAN", 64 | help='model_1 or model_2') 65 | 66 | parser.add_argument('--train', type = bool, default = True, 67 | help = 'True while training and otherwise') 68 | 69 | args = parser.parse_args() 70 | 71 | model_dir, model_chkpnts_dir, model_samples_dir, model_val_samples_dir,\ 72 | model_summaries_dir = initialize_directories(args) 73 | 74 | datasets_root_dir = join(args.data_dir, 'datasets') 75 | loaded_data = load_training_data(datasets_root_dir, args.data_set, 76 | args.caption_vector_length, 77 | args.n_classes) 78 | model_options = { 79 | 'z_dim': args.z_dim, 80 | 't_dim': args.t_dim, 81 | 'batch_size': args.batch_size, 82 | 'image_size': args.image_size, 83 | 'gf_dim': args.gf_dim, 84 | 'df_dim': args.df_dim, 85 | 'caption_vector_length': args.caption_vector_length, 86 | 'n_classes': loaded_data['n_classes'] 87 | } 88 | 89 | # Initialize and build the GAN model 90 | gan = model.GAN(model_options) 91 | input_tensors, variables, loss, outputs, checks = gan.build_model() 92 | 93 | d_optim = tf.train.AdamOptimizer(args.learning_rate, 94 | beta1=args.beta1).minimize(loss['d_loss'], 95 | var_list=variables['d_vars']) 96 | g_optim = tf.train.AdamOptimizer(args.learning_rate, 97 | beta1=args.beta1).minimize(loss['g_loss'], 98 | var_list=variables['g_vars']) 99 | 100 | global_step_tensor = tf.Variable(1, trainable=False, name='global_step') 101 | merged = tf.summary.merge_all() 102 | sess = tf.InteractiveSession() 103 | 104 | summary_writer = tf.summary.FileWriter(model_summaries_dir, sess.graph) 105 | 106 | tf.global_variables_initializer().run() 107 | saver = tf.train.Saver(max_to_keep=10000) 108 | 109 | if args.resume_model: 110 | print('Trying to resume training from a previous checkpoint' + 111 | str(tf.train.latest_checkpoint(model_chkpnts_dir))) 112 | if tf.train.latest_checkpoint(model_chkpnts_dir) is not None: 113 | saver.restore(sess, tf.train.latest_checkpoint(model_chkpnts_dir)) 114 | print('Successfully loaded model. Resuming training.') 115 | else: 116 | print('Could not load checkpoints. Training a new model') 117 | global_step = global_step_tensor.eval() 118 | gs_assign_op = global_step_tensor.assign(global_step) 119 | for i in range(args.epochs): 120 | batch_no = 0 121 | while batch_no * args.batch_size + args.batch_size < \ 122 | loaded_data['data_length']: 123 | 124 | real_images, wrong_images, caption_vectors, z_noise, image_files, \ 125 | real_classes, wrong_classes, image_caps, image_ids = \ 126 | get_training_batch(batch_no, args.batch_size, 127 | args.image_size, args.z_dim, 128 | 'train', datasets_root_dir, 129 | args.data_set, loaded_data) 130 | 131 | # DISCR UPDATE 132 | check_ts = [checks['d_loss1'], checks['d_loss2'], 133 | checks['d_loss3'], checks['d_loss1_1'], 134 | checks['d_loss2_1']] 135 | 136 | feed = { 137 | input_tensors['t_real_image'].name : real_images, 138 | input_tensors['t_wrong_image'].name : wrong_images, 139 | input_tensors['t_real_caption'].name : caption_vectors, 140 | input_tensors['t_z'].name : z_noise, 141 | input_tensors['t_real_classes'].name : real_classes, 142 | input_tensors['t_wrong_classes'].name : wrong_classes, 143 | input_tensors['t_training'].name : args.train 144 | } 145 | 146 | _, d_loss, gen, d1, d2, d3, d4, d5= sess.run([d_optim, 147 | loss['d_loss'],outputs['generator']] + check_ts, 148 | feed_dict=feed) 149 | 150 | print("D total loss: {}\n" 151 | "D loss-1 [Real/Fake loss for real images] : {} \n" 152 | "D loss-2 [Real/Fake loss for wrong images]: {} \n" 153 | "D loss-3 [Real/Fake loss for fake images]: {} \n" 154 | "D loss-4 [Aux Classifier loss for real images]: {} \n" 155 | "D loss-5 [Aux Classifier loss for wrong images]: {}" 156 | " ".format(d_loss, d1, d2, d3, d4, d5)) 157 | 158 | # GEN UPDATE 159 | _, g_loss, gen = sess.run([g_optim, loss['g_loss'], 160 | outputs['generator']], feed_dict=feed) 161 | 162 | # GEN UPDATE TWICE 163 | _, summary, g_loss, gen, g1, g2 = sess.run([g_optim, merged, 164 | loss['g_loss'], outputs['generator'], checks['g_loss_1'], 165 | checks['g_loss_2']], feed_dict=feed) 166 | summary_writer.add_summary(summary, global_step) 167 | print("\n\nLOSSES\nDiscriminator Loss: {}\nGenerator Loss: {" 168 | "}\nBatch Number: {}\nEpoch: {},\nTotal Batches per " 169 | "epoch: {}\n".format( d_loss, g_loss, batch_no, i, 170 | int(len(loaded_data['image_list']) / args.batch_size))) 171 | print("\nG loss-1 [Real/Fake loss for fake images] : {} \n" 172 | "G loss-2 [Aux Classifier loss for fake images]: {} \n" 173 | " ".format(g1, g2)) 174 | global_step += 1 175 | sess.run(gs_assign_op) 176 | batch_no += 1 177 | if (batch_no % args.save_every) == 0 and batch_no != 0: 178 | print("Saving Images and the Model\n\n") 179 | 180 | save_for_vis(model_samples_dir, real_images, gen, image_files, 181 | image_caps, image_ids) 182 | save_path = saver.save(sess, 183 | join(model_chkpnts_dir, 184 | "latest_model_{}_temp.ckpt".format( 185 | args.data_set))) 186 | 187 | # Getting a batch for validation 188 | val_captions, val_image_files, val_image_caps, val_image_ids = \ 189 | get_val_caps_batch(args.batch_size, loaded_data, 190 | args.data_set, datasets_root_dir) 191 | 192 | shutil.rmtree(model_val_samples_dir) 193 | os.makedirs(model_val_samples_dir) 194 | 195 | for val_viz_cnt in range(0, 4): 196 | val_z_noise = np.random.uniform(-1, 1, [args.batch_size, 197 | args.z_dim]) 198 | 199 | val_feed = { 200 | input_tensors['t_real_caption'].name : val_captions, 201 | input_tensors['t_z'].name : val_z_noise, 202 | input_tensors['t_training'].name : True 203 | } 204 | 205 | val_gen = sess.run([outputs['generator']], 206 | feed_dict=val_feed) 207 | save_for_viz_val(model_val_samples_dir, val_gen, 208 | val_image_files, val_image_caps, 209 | val_image_ids, args.image_size, 210 | val_viz_cnt) 211 | 212 | # Save the model after every epoch 213 | if i % 1 == 0: 214 | epoch_dir = join(model_chkpnts_dir, str(i)) 215 | if not os.path.exists(epoch_dir): 216 | os.makedirs(epoch_dir) 217 | 218 | save_path = saver.save(sess, 219 | join(epoch_dir, 220 | "model_after_{}_epoch_{}.ckpt". 221 | format(args.data_set, i))) 222 | val_captions, val_image_files, val_image_caps, val_image_ids = \ 223 | get_val_caps_batch(args.batch_size, loaded_data, 224 | args.data_set, datasets_root_dir) 225 | 226 | shutil.rmtree(model_val_samples_dir) 227 | os.makedirs(model_val_samples_dir) 228 | 229 | for val_viz_cnt in range(0, 10): 230 | val_z_noise = np.random.uniform(-1, 1, [args.batch_size, 231 | args.z_dim]) 232 | val_feed = { 233 | input_tensors['t_real_caption'].name : val_captions, 234 | input_tensors['t_z'].name : val_z_noise, 235 | input_tensors['t_training'].name : True 236 | } 237 | val_gen = sess.run([outputs['generator']], feed_dict=val_feed) 238 | save_for_viz_val(model_val_samples_dir, val_gen, 239 | val_image_files, val_image_caps, 240 | val_image_ids, args.image_size, 241 | val_viz_cnt) 242 | 243 | 244 | def load_training_data(data_dir, data_set, caption_vector_length, n_classes) : 245 | if data_set == 'flowers' : 246 | flower_str_captions = pickle.load( 247 | open(join(data_dir, 'flowers', 'flowers_caps.pkl'), "rb")) 248 | 249 | img_classes = pickle.load( 250 | open(join(data_dir, 'flowers', 'flower_tc.pkl'), "rb")) 251 | 252 | flower_enc_captions = pickle.load( 253 | open(join(data_dir, 'flowers', 'flower_tv.pkl'), "rb")) 254 | tr_image_ids = pickle.load( 255 | open(join(data_dir, 'flowers', 'train_ids.pkl'), "rb")) 256 | val_image_ids = pickle.load( 257 | open(join(data_dir, 'flowers', 'val_ids.pkl'), "rb")) 258 | 259 | max_caps_len = caption_vector_length 260 | tr_n_imgs = len(tr_image_ids) 261 | val_n_imgs = len(val_image_ids) 262 | 263 | return { 264 | 'image_list' : tr_image_ids, 265 | 'captions' : flower_enc_captions, 266 | 'data_length' : tr_n_imgs, 267 | 'classes' : img_classes, 268 | 'n_classes' : n_classes, 269 | 'max_caps_len' : max_caps_len, 270 | 'val_img_list' : val_image_ids, 271 | 'val_captions' : flower_enc_captions, 272 | 'val_data_len' : val_n_imgs, 273 | 'str_captions' : flower_str_captions 274 | } 275 | 276 | else : 277 | raise Exception('No Dataset Found') 278 | 279 | 280 | def initialize_directories(args): 281 | model_dir = join(args.data_dir, 'training', args.model_name) 282 | if not os.path.exists(model_dir): 283 | os.makedirs(model_dir) 284 | 285 | model_chkpnts_dir = join(model_dir, 'checkpoints') 286 | if not os.path.exists(model_chkpnts_dir): 287 | os.makedirs(model_chkpnts_dir) 288 | 289 | model_summaries_dir = join(model_dir, 'summaries') 290 | if not os.path.exists(model_summaries_dir): 291 | os.makedirs(model_summaries_dir) 292 | 293 | model_samples_dir = join(model_dir, 'samples') 294 | if not os.path.exists(model_samples_dir): 295 | os.makedirs(model_samples_dir) 296 | 297 | model_val_samples_dir = join(model_dir, 'val_samples') 298 | if not os.path.exists(model_val_samples_dir): 299 | os.makedirs(model_val_samples_dir) 300 | 301 | return model_dir, model_chkpnts_dir, model_samples_dir, \ 302 | model_val_samples_dir, model_summaries_dir 303 | 304 | 305 | def save_for_viz_val(data_dir, generated_images, image_files, image_caps, 306 | image_ids, image_size, id): 307 | 308 | generated_images = np.squeeze(np.array(generated_images)) 309 | for i in range(0, generated_images.shape[0]) : 310 | image_dir = join(data_dir, str(image_ids[i])) 311 | if not os.path.exists(image_dir): 312 | os.makedirs(image_dir) 313 | 314 | real_image_path = join(image_dir, 315 | '{}.jpg'.format(image_ids[i])) 316 | if os.path.exists(image_dir): 317 | real_images_255 = image_processing.load_image_array(image_files[i], 318 | image_size, image_ids[i], mode='val') 319 | scipy.misc.imsave(real_image_path, real_images_255) 320 | 321 | caps_dir = join(image_dir, "caps.txt") 322 | if not os.path.exists(caps_dir): 323 | with open(caps_dir, "w") as text_file: 324 | text_file.write(image_caps[i]+"\n") 325 | 326 | fake_images_255 = generated_images[i] 327 | scipy.misc.imsave(join(image_dir, 'fake_image_{}.jpg'.format(id)), 328 | fake_images_255) 329 | 330 | 331 | def save_for_vis(data_dir, real_images, generated_images, image_files, 332 | image_caps, image_ids) : 333 | 334 | shutil.rmtree(data_dir) 335 | os.makedirs(data_dir) 336 | 337 | for i in range(0, real_images.shape[0]) : 338 | real_images_255 = (real_images[i, :, :, :]) 339 | scipy.misc.imsave(join(data_dir, 340 | '{}_{}.jpg'.format(i, image_files[i].split('/')[-1])), 341 | real_images_255) 342 | 343 | fake_images_255 = (generated_images[i, :, :, :]) 344 | scipy.misc.imsave(join(data_dir, 'fake_image_{}.jpg'.format( 345 | i)), fake_images_255) 346 | 347 | str_caps = '\n'.join(image_caps) 348 | str_image_ids = '\n'.join([str(image_id) for image_id in image_ids]) 349 | with open(join(data_dir, "caps.txt"), "w") as text_file: 350 | text_file.write(str_caps) 351 | with open(join(data_dir, "ids.txt"), "w") as text_file: 352 | text_file.write(str_image_ids) 353 | 354 | 355 | def get_val_caps_batch(batch_size, loaded_data, data_set, data_dir): 356 | 357 | if data_set == 'flowers': 358 | captions = np.zeros((batch_size, loaded_data['max_caps_len'])) 359 | 360 | batch_idx = np.random.randint(0, loaded_data['val_data_len'], 361 | size = batch_size) 362 | image_ids = np.take(loaded_data['val_img_list'], batch_idx) 363 | image_files = [] 364 | image_caps = [] 365 | for idx, image_id in enumerate(image_ids) : 366 | image_file = join(data_dir, 367 | 'flowers/jpg/' + image_id) 368 | random_caption = random.randint(0, 4) 369 | captions[idx, :] = \ 370 | loaded_data['val_captions'][image_id][random_caption][ 371 | 0 :loaded_data['max_caps_len']] 372 | 373 | image_caps.append(loaded_data['str_captions'] 374 | [image_id][random_caption]) 375 | image_files.append(image_file) 376 | 377 | return captions, image_files, image_caps, image_ids 378 | else: 379 | raise Exception('Dataset not found') 380 | 381 | 382 | def get_training_batch(batch_no, batch_size, image_size, z_dim, split, 383 | data_dir, data_set, loaded_data = None) : 384 | if data_set == 'flowers': 385 | real_images = np.zeros((batch_size, image_size, image_size, 3)) 386 | wrong_images = np.zeros((batch_size, image_size, image_size, 3)) 387 | captions = np.zeros((batch_size, loaded_data['max_caps_len'])) 388 | real_classes = np.zeros((batch_size, loaded_data['n_classes'])) 389 | wrong_classes = np.zeros((batch_size, loaded_data['n_classes'])) 390 | 391 | cnt = 0 392 | image_files = [] 393 | image_caps = [] 394 | image_ids = [] 395 | for i in range(batch_no * batch_size, 396 | batch_no * batch_size + batch_size) : 397 | idx = i % len(loaded_data['image_list']) 398 | image_file = join(data_dir, 399 | 'flowers/jpg/' + loaded_data['image_list'][idx]) 400 | 401 | image_ids.append(loaded_data['image_list'][idx]) 402 | 403 | image_array = image_processing.load_image_array_flowers(image_file, 404 | image_size) 405 | real_images[cnt, :, :, :] = image_array 406 | 407 | # Improve this selection of wrong image 408 | wrong_image_id = random.randint(0, 409 | len(loaded_data['image_list']) - 1) 410 | wrong_image_file = join(data_dir, 411 | 'flowers/jpg/' + loaded_data['image_list'][ 412 | wrong_image_id]) 413 | wrong_image_array = image_processing.load_image_array_flowers(wrong_image_file, 414 | image_size) 415 | wrong_images[cnt, :, :, :] = wrong_image_array 416 | 417 | wrong_classes[cnt, :] = loaded_data['classes'][loaded_data['image_list'][ 418 | wrong_image_id]][0 :loaded_data['n_classes']] 419 | 420 | random_caption = random.randint(0, 4) 421 | captions[cnt, :] = \ 422 | loaded_data['captions'][loaded_data['image_list'][idx]][ 423 | random_caption][0 :loaded_data['max_caps_len']] 424 | 425 | real_classes[cnt, :] = \ 426 | loaded_data['classes'][loaded_data['image_list'][idx]][ 427 | 0 :loaded_data['n_classes']] 428 | str_cap = loaded_data['str_captions'][loaded_data['image_list'] 429 | [idx]][random_caption] 430 | 431 | image_files.append(image_file) 432 | image_caps.append(str_cap) 433 | cnt += 1 434 | 435 | z_noise = np.random.uniform(-1, 1, [batch_size, z_dim]) 436 | return real_images, wrong_images, captions, z_noise, image_files, \ 437 | real_classes, wrong_classes, image_caps, image_ids 438 | else: 439 | raise Exception('Dataset not found') 440 | 441 | 442 | if __name__ == '__main__' : 443 | main() 444 | -------------------------------------------------------------------------------- /z_interpolation.py: -------------------------------------------------------------------------------- 1 | import model 2 | import argparse 3 | import pickle 4 | import scipy.misc 5 | import random 6 | import os 7 | import progressbar 8 | 9 | import tensorflow as tf 10 | import numpy as np 11 | 12 | from os.path import join 13 | 14 | def main(): 15 | parser = argparse.ArgumentParser() 16 | parser.add_argument('--z_dim', type=int, default=100, 17 | help='Noise dimension') 18 | 19 | parser.add_argument('--t_dim', type=int, default=256, 20 | help='Text feature dimension') 21 | 22 | parser.add_argument('--batch_size', type=int, default=64, 23 | help='Batch Size') 24 | 25 | parser.add_argument('--image_size', type=int, default=128, 26 | help='Image Size a, a x a') 27 | 28 | parser.add_argument('--gf_dim', type=int, default=64, 29 | help='Number of conv in the first layer gen.') 30 | 31 | parser.add_argument('--df_dim', type=int, default=64, 32 | help='Number of conv in the first layer discr.') 33 | 34 | parser.add_argument('--caption_vector_length', type=int, default=4800, 35 | help='Caption Vector Length') 36 | 37 | parser.add_argument('--n_classes', type=int, default=102, 38 | help='Number of classes/class labels') 39 | 40 | parser.add_argument('--data_dir', type=str, default="Data", 41 | help='Data Directory') 42 | 43 | parser.add_argument('--learning_rate', type=float, default=0.0002, 44 | help='Learning Rate') 45 | 46 | parser.add_argument('--beta1', type=float, default=0.5, 47 | help='Momentum for Adam Update') 48 | 49 | parser.add_argument('--data_set', type=str, default="flowers", 50 | help='Dat set: flowers') 51 | 52 | parser.add_argument('--output_dir', type=str, 53 | default="Data/synthetic_dataset", 54 | help='The directory in which this dataset will be ' 55 | 'created') 56 | 57 | parser.add_argument('--checkpoints_dir', type=str, default="/tmp", 58 | help='Path to the checkpoints directory') 59 | 60 | parser.add_argument('--n_interp', type=int, default=100, 61 | help='The difference between each interpolation. ' 62 | 'Should ideally be a multiple of 10') 63 | 64 | parser.add_argument('--n_images', type=int, default=500, 65 | help='Number of images to randomply sample for ' 66 | 'generating interpolation results') 67 | 68 | args = parser.parse_args() 69 | datasets_root_dir = join(args.data_dir, 'datasets') 70 | 71 | loaded_data = load_training_data(datasets_root_dir, args.data_set, 72 | args.caption_vector_length, args.n_classes) 73 | 74 | model_options = { 75 | 'z_dim': args.z_dim, 76 | 't_dim': args.t_dim, 77 | 'batch_size': args.batch_size, 78 | 'image_size': args.image_size, 79 | 'gf_dim': args.gf_dim, 80 | 'df_dim': args.df_dim, 81 | 'caption_vector_length': args.caption_vector_length, 82 | 'n_classes': loaded_data['n_classes'] 83 | } 84 | 85 | gan = model.GAN(model_options) 86 | input_tensors, variables, loss, outputs, checks = gan.build_model() 87 | 88 | sess = tf.InteractiveSession() 89 | tf.initialize_all_variables().run() 90 | 91 | saver = tf.train.Saver(max_to_keep=10000) 92 | print('resuming model from checkpoint' + 93 | str(tf.train.latest_checkpoint(args.checkpoints_dir))) 94 | if tf.train.latest_checkpoint(args.checkpoints_dir) is not None: 95 | saver.restore(sess, tf.train.latest_checkpoint(args.checkpoints_dir)) 96 | print('Successfully loaded model') 97 | else: 98 | print('Could not load checkpoints') 99 | exit() 100 | 101 | random.shuffle(loaded_data['image_list']) 102 | selected_images = loaded_data['image_list'][:args.n_images] 103 | cap_id = [np.random.randint(0, 4) for cap_i in range(len(selected_images))] 104 | 105 | print('Generating Images by interpolating z') 106 | bar = progressbar.ProgressBar(redirect_stdout=True, 107 | max_value=args.n_images) 108 | for sel_i, (sel_img, sel_cap) in enumerate(zip(selected_images, cap_id)): 109 | captions, image_files, image_caps, image_ids, image_caps_ids = \ 110 | get_images_z_intr(sel_img, sel_cap, loaded_data, 111 | datasets_root_dir, args.batch_size) 112 | 113 | z_noise_1 = np.full((args.batch_size, args.z_dim), -1.0) 114 | z_noise_2 = np.full((args.batch_size, args.z_dim), 1.0) 115 | intr_z_list = get_interp_vec(z_noise_1, z_noise_2, args.z_dim, 116 | args.n_interp, args.batch_size) 117 | 118 | for z_i, z_noise in enumerate(intr_z_list): 119 | val_feed = { 120 | input_tensors['t_real_caption'].name: captions, 121 | input_tensors['t_z'].name: z_noise, 122 | input_tensors['t_training'].name: True 123 | } 124 | 125 | val_gen = sess.run([outputs['generator']], feed_dict=val_feed) 126 | 127 | save_distributed_image_batch(args.output_dir, val_gen, sel_i, z_i, 128 | sel_img, sel_cap, args.batch_size) 129 | bar.update(sel_i) 130 | bar.finish() 131 | print('Finished generating interpolated images') 132 | 133 | 134 | def load_training_data(data_dir, data_set, caption_vector_length, n_classes): 135 | if data_set == 'flowers': 136 | flower_str_captions = pickle.load( 137 | open(join(data_dir, 'flowers', 'flowers_caps.pkl'), "rb")) 138 | 139 | img_classes = pickle.load( 140 | open(join(data_dir, 'flowers', 'flower_tc.pkl'), "rb")) 141 | 142 | flower_enc_captions = pickle.load( 143 | open(join(data_dir, 'flowers', 'flower_tv.pkl'), "rb")) 144 | # h1 = h5py.File(join(data_dir, 'flower_tc.hdf5')) 145 | tr_image_ids = pickle.load( 146 | open(join(data_dir, 'flowers', 'train_ids.pkl'), "rb")) 147 | val_image_ids = pickle.load( 148 | open(join(data_dir, 'flowers', 'val_ids.pkl'), "rb")) 149 | 150 | max_caps_len = caption_vector_length 151 | 152 | tr_n_imgs = len(tr_image_ids) 153 | val_n_imgs = len(val_image_ids) 154 | 155 | return { 156 | 'image_list': tr_image_ids, 157 | 'captions': flower_enc_captions, 158 | 'data_length': tr_n_imgs, 159 | 'classes': img_classes, 160 | 'n_classes': n_classes, 161 | 'max_caps_len': max_caps_len, 162 | 'val_img_list': val_image_ids, 163 | 'val_captions': flower_enc_captions, 164 | 'val_data_len': val_n_imgs, 165 | 'str_captions': flower_str_captions 166 | } 167 | 168 | else: 169 | raise Exception('Dataset Not Found!!') 170 | 171 | def save_distributed_image_batch(data_dir, generated_images, sel_i, z_i, 172 | sel_img, sel_cap, batch_size): 173 | 174 | generated_images = np.squeeze(generated_images) 175 | image_dir = join(data_dir, 'z_interpolation', str(sel_i)) 176 | if not os.path.exists(image_dir): 177 | os.makedirs(image_dir) 178 | meta_path = os.path.join(image_dir, "meta.txt") 179 | with open(meta_path, "w") as text_file: 180 | text_file.write(str(sel_img) + "\t" + str(sel_cap)) 181 | fake_image_255 = generated_images[batch_size - 1] 182 | scipy.misc.imsave(join(image_dir, '{}.jpg'.format(z_i)), 183 | fake_image_255) 184 | 185 | 186 | def get_images_z_intr(sel_img, sel_cap, loaded_data, data_dir, batch_size=64): 187 | 188 | captions = np.zeros((batch_size, loaded_data['max_caps_len'])) 189 | batch_idx = np.random.randint(0, loaded_data['data_length'], 190 | size = batch_size-1) 191 | 192 | image_ids = np.take(loaded_data['image_list'], batch_idx) 193 | image_files = [] 194 | image_caps = [] 195 | image_caps_ids = [] 196 | 197 | for idx, image_id in enumerate(image_ids): 198 | image_file = join(data_dir, 199 | 'flowers/jpg/' + image_id) 200 | random_caption = random.randint(0, 4) 201 | image_caps_ids.append(random_caption) 202 | captions[idx, :] = \ 203 | loaded_data['captions'][image_id][random_caption][ 204 | 0:loaded_data['max_caps_len']] 205 | str_cap = loaded_data['str_captions'][image_id][random_caption] 206 | 207 | image_caps.append(loaded_data['captions'] 208 | [image_id][random_caption]) 209 | image_files.append(image_file) 210 | if idx == batch_size-2: 211 | idx = idx+1 212 | image_id = sel_img 213 | image_file = join(data_dir, 214 | 'flowers/jpg/' + sel_img) 215 | random_caption = sel_cap 216 | image_caps_ids.append(random_caption) 217 | captions[idx, :] = \ 218 | loaded_data['captions'][image_id][random_caption][ 219 | 0:loaded_data['max_caps_len']] 220 | str_cap = loaded_data['str_captions'][image_id][random_caption] 221 | image_caps.append(loaded_data['str_captions'] 222 | [image_id][random_caption]) 223 | image_files.append(image_file) 224 | break 225 | 226 | return captions, image_files, image_caps, image_ids, image_caps_ids 227 | 228 | 229 | def get_interp_vec(vec_1, vec_2, dim, n_interp, batch_size): 230 | 231 | intrip_list = [] 232 | bals = np.arange(0, 1, 1/n_interp) 233 | for bal in bals: 234 | left = np.full((batch_size, dim), bal) 235 | right = np.full((batch_size, dim), 1.0 - bal) 236 | intrip_vec = np.multiply(vec_1, left) + np.multiply(vec_2, right) 237 | intrip_list.append(intrip_vec) 238 | return intrip_list 239 | 240 | 241 | if __name__ == '__main__': 242 | main() 243 | --------------------------------------------------------------------------------