├── LICENSE
├── README.md
└── RNN_LSTM_from_scratch.ipynb
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # How to build RNNs and LSTMs from scratch with NumPy
2 |
3 | **\[Update 08/18/2020\] Improvements to dataset; exercises and descriptions have been made more clear.**
4 |
5 | Originally developed by me (Nicklas Hansen), Peter E. Christensen and Alexander R. Johansen as educational material for the graduate deep learning course at the Technical University of Denmark (DTU). You can access the full course material [here](https://github.com/DeepLearningDTU/02456-deep-learning-with-PyTorch). Inspired by the great [Andrej Karpathy](https://karpathy.ai/).
6 | ____
7 |
8 | In this lab we will introduce different ways of learning from sequential data.
9 | As an example, we will train a neural network to do language modelling, i.e. predict the next token in a sentence. In the context of natural language processing a token could be a character or a word, but mind you that the concepts introduced here apply to all kinds of sequential data, such as e.g. protein sequences, weather measurements, audio signals or monetary transaction history, just to name a few.
10 |
11 | To really get a grasp of what is going on inside the recurrent neural networks that we are about to teach you, we will carry out a substantial part of this exercise in NumPy rather than PyTorch. Once you get a hold of it, we will proceed to the PyTorch implementation.
12 |
13 | In this notebook we will show you:
14 | * How to represent categorical variables in networks
15 | * How to build a recurrent neural network (RNN) from scratch
16 | * How to build a LSTM network from scratch
17 | * How to build a LSTM network in PyTorch
18 |
19 |
20 | ## Dataset
21 |
22 | For this exercise we will create a simple dataset that we can learn from. We generate sequences of the form:
23 |
24 | `a b EOS`,
25 |
26 | `a a b b EOS`,
27 |
28 | `a a a a a b b b b b EOS`
29 |
30 | where `EOS` is a special character denoting the end of a sequence. The task is to predict the next token `t_n`, i.e. `a`, `b`, `EOS` or the unknown token `UNK` given the sequence of tokens `t_1`, `t_2`, `...`, `t_n-1` and we are to process sequences in a sequential manner. As such, the network will need to learn that e.g. 5 `b`s and an `EOS` token will follow 5 `a`s.
31 |
32 | ## Results
33 |
34 | The RNN takes considerable effort to converge to a nice solution:
35 |
36 | 
37 |
38 | The LSTM learns much faster than the RNN:
39 |
40 | 
41 |
42 | And finally, the PyTorch LSTM learns even faster and converges to a better local minimum:
43 |
44 | 
45 |
46 | After working your way through these exercises, you should have a better understanding of how RNNs work, how to train them, and what they can be used for. And the conclusion? - use PyTorch.
47 |
--------------------------------------------------------------------------------
/RNN_LSTM_from_scratch.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "name": "5.1-EXE-Recurrent-Neural-Networks.ipynb",
7 | "provenance": [],
8 | "collapsed_sections": []
9 | },
10 | "kernelspec": {
11 | "display_name": "Python 3",
12 | "language": "python",
13 | "name": "python3"
14 | },
15 | "language_info": {
16 | "codemirror_mode": {
17 | "name": "ipython",
18 | "version": 3
19 | },
20 | "file_extension": ".py",
21 | "mimetype": "text/x-python",
22 | "name": "python",
23 | "nbconvert_exporter": "python",
24 | "pygments_lexer": "ipython3",
25 | "version": "3.7.4"
26 | }
27 | },
28 | "cells": [
29 | {
30 | "cell_type": "markdown",
31 | "metadata": {
32 | "id": "y-CptVs7iACc"
33 | },
34 | "source": [
35 | "# How to build RNNs and LSTMs from scratch with NumPy\n",
36 | "\n",
37 | "Originally developed by Nicklas Hansen, Peter E. Christensen and Alexander R. Johansen as educational material for the graduate deep learning course at the Technical University of Denmark (DTU). You can access the full course material [here](https://github.com/DeepLearningDTU/02456-deep-learning-with-PyTorch). Inspired by the great [Andrej Karpathy](https://karpathy.ai/).\n",
38 | "\n",
39 | "____\n",
40 | "\n",
41 | "\n",
42 | "In this lab, we will introduce different ways of learning from sequential data.\n",
43 | "\n",
44 | "As a recurring example, we will train neural networks to do language modelling, i.e. predict the next token in a sentence. In the context of natural language processing a token could be a character or a word, but mind you that the concepts introduced here apply to all kinds of sequential data, such as e.g. protein sequences, weather measurements, audio signals, or videos, just to name a few.\n",
45 | "\n",
46 | "To really get a grasp of what is going on inside a recurrent neural network (RNN), we will carry out a substantial part of this exercise in NumPy rather than PyTorch. We start off with a simple toy problem, build an RNN using NumPy, train and it, and see for ourselves that it really works. Once we're convinced, we proceed to build and train a Long Short-Term Memory (LSTM) cell, also in NumPy. This is *not* simply to cause you frustration, but rather to provide you with a deeper understanding of the recurrence in RNNs, which will become very beneficial to you in the following weeks. Once you understand the inner workings of an RNN, we will proceed to a PyTorch implementation that you may use for the remainder of the course and in your projects.\n",
47 | "\n",
48 | "To summarize, in this notebook we will show you:\n",
49 | "* How to represent sequences of categorical variables\n",
50 | "* How to build and train an RNN in NumPy\n",
51 | "* How to build and train an LSTM network in NumPy\n",
52 | "* How to build and train an LSTM network in PyTorch"
53 | ]
54 | },
55 | {
56 | "cell_type": "markdown",
57 | "metadata": {
58 | "id": "XapO8SLwiACd"
59 | },
60 | "source": [
61 | "## Representing tokens or text\n",
62 | "\n",
63 | "In previous labs we mainly considered data $x \\in \\mathrm{R}^d$, where $d$ is the feature space dimension.\n",
64 | "With time sequences our data can be represented as $x \\in \\mathrm{R}^{t \\, \\times \\, d}$, where $t$ is the sequence length. \n",
65 | "This emphasises sequence dependence and that the samples along the sequence are not independent and identically distributed (i.i.d.).\n",
66 | "We will model functions as $\\mathrm{R}^{t \\, \\times \\, d} \\rightarrow \\mathrm{R}^c$, where $c$ is the amount of classes in the output.\n",
67 | "\n",
68 | "There are several ways to represent sequences. With text, the challenge is how to represent a word as a feature vector in $d$ dimensions, as we are required to represent text with decimal numbers in order to apply neural networks to it.\n",
69 | "\n",
70 | "In this exercise we will use a simple one-hot encoding but for categorical variables that can take on many values (e.g. words in the English language) this may be infeasible. For such scenarios, you can project the encodings into a smaller space by use of embeddings. If you want to learn more about tokens, encodings and embeddings than what is covered in this exercise, we highly recommend [this lecture](https://www.youtube.com/watch?v=kEMJRjEdNzM&list=PLoROMvodv4rOhcuXMZkNm7j3fVwBBY42z)."
71 | ]
72 | },
73 | {
74 | "cell_type": "markdown",
75 | "metadata": {
76 | "id": "bdA4LPsFiACe"
77 | },
78 | "source": [
79 | "### One-hot encoding over vocabulary\n",
80 | "\n",
81 | "One way to represent a fixed amount of words is by making a one-hot encoded vector, which consists of 0s in all cells with the exception of a single 1 in a cell used uniquely to identify each word.\n",
82 | "\n",
83 | "| vocabulary | one-hot encoded vector |\n",
84 | "| ------------- |--------------------------|\n",
85 | "| Paris | $= [1, 0, 0, \\ldots, 0]$ |\n",
86 | "| Rome | $= [0, 1, 0, \\ldots, 0]$ |\n",
87 | "| Copenhagen | $= [0, 0, 1, \\ldots, 0]$ |\n",
88 | "\n",
89 | "Representing a large vocabulary with one-hot encodings often becomes inefficient because of the size of each sparse vector.\n",
90 | "To overcome this challenge it is common practice to truncate the vocabulary to contain the $k$ most used words and represent the rest with a special symbol, $\\mathtt{UNK}$, to define unknown/unimportant words.\n",
91 | "This often causes entities such as names to be represented with $\\mathtt{UNK}$ because they are rare.\n",
92 | "\n",
93 | "Consider the following text\n",
94 | "> I love the corny jokes in Spielberg's new movie.\n",
95 | "\n",
96 | "where an example result would be similar to\n",
97 | "> I love the corny jokes in $\\mathtt{UNK}$'s new movie."
98 | ]
99 | },
100 | {
101 | "cell_type": "markdown",
102 | "metadata": {
103 | "id": "KNmyPw7zk2gY"
104 | },
105 | "source": [
106 | "## Generating a dataset"
107 | ]
108 | },
109 | {
110 | "cell_type": "markdown",
111 | "metadata": {
112 | "id": "M9IEA4t2k2gb"
113 | },
114 | "source": [
115 | "For this exercise we will create a simple dataset that we can learn from. We generate sequences of the form:\n",
116 | "\n",
117 | "`a b EOS`,\n",
118 | "\n",
119 | "`a a b b EOS`,\n",
120 | "\n",
121 | "`a a a a a b b b b b EOS`\n",
122 | "\n",
123 | "where `EOS` is a special character denoting the end of a sequence. The task is to predict the next token $t_n$, i.e. `a`, `b`, `EOS` or the unknown token `UNK` given a sequence of tokens $\\{ t_{1}, t_{2}, \\dots , t_{n-1}\\}$, and we are to process sequences in a sequential manner. As such, the network will need to learn that e.g. 5 `b`s and an `EOS` token will follow 5 `a`s."
124 | ]
125 | },
126 | {
127 | "cell_type": "code",
128 | "metadata": {
129 | "id": "dcoN-kb7k2gc"
130 | },
131 | "source": [
132 | "import numpy as np\n",
133 | "\n",
134 | "# Set seed such that we always get the same dataset\n",
135 | "# (this is a good idea in general)\n",
136 | "np.random.seed(42)\n",
137 | "\n",
138 | "def generate_dataset(num_sequences=2**8):\n",
139 | " \"\"\"\n",
140 | " Generates a number of sequences as our dataset.\n",
141 | " \n",
142 | " Args:\n",
143 | " `num_sequences`: the number of sequences to be generated.\n",
144 | " \n",
145 | " Returns a list of sequences.\n",
146 | " \"\"\"\n",
147 | " samples = []\n",
148 | " \n",
149 | " for _ in range(num_sequences): \n",
150 | " num_tokens = np.random.randint(1, 12)\n",
151 | " sample = ['a'] * num_tokens + ['b'] * num_tokens + ['EOS']\n",
152 | " samples.append(sample)\n",
153 | " \n",
154 | " return samples\n",
155 | "\n",
156 | "\n",
157 | "sequences = generate_dataset()\n",
158 | "\n",
159 | "print('A single sample from the generated dataset:')\n",
160 | "print(sequences[0])"
161 | ],
162 | "execution_count": null,
163 | "outputs": []
164 | },
165 | {
166 | "cell_type": "markdown",
167 | "metadata": {
168 | "id": "YMLd3Gzak2gp"
169 | },
170 | "source": [
171 | "## Representing tokens as indices"
172 | ]
173 | },
174 | {
175 | "cell_type": "markdown",
176 | "metadata": {
177 | "id": "S9LSqaJSk2gp"
178 | },
179 | "source": [
180 | "To build a one-hot encoding, we need to assign each possible word in our vocabulary an index. We do that by creating two dictionaries: one that allows us to go from a given word to its corresponding index in our vocabulary, and one for the reverse direction. Let's call them `word_to_idx` and `idx_to_word`. The keyword `vocab_size` specifies the maximum size of our vocabulary. If we try to access a word that does not exist in our vocabulary, it is automatically replaced by the `UNK` token or its corresponding index."
181 | ]
182 | },
183 | {
184 | "cell_type": "code",
185 | "metadata": {
186 | "id": "Smdo70UMk2gr"
187 | },
188 | "source": [
189 | "from collections import defaultdict\n",
190 | "\n",
191 | "def sequences_to_dicts(sequences):\n",
192 | " \"\"\"\n",
193 | " Creates word_to_idx and idx_to_word dictionaries for a list of sequences.\n",
194 | " \"\"\"\n",
195 | " # A bit of Python-magic to flatten a nested list\n",
196 | " flatten = lambda l: [item for sublist in l for item in sublist]\n",
197 | " \n",
198 | " # Flatten the dataset\n",
199 | " all_words = flatten(sequences)\n",
200 | " \n",
201 | " # Count number of word occurences\n",
202 | " word_count = defaultdict(int)\n",
203 | " for word in flatten(sequences):\n",
204 | " word_count[word] += 1\n",
205 | "\n",
206 | " # Sort by frequency\n",
207 | " word_count = sorted(list(word_count.items()), key=lambda l: -l[1])\n",
208 | "\n",
209 | " # Create a list of all unique words\n",
210 | " unique_words = [item[0] for item in word_count]\n",
211 | " \n",
212 | " # Add UNK token to list of words\n",
213 | " unique_words.append('UNK')\n",
214 | "\n",
215 | " # Count number of sequences and number of unique words\n",
216 | " num_sentences, vocab_size = len(sequences), len(unique_words)\n",
217 | "\n",
218 | " # Create dictionaries so that we can go from word to index and back\n",
219 | " # If a word is not in our vocabulary, we assign it to token 'UNK'\n",
220 | " word_to_idx = defaultdict(lambda: vocab_size-1)\n",
221 | " idx_to_word = defaultdict(lambda: 'UNK')\n",
222 | "\n",
223 | " # Fill dictionaries\n",
224 | " for idx, word in enumerate(unique_words):\n",
225 | " # YOUR CODE HERE!\n",
226 | " word_to_idx[word] = \n",
227 | " idx_to_word[idx] = \n",
228 | "\n",
229 | " return word_to_idx, idx_to_word, num_sentences, vocab_size\n",
230 | "\n",
231 | "\n",
232 | "word_to_idx, idx_to_word, num_sequences, vocab_size = sequences_to_dicts(sequences)\n",
233 | "\n",
234 | "print(f'We have {num_sequences} sentences and {len(word_to_idx)} unique tokens in our dataset (including UNK).\\n')\n",
235 | "print('The index of \\'b\\' is', word_to_idx['b'])\n",
236 | "print(f'The word corresponding to index 1 is \\'{idx_to_word[1]}\\'')\n",
237 | "\n",
238 | "assert idx_to_word[word_to_idx['b']] == 'b', \\\n",
239 | " 'Consistency error: something went wrong in the conversion.'"
240 | ],
241 | "execution_count": null,
242 | "outputs": []
243 | },
244 | {
245 | "cell_type": "markdown",
246 | "metadata": {
247 | "id": "sNY1OOS_k2gy"
248 | },
249 | "source": [
250 | "## Exercise A:"
251 | ]
252 | },
253 | {
254 | "cell_type": "markdown",
255 | "metadata": {
256 | "id": "Xc-iHbBmk2gz"
257 | },
258 | "source": [
259 | "Complete the `sequences_to_dicts` function above. You will need to fill the `word_to_idx` and `idx_to_word` dictionaries so that we can go back and forth between the two representations."
260 | ]
261 | },
262 | {
263 | "cell_type": "markdown",
264 | "metadata": {
265 | "id": "cGSoDRgHk2g1"
266 | },
267 | "source": [
268 | "## Partitioning the dataset"
269 | ]
270 | },
271 | {
272 | "cell_type": "markdown",
273 | "metadata": {
274 | "id": "UMTn1iLIk2g1"
275 | },
276 | "source": [
277 | "To build our dataset, we need to create inputs and targets for each sequences and partition sentences it into training, validation and test sets. 80%, 10% and 10% is a common distribution, but mind you that this largely depends on the size of the dataset. Since we are doing next-word predictions, our target sequence is simply the input sequence shifted by one word.\n",
278 | "\n",
279 | "We can use PyTorch's `Dataset` class to build a simple dataset where we can easily retrieve (inputs, targets) pairs for each of our sequences."
280 | ]
281 | },
282 | {
283 | "cell_type": "code",
284 | "metadata": {
285 | "id": "9dW7MrPnk2g3"
286 | },
287 | "source": [
288 | "from torch.utils import data\n",
289 | "\n",
290 | "class Dataset(data.Dataset):\n",
291 | " def __init__(self, inputs, targets):\n",
292 | " self.inputs = inputs\n",
293 | " self.targets = targets\n",
294 | "\n",
295 | " def __len__(self):\n",
296 | " # Return the size of the dataset\n",
297 | " return len(self.targets)\n",
298 | "\n",
299 | " def __getitem__(self, index):\n",
300 | " # Retrieve inputs and targets at the given index\n",
301 | " X = self.inputs[index]\n",
302 | " y = self.targets[index]\n",
303 | "\n",
304 | " return X, y\n",
305 | "\n",
306 | " \n",
307 | "def create_datasets(sequences, dataset_class, p_train=0.8, p_val=0.1, p_test=0.1):\n",
308 | " # Define partition sizes\n",
309 | " num_train = int(len(sequences)*p_train)\n",
310 | " num_val = int(len(sequences)*p_val)\n",
311 | " num_test = int(len(sequences)*p_test)\n",
312 | "\n",
313 | " # Split sequences into partitions\n",
314 | " sequences_train = sequences[:num_train]\n",
315 | " sequences_val = sequences[num_train:num_train+num_val]\n",
316 | " sequences_test = sequences[-num_test:]\n",
317 | "\n",
318 | " def get_inputs_targets_from_sequences(sequences):\n",
319 | " # Define empty lists\n",
320 | " inputs, targets = [], []\n",
321 | " \n",
322 | " # Append inputs and targets s.t. both lists contain L-1 words of a sentence of length L\n",
323 | " # but targets are shifted right by one so that we can predict the next word\n",
324 | " for sequence in sequences:\n",
325 | " inputs.append(sequence[:-1])\n",
326 | " targets.append(sequence[1:])\n",
327 | " \n",
328 | " return inputs, targets\n",
329 | "\n",
330 | " # Get inputs and targets for each partition\n",
331 | " inputs_train, targets_train = get_inputs_targets_from_sequences(sequences_train)\n",
332 | " inputs_val, targets_val = get_inputs_targets_from_sequences(sequences_val)\n",
333 | " inputs_test, targets_test = get_inputs_targets_from_sequences(sequences_test)\n",
334 | "\n",
335 | " # Create datasets\n",
336 | " training_set = dataset_class(inputs_train, targets_train)\n",
337 | " validation_set = dataset_class(inputs_val, targets_val)\n",
338 | " test_set = dataset_class(inputs_test, targets_test)\n",
339 | "\n",
340 | " return training_set, validation_set, test_set\n",
341 | " \n",
342 | "\n",
343 | "training_set, validation_set, test_set = create_datasets(sequences, Dataset)\n",
344 | "\n",
345 | "print(f'We have {len(training_set)} samples in the training set.')\n",
346 | "print(f'We have {len(validation_set)} samples in the validation set.')\n",
347 | "print(f'We have {len(test_set)} samples in the test set.')"
348 | ],
349 | "execution_count": null,
350 | "outputs": []
351 | },
352 | {
353 | "cell_type": "markdown",
354 | "metadata": {
355 | "id": "4xMMSm7Mk2g9"
356 | },
357 | "source": [
358 | "When working with more complex data than what we use in this exercise, creating a PyTorch `DataLoader` on top of the dataset can be beneficial. A data loader is basically a fancy generator/iterator that we can use to abstract away all of the data handling and pre-processing + it's super useful for processing batches of data as well! Data loaders will come in handy later when you start to work on your projects, so be sure to check them out!\n",
359 | "\n",
360 | "For more information on how to use datasets and data loaders in PyTorch, [consult the official guide](https://pytorch.org/tutorials/beginner/data_loading_tutorial.html)."
361 | ]
362 | },
363 | {
364 | "cell_type": "markdown",
365 | "metadata": {
366 | "id": "Dzmryk72k2g-"
367 | },
368 | "source": [
369 | "## One-hot encodings"
370 | ]
371 | },
372 | {
373 | "cell_type": "markdown",
374 | "metadata": {
375 | "id": "abRN9f8Xk2g_"
376 | },
377 | "source": [
378 | "We now create a simple function that returns the one-hot encoded representation of a given index of a word in our vocabulary. Notice that the shape of the one-hot encoding is equal to the entire vocabulary (which can be huge!). Additionally, we define a function to automatically one-hot encode a sentence."
379 | ]
380 | },
381 | {
382 | "cell_type": "code",
383 | "metadata": {
384 | "id": "IZruCIHJk2hB"
385 | },
386 | "source": [
387 | "def one_hot_encode(idx, vocab_size):\n",
388 | " \"\"\"\n",
389 | " One-hot encodes a single word given its index and the size of the vocabulary.\n",
390 | " \n",
391 | " Args:\n",
392 | " `idx`: the index of the given word\n",
393 | " `vocab_size`: the size of the vocabulary\n",
394 | " \n",
395 | " Returns a 1-D numpy array of length `vocab_size`.\n",
396 | " \"\"\"\n",
397 | " # Initialize the encoded array\n",
398 | " one_hot = np.zeros(vocab_size)\n",
399 | " \n",
400 | " # Set the appropriate element to one\n",
401 | " one_hot[idx] = 1.0\n",
402 | "\n",
403 | " return one_hot\n",
404 | "\n",
405 | "\n",
406 | "def one_hot_encode_sequence(sequence, vocab_size):\n",
407 | " \"\"\"\n",
408 | " One-hot encodes a sequence of words given a fixed vocabulary size.\n",
409 | " \n",
410 | " Args:\n",
411 | " `sentence`: a list of words to encode\n",
412 | " `vocab_size`: the size of the vocabulary\n",
413 | " \n",
414 | " Returns a 3-D numpy array of shape (num words, vocab size, 1).\n",
415 | " \"\"\"\n",
416 | " # Encode each word in the sentence\n",
417 | " encoding = np.array([one_hot_encode(word_to_idx[word], vocab_size) for word in sequence])\n",
418 | "\n",
419 | " # Reshape encoding s.t. it has shape (num words, vocab size, 1)\n",
420 | " encoding = encoding.reshape(encoding.shape[0], encoding.shape[1], 1)\n",
421 | " \n",
422 | " return encoding\n",
423 | "\n",
424 | "\n",
425 | "test_word = one_hot_encode(word_to_idx['a'], vocab_size)\n",
426 | "print(f'Our one-hot encoding of \\'a\\' has shape {test_word.shape}.')\n",
427 | "\n",
428 | "test_sentence = one_hot_encode_sequence(['a', 'b'], vocab_size)\n",
429 | "print(f'Our one-hot encoding of \\'a b\\' has shape {test_sentence.shape}.')"
430 | ],
431 | "execution_count": null,
432 | "outputs": []
433 | },
434 | {
435 | "cell_type": "markdown",
436 | "metadata": {
437 | "id": "erI_MXvKk2hG"
438 | },
439 | "source": [
440 | "Great! Now that we have our one-hot encodings in place, we can move on to the RNNs!"
441 | ]
442 | },
443 | {
444 | "cell_type": "markdown",
445 | "metadata": {
446 | "id": "MA6bxjGWjeSB"
447 | },
448 | "source": [
449 | "# Introduction to Recurrent Neural Networks (RNN)\n",
450 | "\n",
451 | "Reading material: [blog post](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) and (optionally) [this lecture](https://www.youtube.com/watch?v=iWea12EAu6U&list=PLoROMvodv4rOhcuXMZkNm7j3fVwBBY42z).\n",
452 | "\n",
453 | "___\n",
454 | "\n",
455 | "A recurrent neural network (RNN) is a type of neural network that has been succesful in modelling sequential data, e.g. language, speech, protein sequences, etc.\n",
456 | "\n",
457 | "A RNN performs its computations in a cyclic manner, where the same computation is applied to every sample of a given sequence.\n",
458 | "The idea is that the network should be able to use the previous computations as some form of memory and apply this to future computations.\n",
459 | "An image may best explain how this is to be understood,\n",
460 | "\n",
461 | "\n",
462 | "\n",
463 | "\n",
464 | "where it the network contains the following elements:\n",
465 | "\n",
466 | "- $x$ is the input sequence of samples, \n",
467 | "- $U$ is a weight matrix applied to the given input sample,\n",
468 | "- $V$ is a weight matrix used for the recurrent computation in order to pass memory along the sequence,\n",
469 | "- $W$ is a weight matrix used to compute the output of the every timestep (given that every timestep requires an output),\n",
470 | "- $h$ is the hidden state (the network's memory) for a given time step, and\n",
471 | "- $o$ is the resulting output.\n",
472 | "\n",
473 | "When the network is unrolled as shown, it is easier to refer to a timestep, $t$.\n",
474 | "We have the following computations through the network:\n",
475 | "\n",
476 | "- $h_t = f(U\\,{x_t} + V\\,{h_{t-1}})$, where $f$ is a non-linear activation function, e.g. $\\mathrm{tanh}$.\n",
477 | "- $o_t = W\\,{h_t}$\n",
478 | "\n",
479 | "When we are doing language modelling using a cross-entropy loss, we additionally apply the softmax function to the output $o_{t}$:\n",
480 | "\n",
481 | "- $\\hat{y}_t = \\mathrm{softmax}(o_{t})$"
482 | ]
483 | },
484 | {
485 | "cell_type": "markdown",
486 | "metadata": {
487 | "id": "GuvwbvsGz9KE"
488 | },
489 | "source": [
490 | "## Implementing an RNN"
491 | ]
492 | },
493 | {
494 | "cell_type": "markdown",
495 | "metadata": {
496 | "id": "20WtL0hak2hJ"
497 | },
498 | "source": [
499 | "We will implement the forward pass, backward pass, optimization and training loop for an RNN in numpy so that you can get familiar with the recurrent nature of RNNs. Later, we will go back to PyTorch and appreciate how convenient the implementation becomes!"
500 | ]
501 | },
502 | {
503 | "cell_type": "markdown",
504 | "metadata": {
505 | "id": "oBYpnqINk2hK"
506 | },
507 | "source": [
508 | "Let's first define the necessary model parameters. Recall that an $n \\times m$ weight matrix maps $\\mathbb{R}^{m} \\rightarrow \\mathbb{R}^{n}$."
509 | ]
510 | },
511 | {
512 | "cell_type": "code",
513 | "metadata": {
514 | "id": "m6Q8gTJ0k2hK"
515 | },
516 | "source": [
517 | "hidden_size = 50 # Number of dimensions in the hidden state\n",
518 | "vocab_size = len(word_to_idx) # Size of the vocabulary used\n",
519 | "\n",
520 | "def init_orthogonal(param):\n",
521 | " \"\"\"\n",
522 | " Initializes weight parameters orthogonally.\n",
523 | " This is a common initiailization for recurrent neural networks.\n",
524 | " \n",
525 | " Refer to this paper for an explanation of this initialization:\n",
526 | " https://arxiv.org/abs/1312.6120\n",
527 | " \"\"\"\n",
528 | " if param.ndim < 2:\n",
529 | " raise ValueError(\"Only parameters with 2 or more dimensions are supported.\")\n",
530 | "\n",
531 | " rows, cols = param.shape\n",
532 | " \n",
533 | " new_param = np.random.randn(rows, cols)\n",
534 | " \n",
535 | " if rows < cols:\n",
536 | " new_param = new_param.T\n",
537 | " \n",
538 | " # Compute QR factorization\n",
539 | " q, r = np.linalg.qr(new_param)\n",
540 | " \n",
541 | " # Make Q uniform according to https://arxiv.org/pdf/math-ph/0609050.pdf\n",
542 | " d = np.diag(r, 0)\n",
543 | " ph = np.sign(d)\n",
544 | " q *= ph\n",
545 | "\n",
546 | " if rows < cols:\n",
547 | " q = q.T\n",
548 | " \n",
549 | " new_param = q\n",
550 | " \n",
551 | " return new_param\n",
552 | "\n",
553 | "\n",
554 | "def init_rnn(hidden_size, vocab_size):\n",
555 | " \"\"\"\n",
556 | " Initializes our recurrent neural network.\n",
557 | " \n",
558 | " Args:\n",
559 | " `hidden_size`: the dimensions of the hidden state\n",
560 | " `vocab_size`: the dimensions of our vocabulary\n",
561 | " \"\"\"\n",
562 | " # Weight matrix (input to hidden state)\n",
563 | " # YOUR CODE HERE!\n",
564 | " U = np.zeros((, ))\n",
565 | "\n",
566 | " # Weight matrix (recurrent computation)\n",
567 | " # YOUR CODE HERE!\n",
568 | " V = np.zeros((, ))\n",
569 | "\n",
570 | " # Weight matrix (hidden state to output)\n",
571 | " # YOUR CODE HERE!\n",
572 | " W = np.zeros((, ))\n",
573 | "\n",
574 | " # Bias (hidden state)\n",
575 | " # YOUR CODE HERE!\n",
576 | " b_hidden = np.zeros((, ))\n",
577 | "\n",
578 | " # Bias (output)\n",
579 | " # YOUR CODE HERE!\n",
580 | " b_out = np.zeros((, ))\n",
581 | " \n",
582 | " # Initialize weights\n",
583 | " U = init_orthogonal(U)\n",
584 | " V = init_orthogonal(V)\n",
585 | " W = init_orthogonal(W)\n",
586 | " \n",
587 | " # Return parameters as a tuple\n",
588 | " return U, V, W, b_hidden, b_out\n",
589 | "\n",
590 | "\n",
591 | "params = init_rnn(hidden_size=hidden_size, vocab_size=vocab_size)\n",
592 | "print('U:', params[0].shape)\n",
593 | "print('V:', params[1].shape)\n",
594 | "print('W:', params[2].shape)\n",
595 | "print('b_hidden:', params[3].shape)\n",
596 | "print('b_out:', params[4].shape)\n",
597 | "\n",
598 | "for param in params:\n",
599 | " assert param.ndim == 2, \\\n",
600 | " 'all parameters should be 2-dimensional '\\\n",
601 | " '(hint: a dimension can simply have size 1)'"
602 | ],
603 | "execution_count": null,
604 | "outputs": []
605 | },
606 | {
607 | "cell_type": "markdown",
608 | "metadata": {
609 | "id": "yolo5dKrk2hR"
610 | },
611 | "source": [
612 | "## Exercise B:"
613 | ]
614 | },
615 | {
616 | "cell_type": "markdown",
617 | "metadata": {
618 | "id": "SIyQO1S3k2hS"
619 | },
620 | "source": [
621 | "Define the appropriate shape of the weights and biases in the `init_rnn` function.\n",
622 | "\n",
623 | "You only have to worry about the weight and bias dimensions; you can leave the scaling as is. Refer to the equations and figure above if you're in doubt. Note that `np.zeros()` expects a tuple as its first argument (shape)."
624 | ]
625 | },
626 | {
627 | "cell_type": "markdown",
628 | "metadata": {
629 | "id": "KFH6jRXik2hV"
630 | },
631 | "source": [
632 | "### Function definitions"
633 | ]
634 | },
635 | {
636 | "cell_type": "markdown",
637 | "metadata": {
638 | "id": "nRtByep8k2hW"
639 | },
640 | "source": [
641 | "Below we have defined the `sigmoid`, `tanh` and `softmax` functions for you. You might need them in a bit!"
642 | ]
643 | },
644 | {
645 | "cell_type": "markdown",
646 | "metadata": {
647 | "id": "rxKigMDdk2hY"
648 | },
649 | "source": [
650 | "#### Sigmoid activation"
651 | ]
652 | },
653 | {
654 | "cell_type": "markdown",
655 | "metadata": {
656 | "id": "Qe2sVT0Hk2hY"
657 | },
658 | "source": [
659 | "$\\sigma(x) = \\frac{1}{1 + e^{-x}}$"
660 | ]
661 | },
662 | {
663 | "cell_type": "code",
664 | "metadata": {
665 | "id": "sKw9FNa2k2hZ"
666 | },
667 | "source": [
668 | "def sigmoid(x, derivative=False):\n",
669 | " \"\"\"\n",
670 | " Computes the element-wise sigmoid activation function for an array x.\n",
671 | "\n",
672 | " Args:\n",
673 | " `x`: the array where the function is applied\n",
674 | " `derivative`: if set to True will return the derivative instead of the forward pass\n",
675 | " \"\"\"\n",
676 | " x_safe = x + 1e-12\n",
677 | " f = 1 / (1 + np.exp(-x_safe))\n",
678 | " \n",
679 | " if derivative: # Return the derivative of the function evaluated at x\n",
680 | " return f * (1 - f)\n",
681 | " else: # Return the forward pass of the function at x\n",
682 | " return f"
683 | ],
684 | "execution_count": null,
685 | "outputs": []
686 | },
687 | {
688 | "cell_type": "markdown",
689 | "metadata": {
690 | "id": "QgGTIbNpk2hd"
691 | },
692 | "source": [
693 | "#### Hyperbolic Tangent activation"
694 | ]
695 | },
696 | {
697 | "cell_type": "markdown",
698 | "metadata": {
699 | "id": "s9-qTul2k2he"
700 | },
701 | "source": [
702 | "$\\tanh{x} = \\frac{e^{x} - e^{-x}}{e^{x} + e^{-x}}$"
703 | ]
704 | },
705 | {
706 | "cell_type": "code",
707 | "metadata": {
708 | "id": "NJPhICbKk2hf"
709 | },
710 | "source": [
711 | "def tanh(x, derivative=False):\n",
712 | " \"\"\"\n",
713 | " Computes the element-wise tanh activation function for an array x.\n",
714 | "\n",
715 | " Args:\n",
716 | " `x`: the array where the function is applied\n",
717 | " `derivative`: if set to True will return the derivative instead of the forward pass\n",
718 | " \"\"\"\n",
719 | " x_safe = x + 1e-12\n",
720 | " f = (np.exp(x_safe)-np.exp(-x_safe))/(np.exp(x_safe)+np.exp(-x_safe))\n",
721 | " \n",
722 | " if derivative: # Return the derivative of the function evaluated at x\n",
723 | " return 1-f**2\n",
724 | " else: # Return the forward pass of the function at x\n",
725 | " return f"
726 | ],
727 | "execution_count": null,
728 | "outputs": []
729 | },
730 | {
731 | "cell_type": "markdown",
732 | "metadata": {
733 | "id": "OR4wltaGk2hk"
734 | },
735 | "source": [
736 | "#### Softmax"
737 | ]
738 | },
739 | {
740 | "cell_type": "markdown",
741 | "metadata": {
742 | "id": "uDVaozqLk2hl"
743 | },
744 | "source": [
745 | "$\\mathrm{softmax}(x) = \\frac{e^{x_{i}}}{\\sum_{j=1}^{K} e^{x_{j}}} \\text { for } i=1, \\ldots, K \\text { and } \\mathbf{x}=\\left(x_{1}, \\ldots, x_{K}\\right) \\in \\mathbb{R}^{K}$"
746 | ]
747 | },
748 | {
749 | "cell_type": "code",
750 | "metadata": {
751 | "id": "c-3VX41qk2hn"
752 | },
753 | "source": [
754 | "def softmax(x, derivative=False):\n",
755 | " \"\"\"\n",
756 | " Computes the softmax for an array x.\n",
757 | " \n",
758 | " Args:\n",
759 | " `x`: the array where the function is applied\n",
760 | " `derivative`: if set to True will return the derivative instead of the forward pass\n",
761 | " \"\"\"\n",
762 | " x_safe = x + 1e-12\n",
763 | " f = np.exp(x_safe) / np.sum(np.exp(x_safe))\n",
764 | " \n",
765 | " if derivative: # Return the derivative of the function evaluated at x\n",
766 | " pass # We will not need this one\n",
767 | " else: # Return the forward pass of the function at x\n",
768 | " return f"
769 | ],
770 | "execution_count": null,
771 | "outputs": []
772 | },
773 | {
774 | "cell_type": "markdown",
775 | "metadata": {
776 | "id": "WFUtyOtesrfe"
777 | },
778 | "source": [
779 | "### Implement the forward pass"
780 | ]
781 | },
782 | {
783 | "cell_type": "markdown",
784 | "metadata": {
785 | "id": "xfRLRqrWk2hs"
786 | },
787 | "source": [
788 | "Now that we have all the definitions in place, we can start to implement a forward pass."
789 | ]
790 | },
791 | {
792 | "cell_type": "code",
793 | "metadata": {
794 | "id": "RNZ3IVjs4jFB"
795 | },
796 | "source": [
797 | "def forward_pass(inputs, hidden_state, params):\n",
798 | " \"\"\"\n",
799 | " Computes the forward pass of a vanilla RNN.\n",
800 | " \n",
801 | " Args:\n",
802 | " `inputs`: sequence of inputs to be processed\n",
803 | " `hidden_state`: an already initialized hidden state\n",
804 | " `params`: the parameters of the RNN\n",
805 | " \"\"\"\n",
806 | " # First we unpack our parameters\n",
807 | " U, V, W, b_hidden, b_out = params\n",
808 | " \n",
809 | " # Create a list to store outputs and hidden states\n",
810 | " outputs, hidden_states = [], []\n",
811 | " \n",
812 | " # For each element in input sequence\n",
813 | " for t in range(len(inputs)):\n",
814 | "\n",
815 | " # Compute new hidden state\n",
816 | " # YOUR CODE HERE!\n",
817 | " hidden_state = \n",
818 | "\n",
819 | " # Compute output\n",
820 | " # YOUR CODE HERE!\n",
821 | " out = \n",
822 | " \n",
823 | " # Save results and continue\n",
824 | " outputs.append(out)\n",
825 | " hidden_states.append(hidden_state.copy())\n",
826 | " \n",
827 | " return outputs, hidden_states\n",
828 | "\n",
829 | "\n",
830 | "# Get first sequence in training set\n",
831 | "test_input_sequence, test_target_sequence = training_set[0]\n",
832 | "\n",
833 | "# One-hot encode input and target sequence\n",
834 | "test_input = one_hot_encode_sequence(test_input_sequence, vocab_size)\n",
835 | "test_target = one_hot_encode_sequence(test_target_sequence, vocab_size)\n",
836 | "\n",
837 | "# Initialize hidden state as zeros\n",
838 | "hidden_state = np.zeros((hidden_size, 1))\n",
839 | "\n",
840 | "# Now let's try out our new function\n",
841 | "outputs, hidden_states = forward_pass(test_input, hidden_state, params)\n",
842 | "\n",
843 | "print('Input sequence:')\n",
844 | "print(test_input_sequence)\n",
845 | "\n",
846 | "print('\\nTarget sequence:')\n",
847 | "print(test_target_sequence)\n",
848 | "\n",
849 | "print('\\nPredicted sequence:')\n",
850 | "print([idx_to_word[np.argmax(output)] for output in outputs])"
851 | ],
852 | "execution_count": null,
853 | "outputs": []
854 | },
855 | {
856 | "cell_type": "markdown",
857 | "metadata": {
858 | "id": "WvE8zu8Ck2hx"
859 | },
860 | "source": [
861 | "## Exercise C:"
862 | ]
863 | },
864 | {
865 | "cell_type": "markdown",
866 | "metadata": {
867 | "id": "aDk85eRTk2hx"
868 | },
869 | "source": [
870 | "Implement the forward pass in the code above. Use $\\tanh{x}$ as the non-linear activation function $f$. You can use `np.dot()` to compute dot products. Refer to the equations and the figure if you're in doubt."
871 | ]
872 | },
873 | {
874 | "cell_type": "markdown",
875 | "metadata": {
876 | "id": "Vug6QCohsx_S"
877 | },
878 | "source": [
879 | "### Implement the backward pass"
880 | ]
881 | },
882 | {
883 | "cell_type": "markdown",
884 | "metadata": {
885 | "id": "M4unVioMk2h0"
886 | },
887 | "source": [
888 | "It's now time to implement the backward pass. This can be a bit tricky so it may be helpful to take another look at the RNN equations, figure and your forward pass implementation. Note that (depending on your implementation) you may sometimes need to transpose using `np.transpose()` or simply `.T`."
889 | ]
890 | },
891 | {
892 | "cell_type": "code",
893 | "metadata": {
894 | "id": "roXK0HW6s2Z_"
895 | },
896 | "source": [
897 | "def clip_gradient_norm(grads, max_norm=0.25):\n",
898 | " \"\"\"\n",
899 | " Clips gradients to have a maximum norm of `max_norm`.\n",
900 | " This is to prevent the exploding gradients problem.\n",
901 | " \"\"\" \n",
902 | " # Set the maximum of the norm to be of type float\n",
903 | " max_norm = float(max_norm)\n",
904 | " total_norm = 0\n",
905 | " \n",
906 | " # Calculate the L2 norm squared for each gradient and add them to the total norm\n",
907 | " for grad in grads:\n",
908 | " grad_norm = np.sum(np.power(grad, 2))\n",
909 | " total_norm += grad_norm\n",
910 | " \n",
911 | " total_norm = np.sqrt(total_norm)\n",
912 | " \n",
913 | " # Calculate clipping coeficient\n",
914 | " clip_coef = max_norm / (total_norm + 1e-6)\n",
915 | " \n",
916 | " # If the total norm is larger than the maximum allowable norm, then clip the gradient\n",
917 | " if clip_coef < 1:\n",
918 | " for grad in grads:\n",
919 | " grad *= clip_coef\n",
920 | " \n",
921 | " return grads\n",
922 | "\n",
923 | "\n",
924 | "def backward_pass(inputs, outputs, hidden_states, targets, params):\n",
925 | " \"\"\"\n",
926 | " Computes the backward pass of a vanilla RNN.\n",
927 | " \n",
928 | " Args:\n",
929 | " `inputs`: sequence of inputs to be processed\n",
930 | " `outputs`: sequence of outputs from the forward pass\n",
931 | " `hidden_states`: sequence of hidden_states from the forward pass\n",
932 | " `targets`: sequence of targets\n",
933 | " `params`: the parameters of the RNN\n",
934 | " \"\"\"\n",
935 | " # First we unpack our parameters\n",
936 | " U, V, W, b_hidden, b_out = params\n",
937 | " \n",
938 | " # Initialize gradients as zero\n",
939 | " d_U, d_V, d_W = np.zeros_like(U), np.zeros_like(V), np.zeros_like(W)\n",
940 | " d_b_hidden, d_b_out = np.zeros_like(b_hidden), np.zeros_like(b_out)\n",
941 | " \n",
942 | " # Keep track of hidden state derivative and loss\n",
943 | " d_h_next = np.zeros_like(hidden_states[0])\n",
944 | " loss = 0\n",
945 | " \n",
946 | " # For each element in output sequence\n",
947 | " # NB: We iterate backwards s.t. t = N, N-1, ... 1, 0\n",
948 | " for t in reversed(range(len(outputs))):\n",
949 | "\n",
950 | " # Compute cross-entropy loss (as a scalar)\n",
951 | " # When taking logarithms, it's a good idea to add a small constant (e.g. 1e-9)\n",
952 | " # YOUR CODE HERE!\n",
953 | " loss += \n",
954 | " \n",
955 | " # Backpropagate into output (derivative of cross-entropy)\n",
956 | " # If you're confused about this step, see this link for an explanation:\n",
957 | " # http://cs231n.github.io/neural-networks-case-study/#grad\n",
958 | " d_o = outputs[t].copy()\n",
959 | " d_o[np.argmax(targets[t])] -= 1\n",
960 | " \n",
961 | " # Backpropagate into W\n",
962 | " # YOUR CODE HERE!\n",
963 | " d_W += \n",
964 | " d_b_out += d_o\n",
965 | " \n",
966 | " # Backpropagate into h\n",
967 | " d_h = np.dot(W.T, d_o) + d_h_next\n",
968 | " \n",
969 | " # Backpropagate through non-linearity\n",
970 | " # (we assume tanh is used here)\n",
971 | " d_f = (1 - hidden_states[t]**2) * d_h\n",
972 | " d_b_hidden += d_f\n",
973 | " \n",
974 | " # Backpropagate into U\n",
975 | " # YOUR CODE HERE!\n",
976 | " d_U += \n",
977 | " \n",
978 | " # Backpropagate into V\n",
979 | " # YOUR CODE HERE!\n",
980 | " d_V += \n",
981 | " d_h_next = np.dot(V.T, d_f)\n",
982 | " \n",
983 | " # Pack gradients\n",
984 | " grads = d_U, d_V, d_W, d_b_hidden, d_b_out \n",
985 | " \n",
986 | " # Clip gradients\n",
987 | " grads = clip_gradient_norm(grads)\n",
988 | " \n",
989 | " return loss, grads\n",
990 | "\n",
991 | "\n",
992 | "loss, grads = backward_pass(test_input, outputs, hidden_states, test_target, params)\n",
993 | "\n",
994 | "print('We get a loss of:')\n",
995 | "print(loss)"
996 | ],
997 | "execution_count": null,
998 | "outputs": []
999 | },
1000 | {
1001 | "cell_type": "markdown",
1002 | "metadata": {
1003 | "id": "4OguQafQk2h5"
1004 | },
1005 | "source": [
1006 | "## Exercise D:"
1007 | ]
1008 | },
1009 | {
1010 | "cell_type": "markdown",
1011 | "metadata": {
1012 | "id": "ezSRiVJzk2h5"
1013 | },
1014 | "source": [
1015 | "Implement the missing code in the backward pass above using a cross-entropy loss and $\\tanh{x}$ as non-linear activation function $f$. Refer to previous weeks for the definition of cross-entropy, see week 1 exercise i) for an explanation of its derivative, or follow [this link](http://cs231n.github.io/neural-networks-case-study/#grad) for a hint.\n",
1016 | "\n",
1017 | "**Note:** to compute a cross-entropy loss that is independent of the number of target classes, it is common to divide the loss by the number of targets (i.e. take the mean rather than a sum). It is optional whether you do this or not.\n",
1018 | "\n",
1019 | "**Hint:**\n",
1020 | "To complete the above backward pass implementation, we need to compute the partial derivatives\n",
1021 | "$\n",
1022 | "\\frac{\\partial E}{\\partial W},~\\frac{\\partial E}{\\partial U},~\\frac{\\partial E}{\\partial V}\n",
1023 | "$. Recall though, that RNNs are recurrent and the weights $W,~U,~V$ are shared across time, i.e. we do not have separate weights for each time step. Therefore, to compute e.g. the partial derivative $\\frac{\\partial E}{\\partial W}$, we need to 1) sum up across time, and 2) apply the chain rule:\n",
1024 | "\n",
1025 | "$$\\frac{\\partial E}{\\partial W} = \\sum_{t} \\frac{\\partial E}{\\partial W_{t}} = \\sum_{t} \\frac{\\partial E}{\\partial o_{t}} \\frac{\\partial o_{t}}{\\partial W_{t}}\\,,$$\n",
1026 | "where $o_{t}$ is the resulting output (logits) at time step $t$, as previously covered in week 1 and 2.\n",
1027 | "\n",
1028 | "Now, recall the definition of the RNN forward pass. We have the following computations through the network:\n",
1029 | "\n",
1030 | "- $h_t = f(U\\,{x_t} + V\\,{h_{t-1}})$, where $f$ usually is an activation function, e.g. $\\mathrm{tanh}$.\n",
1031 | "- $o_t = W\\,{h_t}$\n",
1032 | "- $\\hat{y}_t = \\mathrm{softmax}(o_{t})$\n",
1033 | "\n",
1034 | "where\n",
1035 | "- $U$ is a weight matrix applied to the given input sample,\n",
1036 | "- $V$ is a weight matrix used for the recurrent computation in order to pass memory along the sequence,\n",
1037 | "- $W$ is a weight matrix used to compute the output of the every timestep (given that every timestep requires an output), and\n",
1038 | "- $h$ is the hidden state (the network's memory) for a given time step.\n",
1039 | "\n",
1040 | "From week 1 (exercise i) we have that\n",
1041 | "$$\\frac{\\partial E}{\\partial o_{t}} = \\hat{y}_{t} - y_{t}\\,,$$\n",
1042 | "where $\\hat{y}_{t}$ is a softmax distribution over model outputs $o_{t}$ at time $t$, and $y_{t}$ is the target label at time $t$. In the above code, this corresponds to\n",
1043 | "```\n",
1044 | "d_o = outputs[t].copy()\n",
1045 | "d_o[np.argmax(targets[t])] -= 1\n",
1046 | "```\n",
1047 | "where `outputs[t]` is the normalized output $\\hat{y}_{t}$, and `targets[t]` is a one-hot encoded target.\n",
1048 | "\n",
1049 | "Now, to compute $\\frac{\\partial E}{\\partial o_{t}} \\frac{\\partial o_{t}}{\\partial W_{t}}$ (denoted `d_W` in the code) we need to determine $\\frac{\\partial o_{t}}{\\partial W_{t}}$ using the function definitions further up.\n",
1050 | "\n",
1051 | "Likewise, we need to determine $\\frac{\\partial E}{\\partial U_{t}},~\\frac{\\partial E}{\\partial V_{t}}$ using the chain rule, where the intermediate steps $\\frac{\\partial E}{\\partial h_{t}}\\,\\frac{\\partial h_{t}}{\\partial f_{t}}$ are pre-computed for you in the code as `d_f`. To compute $\\frac{\\partial E}{\\partial U_{t}},~\\frac{\\partial E}{\\partial V_{t}}$ you will therefore need to determine $\\frac{\\partial f_{t}}{\\partial U_{t}}$ and $\\frac{\\partial f_{t}}{\\partial V_{t}}$, respectively, using the function definitions.\n",
1052 | "\n",
1053 | "For further explanation, [follow this link](https://www.deeplearningbook.org/contents/rnn.html) (section 10.2.2).\n"
1054 | ]
1055 | },
1056 | {
1057 | "cell_type": "markdown",
1058 | "metadata": {
1059 | "id": "Pxi7sbLus82R"
1060 | },
1061 | "source": [
1062 | "### Optimization"
1063 | ]
1064 | },
1065 | {
1066 | "cell_type": "markdown",
1067 | "metadata": {
1068 | "id": "NkLXBmU0k2h7"
1069 | },
1070 | "source": [
1071 | "Now that we can do forward passes and compute gradients with backpropagation, we're ready to train our network. For that we will need an optimizer. A common and easy to implement optimization method is stochastic gradient descent (SGD), which has the update rule: $\\theta_{n+1} = \\theta_{n} - \\eta \\frac{\\partial E}{\\partial \\theta_{n}}$, where $\\eta$ is the learning rate and $E$ is our cost function. This is essentially what's going on behind the scenes when you run `optimizer.step()` in PyTorch using the SGD optimizer. If you want to learn more about optimization in a deep learning context, [this is a great starting point](https://arxiv.org/abs/1609.04747)."
1072 | ]
1073 | },
1074 | {
1075 | "cell_type": "code",
1076 | "metadata": {
1077 | "id": "N4yTZYkBtAVr"
1078 | },
1079 | "source": [
1080 | "def update_parameters(params, grads, lr=1e-3):\n",
1081 | " # Take a step\n",
1082 | " for param, grad in zip(params, grads):\n",
1083 | " param -= lr * grad\n",
1084 | " \n",
1085 | " return params"
1086 | ],
1087 | "execution_count": null,
1088 | "outputs": []
1089 | },
1090 | {
1091 | "cell_type": "markdown",
1092 | "metadata": {
1093 | "id": "K7ArhViPtEck"
1094 | },
1095 | "source": [
1096 | "### Training loop"
1097 | ]
1098 | },
1099 | {
1100 | "cell_type": "markdown",
1101 | "metadata": {
1102 | "id": "dOZlMx9bk2iB"
1103 | },
1104 | "source": [
1105 | "We need to define a full training loop with a forward pass, backward pass, optimization step and validation. Training will take approximately 5 minutes, so you might want to read on while the notebook is running."
1106 | ]
1107 | },
1108 | {
1109 | "cell_type": "code",
1110 | "metadata": {
1111 | "id": "YMcg90qYs6kW",
1112 | "scrolled": false
1113 | },
1114 | "source": [
1115 | "import matplotlib.pyplot as plt\n",
1116 | "%matplotlib inline\n",
1117 | "\n",
1118 | "# Hyper-parameters\n",
1119 | "num_epochs = 1000\n",
1120 | "\n",
1121 | "# Initialize a new network\n",
1122 | "params = init_rnn(hidden_size=hidden_size, vocab_size=vocab_size)\n",
1123 | "\n",
1124 | "# Initialize hidden state as zeros\n",
1125 | "hidden_state = np.zeros((hidden_size, 1))\n",
1126 | "\n",
1127 | "# Track loss\n",
1128 | "training_loss, validation_loss = [], []\n",
1129 | "\n",
1130 | "# For each epoch\n",
1131 | "for i in range(num_epochs):\n",
1132 | " \n",
1133 | " # Track loss\n",
1134 | " epoch_training_loss = 0\n",
1135 | " epoch_validation_loss = 0\n",
1136 | " \n",
1137 | " # For each sentence in validation set\n",
1138 | " for inputs, targets in validation_set:\n",
1139 | " \n",
1140 | " # One-hot encode input and target sequence\n",
1141 | " inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
1142 | " targets_one_hot = one_hot_encode_sequence(targets, vocab_size)\n",
1143 | " \n",
1144 | " # Re-initialize hidden state\n",
1145 | " hidden_state = np.zeros_like(hidden_state)\n",
1146 | "\n",
1147 | " # Forward pass\n",
1148 | " # YOUR CODE HERE!\n",
1149 | " outputs, hidden_states = \n",
1150 | "\n",
1151 | " # Backward pass\n",
1152 | " # YOUR CODE HERE!\n",
1153 | " loss, _ = \n",
1154 | " \n",
1155 | " # Update loss\n",
1156 | " epoch_validation_loss += loss\n",
1157 | " \n",
1158 | " # For each sentence in training set\n",
1159 | " for inputs, targets in training_set:\n",
1160 | " \n",
1161 | " # One-hot encode input and target sequence\n",
1162 | " inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
1163 | " targets_one_hot = one_hot_encode_sequence(targets, vocab_size)\n",
1164 | " \n",
1165 | " # Re-initialize hidden state\n",
1166 | " hidden_state = np.zeros_like(hidden_state)\n",
1167 | "\n",
1168 | " # Forward pass\n",
1169 | " # YOUR CODE HERE!\n",
1170 | " outputs, hidden_states = \n",
1171 | "\n",
1172 | " # Backward pass\n",
1173 | " # YOUR CODE HERE!\n",
1174 | " loss, grads = \n",
1175 | " \n",
1176 | " if np.isnan(loss):\n",
1177 | " raise ValueError('Gradients have vanished/exploded!')\n",
1178 | " \n",
1179 | " # Update parameters\n",
1180 | " # YOUR CODE HERE!\n",
1181 | " params = \n",
1182 | " \n",
1183 | " # Update loss\n",
1184 | " epoch_training_loss += loss\n",
1185 | " \n",
1186 | " # Save loss for plot\n",
1187 | " training_loss.append(epoch_training_loss/len(training_set))\n",
1188 | " validation_loss.append(epoch_validation_loss/len(validation_set))\n",
1189 | "\n",
1190 | " # Print loss every 100 epochs\n",
1191 | " if i % 100 == 0:\n",
1192 | " print(f'Epoch {i}, training loss: {training_loss[-1]}, validation loss: {validation_loss[-1]}')\n",
1193 | "\n",
1194 | "\n",
1195 | "# Get first sentence in test set\n",
1196 | "inputs, targets = test_set[1]\n",
1197 | "\n",
1198 | "# One-hot encode input and target sequence\n",
1199 | "inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
1200 | "targets_one_hot = one_hot_encode_sequence(targets, vocab_size)\n",
1201 | "\n",
1202 | "# Initialize hidden state as zeros\n",
1203 | "hidden_state = np.zeros((hidden_size, 1))\n",
1204 | "\n",
1205 | "# Forward pass\n",
1206 | "outputs, hidden_states = forward_pass(inputs_one_hot, hidden_state, params)\n",
1207 | "output_sentence = [idx_to_word[np.argmax(output)] for output in outputs]\n",
1208 | "print('Input sentence:')\n",
1209 | "print(inputs)\n",
1210 | "\n",
1211 | "print('\\nTarget sequence:')\n",
1212 | "print(targets)\n",
1213 | "\n",
1214 | "print('\\nPredicted sequence:')\n",
1215 | "print([idx_to_word[np.argmax(output)] for output in outputs])\n",
1216 | "\n",
1217 | "# Plot training and validation loss\n",
1218 | "epoch = np.arange(len(training_loss))\n",
1219 | "plt.figure()\n",
1220 | "plt.plot(epoch, training_loss, 'r', label='Training loss',)\n",
1221 | "plt.plot(epoch, validation_loss, 'b', label='Validation loss')\n",
1222 | "plt.legend()\n",
1223 | "plt.xlabel('Epoch'), plt.ylabel('NLL')\n",
1224 | "plt.show()"
1225 | ],
1226 | "execution_count": null,
1227 | "outputs": []
1228 | },
1229 | {
1230 | "cell_type": "markdown",
1231 | "metadata": {
1232 | "id": "Uo_SNJYlk2iG"
1233 | },
1234 | "source": [
1235 | "## Exercise E:"
1236 | ]
1237 | },
1238 | {
1239 | "cell_type": "markdown",
1240 | "metadata": {
1241 | "id": "Q14DnOhZk2iG"
1242 | },
1243 | "source": [
1244 | "Complete the training loop above and run the training. You can leave the hyper-parameters and network size unchanged.\n",
1245 | "\n",
1246 | "A correct implementation should yield a loss of around **1** (using mean CE) or around **4** (using sum CE) after 1000 epochs. Does it work? If not, try to identify the issue -- perhaps something in the backward pass is not right?"
1247 | ]
1248 | },
1249 | {
1250 | "cell_type": "markdown",
1251 | "metadata": {
1252 | "id": "Nn7QpUZXk2iH"
1253 | },
1254 | "source": [
1255 | "## Extrapolation"
1256 | ]
1257 | },
1258 | {
1259 | "cell_type": "markdown",
1260 | "metadata": {
1261 | "id": "BJIJInBhk2iI"
1262 | },
1263 | "source": [
1264 | "Now that we have trained an RNN, it's time to put it to test. We will provide the network with a starting sentence and let it `freestyle` from there!"
1265 | ]
1266 | },
1267 | {
1268 | "cell_type": "code",
1269 | "metadata": {
1270 | "id": "EOMxSE8Hk2iI"
1271 | },
1272 | "source": [
1273 | "def freestyle(params, sentence='', num_generate=10):\n",
1274 | " \"\"\"\n",
1275 | " Takes in a sentence as a string and outputs a sequence\n",
1276 | " based on the predictions of the RNN.\n",
1277 | " \n",
1278 | " Args:\n",
1279 | " `params`: the parameters of the network\n",
1280 | " `sentence`: string with whitespace-separated tokens\n",
1281 | " `num_generate`: the number of tokens to generate\n",
1282 | " \"\"\"\n",
1283 | " sentence = sentence.split(' ')\n",
1284 | " \n",
1285 | " sentence_one_hot = one_hot_encode_sequence(sentence, vocab_size)\n",
1286 | " \n",
1287 | " # Initialize hidden state as zeros\n",
1288 | " hidden_state = np.zeros((hidden_size, 1))\n",
1289 | "\n",
1290 | " # Generate hidden state for sentence\n",
1291 | " outputs, hidden_states = forward_pass(sentence_one_hot, hidden_state, params)\n",
1292 | " \n",
1293 | " # Output sentence\n",
1294 | " output_sentence = sentence\n",
1295 | " \n",
1296 | " # Append first prediction\n",
1297 | " word = idx_to_word[np.argmax(outputs[-1])] \n",
1298 | " output_sentence.append(word)\n",
1299 | " \n",
1300 | " # Forward pass\n",
1301 | " for i in range(num_generate):\n",
1302 | "\n",
1303 | " # Get the latest prediction and latest hidden state\n",
1304 | " output = outputs[-1]\n",
1305 | " hidden_state = hidden_states[-1]\n",
1306 | " \n",
1307 | " # Reshape our output to match the input shape of our forward pass\n",
1308 | " output = output.reshape(1, output.shape[0], output.shape[1])\n",
1309 | " \n",
1310 | " # Forward pass\n",
1311 | " outputs, hidden_states = forward_pass(output, hidden_state, params)\n",
1312 | " \n",
1313 | " # Compute the index of the most likely word and look up the corresponding word\n",
1314 | " word = idx_to_word[np.argmax(outputs)]\n",
1315 | " \n",
1316 | " output_sentence.append(word)\n",
1317 | " \n",
1318 | " if word == 'EOS':\n",
1319 | " break\n",
1320 | " \n",
1321 | " return output_sentence\n",
1322 | "\n",
1323 | "\n",
1324 | "# Perform freestyle (extrapolation)\n",
1325 | "test_examples = ['a a b', 'a a a a b', 'a a a a a a b', 'a', 'r n n']\n",
1326 | "for i, test_example in enumerate(test_examples):\n",
1327 | " print(f'Example {i}:', test_example)\n",
1328 | " print('Predicted sequence:', freestyle(params, sentence=test_example), end='\\n\\n')"
1329 | ],
1330 | "execution_count": null,
1331 | "outputs": []
1332 | },
1333 | {
1334 | "cell_type": "markdown",
1335 | "metadata": {
1336 | "id": "W8jeDBtFk2iM"
1337 | },
1338 | "source": [
1339 | "## Exercise F:\n",
1340 | "\n",
1341 | "How well does your RNN extrapolate -- does it work as expected? Are there any imperfections? If yes, why could that be?"
1342 | ]
1343 | },
1344 | {
1345 | "cell_type": "markdown",
1346 | "metadata": {
1347 | "id": "oKdqe04-k2iN"
1348 | },
1349 | "source": [
1350 | "## Exercise G (optional):"
1351 | ]
1352 | },
1353 | {
1354 | "cell_type": "markdown",
1355 | "metadata": {
1356 | "id": "C7gp_oS8k2iN"
1357 | },
1358 | "source": [
1359 | "Alter the forward pass, backward pass and training loop to handle batches of samples. You will see great improvements!"
1360 | ]
1361 | },
1362 | {
1363 | "cell_type": "markdown",
1364 | "metadata": {
1365 | "id": "sGeKM44bvISA"
1366 | },
1367 | "source": [
1368 | "# Introduction to the Long Short-Term Memory (LSTM) Cell\n"
1369 | ]
1370 | },
1371 | {
1372 | "cell_type": "markdown",
1373 | "metadata": {
1374 | "id": "X44hQ653vNCj"
1375 | },
1376 | "source": [
1377 | "Reading material: [Christopher Olah's walk-through](http://colah.github.io/posts/2015-08-Understanding-LSTMs/).\n",
1378 | "\n",
1379 | "___\n",
1380 | "\n",
1381 | "\n",
1382 | "A vanilla RNN suffers from [the vanishing gradients problem](http://neuralnetworksanddeeplearning.com/chap5.html#the_vanishing_gradient_problem) which gives challenges in saving memory over longer sequences. To combat these issues the gated hidden units were created. The two most prominent gated hidden units are the Long Short-Term Memory (LSTM) cell and the Gated Recurrent Unit (GRU), both of which have shown increased performance in saving and reusing memory in later timesteps. In this exercise, we will focus on LSTM but you would easily be able to go ahead and implement the GRU as well based on the principles that you learn here.\n",
1383 | "\n",
1384 | "Below is a figure of the LSTM cell:"
1385 | ]
1386 | },
1387 | {
1388 | "cell_type": "markdown",
1389 | "metadata": {
1390 | "id": "5Rgc-g3zwV9f"
1391 | },
1392 | "source": [
1393 | "\n",
1394 | "Source: https://arxiv.org/abs/1412.7828"
1395 | ]
1396 | },
1397 | {
1398 | "cell_type": "markdown",
1399 | "metadata": {
1400 | "id": "ytasZ5cqw4W1"
1401 | },
1402 | "source": [
1403 | "\n",
1404 | "The LSTM cell contains three gates, input, forget, output gates and a memory cell.\n",
1405 | "The output of the LSTM unit is computed with the following functions, where $\\sigma = \\mathrm{softmax}$.\n",
1406 | "We have input gate $i$, forget gate $f$, and output gate $o$ defines as\n",
1407 | "\n",
1408 | "- $i = \\sigma ( W^i [h_{t-1}, x_t])$\n",
1409 | "\n",
1410 | "- $f = \\sigma ( W^f [h_{t-1},x_t])$\n",
1411 | "\n",
1412 | "- $o = \\sigma ( W^o [h_{t-1},x_t])$\n",
1413 | "\n",
1414 | "where $W^i, W^f, W^o$ are weight matrices applied to a concatenated $h_{t-1}$ (hidden state vector) and $x_t$ (input vector) for each respective gate.\n",
1415 | "\n",
1416 | "$h_{t-1}$, from the previous time step along with the current input $x_t$ are used to compute the a candidate $g$\n",
1417 | "\n",
1418 | "- $g = \\mathrm{tanh}( W^g [h_{t-1}, x_t])$\n",
1419 | "\n",
1420 | "The value of the cell's memory, $c_t$, is updated as\n",
1421 | "\n",
1422 | "- $c_t = c_{t-1} \\circ f + g \\circ i$\n",
1423 | "\n",
1424 | "where $c_{t-1}$ is the previous memory, and $\\circ$ refers to element-wise multiplication.\n",
1425 | "\n",
1426 | "The output, $h_t$, is computed as\n",
1427 | "\n",
1428 | "- $h_t = \\mathrm{tanh}(c_t) \\circ o$\n",
1429 | "\n",
1430 | "and it is used for both the timestep's output and the next timestep, whereas $c_t$ is exclusively sent to the next timestep.\n",
1431 | "This makes $c_t$ a memory feature, and is not used directly to compute the output of the timestep."
1432 | ]
1433 | },
1434 | {
1435 | "cell_type": "markdown",
1436 | "metadata": {
1437 | "id": "m8_4RWp3k2iQ"
1438 | },
1439 | "source": [
1440 | "## Initialiation of an LSTM network"
1441 | ]
1442 | },
1443 | {
1444 | "cell_type": "markdown",
1445 | "metadata": {
1446 | "id": "MVn8z4VRk2iR"
1447 | },
1448 | "source": [
1449 | "Similarly to before we will implement the forward pass, backward pass, optimization and training loop, now for an LSTM in numpy. Later, we will go back to PyTorch and appreciate how convenient the implementation becomes."
1450 | ]
1451 | },
1452 | {
1453 | "cell_type": "code",
1454 | "metadata": {
1455 | "id": "w4HETMthk2iS"
1456 | },
1457 | "source": [
1458 | "# Size of concatenated hidden + input vector\n",
1459 | "z_size = hidden_size + vocab_size \n",
1460 | "\n",
1461 | "def init_lstm(hidden_size, vocab_size, z_size):\n",
1462 | " \"\"\"\n",
1463 | " Initializes our LSTM network.\n",
1464 | " \n",
1465 | " Args:\n",
1466 | " `hidden_size`: the dimensions of the hidden state\n",
1467 | " `vocab_size`: the dimensions of our vocabulary\n",
1468 | " `z_size`: the dimensions of the concatenated input \n",
1469 | " \"\"\"\n",
1470 | " # Weight matrix (forget gate)\n",
1471 | " # YOUR CODE HERE!\n",
1472 | " W_f = np.zeros((, ))\n",
1473 | " \n",
1474 | " # Bias for forget gate\n",
1475 | " b_f = np.zeros((hidden_size, 1))\n",
1476 | "\n",
1477 | " # Weight matrix (input gate)\n",
1478 | " # YOUR CODE HERE!\n",
1479 | " W_i = np.zeros((, ))\n",
1480 | " \n",
1481 | " # Bias for input gate\n",
1482 | " b_i = np.zeros((hidden_size, 1))\n",
1483 | "\n",
1484 | " # Weight matrix (candidate)\n",
1485 | " # YOUR CODE HERE!\n",
1486 | " W_g = np.zeros((, ))\n",
1487 | " \n",
1488 | " # Bias for candidate\n",
1489 | " b_g = np.zeros((hidden_size, 1))\n",
1490 | "\n",
1491 | " # Weight matrix of the output gate\n",
1492 | " # YOUR CODE HERE!\n",
1493 | " W_o = np.zeros((, ))\n",
1494 | " \n",
1495 | " # Bias for output gate\n",
1496 | " b_o = np.zeros((hidden_size, 1))\n",
1497 | "\n",
1498 | " # Weight matrix relating the hidden-state to the output\n",
1499 | " # YOUR CODE HERE!\n",
1500 | " W_v = np.zeros((, ))\n",
1501 | " \n",
1502 | " # Bias for logits\n",
1503 | " b_v = np.zeros((vocab_size, 1))\n",
1504 | " \n",
1505 | " # Initialize weights according to https://arxiv.org/abs/1312.6120\n",
1506 | " W_f = init_orthogonal(W_f)\n",
1507 | " W_i = init_orthogonal(W_i)\n",
1508 | " W_g = init_orthogonal(W_g)\n",
1509 | " W_o = init_orthogonal(W_o)\n",
1510 | " W_v = init_orthogonal(W_v)\n",
1511 | "\n",
1512 | " return W_f, W_i, W_g, W_o, W_v, b_f, b_i, b_g, b_o, b_v\n",
1513 | "\n",
1514 | "\n",
1515 | "params = init_lstm(hidden_size=hidden_size, vocab_size=vocab_size, z_size=z_size)\n",
1516 | "print('W_f:', params[0].shape)\n",
1517 | "print('W_i:', params[1].shape)\n",
1518 | "print('W_g:', params[2].shape)\n",
1519 | "print('W_o:', params[3].shape)\n",
1520 | "print('W_v:', params[4].shape)\n",
1521 | "print('b_i:', params[5].shape)\n",
1522 | "print('b_g:', params[6].shape)\n",
1523 | "print('b_o:', params[7].shape)\n",
1524 | "print('b_v:', params[8].shape)\n",
1525 | "\n",
1526 | "for param in params:\n",
1527 | " assert param.ndim == 2, \\\n",
1528 | " 'all parameters should be 2-dimensional '\\\n",
1529 | " '(hint: a dimension can simply have size 1)'"
1530 | ],
1531 | "execution_count": null,
1532 | "outputs": []
1533 | },
1534 | {
1535 | "cell_type": "markdown",
1536 | "metadata": {
1537 | "id": "siljVza0k2iV"
1538 | },
1539 | "source": [
1540 | "## Exercise H:"
1541 | ]
1542 | },
1543 | {
1544 | "cell_type": "markdown",
1545 | "metadata": {
1546 | "id": "uU6Bn1vBk2iW"
1547 | },
1548 | "source": [
1549 | "Implement the initializations in the code above. Refer to the equations and the figure if you're in doubt."
1550 | ]
1551 | },
1552 | {
1553 | "cell_type": "markdown",
1554 | "metadata": {
1555 | "id": "gKu-bfhzk2iY"
1556 | },
1557 | "source": [
1558 | "## Forward pass"
1559 | ]
1560 | },
1561 | {
1562 | "cell_type": "markdown",
1563 | "metadata": {
1564 | "id": "ZBa5XNvEk2iZ"
1565 | },
1566 | "source": [
1567 | "As before we need to bring the equations into pieces of code. This is done in the following function:"
1568 | ]
1569 | },
1570 | {
1571 | "cell_type": "code",
1572 | "metadata": {
1573 | "id": "wGeiytn9k2ia"
1574 | },
1575 | "source": [
1576 | "def forward(inputs, h_prev, C_prev, p):\n",
1577 | " \"\"\"\n",
1578 | " Arguments:\n",
1579 | " x -- your input data at timestep \"t\", numpy array of shape (n_x, m).\n",
1580 | " h_prev -- Hidden state at timestep \"t-1\", numpy array of shape (n_a, m)\n",
1581 | " C_prev -- Memory state at timestep \"t-1\", numpy array of shape (n_a, m)\n",
1582 | " p -- python list containing:\n",
1583 | " W_f -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)\n",
1584 | " b_f -- Bias of the forget gate, numpy array of shape (n_a, 1)\n",
1585 | " W_i -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)\n",
1586 | " b_i -- Bias of the update gate, numpy array of shape (n_a, 1)\n",
1587 | " W_g -- Weight matrix of the first \"tanh\", numpy array of shape (n_a, n_a + n_x)\n",
1588 | " b_g -- Bias of the first \"tanh\", numpy array of shape (n_a, 1)\n",
1589 | " W_o -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)\n",
1590 | " b_o -- Bias of the output gate, numpy array of shape (n_a, 1)\n",
1591 | " W_v -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_v, n_a)\n",
1592 | " b_v -- Bias relating the hidden-state to the output, numpy array of shape (n_v, 1)\n",
1593 | " Returns:\n",
1594 | " z_s, f_s, i_s, g_s, C_s, o_s, h_s, v_s -- lists of size m containing the computations in each forward pass\n",
1595 | " outputs -- prediction at timestep \"t\", numpy array of shape (n_v, m)\n",
1596 | " \"\"\"\n",
1597 | " assert h_prev.shape == (hidden_size, 1)\n",
1598 | " assert C_prev.shape == (hidden_size, 1)\n",
1599 | "\n",
1600 | " # First we unpack our parameters\n",
1601 | " W_f, W_i, W_g, W_o, W_v, b_f, b_i, b_g, b_o, b_v = p\n",
1602 | " \n",
1603 | " # Save a list of computations for each of the components in the LSTM\n",
1604 | " x_s, z_s, f_s, i_s, = [], [] ,[], []\n",
1605 | " g_s, C_s, o_s, h_s = [], [] ,[], []\n",
1606 | " v_s, output_s = [], [] \n",
1607 | " \n",
1608 | " # Append the initial cell and hidden state to their respective lists\n",
1609 | " h_s.append(h_prev)\n",
1610 | " C_s.append(C_prev)\n",
1611 | " \n",
1612 | " for x in inputs:\n",
1613 | " \n",
1614 | " # Concatenate input and hidden state\n",
1615 | " z = np.row_stack((h_prev, x))\n",
1616 | " z_s.append(z)\n",
1617 | " \n",
1618 | " # Calculate forget gate\n",
1619 | " # YOUR CODE HERE!\n",
1620 | " f = \n",
1621 | " f_s.append(f)\n",
1622 | " \n",
1623 | " # Calculate input gate\n",
1624 | " # YOUR CODE HERE!\n",
1625 | " i = \n",
1626 | " i_s.append(i)\n",
1627 | " \n",
1628 | " # Calculate candidate\n",
1629 | " g = tanh(np.dot(W_g, z) + b_g)\n",
1630 | " g_s.append(g)\n",
1631 | " \n",
1632 | " # Calculate memory state\n",
1633 | " # YOUR CODE HERE!\n",
1634 | " C_prev = \n",
1635 | " C_s.append(C_prev)\n",
1636 | " \n",
1637 | " # Calculate output gate\n",
1638 | " # YOUR CODE HERE!\n",
1639 | " o = \n",
1640 | " o_s.append(o)\n",
1641 | " \n",
1642 | " # Calculate hidden state\n",
1643 | " h_prev = o * tanh(C_prev)\n",
1644 | " h_s.append(h_prev)\n",
1645 | "\n",
1646 | " # Calculate logits\n",
1647 | " v = np.dot(W_v, h_prev) + b_v\n",
1648 | " v_s.append(v)\n",
1649 | " \n",
1650 | " # Calculate softmax\n",
1651 | " output = softmax(v)\n",
1652 | " output_s.append(output)\n",
1653 | "\n",
1654 | " return z_s, f_s, i_s, g_s, C_s, o_s, h_s, v_s, output_s\n",
1655 | "\n",
1656 | "\n",
1657 | "# Get first sentence in test set\n",
1658 | "inputs, targets = test_set[1]\n",
1659 | "\n",
1660 | "# One-hot encode input and target sequence\n",
1661 | "inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
1662 | "targets_one_hot = one_hot_encode_sequence(targets, vocab_size)\n",
1663 | "\n",
1664 | "# Initialize hidden state as zeros\n",
1665 | "h = np.zeros((hidden_size, 1))\n",
1666 | "c = np.zeros((hidden_size, 1))\n",
1667 | "\n",
1668 | "# Forward pass\n",
1669 | "z_s, f_s, i_s, g_s, C_s, o_s, h_s, v_s, outputs = forward(inputs_one_hot, h, c, params)\n",
1670 | "\n",
1671 | "output_sentence = [idx_to_word[np.argmax(output)] for output in outputs]\n",
1672 | "print('Input sentence:')\n",
1673 | "print(inputs)\n",
1674 | "\n",
1675 | "print('\\nTarget sequence:')\n",
1676 | "print(targets)\n",
1677 | "\n",
1678 | "print('\\nPredicted sequence:')\n",
1679 | "print([idx_to_word[np.argmax(output)] for output in outputs])"
1680 | ],
1681 | "execution_count": null,
1682 | "outputs": []
1683 | },
1684 | {
1685 | "cell_type": "markdown",
1686 | "metadata": {
1687 | "id": "o4u5sjlKk2id"
1688 | },
1689 | "source": [
1690 | "## Exercise I:"
1691 | ]
1692 | },
1693 | {
1694 | "cell_type": "markdown",
1695 | "metadata": {
1696 | "id": "AhNbDEuMk2id"
1697 | },
1698 | "source": [
1699 | "Complete the implementation of the LSTM forward pass above. Refer to the equations and figures further up if you're in doubt."
1700 | ]
1701 | },
1702 | {
1703 | "cell_type": "markdown",
1704 | "metadata": {
1705 | "id": "G-6tLfsuk2ie"
1706 | },
1707 | "source": [
1708 | "## Backward pass"
1709 | ]
1710 | },
1711 | {
1712 | "cell_type": "markdown",
1713 | "metadata": {
1714 | "id": "H5-ALOUMk2if"
1715 | },
1716 | "source": [
1717 | "Similar to the RNN in numpy we also need to specify a backward pass. Fortunately, we have already done the work for you here :-)\n",
1718 | "\n",
1719 | "Feel free to dive into the code to get a better intuition of what is going on -- otherwise you can jump straight to the training loop."
1720 | ]
1721 | },
1722 | {
1723 | "cell_type": "code",
1724 | "metadata": {
1725 | "id": "snUFSDBDk2ig"
1726 | },
1727 | "source": [
1728 | "def backward(z, f, i, g, C, o, h, v, outputs, targets, p = params):\n",
1729 | " \"\"\"\n",
1730 | " Arguments:\n",
1731 | " z -- your concatenated input data as a list of size m.\n",
1732 | " f -- your forget gate computations as a list of size m.\n",
1733 | " i -- your input gate computations as a list of size m.\n",
1734 | " g -- your candidate computations as a list of size m.\n",
1735 | " C -- your Cell states as a list of size m+1.\n",
1736 | " o -- your output gate computations as a list of size m.\n",
1737 | " h -- your Hidden state computations as a list of size m+1.\n",
1738 | " v -- your logit computations as a list of size m.\n",
1739 | " outputs -- your outputs as a list of size m.\n",
1740 | " targets -- your targets as a list of size m.\n",
1741 | " p -- python list containing:\n",
1742 | " W_f -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)\n",
1743 | " b_f -- Bias of the forget gate, numpy array of shape (n_a, 1)\n",
1744 | " W_i -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)\n",
1745 | " b_i -- Bias of the update gate, numpy array of shape (n_a, 1)\n",
1746 | " W_g -- Weight matrix of the first \"tanh\", numpy array of shape (n_a, n_a + n_x)\n",
1747 | " b_g -- Bias of the first \"tanh\", numpy array of shape (n_a, 1)\n",
1748 | " W_o -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)\n",
1749 | " b_o -- Bias of the output gate, numpy array of shape (n_a, 1)\n",
1750 | " W_v -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_v, n_a)\n",
1751 | " b_v -- Bias relating the hidden-state to the output, numpy array of shape (n_v, 1)\n",
1752 | " Returns:\n",
1753 | " loss -- crossentropy loss for all elements in output\n",
1754 | " grads -- lists of gradients of every element in p\n",
1755 | " \"\"\"\n",
1756 | "\n",
1757 | " # Unpack parameters\n",
1758 | " W_f, W_i, W_g, W_o, W_v, b_f, b_i, b_g, b_o, b_v = p\n",
1759 | "\n",
1760 | " # Initialize gradients as zero\n",
1761 | " W_f_d = np.zeros_like(W_f)\n",
1762 | " b_f_d = np.zeros_like(b_f)\n",
1763 | "\n",
1764 | " W_i_d = np.zeros_like(W_i)\n",
1765 | " b_i_d = np.zeros_like(b_i)\n",
1766 | "\n",
1767 | " W_g_d = np.zeros_like(W_g)\n",
1768 | " b_g_d = np.zeros_like(b_g)\n",
1769 | "\n",
1770 | " W_o_d = np.zeros_like(W_o)\n",
1771 | " b_o_d = np.zeros_like(b_o)\n",
1772 | "\n",
1773 | " W_v_d = np.zeros_like(W_v)\n",
1774 | " b_v_d = np.zeros_like(b_v)\n",
1775 | " \n",
1776 | " # Set the next cell and hidden state equal to zero\n",
1777 | " dh_next = np.zeros_like(h[0])\n",
1778 | " dC_next = np.zeros_like(C[0])\n",
1779 | " \n",
1780 | " # Track loss\n",
1781 | " loss = 0\n",
1782 | " \n",
1783 | " for t in reversed(range(len(outputs))):\n",
1784 | " \n",
1785 | " # Compute the cross entropy\n",
1786 | " loss += -np.mean(np.log(outputs[t]) * targets[t])\n",
1787 | " # Get the previous hidden cell state\n",
1788 | " C_prev= C[t-1]\n",
1789 | " \n",
1790 | " # Compute the derivative of the relation of the hidden-state to the output gate\n",
1791 | " dv = np.copy(outputs[t])\n",
1792 | " dv[np.argmax(targets[t])] -= 1\n",
1793 | "\n",
1794 | " # Update the gradient of the relation of the hidden-state to the output gate\n",
1795 | " W_v_d += np.dot(dv, h[t].T)\n",
1796 | " b_v_d += dv\n",
1797 | "\n",
1798 | " # Compute the derivative of the hidden state and output gate\n",
1799 | " dh = np.dot(W_v.T, dv) \n",
1800 | " dh += dh_next\n",
1801 | " do = dh * tanh(C[t])\n",
1802 | " do = sigmoid(o[t], derivative=True)*do\n",
1803 | " \n",
1804 | " # Update the gradients with respect to the output gate\n",
1805 | " W_o_d += np.dot(do, z[t].T)\n",
1806 | " b_o_d += do\n",
1807 | "\n",
1808 | " # Compute the derivative of the cell state and candidate g\n",
1809 | " dC = np.copy(dC_next)\n",
1810 | " dC += dh * o[t] * tanh(tanh(C[t]), derivative=True)\n",
1811 | " dg = dC * i[t]\n",
1812 | " dg = tanh(g[t], derivative=True) * dg\n",
1813 | " \n",
1814 | " # Update the gradients with respect to the candidate\n",
1815 | " W_g_d += np.dot(dg, z[t].T)\n",
1816 | " b_g_d += dg\n",
1817 | "\n",
1818 | " # Compute the derivative of the input gate and update its gradients\n",
1819 | " di = dC * g[t]\n",
1820 | " di = sigmoid(i[t], True) * di\n",
1821 | " W_i_d += np.dot(di, z[t].T)\n",
1822 | " b_i_d += di\n",
1823 | "\n",
1824 | " # Compute the derivative of the forget gate and update its gradients\n",
1825 | " df = dC * C_prev\n",
1826 | " df = sigmoid(f[t]) * df\n",
1827 | " W_f_d += np.dot(df, z[t].T)\n",
1828 | " b_f_d += df\n",
1829 | "\n",
1830 | " # Compute the derivative of the input and update the gradients of the previous hidden and cell state\n",
1831 | " dz = (np.dot(W_f.T, df)\n",
1832 | " + np.dot(W_i.T, di)\n",
1833 | " + np.dot(W_g.T, dg)\n",
1834 | " + np.dot(W_o.T, do))\n",
1835 | " dh_prev = dz[:hidden_size, :]\n",
1836 | " dC_prev = f[t] * dC\n",
1837 | " \n",
1838 | " grads= W_f_d, W_i_d, W_g_d, W_o_d, W_v_d, b_f_d, b_i_d, b_g_d, b_o_d, b_v_d\n",
1839 | " \n",
1840 | " # Clip gradients\n",
1841 | " grads = clip_gradient_norm(grads)\n",
1842 | " \n",
1843 | " return loss, grads\n",
1844 | "\n",
1845 | "\n",
1846 | "# Perform a backward pass\n",
1847 | "loss, grads = backward(z_s, f_s, i_s, g_s, C_s, o_s, h_s, v_s, outputs, targets_one_hot, params)\n",
1848 | "\n",
1849 | "print('We get a loss of:')\n",
1850 | "print(loss)"
1851 | ],
1852 | "execution_count": null,
1853 | "outputs": []
1854 | },
1855 | {
1856 | "cell_type": "markdown",
1857 | "metadata": {
1858 | "id": "z4r4mgFsk2ik"
1859 | },
1860 | "source": [
1861 | "## Training loop"
1862 | ]
1863 | },
1864 | {
1865 | "cell_type": "markdown",
1866 | "metadata": {
1867 | "id": "7ok73S7ck2ik"
1868 | },
1869 | "source": [
1870 | "It's time to check whether the LSTM really works! Let's train it for some number of epochs and observe the result."
1871 | ]
1872 | },
1873 | {
1874 | "cell_type": "code",
1875 | "metadata": {
1876 | "id": "23N8SVeik2ik"
1877 | },
1878 | "source": [
1879 | "# Hyper-parameters\n",
1880 | "num_epochs = 200\n",
1881 | "\n",
1882 | "# Initialize a new network\n",
1883 | "z_size = hidden_size + vocab_size # Size of concatenated hidden + input vector\n",
1884 | "params = init_lstm(hidden_size=hidden_size, vocab_size=vocab_size, z_size=z_size)\n",
1885 | "\n",
1886 | "# Initialize hidden state as zeros\n",
1887 | "hidden_state = np.zeros((hidden_size, 1))\n",
1888 | "\n",
1889 | "# Track loss\n",
1890 | "training_loss, validation_loss = [], []\n",
1891 | "\n",
1892 | "# For each epoch\n",
1893 | "for i in range(num_epochs):\n",
1894 | " \n",
1895 | " # Track loss\n",
1896 | " epoch_training_loss = 0\n",
1897 | " epoch_validation_loss = 0\n",
1898 | " \n",
1899 | " # For each sentence in validation set\n",
1900 | " for inputs, targets in validation_set:\n",
1901 | " \n",
1902 | " # One-hot encode input and target sequence\n",
1903 | " inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
1904 | " targets_one_hot = one_hot_encode_sequence(targets, vocab_size)\n",
1905 | "\n",
1906 | " # Initialize hidden state and cell state as zeros\n",
1907 | " h = np.zeros((hidden_size, 1))\n",
1908 | " c = np.zeros((hidden_size, 1))\n",
1909 | "\n",
1910 | " # Forward pass\n",
1911 | " z_s, f_s, i_s, g_s, C_s, o_s, h_s, v_s, outputs = forward(inputs_one_hot, h, c, params)\n",
1912 | " \n",
1913 | " # Backward pass\n",
1914 | " loss, _ = backward(z_s, f_s, i_s, g_s, C_s, o_s, h_s, v_s, outputs, targets_one_hot, params)\n",
1915 | " \n",
1916 | " # Update loss\n",
1917 | " epoch_validation_loss += loss\n",
1918 | " \n",
1919 | " # For each sentence in training set\n",
1920 | " for inputs, targets in training_set:\n",
1921 | " \n",
1922 | " # One-hot encode input and target sequence\n",
1923 | " inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
1924 | " targets_one_hot = one_hot_encode_sequence(targets, vocab_size)\n",
1925 | "\n",
1926 | " # Initialize hidden state and cell state as zeros\n",
1927 | " h = np.zeros((hidden_size, 1))\n",
1928 | " c = np.zeros((hidden_size, 1))\n",
1929 | "\n",
1930 | " # Forward pass\n",
1931 | " z_s, f_s, i_s, g_s, C_s, o_s, h_s, v_s, outputs = forward(inputs_one_hot, h, c, params)\n",
1932 | " \n",
1933 | " # Backward pass\n",
1934 | " loss, grads = backward(z_s, f_s, i_s, g_s, C_s, o_s, h_s, v_s, outputs, targets_one_hot, params)\n",
1935 | " \n",
1936 | " # Update parameters\n",
1937 | " params = update_parameters(params, grads, lr=1e-1)\n",
1938 | " \n",
1939 | " # Update loss\n",
1940 | " epoch_training_loss += loss\n",
1941 | " \n",
1942 | " # Save loss for plot\n",
1943 | " training_loss.append(epoch_training_loss/len(training_set))\n",
1944 | " validation_loss.append(epoch_validation_loss/len(validation_set))\n",
1945 | "\n",
1946 | " # Print loss every 10 epochs\n",
1947 | " if i % 10 == 0:\n",
1948 | " print(f'Epoch {i}, training loss: {training_loss[-1]}, validation loss: {validation_loss[-1]}')\n",
1949 | "\n",
1950 | " \n",
1951 | "# Get first sentence in test set\n",
1952 | "inputs, targets = test_set[1]\n",
1953 | "\n",
1954 | "# One-hot encode input and target sequence\n",
1955 | "inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
1956 | "targets_one_hot = one_hot_encode_sequence(targets, vocab_size)\n",
1957 | "\n",
1958 | "# Initialize hidden state as zeros\n",
1959 | "h = np.zeros((hidden_size, 1))\n",
1960 | "c = np.zeros((hidden_size, 1))\n",
1961 | "\n",
1962 | "# Forward pass\n",
1963 | "z_s, f_s, i_s, g_s, C_s, o_s, h_s, v_s, outputs = forward(inputs_one_hot, h, c, params)\n",
1964 | "\n",
1965 | "# Print example\n",
1966 | "print('Input sentence:')\n",
1967 | "print(inputs)\n",
1968 | "\n",
1969 | "print('\\nTarget sequence:')\n",
1970 | "print(targets)\n",
1971 | "\n",
1972 | "print('\\nPredicted sequence:')\n",
1973 | "print([idx_to_word[np.argmax(output)] for output in outputs])\n",
1974 | "\n",
1975 | "# Plot training and validation loss\n",
1976 | "epoch = np.arange(len(training_loss))\n",
1977 | "plt.figure()\n",
1978 | "plt.plot(epoch, training_loss, 'r', label='Training loss',)\n",
1979 | "plt.plot(epoch, validation_loss, 'b', label='Validation loss')\n",
1980 | "plt.legend()\n",
1981 | "plt.xlabel('Epoch'), plt.ylabel('NLL')\n",
1982 | "plt.show()"
1983 | ],
1984 | "execution_count": null,
1985 | "outputs": []
1986 | },
1987 | {
1988 | "cell_type": "markdown",
1989 | "metadata": {
1990 | "id": "_3nTj0CRk2in"
1991 | },
1992 | "source": [
1993 | "## Exercise J:"
1994 | ]
1995 | },
1996 | {
1997 | "cell_type": "markdown",
1998 | "metadata": {
1999 | "id": "GFlWfDOTk2io"
2000 | },
2001 | "source": [
2002 | "Run the training loop above. Compare your LSTM learning curve (NLL and number of epochs) to the vanilla RNN from earlier. Do you observe any improvements? Motivate your answer."
2003 | ]
2004 | },
2005 | {
2006 | "cell_type": "markdown",
2007 | "metadata": {
2008 | "id": "gi51eWgKxyOk"
2009 | },
2010 | "source": [
2011 | "## PyTorch implementation of the LSTM\n",
2012 | "\n",
2013 | "Now that we know how the LSTM cell works, let's see how easy it is to use in PyTorch!"
2014 | ]
2015 | },
2016 | {
2017 | "cell_type": "markdown",
2018 | "metadata": {
2019 | "id": "O6HDdJLuk2ip"
2020 | },
2021 | "source": [
2022 | "Definition of our LSTM network. We define a LSTM layer using the [nn.LSTM](https://pytorch.org/docs/stable/nn.html#lstm) class. The LSTM layer takes as argument the size of the input and the size of the hidden state like in our numpy implementation."
2023 | ]
2024 | },
2025 | {
2026 | "cell_type": "code",
2027 | "metadata": {
2028 | "id": "8UGrvknfk2ip"
2029 | },
2030 | "source": [
2031 | "import torch\n",
2032 | "import torch.nn as nn\n",
2033 | "import torch.nn.functional as F\n",
2034 | "\n",
2035 | "class MyRecurrentNet(nn.Module):\n",
2036 | " def __init__(self):\n",
2037 | " super(MyRecurrentNet, self).__init__()\n",
2038 | " \n",
2039 | " # Recurrent layer\n",
2040 | " # YOUR CODE HERE!\n",
2041 | " self.lstm = nn.LSTM(input_size=vocab_size,\n",
2042 | " hidden_size=50,\n",
2043 | " num_layers=1,\n",
2044 | " bidirectional=False)\n",
2045 | " \n",
2046 | " # Output layer\n",
2047 | " self.l_out = nn.Linear(in_features=50,\n",
2048 | " out_features=vocab_size,\n",
2049 | " bias=False)\n",
2050 | " \n",
2051 | " def forward(self, x):\n",
2052 | " # RNN returns output and last hidden state\n",
2053 | " x, (h, c) = self.lstm(x)\n",
2054 | " \n",
2055 | " # Flatten output for feed-forward layer\n",
2056 | " x = x.view(-1, self.lstm.hidden_size)\n",
2057 | " \n",
2058 | " # Output layer\n",
2059 | " x = self.l_out(x)\n",
2060 | " \n",
2061 | " return x\n",
2062 | "\n",
2063 | "net = MyRecurrentNet()\n",
2064 | "print(net)"
2065 | ],
2066 | "execution_count": null,
2067 | "outputs": []
2068 | },
2069 | {
2070 | "cell_type": "markdown",
2071 | "metadata": {
2072 | "id": "J6r3bPwYk2is"
2073 | },
2074 | "source": [
2075 | "## Exercise K:\n",
2076 | "\n",
2077 | "Define an LSTM for our recurrent neural network `MyRecurrentNet` above. A single LSTM layer is sufficient. What should the input size and hidden size be? Hint: use the PyTorch documentation."
2078 | ]
2079 | },
2080 | {
2081 | "cell_type": "markdown",
2082 | "metadata": {
2083 | "id": "4WpALf2-x7Ty"
2084 | },
2085 | "source": [
2086 | "### Training loop"
2087 | ]
2088 | },
2089 | {
2090 | "cell_type": "markdown",
2091 | "metadata": {
2092 | "id": "IJ8LWatlk2is"
2093 | },
2094 | "source": [
2095 | "It's time for us to train our network. In the section below, you will get to put your deep learning skills to use and create your own training loop. You may want to consult previous exercises if you cannot recall how to define the training loop."
2096 | ]
2097 | },
2098 | {
2099 | "cell_type": "code",
2100 | "metadata": {
2101 | "id": "2URKsyFDx8xG"
2102 | },
2103 | "source": [
2104 | "# Hyper-parameters\n",
2105 | "num_epochs = 200\n",
2106 | "\n",
2107 | "# Initialize a new network\n",
2108 | "net = MyRecurrentNet()\n",
2109 | "\n",
2110 | "# Define a loss function and optimizer for this problem\n",
2111 | "# YOUR CODE HERE!\n",
2112 | "criterion = \n",
2113 | "optimizer = \n",
2114 | "\n",
2115 | "# Track loss\n",
2116 | "training_loss, validation_loss = [], []\n",
2117 | "\n",
2118 | "# For each epoch\n",
2119 | "for i in range(num_epochs):\n",
2120 | " \n",
2121 | " # Track loss\n",
2122 | " epoch_training_loss = 0\n",
2123 | " epoch_validation_loss = 0\n",
2124 | " \n",
2125 | " net.eval()\n",
2126 | " \n",
2127 | " # For each sentence in validation set\n",
2128 | " for inputs, targets in validation_set:\n",
2129 | " \n",
2130 | " # One-hot encode input and target sequence\n",
2131 | " inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
2132 | " targets_idx = [word_to_idx[word] for word in targets]\n",
2133 | " \n",
2134 | " # Convert input to tensor\n",
2135 | " inputs_one_hot = torch.Tensor(inputs_one_hot)\n",
2136 | " inputs_one_hot = inputs_one_hot.permute(0, 2, 1)\n",
2137 | " \n",
2138 | " # Convert target to tensor\n",
2139 | " targets_idx = torch.LongTensor(targets_idx)\n",
2140 | " \n",
2141 | " # Forward pass\n",
2142 | " # YOUR CODE HERE!\n",
2143 | " outputs = \n",
2144 | " \n",
2145 | " # Compute loss\n",
2146 | " # YOUR CODE HERE!\n",
2147 | " loss = \n",
2148 | " \n",
2149 | " # Update loss\n",
2150 | " epoch_validation_loss += loss.detach().numpy()\n",
2151 | " \n",
2152 | " net.train()\n",
2153 | " \n",
2154 | " # For each sentence in training set\n",
2155 | " for inputs, targets in training_set:\n",
2156 | " \n",
2157 | " # One-hot encode input and target sequence\n",
2158 | " inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
2159 | " targets_idx = [word_to_idx[word] for word in targets]\n",
2160 | " \n",
2161 | " # Convert input to tensor\n",
2162 | " inputs_one_hot = torch.Tensor(inputs_one_hot)\n",
2163 | " inputs_one_hot = inputs_one_hot.permute(0, 2, 1)\n",
2164 | " \n",
2165 | " # Convert target to tensor\n",
2166 | " targets_idx = torch.LongTensor(targets_idx)\n",
2167 | " \n",
2168 | " # Forward pass\n",
2169 | " # YOUR CODE HERE!\n",
2170 | " outputs = \n",
2171 | " \n",
2172 | " # Compute loss\n",
2173 | " # YOUR CODE HERE!\n",
2174 | " loss = \n",
2175 | " \n",
2176 | " # Backward pass\n",
2177 | " # YOUR CODE HERE!\n",
2178 | " # zero grad, backward, step...\n",
2179 | " \n",
2180 | " # Update loss\n",
2181 | " epoch_training_loss += loss.detach().numpy()\n",
2182 | " \n",
2183 | " # Save loss for plot\n",
2184 | " training_loss.append(epoch_training_loss/len(training_set))\n",
2185 | " validation_loss.append(epoch_validation_loss/len(validation_set))\n",
2186 | "\n",
2187 | " # Print loss every 10 epochs\n",
2188 | " if i % 10 == 0:\n",
2189 | " print(f'Epoch {i}, training loss: {training_loss[-1]}, validation loss: {validation_loss[-1]}')\n",
2190 | "\n",
2191 | " \n",
2192 | "# Get first sentence in test set\n",
2193 | "inputs, targets = test_set[1]\n",
2194 | "\n",
2195 | "# One-hot encode input and target sequence\n",
2196 | "inputs_one_hot = one_hot_encode_sequence(inputs, vocab_size)\n",
2197 | "targets_idx = [word_to_idx[word] for word in targets]\n",
2198 | "\n",
2199 | "# Convert input to tensor\n",
2200 | "inputs_one_hot = torch.Tensor(inputs_one_hot)\n",
2201 | "inputs_one_hot = inputs_one_hot.permute(0, 2, 1)\n",
2202 | "\n",
2203 | "# Convert target to tensor\n",
2204 | "targets_idx = torch.LongTensor(targets_idx)\n",
2205 | "\n",
2206 | "# Forward pass\n",
2207 | "outputs = net.forward(inputs_one_hot).data.numpy()\n",
2208 | "\n",
2209 | "print('\\nInput sequence:')\n",
2210 | "print(inputs)\n",
2211 | "\n",
2212 | "print('\\nTarget sequence:')\n",
2213 | "print(targets)\n",
2214 | "\n",
2215 | "print('\\nPredicted sequence:')\n",
2216 | "print([idx_to_word[np.argmax(output)] for output in outputs])\n",
2217 | "\n",
2218 | "# Plot training and validation loss\n",
2219 | "epoch = np.arange(len(training_loss))\n",
2220 | "plt.figure()\n",
2221 | "plt.plot(epoch, training_loss, 'r', label='Training loss',)\n",
2222 | "plt.plot(epoch, validation_loss, 'b', label='Validation loss')\n",
2223 | "plt.legend()\n",
2224 | "plt.xlabel('Epoch'), plt.ylabel('NLL')\n",
2225 | "plt.show()"
2226 | ],
2227 | "execution_count": null,
2228 | "outputs": []
2229 | },
2230 | {
2231 | "cell_type": "markdown",
2232 | "metadata": {
2233 | "id": "ydr7Czg_k2iw"
2234 | },
2235 | "source": [
2236 | "## Exercise L:"
2237 | ]
2238 | },
2239 | {
2240 | "cell_type": "markdown",
2241 | "metadata": {
2242 | "id": "M74xjOq0k2ix"
2243 | },
2244 | "source": [
2245 | "Finish the training loop above and run it. Compare your loss to the NumPy implementation. Are they similar? How do they differ?\n",
2246 | "\n",
2247 | "Try to play around with the choice of hyper-parameters, optimizer, and hidden dimensions. How much can you improve the negative log-likelihood by these simple changes?"
2248 | ]
2249 | },
2250 | {
2251 | "cell_type": "markdown",
2252 | "metadata": {
2253 | "id": "M93ORx95k2ix"
2254 | },
2255 | "source": [
2256 | "## Exercise M (optional):\n",
2257 | "\n",
2258 | "Aside from the LSTM cell, various other RNN cells exist. The gated recurrent unit (GRU) is a variation of the LSTM cell that uses less gating mechanisms. Try to look it up in the [PyTorch documentation](https://pytorch.org/docs/stable/nn.html#gru) and switch out the LSTM cell in the code above. What do you notice in terms of performance and convergence speed?"
2259 | ]
2260 | },
2261 | {
2262 | "cell_type": "markdown",
2263 | "metadata": {
2264 | "id": "juN400Ekk2iz"
2265 | },
2266 | "source": [
2267 | "## Exercise N (optional):\n",
2268 | "\n",
2269 | "Go back and generate a more complex patterned dataset to learn from. Do you see any significant differences between the vanilla RNN and LSTM when you increase the difficulty of the task?"
2270 | ]
2271 | },
2272 | {
2273 | "cell_type": "markdown",
2274 | "metadata": {
2275 | "id": "v68YEkEBk2iz"
2276 | },
2277 | "source": [
2278 | "# It works, now what?"
2279 | ]
2280 | },
2281 | {
2282 | "cell_type": "markdown",
2283 | "metadata": {
2284 | "id": "NjpqSrSuk2i0"
2285 | },
2286 | "source": [
2287 | "In this notebook you have learned how to use embeddings, recurrent neural networks, and the LSTM cell in particular.\n",
2288 | "\n",
2289 | "As we have already seen, RNNs are excellent for sequential data such as language. But what do we do if we're modelling data with strong dependency in both directions? Like in many things deep learning, we can build powerful models by stacking layers on top of each other; *bi-directional* RNNs consist of two LSTM cells, one for each direction. A sequence is first fed into the forward LSTM cell and the reversed sequence is then used as input to the backward LSTM cell together with the last hidden state from the forward LSTM cell. Follow [this link](https://pdfs.semanticscholar.org/4b80/89bc9b49f84de43acc2eb8900035f7d492b2.pdf) for the original paper from 1997(!).\n",
2290 | "\n",
2291 | "For even deeper representations, multiple layers of both uni-directional and bi-directional RNNs can be stacked ontop of each other, just like feed-forward and convolutional layers. For more information on this, check out the [LSTM PyTorch documentation](https://pytorch.org/docs/stable/nn.html#lstm). Next week we will also explore ways to combine RNNs with other types of layers for even more expressive function approximators."
2292 | ]
2293 | }
2294 | ]
2295 | }
--------------------------------------------------------------------------------