├── .gitignore ├── LICENSE ├── README.md └── udacity ├── 1_notmnist.ipynb ├── 2_fullyconnected.ipynb ├── 3_regularization.ipynb ├── 4_convolutions.ipynb ├── 5_word2vec.ipynb ├── 6_lstm.ipynb ├── Dockerfile ├── README.md └── Tensorflow Basics.ipynb /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | 64 | # Custom files 65 | # 66 | *.zip 67 | *.pickle 68 | *.tar.gz 69 | udacity/notMNIST_small/* 70 | udacity/notMNIST_large/* 71 | udacity/MNIST_data/* 72 | -------------------------------------------------------------------------------- /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 | # Udacity-Deep-Learning 2 | Assignments for Udacity Deep Learning course using TensorFlow https://www.udacity.com/course/progress#!/c-ud730 3 | -------------------------------------------------------------------------------- /udacity/2_fullyconnected.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "colab_type": "text", 7 | "id": "kR-4eNdK6lYS" 8 | }, 9 | "source": [ 10 | "Deep Learning\n", 11 | "=============\n", 12 | "\n", 13 | "Assignment 2\n", 14 | "------------\n", 15 | "\n", 16 | "Previously in `1_notmnist.ipynb`, we created a pickle with formatted datasets for training, development and testing on the [notMNIST dataset](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html).\n", 17 | "\n", 18 | "The goal of this assignment is to progressively train deeper and more accurate models using TensorFlow." 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 1, 24 | "metadata": { 25 | "cellView": "both", 26 | "colab": { 27 | "autoexec": { 28 | "startup": false, 29 | "wait_interval": 0 30 | } 31 | }, 32 | "colab_type": "code", 33 | "collapsed": true, 34 | "id": "JLpLa8Jt7Vu4" 35 | }, 36 | "outputs": [], 37 | "source": [ 38 | "# These are all the modules we'll be using later. Make sure you can import them\n", 39 | "# before proceeding further.\n", 40 | "import cPickle as pickle\n", 41 | "import numpy as np\n", 42 | "import tensorflow as tf" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": { 48 | "colab_type": "text", 49 | "id": "1HrCK6e17WzV" 50 | }, 51 | "source": [ 52 | "First reload the data we generated in `1_notmist.ipynb`." 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 2, 58 | "metadata": { 59 | "cellView": "both", 60 | "colab": { 61 | "autoexec": { 62 | "startup": false, 63 | "wait_interval": 0 64 | }, 65 | "output_extras": [ 66 | { 67 | "item_id": 1 68 | } 69 | ] 70 | }, 71 | "colab_type": "code", 72 | "collapsed": false, 73 | "executionInfo": { 74 | "elapsed": 19456, 75 | "status": "ok", 76 | "timestamp": 1449847956073, 77 | "user": { 78 | "color": "", 79 | "displayName": "", 80 | "isAnonymous": false, 81 | "isMe": true, 82 | "permissionId": "", 83 | "photoUrl": "", 84 | "sessionId": "0", 85 | "userId": "" 86 | }, 87 | "user_tz": 480 88 | }, 89 | "id": "y3-cj1bpmuxc", 90 | "outputId": "0ddb1607-1fc4-4ddb-de28-6c7ab7fb0c33" 91 | }, 92 | "outputs": [ 93 | { 94 | "name": "stdout", 95 | "output_type": "stream", 96 | "text": [ 97 | "Training set (200000, 28, 28) (200000,)\n", 98 | "Validation set (10000, 28, 28) (10000,)\n", 99 | "Test set (18724, 28, 28) (18724,)\n" 100 | ] 101 | } 102 | ], 103 | "source": [ 104 | "pickle_file = 'notMNIST.pickle'\n", 105 | "\n", 106 | "with open(pickle_file, 'rb') as f:\n", 107 | " save = pickle.load(f)\n", 108 | " train_dataset = save['train_dataset']\n", 109 | " train_labels = save['train_labels']\n", 110 | " valid_dataset = save['valid_dataset']\n", 111 | " valid_labels = save['valid_labels']\n", 112 | " test_dataset = save['test_dataset']\n", 113 | " test_labels = save['test_labels']\n", 114 | " del save # hint to help gc free up memory\n", 115 | " print 'Training set', train_dataset.shape, train_labels.shape\n", 116 | " print 'Validation set', valid_dataset.shape, valid_labels.shape\n", 117 | " print 'Test set', test_dataset.shape, test_labels.shape" 118 | ] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": { 123 | "colab_type": "text", 124 | "id": "L7aHrm6nGDMB" 125 | }, 126 | "source": [ 127 | "Reformat into a shape that's more adapted to the models we're going to train:\n", 128 | "- data as a flat matrix,\n", 129 | "- labels as float 1-hot encodings." 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": 3, 135 | "metadata": { 136 | "cellView": "both", 137 | "colab": { 138 | "autoexec": { 139 | "startup": false, 140 | "wait_interval": 0 141 | }, 142 | "output_extras": [ 143 | { 144 | "item_id": 1 145 | } 146 | ] 147 | }, 148 | "colab_type": "code", 149 | "collapsed": false, 150 | "executionInfo": { 151 | "elapsed": 19723, 152 | "status": "ok", 153 | "timestamp": 1449847956364, 154 | "user": { 155 | "color": "", 156 | "displayName": "", 157 | "isAnonymous": false, 158 | "isMe": true, 159 | "permissionId": "", 160 | "photoUrl": "", 161 | "sessionId": "0", 162 | "userId": "" 163 | }, 164 | "user_tz": 480 165 | }, 166 | "id": "IRSyYiIIGIzS", 167 | "outputId": "2ba0fc75-1487-4ace-a562-cf81cae82793" 168 | }, 169 | "outputs": [ 170 | { 171 | "name": "stdout", 172 | "output_type": "stream", 173 | "text": [ 174 | "Training set (200000, 784) (200000, 10)\n", 175 | "Validation set (10000, 784) (10000, 10)\n", 176 | "Test set (18724, 784) (18724, 10)\n" 177 | ] 178 | } 179 | ], 180 | "source": [ 181 | "image_size = 28\n", 182 | "num_labels = 10\n", 183 | "\n", 184 | "def reformat(dataset, labels):\n", 185 | " dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)\n", 186 | " # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]\n", 187 | " labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n", 188 | " return dataset, labels\n", 189 | "train_dataset, train_labels = reformat(train_dataset, train_labels)\n", 190 | "valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)\n", 191 | "test_dataset, test_labels = reformat(test_dataset, test_labels)\n", 192 | "print 'Training set', train_dataset.shape, train_labels.shape\n", 193 | "print 'Validation set', valid_dataset.shape, valid_labels.shape\n", 194 | "print 'Test set', test_dataset.shape, test_labels.shape" 195 | ] 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "metadata": { 200 | "colab_type": "text", 201 | "id": "nCLVqyQ5vPPH" 202 | }, 203 | "source": [ 204 | "We're first going to train a multinomial logistic regression using simple gradient descent.\n", 205 | "\n", 206 | "TensorFlow works like this:\n", 207 | "* First you describe the computation that you want to see performed: what the inputs, the variables, and the operations look like. These get created as nodes over a computation graph. This description is all contained within the block below:\n", 208 | "\n", 209 | " with graph.as_default():\n", 210 | " ...\n", 211 | "\n", 212 | "* Then you can run the operations on this graph as many times as you want by calling `session.run()`, providing it outputs to fetch from the graph that get returned. This runtime operation is all contained in the block below:\n", 213 | "\n", 214 | " with tf.Session(graph=graph) as session:\n", 215 | " ...\n", 216 | "\n", 217 | "Let's load all the data into TensorFlow and build the computation graph corresponding to our training:" 218 | ] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": 4, 223 | "metadata": { 224 | "cellView": "both", 225 | "colab": { 226 | "autoexec": { 227 | "startup": false, 228 | "wait_interval": 0 229 | } 230 | }, 231 | "colab_type": "code", 232 | "collapsed": true, 233 | "id": "Nfv39qvtvOl_" 234 | }, 235 | "outputs": [], 236 | "source": [ 237 | "# With gradient descent training, even this much data is prohibitive.\n", 238 | "# Subset the training data for faster turnaround.\n", 239 | "train_subset = 10000\n", 240 | "\n", 241 | "graph = tf.Graph()\n", 242 | "with graph.as_default():\n", 243 | "\n", 244 | " # Input data.\n", 245 | " # Load the training, validation and test data into constants that are\n", 246 | " # attached to the graph.\n", 247 | " tf_train_dataset = tf.constant(train_dataset[:train_subset, :])\n", 248 | " tf_train_labels = tf.constant(train_labels[:train_subset])\n", 249 | " tf_valid_dataset = tf.constant(valid_dataset)\n", 250 | " tf_test_dataset = tf.constant(test_dataset)\n", 251 | " \n", 252 | " # Variables.\n", 253 | " # These are the parameters that we are going to be training. The weight\n", 254 | " # matrix will be initialized using random valued following a (truncated)\n", 255 | " # normal distribution. The biases get initialized to zero.\n", 256 | " weights = tf.Variable(\n", 257 | " tf.truncated_normal([image_size * image_size, num_labels]))\n", 258 | " biases = tf.Variable(tf.zeros([num_labels]))\n", 259 | " \n", 260 | " # Training computation.\n", 261 | " # We multiply the inputs with the weight matrix, and add biases. We compute\n", 262 | " # the softmax and cross-entropy (it's one operation in TensorFlow, because\n", 263 | " # it's very common, and it can be optimized). We take the average of this\n", 264 | " # cross-entropy across all training examples: that's our loss.\n", 265 | " logits = tf.matmul(tf_train_dataset, weights) + biases\n", 266 | " loss = tf.reduce_mean(\n", 267 | " tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n", 268 | " \n", 269 | " # Optimizer.\n", 270 | " # We are going to find the minimum of this loss using gradient descent.\n", 271 | " optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)\n", 272 | " \n", 273 | " # Predictions for the training, validation, and test data.\n", 274 | " # These are not part of training, but merely here so that we can report\n", 275 | " # accuracy figures as we train.\n", 276 | " train_prediction = tf.nn.softmax(logits)\n", 277 | " valid_prediction = tf.nn.softmax(\n", 278 | " tf.matmul(tf_valid_dataset, weights) + biases)\n", 279 | " test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)" 280 | ] 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "metadata": { 285 | "colab_type": "text", 286 | "id": "KQcL4uqISHjP" 287 | }, 288 | "source": [ 289 | "Let's run this computation and iterate:" 290 | ] 291 | }, 292 | { 293 | "cell_type": "code", 294 | "execution_count": 5, 295 | "metadata": { 296 | "cellView": "both", 297 | "colab": { 298 | "autoexec": { 299 | "startup": false, 300 | "wait_interval": 0 301 | }, 302 | "output_extras": [ 303 | { 304 | "item_id": 9 305 | } 306 | ] 307 | }, 308 | "colab_type": "code", 309 | "collapsed": false, 310 | "executionInfo": { 311 | "elapsed": 57454, 312 | "status": "ok", 313 | "timestamp": 1449847994134, 314 | "user": { 315 | "color": "", 316 | "displayName": "", 317 | "isAnonymous": false, 318 | "isMe": true, 319 | "permissionId": "", 320 | "photoUrl": "", 321 | "sessionId": "0", 322 | "userId": "" 323 | }, 324 | "user_tz": 480 325 | }, 326 | "id": "z2cjdenH869W", 327 | "outputId": "4c037ba1-b526-4d8e-e632-91e2a0333267" 328 | }, 329 | "outputs": [ 330 | { 331 | "name": "stdout", 332 | "output_type": "stream", 333 | "text": [ 334 | "Initialized\n", 335 | "Loss at step 0 : 14.8329\n", 336 | "Training accuracy: 15.6%\n", 337 | "Validation accuracy: 18.0%\n", 338 | "Loss at step 100 : 2.40644\n", 339 | "Training accuracy: 71.6%\n", 340 | "Validation accuracy: 69.6%\n", 341 | "Loss at step 200 : 1.92211\n", 342 | "Training accuracy: 74.5%\n", 343 | "Validation accuracy: 72.2%\n", 344 | "Loss at step 300 : 1.67095\n", 345 | "Training accuracy: 75.8%\n", 346 | "Validation accuracy: 73.2%\n", 347 | "Loss at step 400 : 1.50335\n", 348 | "Training accuracy: 76.8%\n", 349 | "Validation accuracy: 73.8%\n", 350 | "Loss at step 500 : 1.37768\n", 351 | "Training accuracy: 77.6%\n", 352 | "Validation accuracy: 74.0%\n", 353 | "Loss at step 600 : 1.27806\n", 354 | "Training accuracy: 78.0%\n", 355 | "Validation accuracy: 74.3%\n", 356 | "Loss at step 700 : 1.19632\n", 357 | "Training accuracy: 78.4%\n", 358 | "Validation accuracy: 74.4%\n", 359 | "Loss at step 800 : 1.12767\n", 360 | "Training accuracy: 78.9%\n", 361 | "Validation accuracy: 74.8%\n", 362 | "Test accuracy: 82.7%\n" 363 | ] 364 | } 365 | ], 366 | "source": [ 367 | "num_steps = 801\n", 368 | "\n", 369 | "def accuracy(predictions, labels):\n", 370 | " return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n", 371 | " / predictions.shape[0])\n", 372 | "\n", 373 | "with tf.Session(graph=graph) as session:\n", 374 | " # This is a one-time operation which ensures the parameters get initialized as\n", 375 | " # we described in the graph: random weights for the matrix, zeros for the\n", 376 | " # biases. \n", 377 | " tf.initialize_all_variables().run()\n", 378 | " print 'Initialized'\n", 379 | " for step in xrange(num_steps):\n", 380 | " # Run the computations. We tell .run() that we want to run the optimizer,\n", 381 | " # and get the loss value and the training predictions returned as numpy\n", 382 | " # arrays.\n", 383 | " _, l, predictions = session.run([optimizer, loss, train_prediction])\n", 384 | " if (step % 100 == 0):\n", 385 | " print 'Loss at step', step, ':', l\n", 386 | " print 'Training accuracy: %.1f%%' % accuracy(\n", 387 | " predictions, train_labels[:train_subset, :])\n", 388 | " # Calling .eval() on valid_prediction is basically like calling run(), but\n", 389 | " # just to get that one numpy array. Note that it recomputes all its graph\n", 390 | " # dependencies.\n", 391 | " print 'Validation accuracy: %.1f%%' % accuracy(\n", 392 | " valid_prediction.eval(), valid_labels)\n", 393 | " print 'Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels)" 394 | ] 395 | }, 396 | { 397 | "cell_type": "markdown", 398 | "metadata": { 399 | "colab_type": "text", 400 | "id": "x68f-hxRGm3H" 401 | }, 402 | "source": [ 403 | "Let's now switch to stochastic gradient descent training instead, which is much faster.\n", 404 | "\n", 405 | "The graph will be similar, except that instead of holding all the training data into a constant node, we create a `Placeholder` node which will be fed actual data at every call of `sesion.run()`." 406 | ] 407 | }, 408 | { 409 | "cell_type": "code", 410 | "execution_count": 6, 411 | "metadata": { 412 | "cellView": "both", 413 | "colab": { 414 | "autoexec": { 415 | "startup": false, 416 | "wait_interval": 0 417 | } 418 | }, 419 | "colab_type": "code", 420 | "collapsed": true, 421 | "id": "qhPMzWYRGrzM" 422 | }, 423 | "outputs": [], 424 | "source": [ 425 | "batch_size = 128\n", 426 | "\n", 427 | "graph = tf.Graph()\n", 428 | "with graph.as_default():\n", 429 | "\n", 430 | " # Input data. For the training data, we use a placeholder that will be fed\n", 431 | " # at run time with a training minibatch.\n", 432 | " tf_train_dataset = tf.placeholder(tf.float32,\n", 433 | " shape=(batch_size, image_size * image_size))\n", 434 | " tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n", 435 | " tf_valid_dataset = tf.constant(valid_dataset)\n", 436 | " tf_test_dataset = tf.constant(test_dataset)\n", 437 | " \n", 438 | " # Variables.\n", 439 | " weights = tf.Variable(\n", 440 | " tf.truncated_normal([image_size * image_size, num_labels]))\n", 441 | " biases = tf.Variable(tf.zeros([num_labels]))\n", 442 | " \n", 443 | " # Training computation.\n", 444 | " logits = tf.matmul(tf_train_dataset, weights) + biases\n", 445 | " loss = tf.reduce_mean(\n", 446 | " tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n", 447 | " \n", 448 | " # Optimizer.\n", 449 | " optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)\n", 450 | " \n", 451 | " # Predictions for the training, validation, and test data.\n", 452 | " train_prediction = tf.nn.softmax(logits)\n", 453 | " valid_prediction = tf.nn.softmax(\n", 454 | " tf.matmul(tf_valid_dataset, weights) + biases)\n", 455 | " test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)" 456 | ] 457 | }, 458 | { 459 | "cell_type": "markdown", 460 | "metadata": { 461 | "colab_type": "text", 462 | "id": "XmVZESmtG4JH" 463 | }, 464 | "source": [ 465 | "Let's run it:" 466 | ] 467 | }, 468 | { 469 | "cell_type": "code", 470 | "execution_count": 7, 471 | "metadata": { 472 | "cellView": "both", 473 | "colab": { 474 | "autoexec": { 475 | "startup": false, 476 | "wait_interval": 0 477 | }, 478 | "output_extras": [ 479 | { 480 | "item_id": 6 481 | } 482 | ] 483 | }, 484 | "colab_type": "code", 485 | "collapsed": false, 486 | "executionInfo": { 487 | "elapsed": 66292, 488 | "status": "ok", 489 | "timestamp": 1449848003013, 490 | "user": { 491 | "color": "", 492 | "displayName": "", 493 | "isAnonymous": false, 494 | "isMe": true, 495 | "permissionId": "", 496 | "photoUrl": "", 497 | "sessionId": "0", 498 | "userId": "" 499 | }, 500 | "user_tz": 480 501 | }, 502 | "id": "FoF91pknG_YW", 503 | "outputId": "d255c80e-954d-4183-ca1c-c7333ce91d0a" 504 | }, 505 | "outputs": [ 506 | { 507 | "name": "stdout", 508 | "output_type": "stream", 509 | "text": [ 510 | "Initialized\n", 511 | "Minibatch loss at step 0 : 16.2918\n", 512 | "Minibatch accuracy: 16.4%\n", 513 | "Validation accuracy: 14.9%\n", 514 | "Minibatch loss at step 500 : 1.35108\n", 515 | "Minibatch accuracy: 75.0%\n", 516 | "Validation accuracy: 74.8%\n", 517 | "Minibatch loss at step 1000 : 0.961497\n", 518 | "Minibatch accuracy: 75.8%\n", 519 | "Validation accuracy: 76.4%\n", 520 | "Minibatch loss at step 1500 : 1.08711\n", 521 | "Minibatch accuracy: 78.9%\n", 522 | "Validation accuracy: 76.8%\n", 523 | "Minibatch loss at step 2000 : 0.729816\n", 524 | "Minibatch accuracy: 81.2%\n", 525 | "Validation accuracy: 77.4%\n", 526 | "Minibatch loss at step 2500 : 0.662467\n", 527 | "Minibatch accuracy: 85.9%\n", 528 | "Validation accuracy: 77.8%\n", 529 | "Minibatch loss at step 3000 : 0.858507\n", 530 | "Minibatch accuracy: 78.1%\n", 531 | "Validation accuracy: 78.6%\n", 532 | "Test accuracy: 86.0%\n" 533 | ] 534 | } 535 | ], 536 | "source": [ 537 | "num_steps = 3001\n", 538 | "\n", 539 | "with tf.Session(graph=graph) as session:\n", 540 | " tf.initialize_all_variables().run()\n", 541 | " print \"Initialized\"\n", 542 | " for step in xrange(num_steps):\n", 543 | " # Pick an offset within the training data, which has been randomized.\n", 544 | " # Note: we could use better randomization across epochs.\n", 545 | " offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n", 546 | " # Generate a minibatch.\n", 547 | " batch_data = train_dataset[offset:(offset + batch_size), :]\n", 548 | " batch_labels = train_labels[offset:(offset + batch_size), :]\n", 549 | " # Prepare a dictionary telling the session where to feed the minibatch.\n", 550 | " # The key of the dictionary is the placeholder node of the graph to be fed,\n", 551 | " # and the value is the numpy array to feed to it.\n", 552 | " feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n", 553 | " _, l, predictions = session.run(\n", 554 | " [optimizer, loss, train_prediction], feed_dict=feed_dict)\n", 555 | " if (step % 500 == 0):\n", 556 | " print \"Minibatch loss at step\", step, \":\", l\n", 557 | " print \"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels)\n", 558 | " print \"Validation accuracy: %.1f%%\" % accuracy(\n", 559 | " valid_prediction.eval(), valid_labels)\n", 560 | " print \"Test accuracy: %.1f%%\" % accuracy(test_prediction.eval(), test_labels)" 561 | ] 562 | }, 563 | { 564 | "cell_type": "markdown", 565 | "metadata": { 566 | "colab_type": "text", 567 | "id": "7omWxtvLLxik" 568 | }, 569 | "source": [ 570 | "---\n", 571 | "Problem\n", 572 | "-------\n", 573 | "\n", 574 | "Turn the logistic regression example with SGD into a 1-hidden layer neural network with rectified linear units (nn.relu()) and 1024 hidden nodes. This model should improve your validation / test accuracy.\n", 575 | "\n", 576 | "---" 577 | ] 578 | }, 579 | { 580 | "cell_type": "code", 581 | "execution_count": 8, 582 | "metadata": { 583 | "collapsed": false 584 | }, 585 | "outputs": [], 586 | "source": [ 587 | "batch_size = 128\n", 588 | "n_hidden_nodes = 1024\n", 589 | "\n", 590 | "\n", 591 | "graph = tf.Graph()\n", 592 | "with graph.as_default():\n", 593 | "\n", 594 | " # Input data. For the training data, we use a placeholder that will be fed\n", 595 | " # at run time with a training minibatch.\n", 596 | " tf_train_dataset = tf.placeholder(tf.float32,\n", 597 | " shape=(batch_size, image_size * image_size))\n", 598 | " tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n", 599 | " tf_valid_dataset = tf.constant(valid_dataset)\n", 600 | " tf_test_dataset = tf.constant(test_dataset)\n", 601 | " \n", 602 | " # Variables.\n", 603 | " weights_01 = tf.Variable(\n", 604 | " tf.truncated_normal([image_size * image_size, n_hidden_nodes]))\n", 605 | " weights_12 = tf.Variable(tf.truncated_normal([n_hidden_nodes, num_labels]))\n", 606 | " biases_01 = tf.Variable(tf.zeros([n_hidden_nodes]))\n", 607 | " biases_12 = tf.Variable(tf.zeros([num_labels]))\n", 608 | " \n", 609 | " # Training computation.\n", 610 | " z_01= tf.matmul(tf_train_dataset, weights_01) + biases_01\n", 611 | " h1 = tf.nn.relu(z_01)\n", 612 | " z_12 = tf.matmul(h1, weights_12) + biases_12\n", 613 | " loss = tf.reduce_mean(\n", 614 | " tf.nn.softmax_cross_entropy_with_logits(z_12, tf_train_labels))\n", 615 | " \n", 616 | " # Optimizer.\n", 617 | " optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)\n", 618 | " \n", 619 | " # Predictions for the training, validation, and test data.\n", 620 | " train_prediction = tf.nn.softmax(z_12)\n", 621 | " valid_prediction = tf.nn.softmax(\n", 622 | " tf.matmul(tf.nn.relu(tf.matmul(tf_valid_dataset, weights_01) + biases_01), weights_12) + biases_12)\n", 623 | " test_prediction = tf.nn.softmax(\n", 624 | " tf.matmul(tf.nn.relu(tf.matmul(tf_test_dataset, weights_01) + biases_01), weights_12) + biases_12)" 625 | ] 626 | }, 627 | { 628 | "cell_type": "code", 629 | "execution_count": 9, 630 | "metadata": { 631 | "collapsed": false 632 | }, 633 | "outputs": [ 634 | { 635 | "name": "stdout", 636 | "output_type": "stream", 637 | "text": [ 638 | "Initialized\n", 639 | "Minibatch loss at step 0 : 315.36\n", 640 | "Minibatch accuracy: 14.8%\n", 641 | "Validation accuracy: 20.1%\n", 642 | "Minibatch loss at step 500 : 12.9164\n", 643 | "Minibatch accuracy: 83.6%\n", 644 | "Validation accuracy: 78.2%\n", 645 | "Minibatch loss at step 1000 : 7.46024\n", 646 | "Minibatch accuracy: 79.7%\n", 647 | "Validation accuracy: 80.0%\n", 648 | "Minibatch loss at step 1500 : 11.3026\n", 649 | "Minibatch accuracy: 78.9%\n", 650 | "Validation accuracy: 80.6%\n", 651 | "Minibatch loss at step 2000 : 5.03315\n", 652 | "Minibatch accuracy: 87.5%\n", 653 | "Validation accuracy: 80.7%\n", 654 | "Minibatch loss at step 2500 : 3.73228\n", 655 | "Minibatch accuracy: 87.5%\n", 656 | "Validation accuracy: 81.8%\n", 657 | "Minibatch loss at step 3000 : 3.90598\n", 658 | "Minibatch accuracy: 83.6%\n", 659 | "Validation accuracy: 82.4%\n", 660 | "Test accuracy: 89.2%\n" 661 | ] 662 | } 663 | ], 664 | "source": [ 665 | "num_steps = 3001\n", 666 | "\n", 667 | "with tf.Session(graph=graph) as session:\n", 668 | " tf.initialize_all_variables().run()\n", 669 | " print \"Initialized\"\n", 670 | " for step in xrange(num_steps):\n", 671 | " # Pick an offset within the training data, which has been randomized.\n", 672 | " # Note: we could use better randomization across epochs.\n", 673 | " offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n", 674 | " # Generate a minibatch.\n", 675 | " batch_data = train_dataset[offset:(offset + batch_size), :]\n", 676 | " batch_labels = train_labels[offset:(offset + batch_size), :]\n", 677 | " # Prepare a dictionary telling the session where to feed the minibatch.\n", 678 | " # The key of the dictionary is the placeholder node of the graph to be fed,\n", 679 | " # and the value is the numpy array to feed to it.\n", 680 | " feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n", 681 | " _, l, predictions = session.run(\n", 682 | " [optimizer, loss, train_prediction], feed_dict=feed_dict)\n", 683 | " if (step % 500 == 0):\n", 684 | " print \"Minibatch loss at step\", step, \":\", l\n", 685 | " print \"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels)\n", 686 | " print \"Validation accuracy: %.1f%%\" % accuracy(\n", 687 | " valid_prediction.eval(), valid_labels)\n", 688 | " print \"Test accuracy: %.1f%%\" % accuracy(test_prediction.eval(), test_labels)" 689 | ] 690 | } 691 | ], 692 | "metadata": { 693 | "colabVersion": "0.3.2", 694 | "colab_default_view": {}, 695 | "colab_views": {}, 696 | "kernelspec": { 697 | "display_name": "Python 2", 698 | "language": "python", 699 | "name": "python2" 700 | }, 701 | "language_info": { 702 | "codemirror_mode": { 703 | "name": "ipython", 704 | "version": 2 705 | }, 706 | "file_extension": ".py", 707 | "mimetype": "text/x-python", 708 | "name": "python", 709 | "nbconvert_exporter": "python", 710 | "pygments_lexer": "ipython2", 711 | "version": "2.7.6" 712 | } 713 | }, 714 | "nbformat": 4, 715 | "nbformat_minor": 0 716 | } 717 | -------------------------------------------------------------------------------- /udacity/3_regularization.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "colab_type": "text", 7 | "id": "kR-4eNdK6lYS" 8 | }, 9 | "source": [ 10 | "Deep Learning\n", 11 | "=============\n", 12 | "\n", 13 | "Assignment 3\n", 14 | "------------\n", 15 | "\n", 16 | "Previously in `2_fullyconnected.ipynb`, you trained a logistic regression and a neural network model.\n", 17 | "\n", 18 | "The goal of this assignment is to explore regularization techniques." 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 1, 24 | "metadata": { 25 | "cellView": "both", 26 | "colab": { 27 | "autoexec": { 28 | "startup": false, 29 | "wait_interval": 0 30 | } 31 | }, 32 | "colab_type": "code", 33 | "collapsed": true, 34 | "id": "JLpLa8Jt7Vu4" 35 | }, 36 | "outputs": [], 37 | "source": [ 38 | "# These are all the modules we'll be using later. Make sure you can import them\n", 39 | "# before proceeding further.\n", 40 | "import cPickle as pickle\n", 41 | "import numpy as np\n", 42 | "import tensorflow as tf" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": { 48 | "colab_type": "text", 49 | "id": "1HrCK6e17WzV" 50 | }, 51 | "source": [ 52 | "First reload the data we generated in _notmist.ipynb_." 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 2, 58 | "metadata": { 59 | "cellView": "both", 60 | "colab": { 61 | "autoexec": { 62 | "startup": false, 63 | "wait_interval": 0 64 | }, 65 | "output_extras": [ 66 | { 67 | "item_id": 1 68 | } 69 | ] 70 | }, 71 | "colab_type": "code", 72 | "collapsed": false, 73 | "executionInfo": { 74 | "elapsed": 11777, 75 | "status": "ok", 76 | "timestamp": 1449849322348, 77 | "user": { 78 | "color": "", 79 | "displayName": "", 80 | "isAnonymous": false, 81 | "isMe": true, 82 | "permissionId": "", 83 | "photoUrl": "", 84 | "sessionId": "0", 85 | "userId": "" 86 | }, 87 | "user_tz": 480 88 | }, 89 | "id": "y3-cj1bpmuxc", 90 | "outputId": "e03576f1-ebbe-4838-c388-f1777bcc9873" 91 | }, 92 | "outputs": [ 93 | { 94 | "name": "stdout", 95 | "output_type": "stream", 96 | "text": [ 97 | "Training set (200000, 28, 28) (200000,)\n", 98 | "Validation set (10000, 28, 28) (10000,)\n", 99 | "Test set (18724, 28, 28) (18724,)\n" 100 | ] 101 | } 102 | ], 103 | "source": [ 104 | "pickle_file = 'notMNIST.pickle'\n", 105 | "\n", 106 | "with open(pickle_file, 'rb') as f:\n", 107 | " save = pickle.load(f)\n", 108 | " train_dataset = save['train_dataset']\n", 109 | " train_labels = save['train_labels']\n", 110 | " valid_dataset = save['valid_dataset']\n", 111 | " valid_labels = save['valid_labels']\n", 112 | " test_dataset = save['test_dataset']\n", 113 | " test_labels = save['test_labels']\n", 114 | " del save # hint to help gc free up memory\n", 115 | " print 'Training set', train_dataset.shape, train_labels.shape\n", 116 | " print 'Validation set', valid_dataset.shape, valid_labels.shape\n", 117 | " print 'Test set', test_dataset.shape, test_labels.shape" 118 | ] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": { 123 | "colab_type": "text", 124 | "id": "L7aHrm6nGDMB" 125 | }, 126 | "source": [ 127 | "Reformat into a shape that's more adapted to the models we're going to train:\n", 128 | "- data as a flat matrix,\n", 129 | "- labels as float 1-hot encodings." 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": 3, 135 | "metadata": { 136 | "cellView": "both", 137 | "colab": { 138 | "autoexec": { 139 | "startup": false, 140 | "wait_interval": 0 141 | }, 142 | "output_extras": [ 143 | { 144 | "item_id": 1 145 | } 146 | ] 147 | }, 148 | "colab_type": "code", 149 | "collapsed": false, 150 | "executionInfo": { 151 | "elapsed": 11728, 152 | "status": "ok", 153 | "timestamp": 1449849322356, 154 | "user": { 155 | "color": "", 156 | "displayName": "", 157 | "isAnonymous": false, 158 | "isMe": true, 159 | "permissionId": "", 160 | "photoUrl": "", 161 | "sessionId": "0", 162 | "userId": "" 163 | }, 164 | "user_tz": 480 165 | }, 166 | "id": "IRSyYiIIGIzS", 167 | "outputId": "3f8996ee-3574-4f44-c953-5c8a04636582" 168 | }, 169 | "outputs": [ 170 | { 171 | "name": "stdout", 172 | "output_type": "stream", 173 | "text": [ 174 | "Training set (200000, 784) (200000, 10)\n", 175 | "Validation set (10000, 784) (10000, 10)\n", 176 | "Test set (18724, 784) (18724, 10)\n" 177 | ] 178 | } 179 | ], 180 | "source": [ 181 | "image_size = 28\n", 182 | "num_labels = 10\n", 183 | "\n", 184 | "def reformat(dataset, labels):\n", 185 | " dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)\n", 186 | " # Map 2 to [0.0, 1.0, 0.0 ...], 3 to [0.0, 0.0, 1.0 ...]\n", 187 | " labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n", 188 | " return dataset, labels\n", 189 | "train_dataset, train_labels = reformat(train_dataset, train_labels)\n", 190 | "valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)\n", 191 | "test_dataset, test_labels = reformat(test_dataset, test_labels)\n", 192 | "print 'Training set', train_dataset.shape, train_labels.shape\n", 193 | "print 'Validation set', valid_dataset.shape, valid_labels.shape\n", 194 | "print 'Test set', test_dataset.shape, test_labels.shape" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": 4, 200 | "metadata": { 201 | "cellView": "both", 202 | "colab": { 203 | "autoexec": { 204 | "startup": false, 205 | "wait_interval": 0 206 | } 207 | }, 208 | "colab_type": "code", 209 | "collapsed": true, 210 | "id": "RajPLaL_ZW6w" 211 | }, 212 | "outputs": [], 213 | "source": [ 214 | "def accuracy(predictions, labels):\n", 215 | " return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n", 216 | " / predictions.shape[0])" 217 | ] 218 | }, 219 | { 220 | "cell_type": "markdown", 221 | "metadata": { 222 | "colab_type": "text", 223 | "id": "sgLbUAQ1CW-1" 224 | }, 225 | "source": [ 226 | "---\n", 227 | "Problem 1\n", 228 | "---------\n", 229 | "\n", 230 | "Introduce and tune L2 regularization for both logistic and neural network models. Remember that L2 amounts to adding a penalty on the norm of the weights to the loss. In TensorFlow, you can compue the L2 loss for a tensor `t` using `nn.l2_loss(t)`. The right amount of regularization should improve your validation / test accuracy.\n", 231 | "\n", 232 | "---" 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": 95, 238 | "metadata": { 239 | "collapsed": false 240 | }, 241 | "outputs": [], 242 | "source": [ 243 | "n_hidden = 1024\n", 244 | "L2_weight = 0.5e-3\n", 245 | "\n", 246 | "\n", 247 | "def forward(tf_X):\n", 248 | " \"\"\"\n", 249 | " assert tf.shape(tf_X)[1] == image_size*image_size,\\\n", 250 | " \"Training data not of correct shape. Each input should be of shape: %s\" % (image_size*image_size)\n", 251 | " \"\"\"\n", 252 | " with tf.name_scope('hidden1'):\n", 253 | " weights = tf.Variable(tf.truncated_normal([image_size*image_size, n_hidden]), name=\"weights\")\n", 254 | " biases = tf.Variable(tf.zeros([n_hidden]), name=\"biases\")\n", 255 | " z01 = tf.matmul(tf_X, weights) + biases\n", 256 | " hidden1 = tf.nn.relu(z01)\n", 257 | " l2_reg_01 = tf.nn.l2_loss(weights)\n", 258 | " with tf.name_scope('z12'):\n", 259 | " weights = tf.Variable(tf.truncated_normal([n_hidden, num_labels]), name=\"weights\")\n", 260 | " biases = tf.Variable(tf.zeros([num_labels]), name=\"biases\")\n", 261 | " z12 = tf.matmul(hidden1, weights) + biases\n", 262 | " l2_reg_12 = tf.nn.l2_loss(weights)\n", 263 | " return z12, l2_reg_01+l2_reg_12\n", 264 | "\n", 265 | "# Define loss\n", 266 | "def get_loss(z12, l2_loss, tf_Y):\n", 267 | " \"\"\"\n", 268 | " assert tf.shape(tf_X)[1] == image_size*image_size,\\\n", 269 | " \"Training data not of correct shape. got %s require %s\" % (tf.shape(tf_X)[1], image_size*image_size)\n", 270 | " assert tf.shape(tf_Y)[1] == num_labels,\\\n", 271 | " \"Training data not of correct shape. got %s require %s\" % (tf.shape(tf_Y)[1], num_labels)\n", 272 | " \"\"\"\n", 273 | " loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(z12, tf_training_labels))\n", 274 | " total_loss = loss + L2_weight*l2_loss\n", 275 | " return total_loss\n", 276 | "\n", 277 | "# Define the network graph\n", 278 | "graph = tf.Graph()\n", 279 | "with graph.as_default():\n", 280 | " #tf_training_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size*image_size))\n", 281 | " #tf_training_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n", 282 | " tf_training_dataset = tf.placeholder(tf.float32) # Should have shape (batch_size, image_size*image_size)\n", 283 | " tf_training_labels = tf.placeholder(tf.float32) # Should have shape (batch_size, num_labels)\n", 284 | " \n", 285 | " z12, l2_loss = forward(tf_training_dataset)\n", 286 | " total_loss = get_loss(z12, l2_loss, tf_training_labels)\n", 287 | " optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(total_loss)\n", 288 | " " 289 | ] 290 | }, 291 | { 292 | "cell_type": "code", 293 | "execution_count": 96, 294 | "metadata": { 295 | "collapsed": false 296 | }, 297 | "outputs": [ 298 | { 299 | "name": "stdout", 300 | "output_type": "stream", 301 | "text": [ 302 | "Initialized, using batch size: 128\n", 303 | "Updated batch size: 128\n", 304 | "Minibatch loss at step 0 : 433.335\n", 305 | "Minibatch accuracy: 16.4%\n", 306 | "Validation accuracy: 19.5%\n", 307 | "Updated batch size: 128\n", 308 | "Minibatch loss at step 500 : 154.113\n", 309 | "Minibatch accuracy: 71.1%\n", 310 | "Validation accuracy: 78.1%\n", 311 | "Updated batch size: 128\n", 312 | "Minibatch loss at step 1000 : 99.6778\n", 313 | "Minibatch accuracy: 78.1%\n", 314 | "Validation accuracy: 81.9%\n", 315 | "Updated batch size: 128\n", 316 | "Minibatch loss at step 1500 : 78.0688\n", 317 | "Minibatch accuracy: 78.9%\n", 318 | "Validation accuracy: 80.7%\n", 319 | "Updated batch size: 128\n", 320 | "Minibatch loss at step 2000 : 56.6891\n", 321 | "Minibatch accuracy: 85.9%\n", 322 | "Validation accuracy: 82.3%\n", 323 | "Updated batch size: 128\n", 324 | "Minibatch loss at step 2500 : 43.8642\n", 325 | "Minibatch accuracy: 82.8%\n", 326 | "Validation accuracy: 83.4%\n", 327 | "Updated batch size: 128\n", 328 | "Minibatch loss at step 3000 : 33.9656\n", 329 | "Minibatch accuracy: 89.1%\n", 330 | "Validation accuracy: 84.5%\n", 331 | "Test accuracy: 91.1%\n" 332 | ] 333 | } 334 | ], 335 | "source": [ 336 | "# train the model\n", 337 | "num_steps = 3001\n", 338 | "batch_size = 128\n", 339 | "with tf.Session(graph=graph) as session:\n", 340 | " tf.initialize_all_variables().run()\n", 341 | " print \"Initialized, using batch size: %s\" % batch_size\n", 342 | " for step in xrange(num_steps):\n", 343 | " idx = np.random.randint(train_dataset.shape[0], size=batch_size)\n", 344 | " #offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n", 345 | " # Generate a minibatch.\n", 346 | " batch_data = train_dataset[idx]\n", 347 | " batch_labels = train_labels[idx]\n", 348 | " #batch_data = train_dataset[offset:(offset + batch_size), :]\n", 349 | " #batch_labels = train_labels[offset:(offset + batch_size), :]\n", 350 | " feed_dict = {tf_training_dataset : batch_data, tf_training_labels : batch_labels}\n", 351 | " _, l, predictions = session.run([optimizer, total_loss, z12], feed_dict=feed_dict)\n", 352 | " if (step % 500 == 0):\n", 353 | " #batch_size += 100\n", 354 | " print \"Updated batch size: %s\" % batch_size\n", 355 | " print \"Minibatch loss at step\", step, \":\", l\n", 356 | " print \"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels)\n", 357 | " predictions = session.run(z12, feed_dict={tf_training_dataset: valid_dataset})\n", 358 | " print \"Validation accuracy: %.1f%%\" % accuracy(predictions, valid_labels)\n", 359 | " predictions = session.run(z12, feed_dict={tf_training_dataset: test_dataset})\n", 360 | " print \"Test accuracy: %.1f%%\" % accuracy(predictions, test_labels)\n", 361 | " \n", 362 | " " 363 | ] 364 | }, 365 | { 366 | "cell_type": "code", 367 | "execution_count": 58, 368 | "metadata": { 369 | "collapsed": false 370 | }, 371 | "outputs": [ 372 | { 373 | "data": { 374 | "text/plain": [ 375 | "(200000, 784)" 376 | ] 377 | }, 378 | "execution_count": 58, 379 | "metadata": {}, 380 | "output_type": "execute_result" 381 | } 382 | ], 383 | "source": [ 384 | "train_dataset.shape" 385 | ] 386 | }, 387 | { 388 | "cell_type": "markdown", 389 | "metadata": { 390 | "colab_type": "text", 391 | "id": "na8xX2yHZzNF" 392 | }, 393 | "source": [ 394 | "---\n", 395 | "Problem 2\n", 396 | "---------\n", 397 | "Let's demonstrate an extreme case of overfitting. Restrict your training data to just a few batches. What happens?\n", 398 | "\n", 399 | "---" 400 | ] 401 | }, 402 | { 403 | "cell_type": "code", 404 | "execution_count": 97, 405 | "metadata": { 406 | "collapsed": false 407 | }, 408 | "outputs": [ 409 | { 410 | "name": "stdout", 411 | "output_type": "stream", 412 | "text": [ 413 | "Initialized, using batch size: 100\n", 414 | "Updated batch size: 100\n", 415 | "Minibatch loss at step 0 : 510.032\n", 416 | "Minibatch accuracy: 7.0%\n", 417 | "Validation accuracy: 24.8%\n", 418 | "Updated batch size: 100\n", 419 | "Minibatch loss at step 500 : 122.496\n", 420 | "Minibatch accuracy: 99.0%\n", 421 | "Validation accuracy: 78.4%\n", 422 | "Updated batch size: 100\n", 423 | "Minibatch loss at step 1000 : 95.3546\n", 424 | "Minibatch accuracy: 100.0%\n", 425 | "Validation accuracy: 78.9%\n", 426 | "Updated batch size: 100\n", 427 | "Minibatch loss at step 1500 : 74.2451\n", 428 | "Minibatch accuracy: 100.0%\n", 429 | "Validation accuracy: 78.8%\n", 430 | "Updated batch size: 100\n", 431 | "Minibatch loss at step 2000 : 57.8141\n", 432 | "Minibatch accuracy: 100.0%\n", 433 | "Validation accuracy: 79.0%\n", 434 | "Updated batch size: 100\n", 435 | "Minibatch loss at step 2500 : 45.0234\n", 436 | "Minibatch accuracy: 100.0%\n", 437 | "Validation accuracy: 78.5%\n", 438 | "Updated batch size: 100\n", 439 | "Minibatch loss at step 3000 : 35.0617\n", 440 | "Minibatch accuracy: 100.0%\n", 441 | "Validation accuracy: 78.7%\n", 442 | "Test accuracy: 86.4%\n" 443 | ] 444 | } 445 | ], 446 | "source": [ 447 | "# Overfitting using very small subset of data\n", 448 | "num_steps = 3001\n", 449 | "batch_size = 100\n", 450 | "with tf.Session(graph=graph) as session:\n", 451 | " tf.initialize_all_variables().run()\n", 452 | " print \"Initialized, using batch size: %s\" % batch_size\n", 453 | " for step in xrange(num_steps):\n", 454 | " idx = np.random.randint(train_dataset.shape[0]/100, size=batch_size)\n", 455 | " #offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n", 456 | " # Generate a minibatch.\n", 457 | " batch_data = train_dataset[idx]\n", 458 | " batch_labels = train_labels[idx]\n", 459 | " #batch_data = train_dataset[offset:(offset + batch_size), :]\n", 460 | " #batch_labels = train_labels[offset:(offset + batch_size), :]\n", 461 | " feed_dict = {tf_training_dataset : batch_data, tf_training_labels : batch_labels}\n", 462 | " _, l, predictions = session.run([optimizer, total_loss, z12], feed_dict=feed_dict)\n", 463 | " if (step % 500 == 0):\n", 464 | " #batch_size += 100\n", 465 | " print \"Updated batch size: %s\" % batch_size\n", 466 | " print \"Minibatch loss at step\", step, \":\", l\n", 467 | " print \"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels)\n", 468 | " predictions = session.run(z12, feed_dict={tf_training_dataset: valid_dataset})\n", 469 | " print \"Validation accuracy: %.1f%%\" % accuracy(predictions, valid_labels)\n", 470 | " predictions = session.run(z12, feed_dict={tf_training_dataset: test_dataset})\n", 471 | " print \"Test accuracy: %.1f%%\" % accuracy(predictions, test_labels)\n", 472 | " \n", 473 | " " 474 | ] 475 | }, 476 | { 477 | "cell_type": "markdown", 478 | "metadata": { 479 | "colab_type": "text", 480 | "id": "ww3SCBUdlkRc" 481 | }, 482 | "source": [ 483 | "---\n", 484 | "Problem 3\n", 485 | "---------\n", 486 | "Introduce Dropout on the hidden layer of the neural network. Remember: Dropout should only be introduced during training, not evaluation, otherwise your evaluation results would be stochastic as well. TensorFlow provides `nn.dropout()` for that, but you have to make sure it's only inserted during training.\n", 487 | "\n", 488 | "What happens to our extreme overfitting case?\n", 489 | "\n", 490 | "---" 491 | ] 492 | }, 493 | { 494 | "cell_type": "code", 495 | "execution_count": 105, 496 | "metadata": { 497 | "collapsed": true 498 | }, 499 | "outputs": [], 500 | "source": [ 501 | "batch_size = 128\n", 502 | "n_hidden = 1024\n", 503 | "L2_weight = 0.5e-3\n", 504 | "\n", 505 | "def forward(tf_X, dropout_p):\n", 506 | " \"\"\"\n", 507 | " assert tf.shape(tf_X)[1] == image_size*image_size,\\\n", 508 | " \"Training data not of correct shape. Each input should be of shape: %s\" % (image_size*image_size)\n", 509 | " \"\"\"\n", 510 | " with tf.name_scope('hidden1'):\n", 511 | " weights = tf.Variable(tf.truncated_normal([image_size*image_size, n_hidden]), name=\"weights\")\n", 512 | " biases = tf.Variable(tf.zeros([n_hidden]), name=\"biases\")\n", 513 | " z01 = tf.matmul(tf_X, weights) + biases\n", 514 | " hidden1 = tf.nn.dropout(tf.nn.relu(z01), dropout_p) # Added dropout\n", 515 | " l2_reg_01 = tf.nn.l2_loss(weights)\n", 516 | " with tf.name_scope('z12'):\n", 517 | " weights = tf.Variable(tf.truncated_normal([n_hidden, num_labels]), name=\"weights\")\n", 518 | " biases = tf.Variable(tf.zeros([num_labels]), name=\"biases\")\n", 519 | " z12 = tf.matmul(hidden1, weights) + biases\n", 520 | " l2_reg_12 = tf.nn.l2_loss(weights)\n", 521 | " return z12, l2_reg_01+l2_reg_12\n", 522 | " #return z12, 0\n", 523 | "\n", 524 | "# Define loss\n", 525 | "def get_loss(z12, l2_loss, tf_Y):\n", 526 | " \"\"\"\n", 527 | " assert tf.shape(tf_X)[1] == image_size*image_size,\\\n", 528 | " \"Training data not of correct shape. got %s require %s\" % (tf.shape(tf_X)[1], image_size*image_size)\n", 529 | " assert tf.shape(tf_Y)[1] == num_labels,\\\n", 530 | " \"Training data not of correct shape. got %s require %s\" % (tf.shape(tf_Y)[1], num_labels)\n", 531 | " \"\"\"\n", 532 | " loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(z12, tf_training_labels))\n", 533 | " total_loss = loss + L2_weight*l2_loss\n", 534 | " return total_loss\n", 535 | "\n", 536 | "# Define the network graph\n", 537 | "tf.python.framework.ops.reset_default_graph()\n", 538 | "graph = tf.Graph()\n", 539 | "with graph.as_default():\n", 540 | " #tf_training_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size*image_size))\n", 541 | " #tf_training_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n", 542 | " tf_training_dataset = tf.placeholder(tf.float32) # Should have shape (batch_size, image_size*image_size)\n", 543 | " tf_training_labels = tf.placeholder(tf.float32) # Should have shape (batch_size, num_labels)\n", 544 | " dropout_p = tf.placeholder(tf.float32)\n", 545 | " \n", 546 | " z12, l2_loss = forward(tf_training_dataset, dropout_p)\n", 547 | " total_loss = get_loss(z12, l2_loss, tf_training_labels)\n", 548 | " optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(total_loss)" 549 | ] 550 | }, 551 | { 552 | "cell_type": "code", 553 | "execution_count": 109, 554 | "metadata": { 555 | "collapsed": false 556 | }, 557 | "outputs": [ 558 | { 559 | "name": "stdout", 560 | "output_type": "stream", 561 | "text": [ 562 | "Initialized, using batch size: 128\n", 563 | "Updated batch size: 128\n", 564 | "Minibatch loss at step 0 : 594.441\n", 565 | "Minibatch accuracy: 45.3%\n", 566 | "Validation accuracy: 30.6%\n", 567 | "Updated batch size: 128\n", 568 | "Minibatch loss at step 500 : 135.303\n", 569 | "Minibatch accuracy: 82.8%\n", 570 | "Validation accuracy: 77.0%\n", 571 | "Updated batch size: 128\n", 572 | "Minibatch loss at step 1000 : 106.291\n", 573 | "Minibatch accuracy: 83.6%\n", 574 | "Validation accuracy: 76.9%\n", 575 | "Updated batch size: 128\n", 576 | "Minibatch loss at step 1500 : 78.9362\n", 577 | "Minibatch accuracy: 83.6%\n", 578 | "Validation accuracy: 79.4%\n", 579 | "Updated batch size: 128\n", 580 | "Minibatch loss at step 2000 : 59.3434\n", 581 | "Minibatch accuracy: 83.6%\n", 582 | "Validation accuracy: 80.6%\n", 583 | "Updated batch size: 128\n", 584 | "Minibatch loss at step 2500 : 44.3513\n", 585 | "Minibatch accuracy: 87.5%\n", 586 | "Validation accuracy: 82.0%\n", 587 | "Updated batch size: 128\n", 588 | "Minibatch loss at step 3000 : 34.0546\n", 589 | "Minibatch accuracy: 93.0%\n", 590 | "Validation accuracy: 82.7%\n", 591 | "Test accuracy: 89.7%\n" 592 | ] 593 | } 594 | ], 595 | "source": [ 596 | "# train the model\n", 597 | "num_steps = 3001\n", 598 | "batch_size = 128\n", 599 | "with tf.Session(graph=graph) as session:\n", 600 | " tf.initialize_all_variables().run()\n", 601 | " print \"Initialized, using batch size: %s\" % batch_size\n", 602 | " for step in xrange(num_steps):\n", 603 | " idx = np.random.randint(train_dataset.shape[0], size=batch_size)\n", 604 | " #offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n", 605 | " # Generate a minibatch.\n", 606 | " batch_data = train_dataset[idx]\n", 607 | " batch_labels = train_labels[idx]\n", 608 | " #batch_data = train_dataset[offset:(offset + batch_size), :]\n", 609 | " #batch_labels = train_labels[offset:(offset + batch_size), :]\n", 610 | " feed_dict = {tf_training_dataset : batch_data, tf_training_labels : batch_labels, dropout_p: 0.5}\n", 611 | " _, l = session.run([optimizer, total_loss], feed_dict=feed_dict)\n", 612 | " predictions = session.run(z12, feed_dict={tf_training_dataset: batch_data, dropout_p: 1})\n", 613 | " if (step % 500 == 0):\n", 614 | " #batch_size += 100\n", 615 | " print \"Updated batch size: %s\" % batch_size\n", 616 | " print \"Minibatch loss at step\", step, \":\", l\n", 617 | " print \"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels)\n", 618 | " predictions = session.run(z12, feed_dict={tf_training_dataset: valid_dataset, dropout_p: 1})\n", 619 | " print \"Validation accuracy: %.1f%%\" % accuracy(predictions, valid_labels)\n", 620 | " predictions = session.run(z12, feed_dict={tf_training_dataset: test_dataset, dropout_p: 1})\n", 621 | " print \"Test accuracy: %.1f%%\" % accuracy(predictions, test_labels)\n", 622 | " \n", 623 | "\n", 624 | " " 625 | ] 626 | }, 627 | { 628 | "cell_type": "code", 629 | "execution_count": 108, 630 | "metadata": { 631 | "collapsed": false 632 | }, 633 | "outputs": [ 634 | { 635 | "name": "stdout", 636 | "output_type": "stream", 637 | "text": [ 638 | "Initialized, using batch size: 100\n", 639 | "Updated batch size: 100\n", 640 | "Minibatch loss at step 0 : 600.411\n", 641 | "Minibatch accuracy: 53.0%\n", 642 | "Validation accuracy: 34.7%\n", 643 | "Updated batch size: 100\n", 644 | "Minibatch loss at step 500 : 132.637\n", 645 | "Minibatch accuracy: 100.0%\n", 646 | "Validation accuracy: 80.2%\n", 647 | "Updated batch size: 100\n", 648 | "Minibatch loss at step 1000 : 100.23\n", 649 | "Minibatch accuracy: 100.0%\n", 650 | "Validation accuracy: 80.0%\n", 651 | "Updated batch size: 100\n", 652 | "Minibatch loss at step 1500 : 80.0319\n", 653 | "Minibatch accuracy: 100.0%\n", 654 | "Validation accuracy: 79.9%\n", 655 | "Updated batch size: 100\n", 656 | "Minibatch loss at step 2000 : 60.3647\n", 657 | "Minibatch accuracy: 100.0%\n", 658 | "Validation accuracy: 80.7%\n", 659 | "Updated batch size: 100\n", 660 | "Minibatch loss at step 2500 : 47.079\n", 661 | "Minibatch accuracy: 100.0%\n", 662 | "Validation accuracy: 80.8%\n", 663 | "Updated batch size: 100\n", 664 | "Minibatch loss at step 3000 : 36.7001\n", 665 | "Minibatch accuracy: 100.0%\n", 666 | "Validation accuracy: 80.2%\n", 667 | "Test accuracy: 88.1%\n" 668 | ] 669 | } 670 | ], 671 | "source": [ 672 | "# train the model using smaller sample resulting in overfitting\n", 673 | "num_steps = 3001\n", 674 | "batch_size = 100\n", 675 | "with tf.Session(graph=graph) as session:\n", 676 | " tf.initialize_all_variables().run()\n", 677 | " print \"Initialized, using batch size: %s\" % batch_size\n", 678 | " for step in xrange(num_steps):\n", 679 | " idx = np.random.randint(train_dataset[:2000].shape[0], size=batch_size)\n", 680 | " #offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n", 681 | " # Generate a minibatch.\n", 682 | " batch_data = train_dataset[:2000][idx]\n", 683 | " batch_labels = train_labels[:2000][idx]\n", 684 | " #batch_data = train_dataset[offset:(offset + batch_size), :]\n", 685 | " #batch_labels = train_labels[offset:(offset + batch_size), :]\n", 686 | " feed_dict = {tf_training_dataset : batch_data, tf_training_labels : batch_labels, dropout_p: 0.5}\n", 687 | " _, l = session.run([optimizer, total_loss], feed_dict=feed_dict)\n", 688 | " predictions = session.run(z12, feed_dict={tf_training_dataset: batch_data, dropout_p: 1})\n", 689 | " if (step % 500 == 0):\n", 690 | " #batch_size += 100\n", 691 | " print \"Updated batch size: %s\" % batch_size\n", 692 | " print \"Minibatch loss at step\", step, \":\", l\n", 693 | " print \"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels)\n", 694 | " predictions = session.run(z12, feed_dict={tf_training_dataset: valid_dataset, dropout_p: 1})\n", 695 | " print \"Validation accuracy: %.1f%%\" % accuracy(predictions, valid_labels)\n", 696 | " predictions = session.run(z12, feed_dict={tf_training_dataset: test_dataset, dropout_p: 1})\n", 697 | " print \"Test accuracy: %.1f%%\" % accuracy(predictions, test_labels)\n", 698 | " " 699 | ] 700 | }, 701 | { 702 | "cell_type": "markdown", 703 | "metadata": { 704 | "colab_type": "text", 705 | "id": "-b1hTz3VWZjw" 706 | }, 707 | "source": [ 708 | "---\n", 709 | "Problem 4\n", 710 | "---------\n", 711 | "\n", 712 | "Try to get the best performance you can using a multi-layer model! The best reported test accuracy using a deep network is [97.1%](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html?showComment=1391023266211#c8758720086795711595).\n", 713 | "\n", 714 | "One avenue you can explore is to add multiple layers.\n", 715 | "\n", 716 | "Another one is to use learning rate decay:\n", 717 | "\n", 718 | " global_step = tf.Variable(0) # count the number of steps taken.\n", 719 | " learning_rate = tf.train.exponential_decay(0.5, step, ...)\n", 720 | " optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)\n", 721 | " \n", 722 | " ---\n" 723 | ] 724 | }, 725 | { 726 | "cell_type": "code", 727 | "execution_count": 186, 728 | "metadata": { 729 | "collapsed": false 730 | }, 731 | "outputs": [], 732 | "source": [ 733 | "## BEST MODEL\n", 734 | "\"\"\"\n", 735 | "[Step: 5000] Minibatch loss 12.6376, accuracy: 89.5%\n", 736 | "[Step: 5000] Validation loss 12.6891, accuracy: 86.9%\n", 737 | "Test loss 12.4793, accuracy: 93.0%\n", 738 | "\"\"\"\n", 739 | "\n", 740 | "batch_size = 128\n", 741 | "n_hidden = 1024\n", 742 | "L2_weight = 0.5e-3\n", 743 | "\n", 744 | "def forward(tf_X, dropout_p):\n", 745 | " \"\"\"\n", 746 | " assert tf.shape(tf_X)[1] == image_size*image_size,\\\n", 747 | " \"Training data not of correct shape. Each input should be of shape: %s\" % (image_size*image_size)\n", 748 | " \"\"\"\n", 749 | " l2_weight_loss = [0]\n", 750 | " #tf.Variable(0, name=\"l2_weight_loss\")\n", 751 | " with tf.name_scope('hidden1'):\n", 752 | " weights = tf.Variable(tf.truncated_normal([image_size*image_size, n_hidden]), name=\"weights\")\n", 753 | " biases = tf.Variable(tf.zeros([n_hidden]), name=\"biases\")\n", 754 | " z01 = tf.matmul(tf.nn.dropout(tf_X, 0.9), weights) + biases # Dropout input keeping 0.9 inputs always\n", 755 | " hidden1 = tf.nn.dropout(tf.nn.relu(z01), dropout_p) # Added dropout\n", 756 | " #hidden1 = tf.nn.relu(z01) # No dropout\n", 757 | " l2_weight_loss.append(tf.nn.l2_loss(weights))\n", 758 | " \"\"\"\n", 759 | " with tf.name_scope('z12'):\n", 760 | " weights = tf.Variable(tf.truncated_normal([n_hidden, n_hidden]), name=\"weights\")\n", 761 | " biases = tf.Variable(tf.zeros([n_hidden]), name=\"biases\")\n", 762 | " z12 = tf.matmul(hidden1, weights) + biases\n", 763 | " hidden2 = tf.nn.dropout(tf.nn.tanh(z12), dropout_p) # Added dropout\n", 764 | " #hidden2 = tf.nn.relu(z12) # No dropout\n", 765 | " #l2_weight_loss.append(tf.nn.l2_loss(weights))\n", 766 | " \"\"\"\n", 767 | " with tf.name_scope('outputs'):\n", 768 | " weights = tf.Variable(tf.truncated_normal([n_hidden, num_labels]), name=\"weights\")\n", 769 | " biases = tf.Variable(tf.zeros([num_labels]), name=\"biases\")\n", 770 | " outputs = tf.matmul(hidden1, weights) + biases # Add constant to ensure input to log is never zero.\n", 771 | " l2_weight_loss.append(tf.nn.l2_loss(weights))\n", 772 | " return outputs, reduce(lambda x, y: x + y, l2_weight_loss)\n", 773 | " #return outputs, 0\n", 774 | "\n", 775 | "# Define loss\n", 776 | "def get_loss(outputs, l2_loss, tf_Y):\n", 777 | " \"\"\"\n", 778 | " assert tf.shape(tf_X)[1] == image_size*image_size,\\\n", 779 | " \"Training data not of correct shape. got %s require %s\" % (tf.shape(tf_X)[1], image_size*image_size)\n", 780 | " assert tf.shape(tf_Y)[1] == num_labels,\\\n", 781 | " \"Training data not of correct shape. got %s require %s\" % (tf.shape(tf_Y)[1], num_labels)\n", 782 | " \"\"\"\n", 783 | " loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(outputs, tf_training_labels))\n", 784 | " total_loss = loss + L2_weight*l2_loss\n", 785 | " return total_loss\n", 786 | "\n", 787 | "# Define the network graph\n", 788 | "tf.python.framework.ops.reset_default_graph()\n", 789 | "graph = tf.Graph()\n", 790 | "with graph.as_default():\n", 791 | " tf_training_dataset = tf.placeholder(tf.float32) # Should have shape (batch_size, image_size*image_size)\n", 792 | " tf_training_labels = tf.placeholder(tf.float32) # Should have shape (batch_size, num_labels)\n", 793 | " dropout_p = tf.placeholder(tf.float32)\n", 794 | " \n", 795 | " outputs, l2_loss = forward(tf_training_dataset, dropout_p)\n", 796 | " total_loss = get_loss(outputs, l2_loss, tf_training_labels)\n", 797 | " \n", 798 | " global_step = tf.Variable(0, trainable=False) # count the number of steps taken.\n", 799 | " #learning_rate = tf.train.exponential_decay(0.5, global_step, 10000, 0.96)\n", 800 | " learning_rate = 0.5\n", 801 | " optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss, global_step=global_step)" 802 | ] 803 | }, 804 | { 805 | "cell_type": "code", 806 | "execution_count": 188, 807 | "metadata": { 808 | "collapsed": false 809 | }, 810 | "outputs": [ 811 | { 812 | "name": "stdout", 813 | "output_type": "stream", 814 | "text": [ 815 | "Initialized, using batch size: 128\n", 816 | "Updated batch size: 228\n", 817 | "[Step: 0] Minibatch loss 594.078, accuracy: 50.0%\n", 818 | "[Step: 0] Validation loss 1413.83, accuracy: 33.0%\n", 819 | "Updated batch size: 328\n", 820 | "[Step: 500] Minibatch loss 130.521, accuracy: 83.3%\n", 821 | "[Step: 500] Validation loss 137.902, accuracy: 76.8%\n", 822 | "Updated batch size: 428\n", 823 | "[Step: 1000] Minibatch loss 95.7518, accuracy: 85.1%\n", 824 | "[Step: 1000] Validation loss 96.2667, accuracy: 81.0%\n", 825 | "Updated batch size: 528\n", 826 | "[Step: 1500] Minibatch loss 72.8652, accuracy: 84.1%\n", 827 | "[Step: 1500] Validation loss 73.9434, accuracy: 80.1%\n", 828 | "Updated batch size: 628\n", 829 | "[Step: 2000] Minibatch loss 56.29, accuracy: 85.0%\n", 830 | "[Step: 2000] Validation loss 56.8085, accuracy: 82.1%\n", 831 | "Updated batch size: 728\n", 832 | "[Step: 2500] Minibatch loss 43.5756, accuracy: 85.2%\n", 833 | "[Step: 2500] Validation loss 43.8024, accuracy: 82.5%\n", 834 | "Updated batch size: 828\n", 835 | "[Step: 3000] Minibatch loss 33.9084, accuracy: 88.0%\n", 836 | "[Step: 3000] Validation loss 33.9835, accuracy: 84.0%\n", 837 | "Updated batch size: 928\n", 838 | "[Step: 3500] Minibatch loss 26.4319, accuracy: 86.7%\n", 839 | "[Step: 3500] Validation loss 26.7211, accuracy: 81.8%\n", 840 | "Updated batch size: 1028\n", 841 | "[Step: 4000] Minibatch loss 20.5894, accuracy: 88.9%\n", 842 | "[Step: 4000] Validation loss 20.6519, accuracy: 86.1%\n", 843 | "Updated batch size: 1128\n", 844 | "[Step: 4500] Minibatch loss 16.1211, accuracy: 89.2%\n", 845 | "[Step: 4500] Validation loss 16.1746, accuracy: 86.3%\n", 846 | "Updated batch size: 1228\n", 847 | "[Step: 5000] Minibatch loss 12.6376, accuracy: 89.5%\n", 848 | "[Step: 5000] Validation loss 12.6891, accuracy: 86.9%\n", 849 | "Test loss 12.4793, accuracy: 93.0%\n" 850 | ] 851 | } 852 | ], 853 | "source": [ 854 | "# train the model\n", 855 | "num_steps = 5001\n", 856 | "batch_size = 128\n", 857 | "with tf.Session(graph=graph) as session:\n", 858 | " tf.initialize_all_variables().run()\n", 859 | " print \"Initialized, using batch size: %s\" % batch_size\n", 860 | " for step in xrange(num_steps):\n", 861 | " idx = np.random.randint(train_dataset.shape[0], size=batch_size)\n", 862 | " #offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n", 863 | " # Generate a minibatch.\n", 864 | " batch_data = train_dataset[idx]\n", 865 | " batch_labels = train_labels[idx]\n", 866 | " #batch_data = train_dataset[offset:(offset + batch_size), :]\n", 867 | " #batch_labels = train_labels[offset:(offset + batch_size), :]\n", 868 | " feed_dict = {tf_training_dataset : batch_data, tf_training_labels : batch_labels, dropout_p: 1}\n", 869 | " _, l = session.run([optimizer, total_loss], feed_dict=feed_dict)\n", 870 | " predictions = session.run(outputs, feed_dict={tf_training_dataset: batch_data, dropout_p: 1})\n", 871 | " if (step % 500 == 0):\n", 872 | " batch_size += 100\n", 873 | " print \"Updated batch size: %s\" % batch_size\n", 874 | " print \"[Step: %s] Minibatch loss %s, accuracy: %.1f%%\" % (step, l, accuracy(predictions, batch_labels))\n", 875 | " predictions, l = session.run([outputs, total_loss], \n", 876 | " feed_dict={tf_training_dataset: valid_dataset, tf_training_labels : valid_labels, dropout_p: 1})\n", 877 | " print \"[Step: %s] Validation loss %s, accuracy: %.1f%%\" % (step, l, accuracy(predictions, valid_labels))\n", 878 | " predictions, l = session.run([outputs, total_loss], \n", 879 | " feed_dict={tf_training_dataset: test_dataset, tf_training_labels : test_labels, dropout_p: 1})\n", 880 | " print \"Test loss %s, accuracy: %.1f%%\" % (l, accuracy(predictions, test_labels))\n", 881 | "\n", 882 | " " 883 | ] 884 | }, 885 | { 886 | "cell_type": "code", 887 | "execution_count": null, 888 | "metadata": { 889 | "collapsed": true 890 | }, 891 | "outputs": [], 892 | "source": [] 893 | } 894 | ], 895 | "metadata": { 896 | "colabVersion": "0.3.2", 897 | "colab_default_view": {}, 898 | "colab_views": {}, 899 | "kernelspec": { 900 | "display_name": "Python 2", 901 | "language": "python", 902 | "name": "python2" 903 | }, 904 | "language_info": { 905 | "codemirror_mode": { 906 | "name": "ipython", 907 | "version": 2 908 | }, 909 | "file_extension": ".py", 910 | "mimetype": "text/x-python", 911 | "name": "python", 912 | "nbconvert_exporter": "python", 913 | "pygments_lexer": "ipython2", 914 | "version": "2.7.6" 915 | } 916 | }, 917 | "nbformat": 4, 918 | "nbformat_minor": 0 919 | } 920 | -------------------------------------------------------------------------------- /udacity/4_convolutions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "worksheets": [ 3 | { 4 | "cells": [ 5 | { 6 | "metadata": { 7 | "id": "4embtkV0pNxM", 8 | "colab_type": "text" 9 | }, 10 | "cell_type": "markdown", 11 | "source": "Deep Learning\n=============\n\nAssignment 4\n------------\n\nPreviously in `2_fullyconnected.ipynb` and `3_regularization.ipynb`, we trained fully connected networks to classify [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) characters.\n\nThe goal of this assignment is make the neural network convolutional." 12 | }, 13 | { 14 | "metadata": { 15 | "id": "tm2CQN_Cpwj0", 16 | "colab_type": "code", 17 | "colab": { 18 | "autoexec": { 19 | "startup": false, 20 | "wait_interval": 0 21 | } 22 | }, 23 | "cellView": "both" 24 | }, 25 | "cell_type": "code", 26 | "input": "# These are all the modules we'll be using later. Make sure you can import them\n# before proceeding further.\nimport cPickle as pickle\nimport numpy as np\nimport tensorflow as tf", 27 | "language": "python", 28 | "outputs": [] 29 | }, 30 | { 31 | "metadata": { 32 | "id": "y3-cj1bpmuxc", 33 | "colab_type": "code", 34 | "colab": { 35 | "autoexec": { 36 | "startup": false, 37 | "wait_interval": 0 38 | }, 39 | "output_extras": [ 40 | { 41 | "item_id": 1 42 | } 43 | ] 44 | }, 45 | "cellView": "both", 46 | "executionInfo": { 47 | "elapsed": 11948, 48 | "status": "ok", 49 | "timestamp": 1446658914837, 50 | "user": { 51 | "color": "", 52 | "displayName": "", 53 | "isAnonymous": false, 54 | "isMe": true, 55 | "permissionId": "", 56 | "photoUrl": "", 57 | "sessionId": "0", 58 | "userId": "" 59 | }, 60 | "user_tz": 480 61 | }, 62 | "outputId": "016b1a51-0290-4b08-efdb-8c95ffc3cd01" 63 | }, 64 | "cell_type": "code", 65 | "input": "pickle_file = 'notMNIST.pickle'\n\nwith open(pickle_file, 'rb') as f:\n save = pickle.load(f)\n train_dataset = save['train_dataset']\n train_labels = save['train_labels']\n valid_dataset = save['valid_dataset']\n valid_labels = save['valid_labels']\n test_dataset = save['test_dataset']\n test_labels = save['test_labels']\n del save # hint to help gc free up memory\n print 'Training set', train_dataset.shape, train_labels.shape\n print 'Validation set', valid_dataset.shape, valid_labels.shape\n print 'Test set', test_dataset.shape, test_labels.shape", 66 | "language": "python", 67 | "outputs": [ 68 | { 69 | "output_type": "stream", 70 | "stream": "stdout", 71 | "text": "Training set (200000, 28, 28) (200000,)\nValidation set (10000, 28, 28) (10000,)\nTest set (18724, 28, 28) (18724,)\n" 72 | } 73 | ] 74 | }, 75 | { 76 | "metadata": { 77 | "id": "L7aHrm6nGDMB", 78 | "colab_type": "text" 79 | }, 80 | "cell_type": "markdown", 81 | "source": "Reformat into a TensorFlow-friendly shape:\n- convolutions need the image data formatted as a cube (width by height by #channels)\n- labels as float 1-hot encodings." 82 | }, 83 | { 84 | "metadata": { 85 | "id": "IRSyYiIIGIzS", 86 | "colab_type": "code", 87 | "colab": { 88 | "autoexec": { 89 | "startup": false, 90 | "wait_interval": 0 91 | }, 92 | "output_extras": [ 93 | { 94 | "item_id": 1 95 | } 96 | ] 97 | }, 98 | "cellView": "both", 99 | "executionInfo": { 100 | "elapsed": 11952, 101 | "status": "ok", 102 | "timestamp": 1446658914857, 103 | "user": { 104 | "color": "", 105 | "displayName": "", 106 | "isAnonymous": false, 107 | "isMe": true, 108 | "permissionId": "", 109 | "photoUrl": "", 110 | "sessionId": "0", 111 | "userId": "" 112 | }, 113 | "user_tz": 480 114 | }, 115 | "outputId": "650a208c-8359-4852-f4f5-8bf10e80ef6c" 116 | }, 117 | "cell_type": "code", 118 | "input": "image_size = 28\nnum_labels = 10\nnum_channels = 1 # grayscale\n\nimport numpy as np\n\ndef reformat(dataset, labels):\n dataset = dataset.reshape(\n (-1, image_size, image_size, num_channels)).astype(np.float32)\n labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n return dataset, labels\ntrain_dataset, train_labels = reformat(train_dataset, train_labels)\nvalid_dataset, valid_labels = reformat(valid_dataset, valid_labels)\ntest_dataset, test_labels = reformat(test_dataset, test_labels)\nprint 'Training set', train_dataset.shape, train_labels.shape\nprint 'Validation set', valid_dataset.shape, valid_labels.shape\nprint 'Test set', test_dataset.shape, test_labels.shape", 119 | "language": "python", 120 | "outputs": [ 121 | { 122 | "output_type": "stream", 123 | "stream": "stdout", 124 | "text": "Training set (200000, 28, 28, 1) (200000, 10)\nValidation set (10000, 28, 28, 1) (10000, 10)\nTest set (18724, 28, 28, 1) (18724, 10)\n" 125 | } 126 | ] 127 | }, 128 | { 129 | "metadata": { 130 | "id": "AgQDIREv02p1", 131 | "colab_type": "code", 132 | "colab": { 133 | "autoexec": { 134 | "startup": false, 135 | "wait_interval": 0 136 | } 137 | }, 138 | "cellView": "both" 139 | }, 140 | "cell_type": "code", 141 | "input": "def accuracy(predictions, labels):\n return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n / predictions.shape[0])", 142 | "language": "python", 143 | "outputs": [] 144 | }, 145 | { 146 | "metadata": { 147 | "id": "5rhgjmROXu2O", 148 | "colab_type": "text" 149 | }, 150 | "cell_type": "markdown", 151 | "source": "Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes." 152 | }, 153 | { 154 | "metadata": { 155 | "id": "IZYv70SvvOan", 156 | "colab_type": "code", 157 | "colab": { 158 | "autoexec": { 159 | "startup": false, 160 | "wait_interval": 0 161 | } 162 | }, 163 | "cellView": "both" 164 | }, 165 | "cell_type": "code", 166 | "input": "batch_size = 16\npatch_size = 5\ndepth = 16\nnum_hidden = 64\n\ngraph = tf.Graph()\n\nwith graph.as_default():\n\n # Input data.\n tf_train_dataset = tf.placeholder(\n tf.float32, shape=(batch_size, image_size, image_size, num_channels))\n tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n tf_valid_dataset = tf.constant(valid_dataset)\n tf_test_dataset = tf.constant(test_dataset)\n \n # Variables.\n layer1_weights = tf.Variable(tf.truncated_normal(\n [patch_size, patch_size, num_channels, depth], stddev=0.1))\n layer1_biases = tf.Variable(tf.zeros([depth]))\n layer2_weights = tf.Variable(tf.truncated_normal(\n [patch_size, patch_size, depth, depth], stddev=0.1))\n layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))\n layer3_weights = tf.Variable(tf.truncated_normal(\n [image_size / 4 * image_size / 4 * depth, num_hidden], stddev=0.1))\n layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))\n layer4_weights = tf.Variable(tf.truncated_normal(\n [num_hidden, num_labels], stddev=0.1))\n layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))\n \n # Model.\n def model(data):\n conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')\n hidden = tf.nn.relu(conv + layer1_biases)\n conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')\n hidden = tf.nn.relu(conv + layer2_biases)\n shape = hidden.get_shape().as_list()\n reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])\n hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)\n return tf.matmul(hidden, layer4_weights) + layer4_biases\n \n # Training computation.\n logits = model(tf_train_dataset)\n loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n \n # Optimizer.\n optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)\n \n # Predictions for the training, validation, and test data.\n train_prediction = tf.nn.softmax(logits)\n valid_prediction = tf.nn.softmax(model(tf_valid_dataset))\n test_prediction = tf.nn.softmax(model(tf_test_dataset))", 167 | "language": "python", 168 | "outputs": [] 169 | }, 170 | { 171 | "metadata": { 172 | "id": "noKFb2UovVFR", 173 | "colab_type": "code", 174 | "colab": { 175 | "autoexec": { 176 | "startup": false, 177 | "wait_interval": 0 178 | }, 179 | "output_extras": [ 180 | { 181 | "item_id": 37 182 | } 183 | ] 184 | }, 185 | "cellView": "both", 186 | "executionInfo": { 187 | "elapsed": 63292, 188 | "status": "ok", 189 | "timestamp": 1446658966251, 190 | "user": { 191 | "color": "", 192 | "displayName": "", 193 | "isAnonymous": false, 194 | "isMe": true, 195 | "permissionId": "", 196 | "photoUrl": "", 197 | "sessionId": "0", 198 | "userId": "" 199 | }, 200 | "user_tz": 480 201 | }, 202 | "outputId": "28941338-2ef9-4088-8bd1-44295661e628" 203 | }, 204 | "cell_type": "code", 205 | "input": "num_steps = 1001\n\nwith tf.Session(graph=graph) as session:\n tf.initialize_all_variables().run()\n print \"Initialized\"\n for step in xrange(num_steps):\n offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n batch_data = train_dataset[offset:(offset + batch_size), :, :, :]\n batch_labels = train_labels[offset:(offset + batch_size), :]\n feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n _, l, predictions = session.run(\n [optimizer, loss, train_prediction], feed_dict=feed_dict)\n if (step % 50 == 0):\n print \"Minibatch loss at step\", step, \":\", l\n print \"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels)\n print \"Validation accuracy: %.1f%%\" % accuracy(\n valid_prediction.eval(), valid_labels)\n print \"Test accuracy: %.1f%%\" % accuracy(test_prediction.eval(), test_labels)", 206 | "language": "python", 207 | "outputs": [ 208 | { 209 | "output_type": "stream", 210 | "stream": "stdout", 211 | "text": "Initialized\nMinibatch loss at step 0 : 3.51275\nMinibatch accuracy: 6.2%\nValidation accuracy: 12.8%\nMinibatch loss at step 50 : 1.48703\nMinibatch accuracy: 43.8%\nValidation accuracy: 50.4%\nMinibatch loss at step 100 : 1.04377\nMinibatch accuracy: 68.8%\nValidation accuracy: 67.4%\nMinibatch loss at step 150 : 0.601682\nMinibatch accuracy: 68.8%\nValidation accuracy: 73.0%\nMinibatch loss at step 200 : 0.898649\nMinibatch accuracy: 75.0%\nValidation accuracy: 77.8%\nMinibatch loss at step 250 : 1.3637\nMinibatch accuracy: 56.2%\nValidation accuracy: 75.4%\nMinibatch loss at step 300 : 1.41968\nMinibatch accuracy: 62.5%\nValidation accuracy: 76.0%\nMinibatch loss at step 350 : 0.300648\nMinibatch accuracy: 81.2%\nValidation accuracy: 80.2%\nMinibatch loss at step 400 : 1.32092\nMinibatch accuracy: 56.2%\nValidation accuracy: 80.4%\nMinibatch loss at step 450 : 0.556701\nMinibatch accuracy: 81.2%\nValidation accuracy: 79.4%\nMinibatch loss at step 500 : 1.65595\nMinibatch accuracy: 43.8%\nValidation accuracy: 79.6%\nMinibatch loss at step 550 : 1.06995\nMinibatch accuracy: 75.0%\nValidation accuracy: 81.2%\nMinibatch loss at step 600 : 0.223684\nMinibatch accuracy: 100.0%\nValidation accuracy: 82.3%\nMinibatch loss at step 650 : 0.619602\nMinibatch accuracy: 87.5%\nValidation accuracy: 81.8%\nMinibatch loss at step 700 : 0.812091\nMinibatch accuracy: 75.0%\nValidation accuracy: 82.4%\nMinibatch loss at step 750 : 0.276302\nMinibatch accuracy: 87.5%\nValidation accuracy: 82.3%\nMinibatch loss at step 800 : 0.450241\nMinibatch accuracy: 81.2%\nValidation accuracy: 82.3%\nMinibatch loss at step 850 : 0.137139\nMinibatch accuracy: 93.8%\nValidation accuracy: 82.3%\nMinibatch loss at step 900 : 0.52664\nMinibatch accuracy: 75.0%\nValidation accuracy: 82.2%\nMinibatch loss at step 950 : 0.623835\nMinibatch accuracy: 87.5%\nValidation accuracy: 82.1%\nMinibatch loss at step 1000 : 0.243114\nMinibatch accuracy: 93.8%\nValidation accuracy: 82.9%\nTest accuracy: 90.0%\n" 212 | } 213 | ] 214 | }, 215 | { 216 | "metadata": { 217 | "id": "KedKkn4EutIK", 218 | "colab_type": "text" 219 | }, 220 | "cell_type": "markdown", 221 | "source": "---\nProblem 1\n---------\n\nThe convolutional model above uses convolutions with stride 2 to reduce the dimensionality. Replace the strides by a max pooling operation (`nn.max_pool()`) of stride 2 and kernel size 2.\n\n---" 222 | }, 223 | { 224 | "metadata": { 225 | "id": "klf21gpbAgb-", 226 | "colab_type": "text" 227 | }, 228 | "cell_type": "markdown", 229 | "source": "---\nProblem 2\n---------\n\nTry to get the best performance you can using a convolutional net. Look for example at the classic [LeNet5](http://yann.lecun.com/exdb/lenet/) architecture, adding Dropout, and/or adding learning rate decay.\n\n---" 230 | } 231 | ] 232 | } 233 | ], 234 | "metadata": { 235 | "name": "4_convolutions.ipynb", 236 | "colabVersion": "0.3.2", 237 | "colab_views": {}, 238 | "colab_default_view": {} 239 | }, 240 | "nbformat": 3, 241 | "nbformat_minor": 0 242 | } 243 | -------------------------------------------------------------------------------- /udacity/6_lstm.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "colab_type": "text", 7 | "id": "8tQJd2YSCfWR" 8 | }, 9 | "source": [] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "metadata": { 14 | "colab_type": "text", 15 | "id": "D7tqLMoKF6uq" 16 | }, 17 | "source": [ 18 | "Deep Learning\n", 19 | "=============\n", 20 | "\n", 21 | "Assignment 6\n", 22 | "------------\n", 23 | "\n", 24 | "After training a skip-gram model in `5_word2vec.ipynb`, the goal of this notebook is to train a LSTM character model over [Text8](http://mattmahoney.net/dc/textdata) data." 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "metadata": { 31 | "cellView": "both", 32 | "colab": { 33 | "autoexec": { 34 | "startup": false, 35 | "wait_interval": 0 36 | } 37 | }, 38 | "colab_type": "code", 39 | "collapsed": true, 40 | "id": "MvEblsgEXxrd" 41 | }, 42 | "outputs": [], 43 | "source": [ 44 | "# These are all the modules we'll be using later. Make sure you can import them\n", 45 | "# before proceeding further.\n", 46 | "import os\n", 47 | "import numpy as np\n", 48 | "import random\n", 49 | "import string\n", 50 | "import tensorflow as tf\n", 51 | "import urllib\n", 52 | "import zipfile" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "metadata": { 59 | "cellView": "both", 60 | "colab": { 61 | "autoexec": { 62 | "startup": false, 63 | "wait_interval": 0 64 | }, 65 | "output_extras": [ 66 | { 67 | "item_id": 1 68 | } 69 | ] 70 | }, 71 | "colab_type": "code", 72 | "collapsed": false, 73 | "executionInfo": { 74 | "elapsed": 5993, 75 | "status": "ok", 76 | "timestamp": 1445965582896, 77 | "user": { 78 | "color": "#1FA15D", 79 | "displayName": "Vincent Vanhoucke", 80 | "isAnonymous": false, 81 | "isMe": true, 82 | "permissionId": "05076109866853157986", 83 | "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", 84 | "sessionId": "6f6f07b359200c46", 85 | "userId": "102167687554210253930" 86 | }, 87 | "user_tz": 420 88 | }, 89 | "id": "RJ-o3UBUFtCw", 90 | "outputId": "d530534e-0791-4a94-ca6d-1c8f1b908a9e" 91 | }, 92 | "outputs": [ 93 | { 94 | "name": "stdout", 95 | "output_type": "stream", 96 | "text": [ 97 | "Found and verified text8.zip\n" 98 | ] 99 | } 100 | ], 101 | "source": [ 102 | "url = 'http://mattmahoney.net/dc/'\n", 103 | "\n", 104 | "def maybe_download(filename, expected_bytes):\n", 105 | " \"\"\"Download a file if not present, and make sure it's the right size.\"\"\"\n", 106 | " if not os.path.exists(filename):\n", 107 | " filename, _ = urllib.urlretrieve(url + filename, filename)\n", 108 | " statinfo = os.stat(filename)\n", 109 | " if statinfo.st_size == expected_bytes:\n", 110 | " print 'Found and verified', filename\n", 111 | " else:\n", 112 | " print statinfo.st_size\n", 113 | " raise Exception(\n", 114 | " 'Failed to verify ' + filename + '. Can you get to it with a browser?')\n", 115 | " return filename\n", 116 | "\n", 117 | "filename = maybe_download('text8.zip', 31344016)" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "metadata": { 124 | "cellView": "both", 125 | "colab": { 126 | "autoexec": { 127 | "startup": false, 128 | "wait_interval": 0 129 | }, 130 | "output_extras": [ 131 | { 132 | "item_id": 1 133 | } 134 | ] 135 | }, 136 | "colab_type": "code", 137 | "collapsed": false, 138 | "executionInfo": { 139 | "elapsed": 5982, 140 | "status": "ok", 141 | "timestamp": 1445965582916, 142 | "user": { 143 | "color": "#1FA15D", 144 | "displayName": "Vincent Vanhoucke", 145 | "isAnonymous": false, 146 | "isMe": true, 147 | "permissionId": "05076109866853157986", 148 | "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", 149 | "sessionId": "6f6f07b359200c46", 150 | "userId": "102167687554210253930" 151 | }, 152 | "user_tz": 420 153 | }, 154 | "id": "Mvf09fjugFU_", 155 | "outputId": "8f75db58-3862-404b-a0c3-799380597390" 156 | }, 157 | "outputs": [ 158 | { 159 | "name": "stdout", 160 | "output_type": "stream", 161 | "text": [ 162 | "Data size 100000000\n" 163 | ] 164 | } 165 | ], 166 | "source": [ 167 | "def read_data(filename):\n", 168 | " f = zipfile.ZipFile(filename)\n", 169 | " for name in f.namelist():\n", 170 | " return f.read(name)\n", 171 | " f.close()\n", 172 | " \n", 173 | "text = read_data(filename)\n", 174 | "print \"Data size\", len(text)" 175 | ] 176 | }, 177 | { 178 | "cell_type": "markdown", 179 | "metadata": { 180 | "colab_type": "text", 181 | "id": "ga2CYACE-ghb" 182 | }, 183 | "source": [ 184 | "Create a small validation set." 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": null, 190 | "metadata": { 191 | "cellView": "both", 192 | "colab": { 193 | "autoexec": { 194 | "startup": false, 195 | "wait_interval": 0 196 | }, 197 | "output_extras": [ 198 | { 199 | "item_id": 1 200 | } 201 | ] 202 | }, 203 | "colab_type": "code", 204 | "collapsed": false, 205 | "executionInfo": { 206 | "elapsed": 6184, 207 | "status": "ok", 208 | "timestamp": 1445965583138, 209 | "user": { 210 | "color": "#1FA15D", 211 | "displayName": "Vincent Vanhoucke", 212 | "isAnonymous": false, 213 | "isMe": true, 214 | "permissionId": "05076109866853157986", 215 | "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", 216 | "sessionId": "6f6f07b359200c46", 217 | "userId": "102167687554210253930" 218 | }, 219 | "user_tz": 420 220 | }, 221 | "id": "w-oBpfFG-j43", 222 | "outputId": "bdb96002-d021-4379-f6de-a977924f0d02" 223 | }, 224 | "outputs": [ 225 | { 226 | "name": "stdout", 227 | "output_type": "stream", 228 | "text": [ 229 | "99999000 ons anarchists advocate social relations based upon voluntary as\n", 230 | "1000 anarchism originated as a term of abuse first used against earl\n" 231 | ] 232 | } 233 | ], 234 | "source": [ 235 | "valid_size = 1000\n", 236 | "valid_text = text[:valid_size]\n", 237 | "train_text = text[valid_size:]\n", 238 | "train_size = len(train_text)\n", 239 | "print train_size, train_text[:64]\n", 240 | "print valid_size, valid_text[:64]" 241 | ] 242 | }, 243 | { 244 | "cell_type": "markdown", 245 | "metadata": { 246 | "colab_type": "text", 247 | "id": "Zdw6i4F8glpp" 248 | }, 249 | "source": [ 250 | "Utility functions to map characters to vocabulary IDs and back." 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": null, 256 | "metadata": { 257 | "cellView": "both", 258 | "colab": { 259 | "autoexec": { 260 | "startup": false, 261 | "wait_interval": 0 262 | }, 263 | "output_extras": [ 264 | { 265 | "item_id": 1 266 | } 267 | ] 268 | }, 269 | "colab_type": "code", 270 | "collapsed": false, 271 | "executionInfo": { 272 | "elapsed": 6276, 273 | "status": "ok", 274 | "timestamp": 1445965583249, 275 | "user": { 276 | "color": "#1FA15D", 277 | "displayName": "Vincent Vanhoucke", 278 | "isAnonymous": false, 279 | "isMe": true, 280 | "permissionId": "05076109866853157986", 281 | "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", 282 | "sessionId": "6f6f07b359200c46", 283 | "userId": "102167687554210253930" 284 | }, 285 | "user_tz": 420 286 | }, 287 | "id": "gAL1EECXeZsD", 288 | "outputId": "88fc9032-feb9-45ff-a9a0-a26759cc1f2e" 289 | }, 290 | "outputs": [ 291 | { 292 | "name": "stdout", 293 | "output_type": "stream", 294 | "text": [ 295 | "1 26 0 Unexpected character: ï\n", 296 | "0\n", 297 | "a z \n" 298 | ] 299 | } 300 | ], 301 | "source": [ 302 | "vocabulary_size = len(string.ascii_lowercase) + 1 # [a-z] + ' '\n", 303 | "first_letter = ord(string.ascii_lowercase[0])\n", 304 | "\n", 305 | "def char2id(char):\n", 306 | " if char in string.ascii_lowercase:\n", 307 | " return ord(char) - first_letter + 1\n", 308 | " elif char == ' ':\n", 309 | " return 0\n", 310 | " else:\n", 311 | " print 'Unexpected character:', char\n", 312 | " return 0\n", 313 | " \n", 314 | "def id2char(dictid):\n", 315 | " if dictid > 0:\n", 316 | " return chr(dictid + first_letter - 1)\n", 317 | " else:\n", 318 | " return ' '\n", 319 | "\n", 320 | "print char2id('a'), char2id('z'), char2id(' '), char2id('ï')\n", 321 | "print id2char(1), id2char(26), id2char(0)" 322 | ] 323 | }, 324 | { 325 | "cell_type": "markdown", 326 | "metadata": { 327 | "colab_type": "text", 328 | "id": "lFwoyygOmWsL" 329 | }, 330 | "source": [ 331 | "Function to generate a training batch for the LSTM model." 332 | ] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "execution_count": null, 337 | "metadata": { 338 | "cellView": "both", 339 | "colab": { 340 | "autoexec": { 341 | "startup": false, 342 | "wait_interval": 0 343 | }, 344 | "output_extras": [ 345 | { 346 | "item_id": 1 347 | } 348 | ] 349 | }, 350 | "colab_type": "code", 351 | "collapsed": false, 352 | "executionInfo": { 353 | "elapsed": 6473, 354 | "status": "ok", 355 | "timestamp": 1445965583467, 356 | "user": { 357 | "color": "#1FA15D", 358 | "displayName": "Vincent Vanhoucke", 359 | "isAnonymous": false, 360 | "isMe": true, 361 | "permissionId": "05076109866853157986", 362 | "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", 363 | "sessionId": "6f6f07b359200c46", 364 | "userId": "102167687554210253930" 365 | }, 366 | "user_tz": 420 367 | }, 368 | "id": "d9wMtjy5hCj9", 369 | "outputId": "3dd79c80-454a-4be0-8b71-4a4a357b3367" 370 | }, 371 | "outputs": [ 372 | { 373 | "name": "stdout", 374 | "output_type": "stream", 375 | "text": [ 376 | "['ons anarchi', 'when milita', 'lleria arch', ' abbeys and', 'married urr', 'hel and ric', 'y and litur', 'ay opened f', 'tion from t', 'migration t', 'new york ot', 'he boeing s', 'e listed wi', 'eber has pr', 'o be made t', 'yer who rec', 'ore signifi', 'a fierce cr', ' two six ei', 'aristotle s', 'ity can be ', ' and intrac', 'tion of the', 'dy to pass ', 'f certain d', 'at it will ', 'e convince ', 'ent told hi', 'ampaign and', 'rver side s', 'ious texts ', 'o capitaliz', 'a duplicate', 'gh ann es d', 'ine january', 'ross zero t', 'cal theorie', 'ast instanc', ' dimensiona', 'most holy m', 't s support', 'u is still ', 'e oscillati', 'o eight sub', 'of italy la', 's the tower', 'klahoma pre', 'erprise lin', 'ws becomes ', 'et in a naz', 'the fabian ', 'etchy to re', ' sharman ne', 'ised empero', 'ting in pol', 'd neo latin', 'th risky ri', 'encyclopedi', 'fense the a', 'duating fro', 'treet grid ', 'ations more', 'appeal of d', 'si have mad']\n", 377 | "['ists advoca', 'ary governm', 'hes nationa', 'd monasteri', 'raca prince', 'chard baer ', 'rgical lang', 'for passeng', 'the nationa', 'took place ', 'ther well k', 'seven six s', 'ith a gloss', 'robably bee', 'to recogniz', 'ceived the ', 'icant than ', 'ritic of th', 'ight in sig', 's uncaused ', ' lost as in', 'cellular ic', 'e size of t', ' him a stic', 'drugs confu', ' take to co', ' the priest', 'im to name ', 'd barred at', 'standard fo', ' such as es', 'ze on the g', 'e of the or', 'd hiver one', 'y eight mar', 'the lead ch', 'es classica', 'ce the non ', 'al analysis', 'mormons bel', 't or at lea', ' disagreed ', 'ing system ', 'btypes base', 'anguages th', 'r commissio', 'ess one nin', 'nux suse li', ' the first ', 'zi concentr', ' society ne', 'elatively s', 'etworks sha', 'or hirohito', 'litical ini', 'n most of t', 'iskerdoo ri', 'ic overview', 'air compone', 'om acnm acc', ' centerline', 'e than any ', 'devotional ', 'de such dev']\n", 378 | "[' a']\n", 379 | "['an']\n" 380 | ] 381 | } 382 | ], 383 | "source": [ 384 | "batch_size=64\n", 385 | "num_unrollings=10\n", 386 | "\n", 387 | "class BatchGenerator(object):\n", 388 | " def __init__(self, text, batch_size, num_unrollings):\n", 389 | " self._text = text\n", 390 | " self._text_size = len(text)\n", 391 | " self._batch_size = batch_size\n", 392 | " self._num_unrollings = num_unrollings\n", 393 | " segment = self._text_size / batch_size\n", 394 | " self._cursor = [ offset * segment for offset in xrange(batch_size)]\n", 395 | " self._last_batch = self._next_batch()\n", 396 | " \n", 397 | " def _next_batch(self):\n", 398 | " \"\"\"Generate a single batch from the current cursor position in the data.\"\"\"\n", 399 | " batch = np.zeros(shape=(self._batch_size, vocabulary_size), dtype=np.float)\n", 400 | " for b in xrange(self._batch_size):\n", 401 | " batch[b, char2id(self._text[self._cursor[b]])] = 1.0\n", 402 | " self._cursor[b] = (self._cursor[b] + 1) % self._text_size\n", 403 | " return batch\n", 404 | " \n", 405 | " def next(self):\n", 406 | " \"\"\"Generate the next array of batches from the data. The array consists of\n", 407 | " the last batch of the previous array, followed by num_unrollings new ones.\n", 408 | " \"\"\"\n", 409 | " batches = [self._last_batch]\n", 410 | " for step in xrange(self._num_unrollings):\n", 411 | " batches.append(self._next_batch())\n", 412 | " self._last_batch = batches[-1]\n", 413 | " return batches\n", 414 | "\n", 415 | "def characters(probabilities):\n", 416 | " \"\"\"Turn a 1-hot encoding or a probability distribution over the possible\n", 417 | " characters back into its (mostl likely) character representation.\"\"\"\n", 418 | " return [id2char(c) for c in np.argmax(probabilities, 1)]\n", 419 | "\n", 420 | "def batches2string(batches):\n", 421 | " \"\"\"Convert a sequence of batches back into their (most likely) string\n", 422 | " representation.\"\"\"\n", 423 | " s = [''] * batches[0].shape[0]\n", 424 | " for b in batches:\n", 425 | " s = [''.join(x) for x in zip(s, characters(b))]\n", 426 | " return s\n", 427 | "\n", 428 | "train_batches = BatchGenerator(train_text, batch_size, num_unrollings)\n", 429 | "valid_batches = BatchGenerator(valid_text, 1, 1)\n", 430 | "\n", 431 | "print batches2string(train_batches.next())\n", 432 | "print batches2string(train_batches.next())\n", 433 | "print batches2string(valid_batches.next())\n", 434 | "print batches2string(valid_batches.next())" 435 | ] 436 | }, 437 | { 438 | "cell_type": "code", 439 | "execution_count": null, 440 | "metadata": { 441 | "cellView": "both", 442 | "colab": { 443 | "autoexec": { 444 | "startup": false, 445 | "wait_interval": 0 446 | } 447 | }, 448 | "colab_type": "code", 449 | "collapsed": true, 450 | "id": "KyVd8FxT5QBc" 451 | }, 452 | "outputs": [], 453 | "source": [ 454 | "def logprob(predictions, labels):\n", 455 | " \"\"\"Log-probability of the true labels in a predicted batch.\"\"\"\n", 456 | " predictions[predictions < 1e-10] = 1e-10\n", 457 | " return np.sum(np.multiply(labels, -np.log(predictions))) / labels.shape[0]\n", 458 | "\n", 459 | "def sample_distribution(distribution):\n", 460 | " \"\"\"Sample one element from a distribution assumed to be an array of normalized\n", 461 | " probabilities.\n", 462 | " \"\"\"\n", 463 | " r = random.uniform(0, 1)\n", 464 | " s = 0\n", 465 | " for i in xrange(len(distribution)):\n", 466 | " s += distribution[i]\n", 467 | " if s >= r:\n", 468 | " return i\n", 469 | " return len(distribution) - 1\n", 470 | "\n", 471 | "def sample(prediction):\n", 472 | " \"\"\"Turn a (column) prediction into 1-hot encoded samples.\"\"\"\n", 473 | " p = np.zeros(shape=[1, vocabulary_size], dtype=np.float)\n", 474 | " p[0, sample_distribution(prediction[0])] = 1.0\n", 475 | " return p\n", 476 | "\n", 477 | "def random_distribution():\n", 478 | " \"\"\"Generate a random column of probabilities.\"\"\"\n", 479 | " b = np.random.uniform(0.0, 1.0, size=[1, vocabulary_size])\n", 480 | " return b/np.sum(b, 1)[:,None]" 481 | ] 482 | }, 483 | { 484 | "cell_type": "markdown", 485 | "metadata": { 486 | "colab_type": "text", 487 | "id": "K8f67YXaDr4C" 488 | }, 489 | "source": [ 490 | "Simple LSTM Model." 491 | ] 492 | }, 493 | { 494 | "cell_type": "code", 495 | "execution_count": null, 496 | "metadata": { 497 | "cellView": "both", 498 | "colab": { 499 | "autoexec": { 500 | "startup": false, 501 | "wait_interval": 0 502 | } 503 | }, 504 | "colab_type": "code", 505 | "collapsed": true, 506 | "id": "Q5rxZK6RDuGe" 507 | }, 508 | "outputs": [], 509 | "source": [ 510 | "num_nodes = 64\n", 511 | "\n", 512 | "graph = tf.Graph()\n", 513 | "with graph.as_default():\n", 514 | " \n", 515 | " # Parameters:\n", 516 | " # Input gate: input, previous output, and bias.\n", 517 | " ix = tf.Variable(tf.truncated_normal([vocabulary_size, num_nodes], -0.1, 0.1))\n", 518 | " im = tf.Variable(tf.truncated_normal([num_nodes, num_nodes], -0.1, 0.1))\n", 519 | " ib = tf.Variable(tf.zeros([1, num_nodes]))\n", 520 | " # Forget gate: input, previous output, and bias.\n", 521 | " fx = tf.Variable(tf.truncated_normal([vocabulary_size, num_nodes], -0.1, 0.1))\n", 522 | " fm = tf.Variable(tf.truncated_normal([num_nodes, num_nodes], -0.1, 0.1))\n", 523 | " fb = tf.Variable(tf.zeros([1, num_nodes]))\n", 524 | " # Memory cell: input, state and bias. \n", 525 | " cx = tf.Variable(tf.truncated_normal([vocabulary_size, num_nodes], -0.1, 0.1))\n", 526 | " cm = tf.Variable(tf.truncated_normal([num_nodes, num_nodes], -0.1, 0.1))\n", 527 | " cb = tf.Variable(tf.zeros([1, num_nodes]))\n", 528 | " # Output gate: input, previous output, and bias.\n", 529 | " ox = tf.Variable(tf.truncated_normal([vocabulary_size, num_nodes], -0.1, 0.1))\n", 530 | " om = tf.Variable(tf.truncated_normal([num_nodes, num_nodes], -0.1, 0.1))\n", 531 | " ob = tf.Variable(tf.zeros([1, num_nodes]))\n", 532 | " # Variables saving state across unrollings.\n", 533 | " saved_output = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False)\n", 534 | " saved_state = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False)\n", 535 | " # Classifier weights and biases.\n", 536 | " w = tf.Variable(tf.truncated_normal([num_nodes, vocabulary_size], -0.1, 0.1))\n", 537 | " b = tf.Variable(tf.zeros([vocabulary_size]))\n", 538 | " \n", 539 | " # Definition of the cell computation.\n", 540 | " def lstm_cell(i, o, state):\n", 541 | " \"\"\"Create a LSTM cell. See e.g.: http://arxiv.org/pdf/1402.1128v1.pdf\n", 542 | " Note that in this formulation, we omit the various connections between the\n", 543 | " previous state and the gates.\"\"\"\n", 544 | " input_gate = tf.sigmoid(tf.matmul(i, ix) + tf.matmul(o, im) + ib)\n", 545 | " forget_gate = tf.sigmoid(tf.matmul(i, fx) + tf.matmul(o, fm) + fb)\n", 546 | " update = tf.matmul(i, cx) + tf.matmul(o, cm) + cb\n", 547 | " state = forget_gate * state + input_gate * tf.tanh(update)\n", 548 | " output_gate = tf.sigmoid(tf.matmul(i, ox) + tf.matmul(o, om) + ob)\n", 549 | " return output_gate * tf.tanh(state), state\n", 550 | "\n", 551 | " # Input data.\n", 552 | " train_data = list()\n", 553 | " for _ in xrange(num_unrollings + 1):\n", 554 | " train_data.append(\n", 555 | " tf.placeholder(tf.float32, shape=[batch_size,vocabulary_size]))\n", 556 | " train_inputs = train_data[:num_unrollings]\n", 557 | " train_labels = train_data[1:] # labels are inputs shifted by one time step.\n", 558 | "\n", 559 | " # Unrolled LSTM loop.\n", 560 | " outputs = list()\n", 561 | " output = saved_output\n", 562 | " state = saved_state\n", 563 | " for i in train_inputs:\n", 564 | " output, state = lstm_cell(i, output, state)\n", 565 | " outputs.append(output)\n", 566 | "\n", 567 | " # State saving across unrollings.\n", 568 | " with tf.control_dependencies([saved_output.assign(output),\n", 569 | " saved_state.assign(state)]):\n", 570 | " # Classifier.\n", 571 | " logits = tf.nn.xw_plus_b(tf.concat(0, outputs), w, b)\n", 572 | " loss = tf.reduce_mean(\n", 573 | " tf.nn.softmax_cross_entropy_with_logits(\n", 574 | " logits, tf.concat(0, train_labels)))\n", 575 | "\n", 576 | " # Optimizer.\n", 577 | " global_step = tf.Variable(0)\n", 578 | " learning_rate = tf.train.exponential_decay(\n", 579 | " 10.0, global_step, 5000, 0.1, staircase=True)\n", 580 | " optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n", 581 | " gradients, v = zip(*optimizer.compute_gradients(loss))\n", 582 | " gradients, _ = tf.clip_by_global_norm(gradients, 1.25)\n", 583 | " optimizer = optimizer.apply_gradients(\n", 584 | " zip(gradients, v), global_step=global_step)\n", 585 | "\n", 586 | " # Predictions.\n", 587 | " train_prediction = tf.nn.softmax(logits)\n", 588 | " \n", 589 | " # Sampling and validation eval: batch 1, no unrolling.\n", 590 | " sample_input = tf.placeholder(tf.float32, shape=[1, vocabulary_size])\n", 591 | " saved_sample_output = tf.Variable(tf.zeros([1, num_nodes]))\n", 592 | " saved_sample_state = tf.Variable(tf.zeros([1, num_nodes]))\n", 593 | " reset_sample_state = tf.group(\n", 594 | " saved_sample_output.assign(tf.zeros([1, num_nodes])),\n", 595 | " saved_sample_state.assign(tf.zeros([1, num_nodes])))\n", 596 | " sample_output, sample_state = lstm_cell(\n", 597 | " sample_input, saved_sample_output, saved_sample_state)\n", 598 | " with tf.control_dependencies([saved_sample_output.assign(sample_output),\n", 599 | " saved_sample_state.assign(sample_state)]):\n", 600 | " sample_prediction = tf.nn.softmax(tf.nn.xw_plus_b(sample_output, w, b))" 601 | ] 602 | }, 603 | { 604 | "cell_type": "code", 605 | "execution_count": null, 606 | "metadata": { 607 | "cellView": "both", 608 | "colab": { 609 | "autoexec": { 610 | "startup": false, 611 | "wait_interval": 0 612 | }, 613 | "output_extras": [ 614 | { 615 | "item_id": 41 616 | }, 617 | { 618 | "item_id": 80 619 | }, 620 | { 621 | "item_id": 126 622 | }, 623 | { 624 | "item_id": 144 625 | } 626 | ] 627 | }, 628 | "colab_type": "code", 629 | "collapsed": false, 630 | "executionInfo": { 631 | "elapsed": 199909, 632 | "status": "ok", 633 | "timestamp": 1445965877333, 634 | "user": { 635 | "color": "#1FA15D", 636 | "displayName": "Vincent Vanhoucke", 637 | "isAnonymous": false, 638 | "isMe": true, 639 | "permissionId": "05076109866853157986", 640 | "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", 641 | "sessionId": "6f6f07b359200c46", 642 | "userId": "102167687554210253930" 643 | }, 644 | "user_tz": 420 645 | }, 646 | "id": "RD9zQCZTEaEm", 647 | "outputId": "5e868466-2532-4545-ce35-b403cf5d9de6" 648 | }, 649 | "outputs": [ 650 | { 651 | "name": "stdout", 652 | "output_type": "stream", 653 | "text": [ 654 | "Initialized\n", 655 | "Average loss at step 0 : 3.29904174805 learning rate: 10.0\n", 656 | "Minibatch perplexity: 27.09\n", 657 | "================================================================================\n", 658 | "srk dwmrnuldtbbgg tapootidtu xsciu sgokeguw hi ieicjq lq piaxhazvc s fht wjcvdlh\n", 659 | "lhrvallvbeqqquc dxd y siqvnle bzlyw nr rwhkalezo siie o deb e lpdg storq u nx o\n", 660 | "meieu nantiouie gdys qiuotblci loc hbiznauiccb cqzed acw l tsm adqxplku gn oaxet\n", 661 | "unvaouc oxchywdsjntdh zpklaejvxitsokeerloemee htphisb th eaeqseibumh aeeyj j orw\n", 662 | "ogmnictpycb whtup otnilnesxaedtekiosqet liwqarysmt arj flioiibtqekycbrrgoysj\n", 663 | "================================================================================\n", 664 | "Validation set perplexity: 19.99\n", 665 | "Average loss at step 100 : 2.59553678274 learning rate: 10.0\n", 666 | "Minibatch perplexity: 9.57\n", 667 | "Validation set perplexity: 10.60\n", 668 | "Average loss at step 200 : 2.24747137785 learning rate: 10.0\n", 669 | "Minibatch perplexity: 7.68\n", 670 | "Validation set perplexity: 8.84\n", 671 | "Average loss at step 300 : 2.09438110709 learning rate: 10.0\n", 672 | "Minibatch perplexity: 7.41\n", 673 | "Validation set perplexity: 8.13\n", 674 | "Average loss at step 400 : 1.99440989017 learning rate: 10.0\n", 675 | "Minibatch perplexity: 6.46\n", 676 | "Validation set perplexity: 7.58\n", 677 | "Average loss at step 500 : 1.9320810616 learning rate: 10.0\n", 678 | "Minibatch perplexity: 6.30\n", 679 | "Validation set perplexity: 6.88\n", 680 | "Average loss at step 600 : 1.90935629249 learning rate: 10.0\n", 681 | "Minibatch perplexity: 7.21\n", 682 | "Validation set perplexity: 6.91\n", 683 | "Average loss at step 700 : 1.85583009005 learning rate: 10.0\n", 684 | "Minibatch perplexity: 6.13\n", 685 | "Validation set perplexity: 6.60\n", 686 | "Average loss at step 800 : 1.82152368546 learning rate: 10.0\n", 687 | "Minibatch perplexity: 6.01\n", 688 | "Validation set perplexity: 6.37\n", 689 | "Average loss at step 900 : 1.83169809818 learning rate: 10.0\n", 690 | "Minibatch perplexity: 7.20\n", 691 | "Validation set perplexity: 6.23\n", 692 | "Average loss at step 1000 : 1.82217029214 learning rate: 10.0\n", 693 | "Minibatch perplexity: 6.73\n", 694 | "================================================================================\n", 695 | "le action b of the tert sy ofter selvorang previgned stischdy yocal chary the co\n", 696 | "le relganis networks partucy cetinning wilnchan sics rumeding a fulch laks oftes\n", 697 | "hian andoris ret the ecause bistory l pidect one eight five lack du that the ses\n", 698 | "aiv dromery buskocy becomer worils resism disele retery exterrationn of hide in \n", 699 | "mer miter y sught esfectur of the upission vain is werms is vul ugher compted by\n", 700 | "================================================================================\n", 701 | "Validation set perplexity: 6.07\n", 702 | "Average loss at step 1100 : 1.77301145077 learning rate: 10.0\n", 703 | "Minibatch perplexity: 6.03\n", 704 | "Validation set perplexity: 5.89\n", 705 | "Average loss at step 1200 : 1.75306463003 learning rate: 10.0\n", 706 | "Minibatch perplexity: 6.50\n", 707 | "Validation set perplexity: 5.61\n", 708 | "Average loss at step 1300 : 1.72937195778 learning rate: 10.0\n", 709 | "Minibatch perplexity: 5.00\n", 710 | "Validation set perplexity: 5.60\n", 711 | "Average loss at step 1400 : 1.74773373723 learning rate: 10.0\n", 712 | "Minibatch perplexity: 6.48\n", 713 | "Validation set perplexity: 5.66\n", 714 | "Average loss at step 1500 : 1.7368799901 learning rate: 10.0\n", 715 | "Minibatch perplexity: 5.22\n", 716 | "Validation set perplexity: 5.44\n", 717 | "Average loss at step 1600 : 1.74528762937 learning rate: 10.0\n", 718 | "Minibatch perplexity: 5.85\n", 719 | "Validation set perplexity: 5.33\n", 720 | "Average loss at step 1700 : 1.70881183743 learning rate: 10.0\n", 721 | "Minibatch perplexity: 5.33\n", 722 | "Validation set perplexity: 5.56\n", 723 | "Average loss at step 1800 : 1.67776108027 learning rate: 10.0\n", 724 | "Minibatch perplexity: 5.33\n", 725 | "Validation set perplexity: 5.29\n", 726 | "Average loss at step 1900 : 1.64935536742 learning rate: 10.0\n", 727 | "Minibatch perplexity: 5.29\n", 728 | "Validation set perplexity: 5.15\n", 729 | "Average loss at step 2000 : 1.69528644681 learning rate: 10.0\n", 730 | "Minibatch perplexity: 5.13\n", 731 | "================================================================================\n", 732 | "vers soqually have one five landwing to docial page kagan lower with ther batern\n", 733 | "ctor son alfortmandd tethre k skin the known purated to prooust caraying the fit\n", 734 | "je in beverb is the sournction bainedy wesce tu sture artualle lines digra forme\n", 735 | "m rousively haldio ourso ond anvary was for the seven solies hild buil s to te\n", 736 | "zall for is it is one nine eight eight one neval to the kime typer oene where he\n", 737 | "================================================================================\n", 738 | "Validation set perplexity: 5.25\n", 739 | "Average loss at step 2100 : 1.68808053017 learning rate: 10.0\n", 740 | "Minibatch perplexity: 5.17\n", 741 | "Validation set perplexity: 5.01\n", 742 | "Average loss at step 2200 : 1.68322490931 learning rate: 10.0\n", 743 | "Minibatch perplexity: 5.09\n", 744 | "Validation set perplexity: 5.15\n", 745 | "Average loss at step 2300 : 1.64465074301 learning rate: 10.0\n", 746 | "Minibatch perplexity: 5.51\n", 747 | "Validation set perplexity: 5.00\n", 748 | "Average loss at step 2400 : 1.66408578038 learning rate: 10.0\n", 749 | "Minibatch perplexity: 5.86\n", 750 | "Validation set perplexity: 4.80\n", 751 | "Average loss at step 2500 : 1.68515402555 learning rate: 10.0\n", 752 | "Minibatch perplexity: 5.75\n", 753 | "Validation set perplexity: 4.82\n", 754 | "Average loss at step 2600 : 1.65405208349 learning rate: 10.0\n", 755 | "Minibatch perplexity: 5.38\n", 756 | "Validation set perplexity: 4.85\n", 757 | "Average loss at step 2700 : 1.65706222177 learning rate: 10.0\n", 758 | "Minibatch perplexity: 5.46\n", 759 | "Validation set perplexity: 4.78\n", 760 | "Average loss at step 2800 : 1.65204829812 learning rate: 10.0\n", 761 | "Minibatch perplexity: 5.06\n", 762 | "Validation set perplexity: 4.64\n", 763 | "Average loss at step 2900 : 1.65107253551 learning rate: 10.0\n", 764 | "Minibatch perplexity: 5.00\n", 765 | "Validation set perplexity: 4.61\n", 766 | "Average loss at step 3000 : 1.6495274055 learning rate: 10.0\n", 767 | "Minibatch perplexity: 4.53\n", 768 | "================================================================================\n", 769 | "ject covered in belo one six six to finsh that all di rozial sime it a the lapse\n", 770 | "ble which the pullic bocades record r to sile dric two one four nine seven six f\n", 771 | " originally ame the playa ishaps the stotchational in a p dstambly name which as\n", 772 | "ore volum to bay riwer foreal in nuily operety can and auscham frooripm however \n", 773 | "kan traogey was lacous revision the mott coupofiteditey the trando insended frop\n", 774 | "================================================================================\n", 775 | "Validation set perplexity: 4.76\n", 776 | "Average loss at step 3100 : 1.63705502152 learning rate: 10.0\n", 777 | "Minibatch perplexity: 5.50\n", 778 | "Validation set perplexity: 4.76\n", 779 | "Average loss at step 3200 : 1.64740695596 learning rate: 10.0\n", 780 | "Minibatch perplexity: 4.84\n", 781 | "Validation set perplexity: 4.67\n", 782 | "Average loss at step 3300 : 1.64711504817 learning rate: 10.0\n", 783 | "Minibatch perplexity: 5.39\n", 784 | "Validation set perplexity: 4.57\n", 785 | "Average loss at step 3400 : 1.67113256454 learning rate: 10.0\n", 786 | "Minibatch perplexity: 5.56\n", 787 | "Validation set perplexity: 4.71\n", 788 | "Average loss at step 3500 : 1.65637169957 learning rate: 10.0\n", 789 | "Minibatch perplexity: 5.03\n", 790 | "Validation set perplexity: 4.80\n", 791 | "Average loss at step 3600 : 1.66601825476 learning rate: 10.0\n", 792 | "Minibatch perplexity: 4.63\n", 793 | "Validation set perplexity: 4.52\n", 794 | "Average loss at step 3700 : 1.65021387935 learning rate: 10.0\n", 795 | "Minibatch perplexity: 5.50\n", 796 | "Validation set perplexity: 4.56\n", 797 | "Average loss at step 3800 : 1.64481814981 learning rate: 10.0\n", 798 | "Minibatch perplexity: 4.60\n", 799 | "Validation set perplexity: 4.54\n", 800 | "Average loss at step 3900 : 1.642069453 learning rate: 10.0\n", 801 | "Minibatch perplexity: 4.91\n", 802 | "Validation set perplexity: 4.54\n", 803 | "Average loss at step 4000 : 1.65179730773 learning rate: 10.0\n", 804 | "Minibatch perplexity: 4.77\n", 805 | "================================================================================\n", 806 | "k s rasbonish roctes the nignese at heacle was sito of beho anarchys and with ro\n", 807 | "jusar two sue wletaus of chistical in causations d ow trancic bruthing ha laters\n", 808 | "de and speacy pulted yoftret worksy zeatlating to eight d had to ie bue seven si\n", 809 | "s fiction of the feelly constive suq flanch earlied curauking bjoventation agent\n", 810 | "quen s playing it calana our seopity also atbellisionaly comexing the revideve i\n", 811 | "================================================================================\n", 812 | "Validation set perplexity: 4.58\n", 813 | "Average loss at step 4100 : 1.63794238806 learning rate: 10.0\n", 814 | "Minibatch perplexity: 5.47\n", 815 | "Validation set perplexity: 4.79\n", 816 | "Average loss at step 4200 : 1.63822438836 learning rate: 10.0\n", 817 | "Minibatch perplexity: 5.30\n", 818 | "Validation set perplexity: 4.54\n", 819 | "Average loss at step 4300 : 1.61844664574 learning rate: 10.0\n", 820 | "Minibatch perplexity: 4.69\n", 821 | "Validation set perplexity: 4.54\n", 822 | "Average loss at step 4400 : 1.61255454302 learning rate: 10.0\n", 823 | "Minibatch perplexity: 4.67\n", 824 | "Validation set perplexity: 4.54\n", 825 | "Average loss at step 4500 : 1.61543365479 learning rate: 10.0\n", 826 | "Minibatch perplexity: 4.83\n", 827 | "Validation set perplexity: 4.69\n", 828 | "Average loss at step 4600 : 1.61607327104 learning rate: 10.0\n", 829 | "Minibatch perplexity: 5.18\n", 830 | "Validation set perplexity: 4.64\n", 831 | "Average loss at step 4700 : 1.62757282495 learning rate: 10.0\n", 832 | "Minibatch perplexity: 4.24\n", 833 | "Validation set perplexity: 4.66\n", 834 | "Average loss at step 4800 : 1.63222063541 learning rate: 10.0\n", 835 | "Minibatch perplexity: 5.30\n", 836 | "Validation set perplexity: 4.53\n", 837 | "Average loss at step 4900 : 1.63678096652 learning rate: 10.0\n", 838 | "Minibatch perplexity: 5.43\n", 839 | "Validation set perplexity: 4.64\n", 840 | "Average loss at step 5000 : 1.610340662 learning rate: 1.0\n", 841 | "Minibatch perplexity: 5.10\n", 842 | "================================================================================\n", 843 | "in b one onarbs revieds the kimiluge that fondhtic fnoto cre one nine zero zero \n", 844 | " of is it of marking panzia t had wap ironicaghni relly deah the omber b h menba\n", 845 | "ong messified it his the likdings ara subpore the a fames distaled self this int\n", 846 | "y advante authors the end languarle meit common tacing bevolitione and eight one\n", 847 | "zes that materly difild inllaring the fusts not panition assertian causecist bas\n", 848 | "================================================================================\n", 849 | "Validation set perplexity: 4.69\n", 850 | "Average loss at step 5100 : 1.60593637228 learning rate: 1.0\n", 851 | "Minibatch perplexity: 4.69\n", 852 | "Validation set perplexity: 4.47\n", 853 | "Average loss at step 5200 : 1.58993269444 learning rate: 1.0\n", 854 | "Minibatch perplexity: 4.65\n", 855 | "Validation set perplexity: 4.39\n", 856 | "Average loss at step 5300 : 1.57930587292 learning rate: 1.0\n", 857 | "Minibatch perplexity: 5.11\n", 858 | "Validation set perplexity: 4.39\n", 859 | "Average loss at step 5400 : 1.58022856832 learning rate: 1.0\n", 860 | "Minibatch perplexity: 5.19\n", 861 | "Validation set perplexity: 4.37\n", 862 | "Average loss at step 5500 : 1.56654450059 learning rate: 1.0\n", 863 | "Minibatch perplexity: 4.69\n", 864 | "Validation set perplexity: 4.33\n", 865 | "Average loss at step 5600 : 1.58013380885 learning rate: 1.0\n", 866 | "Minibatch perplexity: 5.13\n", 867 | "Validation set perplexity: 4.35\n", 868 | "Average loss at step 5700 : 1.56974959254 learning rate: 1.0\n", 869 | "Minibatch perplexity: 5.00\n", 870 | "Validation set perplexity: 4.34\n", 871 | "Average loss at step 5800 : 1.5839582932 learning rate: 1.0\n", 872 | "Minibatch perplexity: 4.88\n", 873 | "Validation set perplexity: 4.31\n", 874 | "Average loss at step 5900 : 1.57129439116 learning rate: 1.0\n", 875 | "Minibatch perplexity: 4.66\n", 876 | "Validation set perplexity: 4.32\n", 877 | "Average loss at step 6000 : 1.55144061089 learning rate: 1.0\n", 878 | "Minibatch perplexity: 4.55\n", 879 | "================================================================================\n", 880 | "utic clositical poopy stribe addi nixe one nine one zero zero eight zero b ha ex\n", 881 | "zerns b one internequiption of the secordy way anti proble akoping have fictiona\n", 882 | "phare united from has poporarly cities book ins sweden emperor a sass in origina\n", 883 | "quulk destrebinist and zeilazar and on low and by in science over country weilti\n", 884 | "x are holivia work missincis ons in the gages to starsle histon one icelanctrotu\n", 885 | "================================================================================\n", 886 | "Validation set perplexity: 4.30\n", 887 | "Average loss at step 6100 : 1.56450940847 learning rate: 1.0\n", 888 | "Minibatch perplexity: 4.77\n", 889 | "Validation set perplexity: 4.27\n", 890 | "Average loss at step 6200 : 1.53433164835 learning rate: 1.0\n", 891 | "Minibatch perplexity: 4.77\n", 892 | "Validation set perplexity: 4.27\n", 893 | "Average loss at step 6300 : 1.54773445129 learning rate: 1.0\n", 894 | "Minibatch perplexity: 4.76\n", 895 | "Validation set perplexity: 4.25\n", 896 | "Average loss at step 6400 : 1.54021131516 learning rate: 1.0\n", 897 | "Minibatch perplexity: 4.56\n", 898 | "Validation set perplexity: 4.24\n", 899 | "Average loss at step 6500 : 1.56153374553 learning rate: 1.0\n", 900 | "Minibatch perplexity: 5.43\n", 901 | "Validation set perplexity: 4.27\n", 902 | "Average loss at step 6600 : 1.59556478739 learning rate: 1.0\n", 903 | "Minibatch perplexity: 4.92\n", 904 | "Validation set perplexity: 4.28\n", 905 | "Average loss at step 6700 : 1.58076951623 learning rate: 1.0\n", 906 | "Minibatch perplexity: 4.77\n", 907 | "Validation set perplexity: 4.30\n", 908 | "Average loss at step 6800 : 1.6070714438 learning rate: 1.0\n", 909 | "Minibatch perplexity: 4.98\n", 910 | "Validation set perplexity: 4.28\n", 911 | "Average loss at step 6900 : 1.58413293839 learning rate: 1.0\n", 912 | "Minibatch perplexity: 4.61\n", 913 | "Validation set perplexity: 4.29\n", 914 | "Average loss at step 7000 : 1.57905534983 learning rate: 1.0\n", 915 | "Minibatch perplexity: 5.08\n", 916 | "================================================================================\n", 917 | "jague are officiencinels ored by film voon higherise haik one nine on the iffirc\n", 918 | "oshe provision that manned treatists on smalle bodariturmeristing the girto in s\n", 919 | "kis would softwenn mustapultmine truativersakys bersyim by s of confound esc bub\n", 920 | "ry of the using one four six blain ira mannom marencies g with fextificallise re\n", 921 | " one son vit even an conderouss to person romer i a lebapter at obiding are iuse\n", 922 | "================================================================================\n", 923 | "Validation set perplexity: 4.25\n" 924 | ] 925 | } 926 | ], 927 | "source": [ 928 | "num_steps = 7001\n", 929 | "summary_frequency = 100\n", 930 | "\n", 931 | "with tf.Session(graph=graph) as session:\n", 932 | " tf.initialize_all_variables().run()\n", 933 | " print 'Initialized'\n", 934 | " mean_loss = 0\n", 935 | " for step in xrange(num_steps):\n", 936 | " batches = train_batches.next()\n", 937 | " feed_dict = dict()\n", 938 | " for i in xrange(num_unrollings + 1):\n", 939 | " feed_dict[train_data[i]] = batches[i]\n", 940 | " _, l, predictions, lr = session.run(\n", 941 | " [optimizer, loss, train_prediction, learning_rate], feed_dict=feed_dict)\n", 942 | " mean_loss += l\n", 943 | " if step % summary_frequency == 0:\n", 944 | " if step > 0:\n", 945 | " mean_loss = mean_loss / summary_frequency\n", 946 | " # The mean loss is an estimate of the loss over the last few batches.\n", 947 | " print 'Average loss at step', step, ':', mean_loss, 'learning rate:', lr\n", 948 | " mean_loss = 0\n", 949 | " labels = np.concatenate(list(batches)[1:])\n", 950 | " print 'Minibatch perplexity: %.2f' % float(\n", 951 | " np.exp(logprob(predictions, labels)))\n", 952 | " if step % (summary_frequency * 10) == 0:\n", 953 | " # Generate some samples.\n", 954 | " print '=' * 80\n", 955 | " for _ in xrange(5):\n", 956 | " feed = sample(random_distribution())\n", 957 | " sentence = characters(feed)[0]\n", 958 | " reset_sample_state.run()\n", 959 | " for _ in xrange(79):\n", 960 | " prediction = sample_prediction.eval({sample_input: feed})\n", 961 | " feed = sample(prediction)\n", 962 | " sentence += characters(feed)[0]\n", 963 | " print sentence\n", 964 | " print '=' * 80\n", 965 | " # Measure validation set perplexity.\n", 966 | " reset_sample_state.run()\n", 967 | " valid_logprob = 0\n", 968 | " for _ in xrange(valid_size):\n", 969 | " b = valid_batches.next()\n", 970 | " predictions = sample_prediction.eval({sample_input: b[0]})\n", 971 | " valid_logprob = valid_logprob + logprob(predictions, b[1])\n", 972 | " print 'Validation set perplexity: %.2f' % float(np.exp(\n", 973 | " valid_logprob / valid_size))" 974 | ] 975 | }, 976 | { 977 | "cell_type": "markdown", 978 | "metadata": { 979 | "colab_type": "text", 980 | "id": "pl4vtmFfa5nn" 981 | }, 982 | "source": [ 983 | "---\n", 984 | "Problem 1\n", 985 | "---------\n", 986 | "\n", 987 | "You might have noticed that the definition of the LSTM cell involves 4 matrix multiplications with the input, and 4 matrix multiplications with the output. Simplify the expression by using a single matrix multiply for each, and variables that are 4 times larger.\n", 988 | "\n", 989 | "---" 990 | ] 991 | }, 992 | { 993 | "cell_type": "markdown", 994 | "metadata": { 995 | "colab_type": "text", 996 | "id": "4eErTCTybtph" 997 | }, 998 | "source": [ 999 | "---\n", 1000 | "Problem 2\n", 1001 | "---------\n", 1002 | "\n", 1003 | "We want to train a LSTM over bigrams, that is pairs of consecutive characters like 'ab' instead of single characters like 'a'. Since the number of possible bigrams is large, feeding them directly to the LSTM using 1-hot encodings will lead to a very sparse representation that is very wasteful computationally.\n", 1004 | "\n", 1005 | "a- Introduce an embedding lookup on the inputs, and feed the embeddings to the LSTM cell instead of the inputs themselves.\n", 1006 | "\n", 1007 | "b- Write a bigram-based LSTM, modeled on the character LSTM above.\n", 1008 | "\n", 1009 | "c- Introduce Dropout. For best practices on how to use Dropout in LSTMs, refer to this [article](http://arxiv.org/abs/1409.2329).\n", 1010 | "\n", 1011 | "---" 1012 | ] 1013 | }, 1014 | { 1015 | "cell_type": "markdown", 1016 | "metadata": { 1017 | "colab_type": "text", 1018 | "id": "Y5tapX3kpcqZ" 1019 | }, 1020 | "source": [ 1021 | "---\n", 1022 | "Problem 3\n", 1023 | "---------\n", 1024 | "\n", 1025 | "(difficult!)\n", 1026 | "\n", 1027 | "Write a sequence-to-sequence LSTM which mirrors all the words in a sentence. For example, if your input is:\n", 1028 | "\n", 1029 | " the quick brown fox\n", 1030 | " \n", 1031 | "the model should attempt to output:\n", 1032 | "\n", 1033 | " eht kciuq nworb xof\n", 1034 | " \n", 1035 | "Refer to the lecture on how to put together a sequence-to-sequence model, as well as [this article](http://arxiv.org/abs/1409.3215) for best practices.\n", 1036 | "\n", 1037 | "---" 1038 | ] 1039 | } 1040 | ], 1041 | "metadata": { 1042 | "anaconda-cloud": {}, 1043 | "colabVersion": "0.3.2", 1044 | "colab_default_view": {}, 1045 | "colab_views": {}, 1046 | "kernelspec": { 1047 | "display_name": "Python [default]", 1048 | "language": "python", 1049 | "name": "python2" 1050 | }, 1051 | "language_info": { 1052 | "codemirror_mode": { 1053 | "name": "ipython", 1054 | "version": 2 1055 | }, 1056 | "file_extension": ".py", 1057 | "mimetype": "text/x-python", 1058 | "name": "python", 1059 | "nbconvert_exporter": "python", 1060 | "pygments_lexer": "ipython2", 1061 | "version": "2.7.12" 1062 | } 1063 | }, 1064 | "nbformat": 4, 1065 | "nbformat_minor": 0 1066 | } 1067 | -------------------------------------------------------------------------------- /udacity/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM b.gcr.io/tensorflow/tensorflow:latest 2 | MAINTAINER Vincent Vanhoucke 3 | RUN pip install scikit-learn 4 | ADD *.ipynb /notebooks/ 5 | WORKDIR /notebooks 6 | CMD ["/run_jupyter.sh"] 7 | -------------------------------------------------------------------------------- /udacity/README.md: -------------------------------------------------------------------------------- 1 | Assignments for Udacity Deep Learning class with TensorFlow 2 | =========================================================== 3 | 4 | Running the Docker container from the Google Cloud repository 5 | ------------------------------------------------------------- 6 | 7 | docker run -p 8888:8888 -it --rm b.gcr.io/tensorflow-udacity/assignments 8 | 9 | Accessing the Notebooks 10 | ----------------------- 11 | 12 | On linux, go to: http://127.0.0.1:8888 13 | 14 | On mac, find the virtual machine's IP using: 15 | 16 | docker-machine ip default 17 | 18 | Then go to: http://IP:8888 (likely http://192.168.99.100:8888) 19 | 20 | Building a local Docker container 21 | --------------------------------- 22 | 23 | cd tensorflow/examples/udacity 24 | docker build -t $USER/assignments . 25 | 26 | Running the local container 27 | --------------------------- 28 | 29 | docker run -p 8888:8888 -it --rm $USER/assignments 30 | 31 | Pushing a Google Cloud release 32 | ------------------------------ 33 | 34 | V=0.1.0 35 | docker tag $USER/assignments b.gcr.io/tensorflow-udacity/assignments:$V 36 | docker tag $USER/assignments b.gcr.io/tensorflow-udacity/assignments:latest 37 | gcloud docker push b.gcr.io/tensorflow-udacity/assignments 38 | --------------------------------------------------------------------------------