Compare commits

...

411 Commits

Author SHA1 Message Date
udlbook
d80d04c2d4 Add files via upload 2024-07-02 14:42:18 -04:00
udlbook
c1f0181653 Update 10_4_Downsampling_and_Upsampling.ipynb 2024-07-02 14:24:36 -04:00
udlbook
6e18234d24 Merge pull request #206 from tomheaton/github-icon
website: Add GitHub social link
2024-07-02 14:23:00 -04:00
udlbook
5730c05547 Create LICENSE (MIT) 2024-07-01 09:34:05 -04:00
Tom Heaton
ccb80c16b8 GitHub social link 2024-06-27 19:41:34 +01:00
Tom Heaton
87387b2b4c fix import 2024-06-27 19:38:52 +01:00
Simon Prince
06eaec9749 Fix file extension 2024-06-24 17:49:03 -04:00
udlbook
9aeda14efa Merge pull request #203 from tomheaton/more-news
website: changes to news section
2024-06-21 09:51:51 -04:00
Tom Heaton
d1df6426b2 cleanup some state and functions 2024-06-21 10:21:11 +01:00
Tom Heaton
43b8fa3685 fix pdf download texts 2024-06-21 10:19:07 +01:00
Tom Heaton
ca6e4b29ac simple show more news working 2024-06-21 10:18:16 +01:00
Tom Heaton
267d6ccb7f remove book selling news 2024-06-20 10:43:35 +01:00
Tom Heaton
735947b728 dynamic rendering for news items 2024-06-20 10:39:17 +01:00
Tom Heaton
251aef1876 fix vite error 2024-06-20 10:12:05 +01:00
Tom Heaton
07ff6c06b1 fix import 2024-06-20 10:11:17 +01:00
Tom Heaton
29e4cec04e fix eslint error 2024-06-20 10:10:53 +01:00
Simon Prince
c3ce38410c minor fixes to website 2024-06-19 12:08:06 -04:00
udlbook
646e60ed95 Merge pull request #202 from tomheaton/path-aliases-new
website: Add path aliases + some fixes
2024-06-19 12:03:03 -04:00
Tom Heaton
5e61bcf694 fix links 2024-06-19 15:35:44 +01:00
Tom Heaton
54399a3c68 fix hero section on mobile 2024-06-19 15:35:17 +01:00
Tom Heaton
3926ff41ea fix navbar naming 2024-06-19 15:16:58 +01:00
Tom Heaton
9c34bfed02 Rename NavBar_temp to Navbar 2024-06-19 15:16:17 +01:00
Tom Heaton
9176623331 Rename NavBar to NavBar_temp 2024-06-19 15:15:45 +01:00
Tom Heaton
5534df187e refactor index page 2024-06-19 15:15:16 +01:00
Tom Heaton
9b58b2862f remove old dep 2024-06-19 15:14:34 +01:00
Tom Heaton
2070ac4400 delete old code 2024-06-19 15:13:46 +01:00
Tom Heaton
393e4907dc path aliases 2024-06-19 15:13:34 +01:00
udlbook
e850676722 Merge pull request #200 from tomheaton/dynamic
website dynamic data
2024-06-19 09:08:12 -04:00
Tom Heaton
796f17ed90 media dynamic rendering (partial) 2024-06-18 12:40:09 +01:00
Tom Heaton
dc0301a86e footer dynamic rendering 2024-06-18 12:33:53 +01:00
Tom Heaton
813f628e4e fixes 2024-06-18 12:23:48 +01:00
Tom Heaton
3ae7d68f6e more dynamic rendering 2024-06-18 12:21:35 +01:00
Tom Heaton
a96a14999f instructors dynamic rendering 2024-06-18 12:03:39 +01:00
Tom Heaton
f91e878eef notebooks dynamic rendering 2024-06-18 11:47:46 +01:00
Tom Heaton
9b89499b75 delete build dir 2024-06-17 21:53:13 +01:00
Simon Prince
7d6ac5e34f fixed tiny mistake in link 2024-06-17 16:42:54 -04:00
udlbook
55dbe7e0c4 Merge pull request #198 from tomheaton/cleanup
website code cleanup
2024-06-17 16:15:54 -04:00
udlbook
1cf21ea61a Created using Colab 2024-06-17 15:11:34 -04:00
Tom Heaton
e4191beb79 refactor styles 2024-06-17 15:28:43 +01:00
Tom Heaton
10b9dea9a4 change build dir to dist 2024-06-17 15:24:35 +01:00
Tom Heaton
414eeb3557 formatting 2024-06-17 15:22:26 +01:00
Tom Heaton
f126809572 Merge branch 'main' into cleanup 2024-06-17 15:20:21 +01:00
Tom Heaton
2a30c49d22 fix deploy 2024-06-17 14:52:47 +01:00
udlbook
bb32fe0cdf Created using Colab 2024-06-11 18:35:42 -04:00
udlbook
1ee756cf9a Update 17_3_Importance_Sampling.ipynb 2024-06-11 15:07:57 -04:00
udlbook
742d922ce7 Created using Colab 2024-06-07 15:21:45 -04:00
Simon Prince
c02eea499c Merge branch 'main' of https://github.com/udlbook/udlbook 2024-06-06 15:10:46 -04:00
Simon Prince
cb94b61abd new NKT tutorial 2024-06-06 15:02:21 -04:00
Tom Heaton
447bb82e2f remove nav listener on unmount 2024-06-06 00:46:46 +01:00
Tom Heaton
77da5694bb use default exports 2024-06-06 00:38:13 +01:00
Tom Heaton
96c7e41c9d update deps 2024-06-06 00:31:00 +01:00
Tom Heaton
625d1e29bb code cleanup 2024-06-06 00:23:19 +01:00
Tom Heaton
3cf0c4c418 add readme 2024-06-06 00:08:09 +01:00
Tom Heaton
03c92541ad formatting 2024-06-05 23:58:58 +01:00
Tom Heaton
def3e5234b setup formatting 2024-06-05 23:56:37 +01:00
Tom Heaton
815adb9b21 cleanup package.json 2024-06-05 23:51:49 +01:00
udlbook
5ba28e5b56 Update 12_2_Multihead_Self_Attention.ipynb 2024-06-05 16:11:17 -04:00
udlbook
8566a7322f Merge pull request #196 from tomheaton/website-changes
Migrate from `create-react-app` to `vite`
2024-06-05 16:09:55 -04:00
udlbook
c867e67e8c Created using Colab 2024-06-05 10:55:51 -04:00
udlbook
cba27b3da4 Add files via upload 2024-05-27 18:15:58 -04:00
Tom Heaton
1c706bd058 update eslint ignore 2024-05-25 01:38:19 +01:00
Tom Heaton
72514994bf delete dist dir 2024-05-25 00:53:16 +01:00
Tom Heaton
872926c17e remove dist dir from .gitignore 2024-05-25 00:51:05 +01:00
Tom Heaton
0dfeb169be fix build dir 2024-05-25 00:50:34 +01:00
Tom Heaton
89a0532283 vite 2024-05-25 00:07:44 +01:00
udlbook
af5a719496 Merge pull request #195 from SwayStar123/patch-3
Fix typo in 7_2_Backpropagation.ipynb
2024-05-23 15:02:54 -04:00
SwayStar123
56c31efc90 Update 7_2_Backpropagation.ipynb 2024-05-23 14:59:55 +05:30
udlbook
06fc37c243 Add files via upload 2024-05-22 15:41:23 -04:00
udlbook
45793f02f8 Merge pull request #189 from ferdiekrammer/patch-1
Update 3_3_Shallow_Network_Regions.ipynb
2024-05-22 15:22:55 -04:00
udlbook
7c4cc1ddb4 Merge pull request #192 from SwayStar123/patch-2
Fix typo in 6_5_Adam.ipynb
2024-05-22 15:15:28 -04:00
SwayStar123
35b6f67bbf Update 6_5_Adam.ipynb 2024-05-22 12:59:03 +05:30
ferdiekrammer
194baf622a Update 3_3_Shallow_Network_Regions.ipynb
removes  <br> correcting the format of the equation in the notebook
2024-05-18 01:15:29 +01:00
udlbook
a547fee3f4 Created using Colab 2024-05-16 16:30:16 -04:00
udlbook
ea4858e78e Created using Colab 2024-05-16 16:29:05 -04:00
udlbook
444b06d5c2 Created using Colab 2024-05-16 16:27:48 -04:00
udlbook
98bce9edb5 Created using Colab 2024-05-16 16:25:26 -04:00
udlbook
37e9ae2311 Created using Colab 2024-05-16 16:24:45 -04:00
udlbook
ea1b6ad998 Created using Colab 2024-05-16 16:22:35 -04:00
udlbook
d17a5a3872 Created using Colab 2024-05-16 16:21:10 -04:00
udlbook
3e7e059bff Created using Colab 2024-05-16 16:19:57 -04:00
udlbook
445ad11c46 Created using Colab 2024-05-16 16:18:07 -04:00
udlbook
6928b50966 Created using Colab 2024-05-16 16:16:44 -04:00
udlbook
e1d34ed561 Merge pull request #185 from DhruvPatel01/chap8_fixes
Fixed 8.1 Notebook to install mnist1d
2024-05-16 16:14:53 -04:00
udlbook
f3528f758b Merge pull request #187 from SwayStar123/patch-1
Remove redundant `to`
2024-05-16 16:02:25 -04:00
udlbook
5c7a03172a Merge pull request #188 from yrahal/main
Fix more Chap09 tiny typos
2024-05-16 16:01:49 -04:00
Youcef Rahal
0233131b07 Notebook 9.5 2024-05-12 15:27:57 -04:00
SwayStar123
8200299e64 Update 2_1_Supervised_Learning.ipynb 2024-05-12 15:01:36 +05:30
Youcef Rahal
2ac42e70d3 Fix more Chap09 tiny typos 2024-05-11 15:20:11 -04:00
udlbook
dd0eaeb781 Add files via upload 2024-05-10 10:14:29 -04:00
Dhruv Patel
2cdff544f3 Fixed to install mnist1d for collab 2024-05-10 09:32:20 +05:30
Dhruv Patel
384e122c5f Fixed mnist1d installation for collab 2024-05-10 09:25:05 +05:30
Youcef Rahal
1343b68c60 Fix more Chap09 tiny typos 2024-05-09 17:51:53 -04:00
udlbook
30420a2f92 Merge pull request #183 from yrahal/main
Fix typos in Chap09 notebooks
2024-05-08 17:30:27 -04:00
Youcef Rahal
89e8ebcbc5 Fix typos in Chap09 notebooks 2024-05-06 20:20:35 -04:00
udlbook
14b751ff47 Add files via upload 2024-05-01 17:11:24 -04:00
udlbook
80e99ef2da Created using Colab 2024-05-01 16:43:15 -04:00
udlbook
46214f64bc Delete Old directory 2024-05-01 09:45:28 -04:00
udlbook
c875fb0361 Added correct answer 2024-04-23 15:57:56 -04:00
udlbook
451ccc0832 Created using Colab 2024-04-23 15:43:27 -04:00
Simon Prince
4b939b7426 Merge branch 'main' of https://github.com/udlbook/udlbook 2024-04-18 17:41:24 -04:00
Simon Prince
2d300a16a1 Final website tweaks 2024-04-18 17:41:04 -04:00
udlbook
d057548be9 Add files via upload 2024-04-18 17:40:08 -04:00
udlbook
75976a32d0 Delete UDL_Answer_Booklet.pdf 2024-04-18 17:38:42 -04:00
udlbook
48b204df2c Add files via upload 2024-04-18 17:38:16 -04:00
udlbook
9b68e6a8e6 Created using Colab 2024-04-18 16:14:02 -04:00
udlbook
862ac6e4d3 Created using Colab 2024-04-18 16:11:35 -04:00
udlbook
8fe07cf0fb Created using Colab 2024-04-18 16:08:28 -04:00
udlbook
c9679dee90 Created using Colab 2024-04-18 16:05:59 -04:00
udlbook
90d879494f Created using Colab 2024-04-18 16:01:44 -04:00
udlbook
19bdc23674 Created using Colab 2024-04-18 16:00:36 -04:00
udlbook
d7f9929a3c Created using Colab 2024-04-18 15:59:40 -04:00
udlbook
a7ac089fc0 Created using Colab 2024-04-18 15:58:31 -04:00
udlbook
8fd753d191 Created using Colab 2024-04-18 15:56:44 -04:00
udlbook
51424b57bd Created using Colab 2024-04-18 15:49:55 -04:00
udlbook
80732b29bc Fixed deprecation warning 2024-04-17 14:10:33 -04:00
udlbook
36e3a53764 Add files via upload
Fixed error in problem 4.8 question.
2024-04-16 14:20:06 -04:00
udlbook
569749963b Add files via upload 2024-04-15 16:41:54 -04:00
udlbook
d17e47421b Improved implementation of softmax_cols() 2024-04-15 16:01:38 -04:00
udlbook
e8fca0cb0a Added notation explanation 2024-04-15 14:34:23 -04:00
udlbook
19c0c7ab3e Created using Colab 2024-04-14 09:25:48 -04:00
udlbook
418ea93e83 Created using Colab 2024-04-13 12:50:13 -04:00
udlbook
ea248af22f Added brackets to plt.show() 2024-04-10 15:38:29 -04:00
udlbook
5492ed0ee5 Updated comments to make clearer. 2024-04-10 15:27:28 -04:00
udlbook
d9138d6177 Merge pull request #174 from yrahal/main
Fix minor typos in chap 8 notebooks
2024-04-05 14:10:31 -04:00
Youcef Rahal
a5413d6a15 Fix inor typos in chap 8 notebooks 2024-04-05 08:42:10 -04:00
Simon Prince
faf53a49a0 change index file 2024-04-03 12:38:11 -04:00
Simon Prince
7e41097381 remove ReadMe 2024-04-03 12:21:46 -04:00
Simon Prince
72b2d79ec7 Merge branch 'main' of https://github.com/udlbook/udlbook
Merging udl github with new website
2024-04-03 12:14:15 -04:00
Simon Prince
d81bef8a6e setup gh-pages 2024-04-03 11:38:24 -04:00
udlbook
911da8ca58 Merge pull request #169 from IgorRusso/main
Remove unrelated instruction regarding plot_all
2024-04-01 17:49:29 -04:00
Igor
031401a3dd Remove unrelated instruction regarding plot_all
There is plot_all in Notebook 3.1, but it's enabled by default there, is out of place.
2024-03-30 11:31:07 +01:00
udlbook
4652f90f09 Update index.html 2024-03-26 17:50:11 -04:00
udlbook
5f524edd3b Add files via upload 2024-03-26 17:43:53 -04:00
udlbook
7a423507f5 Update 6_2_Gradient_Descent.ipynb 2024-03-26 17:15:31 -04:00
udlbook
4a5bd9c4d5 Merge pull request #164 from yrahal/main
Fix minor typos in Chap07 notebooks
2024-03-25 16:43:55 -04:00
udlbook
c0cd9c2aea Update 1_1_BackgroundMathematics.ipynb 2024-03-25 15:09:38 -04:00
udlbook
924b6e220d Update 1_1_BackgroundMathematics.ipynb 2024-03-25 15:08:27 -04:00
udlbook
b535a13d57 Created using Colaboratory 2024-03-25 15:00:01 -04:00
Youcef Rahal
d0d413b9f6 Fix minor typos in Chap07 notebooks 2024-03-16 15:46:41 -04:00
udlbook
1b53be1e08 Update index.html 2024-03-06 17:36:07 -05:00
udlbook
bd12e774a4 Add files via upload 2024-03-06 17:33:19 -05:00
udlbook
e6c3938567 Created using Colaboratory 2024-03-05 12:12:54 -05:00
udlbook
50c93469d5 Created using Colaboratory 2024-03-05 09:24:49 -05:00
udlbook
666e2de7d8 Created using Colaboratory 2024-03-04 16:28:34 -05:00
udlbook
e947b261f8 Created using Colaboratory 2024-03-04 12:26:07 -05:00
udlbook
30801a1d2b Created using Colaboratory 2024-03-04 11:45:49 -05:00
udlbook
22d5bc320f Created using Colaboratory 2024-03-04 10:06:34 -05:00
udlbook
5c0fd0057f Created using Colaboratory 2024-03-04 09:43:56 -05:00
udlbook
9b2b30d4cc Update 17_3_Importance_Sampling.ipynb 2024-02-23 12:32:39 -05:00
udlbook
46e119fcf2 Add files via upload 2024-02-17 13:45:26 -05:00
udlbook
f197be3554 Created using Colaboratory 2024-02-17 12:37:25 -05:00
udlbook
0fa468cf2c Created using Colaboratory 2024-02-17 12:35:18 -05:00
udlbook
e11989bd78 Fixed ambiguity of variable name. 2024-02-17 10:07:40 -05:00
udlbook
566120cc48 Update index.html 2024-02-15 16:52:46 -05:00
udlbook
9f2449fcde Add files via upload 2024-02-15 16:51:27 -05:00
udlbook
025b677457 Merge pull request #150 from yrahal/main
Fix minor typos in Chapter 6 notebooks
2024-02-12 13:11:23 -05:00
Youcef Rahal
435971e3e2 Fix typos in 6_5_Adam.ipynb 2024-02-09 03:55:11 -05:00
Youcef Rahal
6e76cb9b96 Fix typos in 6_4_Momentum.ipynb 2024-02-07 20:17:49 -05:00
Youcef Rahal
732fc6f0b7 Fix issues typos in 6_3_Stochastic_Gradient_Descent.ipynb 2024-02-06 20:48:25 -05:00
udlbook
f2a3fab832 Created using Colaboratory 2024-02-06 18:45:05 -05:00
Youcef Rahal
8e3008673d Fix minor typos in 6_1_Line_Search.ipynb and 6_2_Gradient_Descent.ipynb 2024-02-04 11:03:14 -05:00
udlbook
07bcc98a85 Created using Colaboratory 2024-02-01 20:19:34 +00:00
udlbook
f4fa3e8397 Created using Colaboratory 2024-02-01 20:13:01 +00:00
udlbook
21cff37c72 Update index.html 2024-01-28 18:19:44 +00:00
udlbook
187c6a7352 Add files via upload 2024-01-28 10:01:17 +00:00
udlbook
8e4a0d4daf Add files via upload 2024-01-26 14:37:08 +00:00
udlbook
23b5affab3 Update 5_1_Least_Squares_Loss.ipynb 2024-01-25 16:01:23 +00:00
udlbook
4fb8ffe622 Merge pull request #144 from yrahal/main
Fix some typos in Notebooks/Chap05/5_1_Least_Squares_Loss.ipynb
2024-01-25 15:59:23 +00:00
Youcef Rahal
2adc1da566 Fix some typpos in Notebooks/Chap05/5_1_Least_Squares_Loss.ipynb 2024-01-25 10:16:46 -05:00
Youcef Rahal
6e4551a69f Fix some typpos in Notebooks/Chap05/5_1_Least_Squares_Loss.ipynb 2024-01-25 10:14:01 -05:00
udlbook
65c685706a Update 9_2_Implicit_Regularization.ipynb 2024-01-25 09:46:01 +00:00
udlbook
934f5f7748 Created using Colaboratory 2024-01-24 10:56:22 -05:00
udlbook
365cb41bba Update index.html 2024-01-23 10:54:43 +00:00
udlbook
4855761fb2 Update index.html 2024-01-19 15:04:48 -05:00
udlbook
37b4a76130 Update index.html 2024-01-16 18:16:41 -05:00
udlbook
ef791e5195 Add files via upload 2024-01-16 18:12:15 -05:00
udlbook
49945ff1c7 Update index.html 2024-01-16 16:37:43 -05:00
udlbook
cd8f08b2f3 Update index.html 2024-01-16 16:26:31 -05:00
udlbook
8e85e9111c Update 5_2_Binary_Cross_Entropy_Loss.ipynb 2024-01-16 15:41:24 -05:00
udlbook
be6a0a07fe Created using Colaboratory 2024-01-10 16:29:08 -05:00
udlbook
762ac337ae Created using Colaboratory 2024-01-10 16:14:09 -05:00
udlbook
e692fdd226 Update 4_3_Deep_Networks.ipynb 2024-01-10 16:04:22 -05:00
udlbook
a7d363fcf1 Created using Colaboratory 2024-01-10 16:03:48 -05:00
udlbook
69dffd8c79 Update 4_1_Composing_Networks.ipynb 2024-01-10 16:00:15 -05:00
udlbook
c81296d080 Add files via upload 2024-01-05 15:43:29 -05:00
udlbook
7ca2790c65 Add files via upload 2024-01-04 16:54:06 -05:00
udlbook
73d1a4d28e Add files via upload 2024-01-04 16:14:06 -05:00
udlbook
3f268ab9b9 Add files via upload 2024-01-02 15:10:13 -05:00
udlbook
a371b98529 Add files via upload 2024-01-02 13:16:51 -05:00
udlbook
9a683c502f Created using Colaboratory 2024-01-02 13:14:19 -05:00
udlbook
9a22703818 Add files via upload 2024-01-02 13:12:03 -05:00
udlbook
c19e2411c5 Add files via upload 2024-01-02 13:09:22 -05:00
udlbook
db836826f6 Add files via upload 2024-01-02 13:01:51 -05:00
udlbook
6f775910fe Add files via upload 2024-01-02 12:56:29 -05:00
udlbook
c11d57f313 Add files via upload 2024-01-02 12:51:50 -05:00
udlbook
67f102dd65 Add files via upload 2024-01-02 12:29:17 -05:00
udlbook
351199ec7e Add files via upload 2024-01-02 12:23:29 -05:00
udlbook
9409fbb447 Add files via upload 2024-01-02 12:12:20 -05:00
udlbook
707f93daae Add files via upload 2024-01-02 12:06:41 -05:00
udlbook
d2f885db37 Add files via upload 2024-01-02 11:58:12 -05:00
udlbook
8400d98b76 Created using Colaboratory 2024-01-02 09:45:25 -05:00
udlbook
adbf4322b8 Created using Colaboratory 2023-12-28 15:35:22 -05:00
udlbook
c87294176f Update 3_1_Shallow_Networks_I.ipynb 2023-12-24 17:50:50 -05:00
udlbook
b6b121cb1d Update index.html 2023-12-24 13:41:21 -05:00
udlbook
ea1a7aeba0 Add files via upload 2023-12-24 13:38:05 -05:00
udlbook
d6d0afdfd3 Created using Colaboratory 2023-12-24 12:34:48 -05:00
udlbook
56b4edb871 Created using Colaboratory 2023-12-24 12:01:00 -05:00
udlbook
86387e2901 Created using Colaboratory 2023-12-24 11:53:10 -05:00
udlbook
b9ec83d5f5 Created using Colaboratory 2023-12-24 11:49:04 -05:00
udlbook
0748270a1c Created using Colaboratory 2023-12-24 11:42:23 -05:00
udlbook
51c582f693 Update 6_2_Gradient_Descent.ipynb 2023-12-24 11:36:07 -05:00
udlbook
d7ca8b80d4 Update 3_1_Shallow_Networks_I.ipynb 2023-12-24 11:16:55 -05:00
udlbook
7549cbaa59 Update 5_1_Least_Squares_Loss.ipynb 2023-12-24 10:18:32 -05:00
udlbook
3cdb675cef Created using Colaboratory 2023-12-24 10:16:00 -05:00
udlbook
48d9a4e108 Created using Colaboratory 2023-12-24 10:13:36 -05:00
udlbook
73c58fa0fa Created using Colaboratory 2023-12-24 10:12:00 -05:00
udlbook
dbde6d3d89 Created using Colaboratory 2023-12-24 10:03:28 -05:00
udlbook
182293e8d6 Update 6_3_Stochastic_Gradient_Descent.ipynb 2023-12-24 09:19:51 -05:00
udlbook
d7468ee1c1 Add files via upload 2023-12-23 11:16:28 -05:00
udlbook
5abe61e767 Add files via upload 2023-12-23 11:05:04 -05:00
udlbook
476335cc6f Update 13_2_Graph_Classification.ipynb 2023-12-20 15:31:06 -05:00
udlbook
337d6cd544 Update 13_3_Neighborhood_Sampling.ipynb 2023-12-20 15:30:40 -05:00
udlbook
76498f8ef9 Created using Colaboratory 2023-12-20 15:29:10 -05:00
udlbook
89744c0f0f Update 10_1_1D_Convolution.ipynb 2023-12-20 15:27:59 -05:00
udlbook
ec40d10ecd Update 21_1_Bias_Mitigation.ipynb 2023-12-20 15:26:48 -05:00
udlbook
a71283e322 Update 18_1_Diffusion_Encoder.ipynb 2023-12-20 15:24:15 -05:00
udlbook
d9e7306ef4 Update 19_1_Markov_Decision_Processes.ipynb 2023-12-20 15:23:18 -05:00
udlbook
d5304c8034 Created using Colaboratory 2023-12-20 15:22:17 -05:00
udlbook
985c08950e Update 2_1_Supervised_Learning.ipynb 2023-12-20 15:19:07 -05:00
udlbook
97d738d408 Update 13_2_Graph_Classification.ipynb 2023-12-20 14:43:21 -05:00
udlbook
7e264f5310 Created using Colaboratory 2023-12-20 14:38:30 -05:00
udlbook
3b266ba33b Created using Colaboratory 2023-12-20 14:17:47 -05:00
udlbook
f75b1cb983 Created using Colaboratory 2023-12-20 14:15:24 -05:00
udlbook
7afe033e50 Update 4_3_Deep_Networks.ipynb 2023-12-18 16:55:51 -05:00
udlbook
c68045feb1 Update index.html 2023-12-17 17:58:48 -05:00
udlbook
73fb6a2988 Add files via upload 2023-12-17 17:56:56 -05:00
udlbook
aa04c283e8 Update 5_1_Least_Squares_Loss.ipynb 2023-12-17 17:49:34 -05:00
udlbook
c56251df11 Update 3_3_Shallow_Network_Regions.ipynb 2023-12-17 17:27:23 -05:00
udlbook
fa7005b29a Merge pull request #109 from yrahal/main
Typo fixes in Notebooks/Chap03/3_3_Shallow_Network_Regions.ipynb
2023-12-17 17:22:27 -05:00
udlbook
2e343bc652 Created using Colaboratory 2023-12-17 20:30:17 +00:00
udlbook
905d7d1ac4 Created using Colaboratory 2023-12-14 18:35:49 +00:00
udlbook
5f8f05a381 Delete Notebooks/Chap12/12_1_Self_Attention_A.ipynb 2023-12-14 17:36:45 +00:00
Youcef Rahal
2eb8eebf70 Typo fixes 2023-12-13 19:58:52 -05:00
udlbook
73c3fcc40b Update index.html 2023-12-12 19:56:53 +00:00
udlbook
aa9c613167 Update index.html 2023-12-12 19:35:28 +00:00
udlbook
2ec1f42a80 Update index.html 2023-12-12 19:31:30 +00:00
udlbook
e399f14a82 Created using Colaboratory 2023-12-12 11:01:07 +00:00
udlbook
96049aabcb Created using Colaboratory 2023-12-10 17:23:26 +00:00
udlbook
912cc890df Created using Colaboratory 2023-12-10 17:19:43 +00:00
udlbook
88501605df Merge pull request #104 from tonyjo/main
changed to ax.set_title(title) so title appears on plots
2023-12-10 17:11:55 +00:00
udlbook
16ef8a7333 Merge branch 'main' into main 2023-12-10 17:11:38 +00:00
udlbook
aacf54fb8b Created using Colaboratory 2023-12-10 17:07:58 +00:00
udlbook
40fc192198 Created using Colaboratory 2023-12-10 17:06:17 +00:00
udlbook
de1e19ace9 Delete 18_1_Diffusion_Encoder.ipynb 2023-12-10 17:05:32 +00:00
udlbook
5e701faf90 Created using Colaboratory 2023-12-10 17:05:17 +00:00
udlbook
edc78dc659 Merge pull request #108 from ani0075saha/main
Fix math.comb() typo
2023-12-10 14:43:54 +00:00
udlbook
5300392d66 Merge pull request #107 from yrahal/main
Fixes 0.1/0.01 comment/code granularity mismatch in Notebooks/Chap01/1_1_BackgroundMathematics.ipynb
2023-12-10 14:42:49 +00:00
Youcef Rahal
4696eee641 Notebook 3.2: Fixes missing mention of phi_13, phi_23 2023-12-10 09:32:55 -05:00
udlbook
3258300849 Created using Colaboratory 2023-12-07 19:15:25 +00:00
udlbook
5ba36dd1e8 Created using Colaboratory 2023-12-07 18:07:12 +00:00
udlbook
d7750430f7 Created using Colaboratory 2023-12-07 17:29:53 +00:00
udlbook
e184e09b28 Created using Colaboratory 2023-12-07 17:01:48 +00:00
udlbook
6cfd494ed8 Update index.html 2023-12-05 08:45:29 +00:00
udlbook
986b51bdbd Add files via upload 2023-12-05 08:41:36 +00:00
Aniruddha Saha
9a9321d923 Fix math.comb() typo 2023-12-04 20:57:31 -05:00
Youcef Rahal
714c58bbf3 Fixes 0.1/0.01 comment/code granularity mismatch in Notebooks/Chap01/1_1_BackgroundMathematics.ipynb 2023-12-04 06:20:47 -05:00
udlbook
a8ea2b429f Merge pull request #100 from pitmonticone/main
Fix typos in notebooks
2023-11-30 17:07:23 +00:00
Pietro Monticone
fefef63df4 Update CM20315_Transformers.ipynb 2023-11-30 16:46:38 +01:00
Pietro Monticone
193e2329f2 Update CM20315_Training_III.ipynb 2023-11-30 16:45:28 +01:00
Pietro Monticone
9b13823ca8 Update CM20315_Training_II.ipynb 2023-11-30 16:44:42 +01:00
Pietro Monticone
685d910bbc Update CM20315_Training_I.ipynb 2023-11-30 16:44:01 +01:00
Pietro Monticone
4429600bcc Update CM20315_Shallow.ipynb 2023-11-30 16:43:27 +01:00
Pietro Monticone
6b76bbc7c3 Update CM20315_Loss.ipynb 2023-11-30 16:42:27 +01:00
Pietro Monticone
a5d98bb379 Update CM20315_Loss_III.ipynb 2023-11-30 16:40:52 +01:00
Pietro Monticone
428ca727db Update CM20315_Loss_II.ipynb 2023-11-30 16:39:42 +01:00
Pietro Monticone
6c8411ae1c Update CM20315_Intro.ipynb 2023-11-30 16:38:17 +01:00
Pietro Monticone
c951720282 Update CM20315_Intro_Answers.ipynb 2023-11-30 16:37:46 +01:00
Pietro Monticone
79578aa4a1 Update CM20315_Gradients_III.ipynb 2023-11-30 16:37:12 +01:00
Pietro Monticone
6b2f25101e Update CM20315_Gradients_II.ipynb 2023-11-30 16:36:35 +01:00
Pietro Monticone
ef28d848df Update CM20315_Convolution_III.ipynb 2023-11-30 16:33:59 +01:00
Pietro Monticone
e03fad482b Update CM20315_Convolution_II.ipynb 2023-11-30 16:33:04 +01:00
Pietro Monticone
4fc1abc20e Merge branch 'udlbook:main' into main 2023-11-30 16:20:32 +01:00
tonyjo
aea371dc7d changed to ax.set_title(title) so title appears on plots 2023-11-29 13:45:30 -05:00
udlbook
36d2695a41 Created using Colaboratory 2023-11-29 09:36:54 +00:00
udlbook
7a5113de21 Update index.html 2023-11-27 20:35:29 +00:00
udlbook
bf7f511ee9 Created using Colaboratory 2023-11-26 19:00:46 +00:00
Pietro Monticone
a7af9f559e Update 1_1_BackgroundMathematics.ipynb 2023-11-26 11:18:22 +01:00
Pietro Monticone
866861a06c Merge branch 'udlbook:main' into main 2023-11-26 11:15:50 +01:00
udlbook
2cfbcafedc Created using Colaboratory 2023-11-25 17:02:46 +00:00
udlbook
58a150843f Created using Colaboratory 2023-11-25 17:01:43 +00:00
Pietro Monticone
ffe7ffc823 Update 12_1_Self_Attention.ipynb 2023-11-24 11:21:47 +01:00
Pietro Monticone
da3a5ad2e9 Update 21_2_Explainability.ipynb 2023-11-24 11:18:22 +01:00
Pietro Monticone
8411fdd1d2 Update 21_1_Bias_Mitigation.ipynb 2023-11-24 11:18:20 +01:00
udlbook
362d8838e8 Update index.html 2023-11-24 09:53:55 +00:00
udlbook
718cfba4dc Update index.html 2023-11-24 09:47:01 +00:00
udlbook
41d99cf6d3 Created using Colaboratory 2023-11-24 09:01:15 +00:00
udlbook
5c10091b48 Created using Colaboratory 2023-11-23 11:08:41 +00:00
udlbook
b47c4a210a Created using Colaboratory 2023-11-20 21:05:39 +00:00
udlbook
cef074a42b Created using Colaboratory 2023-11-20 16:06:11 +00:00
udlbook
6a8a1092c3 Created using Colaboratory 2023-11-20 15:18:32 +00:00
udlbook
c42f92d6a3 Created using Colaboratory 2023-11-20 15:15:35 +00:00
udlbook
dc87aa07c3 Created using Colaboratory 2023-11-20 14:50:18 +00:00
udlbook
b50b343096 Created using Colaboratory 2023-11-20 14:47:31 +00:00
udlbook
2056594cdd Created using Colaboratory 2023-11-20 14:46:26 +00:00
udlbook
73cf5ff7da Add files via upload 2023-11-15 18:50:13 +00:00
udlbook
a529c94875 Add files via upload 2023-11-15 18:41:18 +00:00
udlbook
07fd109b1f Delete CM20315/Data/val_data_y.npy 2023-11-15 18:40:43 +00:00
udlbook
57a6582798 Delete CM20315/Data/train_data_y.npy 2023-11-15 18:40:33 +00:00
udlbook
55ab79fcf8 Delete CM20315/Data/val_data_x.npy 2023-11-15 18:40:17 +00:00
udlbook
b2d5116140 Delete CM20315/Data/train_data_x.npy 2023-11-15 18:40:06 +00:00
udlbook
87632b5081 Add files via upload 2023-11-15 18:22:25 +00:00
udlbook
845cac5229 Delete CM20315/Data/val_data_y.npy 2023-11-15 18:16:35 +00:00
udlbook
71229805b4 Delete CM20315/Data/val_data_x.npy 2023-11-15 18:16:25 +00:00
udlbook
b06a37349f Delete CM20315/Data/train_data_y.npy 2023-11-15 18:16:14 +00:00
udlbook
164a5dc979 Delete CM20315/Data/train_data_x.npy 2023-11-15 18:16:04 +00:00
udlbook
5e9cc7243d New data files 2023-11-15 18:07:20 +00:00
udlbook
b09262f4ad Delete CM20315/Data/val_data_y.npy 2023-11-15 18:07:02 +00:00
udlbook
058d116638 Delete CM20315/Data/val_data_x.npy 2023-11-15 18:06:46 +00:00
udlbook
4a5e2cf87c Delete CM20315/Data/train_data_y.npy 2023-11-15 18:06:34 +00:00
udlbook
cdeef5f9f7 Delete CM20315/Data/train_data_x.npy 2023-11-15 18:06:23 +00:00
udlbook
79c6bc669b New train test files 2023-11-15 18:05:04 +00:00
udlbook
ed9f9ae8c8 Add files via upload 2023-11-15 18:04:31 +00:00
udlbook
26511a078e Delete CM20315/Data/test_data_y.npy 2023-11-14 19:09:00 +00:00
udlbook
2a53370576 Delete CM20315/Data/test_data_x.npy 2023-11-14 19:08:45 +00:00
udlbook
5b009deabb Created using Colaboratory 2023-11-14 16:41:46 +00:00
udlbook
aaa1343359 Created using Colaboratory 2023-11-14 16:13:06 +00:00
udlbook
259f34e985 Created using Colaboratory 2023-11-14 11:42:12 +00:00
udlbook
f63ddc7313 Created using Colaboratory 2023-11-14 10:34:50 +00:00
udlbook
00d180bf88 Update index.html 2023-11-14 09:41:53 +00:00
udlbook
ecd377e775 Update index.html 2023-11-14 09:15:41 +00:00
udlbook
35bbac271b Update index.html 2023-11-14 09:09:49 +00:00
udlbook
96eeed8194 Created using Colaboratory 2023-11-14 08:58:30 +00:00
udlbook
d58115baaa Delete Notebooks/Chapter21/21_1_Bias_Mitigation.ipynb 2023-11-14 08:57:47 +00:00
udlbook
ae67af61a8 Update index.html 2023-11-14 08:57:01 +00:00
udlbook
fe9fd3da8b Created using Colaboratory 2023-11-13 21:29:35 +00:00
udlbook
b9238e35dc Created using Colaboratory 2023-11-13 21:27:38 +00:00
udlbook
34235a319c Created using Colaboratory 2023-11-06 13:11:13 +00:00
udlbook
0c5aacbd8b Created using Colaboratory 2023-11-06 13:10:09 +00:00
udlbook
7a07cba349 Merge pull request #96 from pitmonticone/main
Fix typos in notebooks
2023-11-02 16:43:34 +00:00
udlbook
110de1488b Created using Colaboratory 2023-10-31 12:01:20 +00:00
Pietro Monticone
8fa8efa9dd Update 19_5_Control_Variates.ipynb 2023-10-30 18:20:33 +01:00
Pietro Monticone
d48eeab4a4 Update 19_4_Temporal_Difference_Methods.ipynb 2023-10-30 18:20:02 +01:00
Pietro Monticone
f855263f9f Update 18_2_1D_Diffusion_Model.ipynb 2023-10-30 18:17:44 +01:00
Pietro Monticone
aa5c7f77d6 Update 18_1_Diffusion_Encoder.ipynb 2023-10-30 18:17:14 +01:00
Pietro Monticone
5cbdaefc96 Update 17_2_Reparameterization_Trick.ipynb 2023-10-30 18:15:51 +01:00
Pietro Monticone
78eaa6312d Update 16_2_Autoregressive_Flows.ipynb 2023-10-30 18:15:48 +01:00
Pietro Monticone
be98b4df14 Update 15_2_Wasserstein_Distance.ipynb 2023-10-30 18:12:54 +01:00
Pietro Monticone
7793b9c553 Update 15_1_GAN_Toy_Example.ipynb 2023-10-30 18:12:09 +01:00
Pietro Monticone
01f3eb30be Update 12_2_Multihead_Self_Attention.ipynb 2023-10-30 18:09:40 +01:00
Pietro Monticone
ecbe2f1051 Update 12_1_Self_Attention.ipynb 2023-10-30 18:08:36 +01:00
Pietro Monticone
4f2d3f31f0 Update 9_4_Bayesian_Approach.ipynb 2023-10-30 18:04:23 +01:00
Pietro Monticone
94df10a9ec Update 9_1_L2_Regularization.ipynb 2023-10-30 18:00:44 +01:00
Pietro Monticone
cd76e76ad2 Update 8_2_Bias_Variance_Trade_Off.ipynb 2023-10-30 17:59:24 +01:00
Pietro Monticone
008b058b14 Merge branch 'main' of https://github.com/pitmonticone/udlbook 2023-10-30 17:57:40 +01:00
Pietro Monticone
f57925947d Update 7_2_Backpropagation.ipynb 2023-10-30 17:57:39 +01:00
Pietro Monticone
b69e7bf696 Merge branch 'udlbook:main' into main 2023-10-30 17:53:42 +01:00
Pietro Monticone
21fe352e75 Update 6_5_Adam.ipynb 2023-10-30 17:52:35 +01:00
Pietro Monticone
e9349b415f Update 6_4_Momentum.ipynb 2023-10-30 17:52:32 +01:00
Pietro Monticone
e412e965ca Update 6_3_Stochastic_Gradient_Descent.ipynb 2023-10-30 17:52:29 +01:00
Pietro Monticone
d60b92b608 Update 6_2_Gradient_Descent.ipynb 2023-10-30 17:52:25 +01:00
udlbook
9266025bdd Created using Colaboratory 2023-10-30 16:28:04 +00:00
Pietro Monticone
594497ee4c Update 5_1_Least_Squares_Loss.ipynb 2023-10-30 17:04:35 +01:00
Pietro Monticone
6eb5986784 Update 2_1_Supervised_Learning.ipynb 2023-10-30 17:01:44 +01:00
udlbook
8c2e3f71e8 Update index.html 2023-10-30 10:50:52 +00:00
udlbook
fbf9ac0e40 Created using Colaboratory 2023-10-30 09:26:06 +00:00
udlbook
fd1844ed44 Created using Colaboratory 2023-10-26 17:51:07 +01:00
udlbook
4d0825ef42 Created using Colaboratory 2023-10-26 17:32:25 +01:00
udlbook
5db114e492 Created using Colaboratory 2023-10-26 17:19:04 +01:00
udlbook
7d9296c157 Created using Colaboratory 2023-10-25 15:59:58 +01:00
udlbook
66016f8dea Created using Colaboratory 2023-10-25 15:35:28 +01:00
udlbook
b3f8533864 Created using Colaboratory 2023-10-25 15:08:28 +01:00
udlbook
2ca7ddb6d9 Created using Colaboratory 2023-10-25 10:23:10 +01:00
udlbook
452edf3a1f Created using Colaboratory 2023-10-24 17:59:40 +01:00
udlbook
78851c3da2 Created using Colaboratory 2023-10-24 13:37:38 +01:00
udlbook
df8829934e Created using Colaboratory 2023-10-24 13:18:55 +01:00
udlbook
fba121b30b Created using Colaboratory 2023-10-24 13:16:34 +01:00
udlbook
33a94fb59f Created using Colaboratory 2023-10-24 13:10:47 +01:00
udlbook
0af1ea979c Update index.html 2023-10-24 08:11:59 +01:00
udlbook
3b171383d5 Update index.html 2023-10-23 17:07:38 +01:00
udlbook
e9fa659fee Created using Colaboratory 2023-10-23 09:34:50 +01:00
udlbook
5db96e8a3d Created using Colaboratory 2023-10-22 20:38:00 +01:00
udlbook
6ac37b5548 Created using Colaboratory 2023-10-22 18:51:09 +01:00
udlbook
9acd27c8b3 Created using Colaboratory 2023-10-22 16:55:29 +01:00
udlbook
a481425005 Created using Colaboratory 2023-10-22 11:00:04 +01:00
udlbook
41e60e8597 Created using Colaboratory 2023-10-20 13:14:40 +01:00
udlbook
ec748ecc18 Created using Colaboratory 2023-10-19 20:56:53 +01:00
udlbook
467a36bed8 Created using Colaboratory 2023-10-19 11:30:16 +01:00
udlbook
351b050e7e Add files via upload 2023-10-18 15:31:24 +01:00
udlbook
5f19405c51 Delete Notebooks/Chap19/4_ReinforcementPenguin.png 2023-10-18 15:31:10 +01:00
udlbook
ad5339a972 Add files via upload 2023-10-18 15:26:09 +01:00
udlbook
1d8a9af439 Created using Colaboratory 2023-10-18 15:24:54 +01:00
udlbook
55a96289fe Created using Colaboratory 2023-10-18 13:08:24 +01:00
udlbook
d72143ff42 Created using Colaboratory 2023-10-18 10:43:37 +01:00
udlbook
a1154e2262 Created using Colaboratory 2023-10-18 09:06:27 +01:00
udlbook
b419f52791 Created using Colaboratory 2023-10-18 08:48:11 +01:00
udlbook
8c0bec30ff Created using Colaboratory 2023-10-17 13:17:00 +01:00
udlbook
87cfb0a846 Created using Colaboratory 2023-10-16 16:36:58 +01:00
udlbook
0fcfa4fe36 Created using Colaboratory 2023-10-16 15:54:36 +01:00
udlbook
8e6fd1bf81 Merge pull request #95 from krishnams0ni/newBranch
A better site
2023-10-14 18:42:10 +01:00
udlbook
7a2a7cd2e8 Merge pull request #91 from dillonplunkett/1.1-notebook-typos
fix a couple of typos in notebook 1.1
2023-10-14 18:37:54 +01:00
udlbook
f46ae30bf2 Merge pull request #93 from ritog/patch-1
Minor typo correction- Update 9_1_L2_Regularization.ipynb
2023-10-14 18:37:17 +01:00
udlbook
24206afa50 Created using Colaboratory 2023-10-14 18:28:15 +01:00
Krishnam Soni
77ec015669 Delete .idea directory 2023-10-14 22:37:14 +05:30
krishnams0ni
1c40b09e48 better site 2023-10-14 22:34:36 +05:30
udlbook
972e035974 Created using Colaboratory 2023-10-14 15:17:59 +01:00
udlbook
d7a792785f Update index.html 2023-10-13 18:48:44 +01:00
udlbook
80ef390e45 Created using Colaboratory 2023-10-13 18:46:12 +01:00
udlbook
f70dd6e60a Update index.html 2023-10-13 15:37:26 +01:00
udlbook
a7d840f204 Update index.html 2023-10-13 12:06:32 +01:00
Ritobrata Ghosh
a32260c39f Minor typo correction- Update 9_1_L2_Regularization.ipynb 2023-09-12 19:42:35 +05:30
Dillon Plunkett
6b2288665f fix a couple of typos in 1.1 notebook 2023-08-13 18:12:25 -04:00
142 changed files with 33047 additions and 2065 deletions

10
.editorconfig Normal file
View File

@@ -0,0 +1,10 @@
root = true
[*.{js,jsx,ts,tsx,md,mdx,json,cjs,mjs,css}]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 100

18
.eslintrc.cjs Normal file
View File

@@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true, node: true },
extends: [
"eslint:recommended",
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:react-hooks/recommended",
],
ignorePatterns: ["build", ".eslintrc.cjs"],
parserOptions: { ecmaVersion: "latest", sourceType: "module" },
settings: { react: { version: "18.2" } },
plugins: ["react-refresh"],
rules: {
"react/jsx-no-target-blank": "off",
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
},
};

30
.gitignore vendored Executable file
View File

@@ -0,0 +1,30 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/dist
# ENV
.env.local
.env.development.local
.env.test.local
.env.production.local
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# IDE
.idea
.vscode
# macOS
.DS_Store

7
.prettierignore Normal file
View File

@@ -0,0 +1,7 @@
# ignore these directories when formatting the repo
/Blogs
/CM20315
/CM20315_2023
/Notebooks
/PDFFigures
/Slides

14
.prettierrc.cjs Normal file
View File

@@ -0,0 +1,14 @@
/** @type {import("prettier").Config} */
const prettierConfig = {
trailingComma: "all",
tabWidth: 4,
useTabs: false,
semi: true,
singleQuote: false,
bracketSpacing: true,
printWidth: 100,
endOfLine: "lf",
plugins: [require.resolve("prettier-plugin-organize-imports")],
};
module.exports = prettierConfig;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,401 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyP9fLqBQPgcYJB1KXs3Scp/",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Blogs/BorealisGradientFlow.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# Gradient flow\n",
"\n",
"This notebook replicates some of the results in the the Borealis AI [blog](https://www.borealisai.com/research-blogs/gradient-flow/) on gradient flow. \n"
],
"metadata": {
"id": "ucrRRJ4dq8_d"
}
},
{
"cell_type": "code",
"source": [
"# Import relevant libraries\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from scipy.linalg import expm\n",
"from matplotlib import cm\n",
"from matplotlib.colors import ListedColormap"
],
"metadata": {
"id": "_IQFHZEMZE8T"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Create the three data points that are used to train the linear model in the blog. Each input point is a column in $\\mathbf{X}$ and consists of the $x$ position in the plot and the value 1, which is used to allow the model to fit bias terms neatly."
],
"metadata": {
"id": "NwgUP3MSriiJ"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cJNZ2VIcYsD8"
},
"outputs": [],
"source": [
"X = np.array([[0.2, 0.4, 0.8],[1,1,1]])\n",
"y = np.array([[-0.1],[0.15],[0.3]])\n",
"D = X.shape[0]\n",
"I = X.shape[1]\n",
"\n",
"print(\"X=\\n\",X)\n",
"print(\"y=\\n\",y)"
]
},
{
"cell_type": "code",
"source": [
"# Draw the three data points\n",
"fig, ax = plt.subplots()\n",
"ax.plot(X[0:1,:],y.T,'ro')\n",
"ax.set_xlim([0,1]); ax.set_ylim([-0.5,0.5])\n",
"ax.set_xlabel('x'); ax.set_ylabel('y')\n",
"plt.show()"
],
"metadata": {
"id": "FpFlD4nUZDRt"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Compute the evolution of the residuals, loss, and parameters as a function of time."
],
"metadata": {
"id": "H2LBR1DasQej"
}
},
{
"cell_type": "code",
"source": [
"# Discretized time to evaluate quantities at\n",
"t_all = np.arange(0,20,0.01)\n",
"nT = t_all.shape[0]\n",
"\n",
"# Initial parameters, and initial function output at training points\n",
"phi_0 = np.array([[-0.05],[-0.4]])\n",
"f_0 = X.T @ phi_0\n",
"\n",
"# Precompute pseudoinverse term (not a very sensible numerical implementation, but it works...)\n",
"XXTInvX = np.linalg.inv(X@X.T)@X\n",
"\n",
"# Create arrays to hold function at data points over time, residual over time, parameters over time\n",
"f_all = np.zeros((I,nT))\n",
"f_minus_y_all = np.zeros((I,nT))\n",
"phi_t_all = np.zeros((D,nT))\n",
"\n",
"# For each time, compute function, residual, and parameters at each time.\n",
"for t in range(len(t_all)):\n",
" f = y + expm(-X.T@X * t_all[t]) @ (f_0-y)\n",
" f_all[:,t:t+1] = f\n",
" f_minus_y_all[:,t:t+1] = f-y\n",
" phi_t_all[:,t:t+1] = phi_0 - XXTInvX @ (np.identity(3)-expm(-X.T@X * t_all[t])) @ (f_0-y)"
],
"metadata": {
"id": "wfF_oTS5Z4Wi"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Plot the results that were calculated in the previous cell"
],
"metadata": {
"id": "9jSjOOFutJUE"
}
},
{
"cell_type": "code",
"source": [
"# Plot function at data points\n",
"fig, ax = plt.subplots()\n",
"ax.plot(t_all,np.squeeze(f_all[0,:]),'r-', label='$f[x_{0},\\phi]$')\n",
"ax.plot(t_all,np.squeeze(f_all[1,:]),'g-', label='$f[x_{1},\\phi]$')\n",
"ax.plot(t_all,np.squeeze(f_all[2,:]),'b-', label='$f[x_{2},\\phi]$')\n",
"ax.set_xlim([0,np.max(t_all)]); ax.set_ylim([-0.5,0.5])\n",
"ax.set_xlabel('t'); ax.set_ylabel('f')\n",
"plt.legend(loc=\"lower right\")\n",
"plt.show()\n",
"\n",
"# Plot residual\n",
"fig, ax = plt.subplots()\n",
"ax.plot(t_all,np.squeeze(f_minus_y_all[0,:]),'r-', label='$f[x_{0},\\phi]-y_{0}$')\n",
"ax.plot(t_all,np.squeeze(f_minus_y_all[1,:]),'g-', label='$f[x_{1},\\phi]-y_{1}$')\n",
"ax.plot(t_all,np.squeeze(f_minus_y_all[2,:]),'b-', label='$f[x_{2},\\phi]-y_{2}$')\n",
"ax.set_xlim([0,np.max(t_all)]); ax.set_ylim([-0.5,0.5])\n",
"ax.set_xlabel('t'); ax.set_ylabel('f-y')\n",
"plt.legend(loc=\"lower right\")\n",
"plt.show()\n",
"\n",
"# Plot loss (sum of residuals)\n",
"fig, ax = plt.subplots()\n",
"square_error = 0.5 * np.sum(f_minus_y_all * f_minus_y_all, axis=0)\n",
"ax.plot(t_all, square_error,'k-')\n",
"ax.set_xlim([0,np.max(t_all)]); ax.set_ylim([-0.0,0.25])\n",
"ax.set_xlabel('t'); ax.set_ylabel('Loss')\n",
"plt.show()\n",
"\n",
"# Plot parameters\n",
"fig, ax = plt.subplots()\n",
"ax.plot(t_all, np.squeeze(phi_t_all[0,:]),'c-',label='$\\phi_{0}$')\n",
"ax.plot(t_all, np.squeeze(phi_t_all[1,:]),'m-',label='$\\phi_{1}$')\n",
"ax.set_xlim([0,np.max(t_all)]); ax.set_ylim([-1,1])\n",
"ax.set_xlabel('t'); ax.set_ylabel('$\\phi$')\n",
"plt.legend(loc=\"lower right\")\n",
"plt.show()"
],
"metadata": {
"id": "G9IwgwKltHz5"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define the model and the loss function"
],
"metadata": {
"id": "N6VaUq2swa8D"
}
},
{
"cell_type": "code",
"source": [
"# Model is just a straight line with intercept phi[0] and slope phi[1]\n",
"def model(phi,x):\n",
" y_pred = phi[0]+phi[1] * x\n",
" return y_pred\n",
"\n",
"# Loss function is 0.5 times sum of squares of residuals for training data\n",
"def compute_loss(data_x, data_y, model, phi):\n",
" pred_y = model(phi, data_x)\n",
" loss = 0.5 * np.sum((pred_y-data_y)*(pred_y-data_y))\n",
" return loss"
],
"metadata": {
"id": "LGHEVUWWiB4f"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Draw the loss function"
],
"metadata": {
"id": "hr3hs7pKwo0g"
}
},
{
"cell_type": "code",
"source": [
"def draw_loss_function(compute_loss, X, y, model, phi_iters):\n",
" # Define pretty colormap\n",
" my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
" my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
" r = np.floor(my_colormap_vals_dec/(256*256))\n",
" g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
" b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
" my_colormap = ListedColormap(np.vstack((r,g,b)).transpose()/255.0)\n",
"\n",
" # Make grid of intercept/slope values to plot\n",
" intercepts_mesh, slopes_mesh = np.meshgrid(np.arange(-1.0,1.0,0.005), np.arange(-1.0,1.0,0.005))\n",
" loss_mesh = np.zeros_like(slopes_mesh)\n",
" # Compute loss for every set of parameters\n",
" for idslope, slope in np.ndenumerate(slopes_mesh):\n",
" loss_mesh[idslope] = compute_loss(X, y, model, np.array([[intercepts_mesh[idslope]], [slope]]))\n",
"\n",
" fig,ax = plt.subplots()\n",
" fig.set_size_inches(8,8)\n",
" ax.contourf(intercepts_mesh,slopes_mesh,loss_mesh,256,cmap=my_colormap)\n",
" ax.contour(intercepts_mesh,slopes_mesh,loss_mesh,40,colors=['#80808080'])\n",
" ax.set_ylim([1,-1]); ax.set_xlim([-1,1])\n",
"\n",
" ax.plot(phi_iters[1,:], phi_iters[0,:],'g-')\n",
" ax.set_xlabel('Intercept'); ax.set_ylabel('Slope')\n",
" plt.show()"
],
"metadata": {
"id": "UCxa3tZ8a9kz"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"draw_loss_function(compute_loss, X[0:1,:], y.T, model, phi_t_all)"
],
"metadata": {
"id": "pXLLBaSaiI2A"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Draw the evolution of the function"
],
"metadata": {
"id": "ZsremHW-xFi5"
}
},
{
"cell_type": "code",
"source": [
"fig, ax = plt.subplots()\n",
"ax.plot(X[0:1,:],y.T,'ro')\n",
"x_vals = np.arange(0,1,0.001)\n",
"ax.plot(x_vals, phi_t_all[0,0]*x_vals + phi_t_all[1,0],'r-', label='t=0.00')\n",
"ax.plot(x_vals, phi_t_all[0,10]*x_vals + phi_t_all[1,10],'g-', label='t=0.10')\n",
"ax.plot(x_vals, phi_t_all[0,30]*x_vals + phi_t_all[1,30],'b-', label='t=0.30')\n",
"ax.plot(x_vals, phi_t_all[0,200]*x_vals + phi_t_all[1,200],'c-', label='t=2.00')\n",
"ax.plot(x_vals, phi_t_all[0,1999]*x_vals + phi_t_all[1,1999],'y-', label='t=20.0')\n",
"ax.set_xlim([0,1]); ax.set_ylim([-0.5,0.5])\n",
"ax.set_xlabel('x'); ax.set_ylabel('y')\n",
"plt.legend(loc=\"upper left\")\n",
"plt.show()"
],
"metadata": {
"id": "cv9ZrUoRkuhI"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Compute MAP and ML solutions\n",
"MLParams = np.linalg.inv(X@X.T)@X@y\n",
"sigma_sq_p = 3.0\n",
"sigma_sq = 0.05\n",
"MAPParams = np.linalg.inv(X@X.T+np.identity(X.shape[0])*sigma_sq/sigma_sq_p)@X@y"
],
"metadata": {
"id": "OU9oegSOof-o"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Finally, we predict both the mean and the uncertainty in the fitted model as a function of time"
],
"metadata": {
"id": "Ul__XvOgyYSA"
}
},
{
"cell_type": "code",
"source": [
"# Define x positions to make predictions (appending a 1 to each column)\n",
"x_predict = np.arange(0,1,0.01)[None,:]\n",
"x_predict = np.concatenate((x_predict,np.ones_like(x_predict)))\n",
"nX = x_predict.shape[1]\n",
"\n",
"# Create variables to store evolution of mean and variance of prediction over time\n",
"predict_mean_all = np.zeros((nT,nX))\n",
"predict_var_all = np.zeros((nT,nX))\n",
"\n",
"# Initial covariance\n",
"sigma_sq_p = 2.0\n",
"cov_init = sigma_sq_p * np.identity(2)\n",
"\n",
"# Run through each time computing a and b and hence mean and variance of prediction\n",
"for t in range(len(t_all)):\n",
" a = x_predict.T @(XXTInvX @ (np.identity(3)-expm(-X.T@X * t_all[t])) @ y)\n",
" b = x_predict.T -x_predict.T@XXTInvX @ (np.identity(3)-expm(-X.T@X * t_all[t])) @ X.T\n",
" predict_mean_all[t:t+1,:] = a.T\n",
" predict_cov = b@ cov_init @b.T\n",
" # We just want the diagonal of the covariance to plot the uncertainty\n",
" predict_var_all[t:t+1,:] = np.reshape(np.diag(predict_cov),(1,nX))"
],
"metadata": {
"id": "aMPADCuByKWr"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Plot the mean and variance at various times"
],
"metadata": {
"id": "PZTj93KK7QH6"
}
},
{
"cell_type": "code",
"source": [
"def plot_mean_var(X,y,x_predict, predict_mean_all, predict_var_all, this_t, sigma_sq = 0.00001):\n",
" fig, ax = plt.subplots()\n",
" ax.plot(X[0:1,:],y.T,'ro')\n",
" ax.plot(x_predict[0:1,:].T, predict_mean_all[this_t:this_t+1,:].T,'r-')\n",
" lower = np.squeeze(predict_mean_all[this_t:this_t+1,:].T-np.sqrt(predict_var_all[this_t:this_t+1,:].T+np.sqrt(sigma_sq)))\n",
" upper = np.squeeze(predict_mean_all[this_t:this_t+1,:].T+np.sqrt(predict_var_all[this_t:this_t+1,:].T+np.sqrt(sigma_sq)))\n",
" ax.fill_between(np.squeeze(x_predict[0:1,:]), lower, upper, color='lightgray')\n",
" ax.set_xlim([0,1]); ax.set_ylim([-0.5,0.5])\n",
" ax.set_xlabel('x'); ax.set_ylabel('y')\n",
" plt.show()\n",
"\n",
"plot_mean_var(X,y,x_predict, predict_mean_all, predict_var_all, this_t=0)\n",
"plot_mean_var(X,y,x_predict, predict_mean_all, predict_var_all, this_t=40)\n",
"plot_mean_var(X,y,x_predict, predict_mean_all, predict_var_all, this_t=80)\n",
"plot_mean_var(X,y,x_predict, predict_mean_all, predict_var_all, this_t=200)\n",
"plot_mean_var(X,y,x_predict, predict_mean_all, predict_var_all, this_t=500)\n",
"plot_mean_var(X,y,x_predict, predict_mean_all, predict_var_all, this_t=1000)"
],
"metadata": {
"id": "bYAFxgB880-v"
},
"execution_count": null,
"outputs": []
}
]
}

1109
Blogs/BorealisNTK.ipynb Normal file

File diff suppressed because one or more lines are too long

1127
Blogs/Borealis_NNGP.ipynb Normal file

File diff suppressed because one or more lines are too long

View File

@@ -105,7 +105,7 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"\n", "\n",
"# TODO Create a model with the folowing layers\n", "# TODO Create a model with the following layers\n",
"# 1. Convolutional layer, (input=length 40 and 1 channel, kernel size 3x3, stride 2, padding=\"valid\", 15 output channels ) \n", "# 1. Convolutional layer, (input=length 40 and 1 channel, kernel size 3x3, stride 2, padding=\"valid\", 15 output channels ) \n",
"# 2. ReLU\n", "# 2. ReLU\n",
"# 3. Convolutional layer, (input=length 19 and 15 channels, kernel size 3x3, stride 2, padding=\"valid\", 15 output channels )\n", "# 3. Convolutional layer, (input=length 19 and 15 channels, kernel size 3x3, stride 2, padding=\"valid\", 15 output channels )\n",
@@ -120,7 +120,7 @@
"# https://pytorch.org/docs/1.13/generated/torch.nn.Linear.html?highlight=linear#torch.nn.Linear\n", "# https://pytorch.org/docs/1.13/generated/torch.nn.Linear.html?highlight=linear#torch.nn.Linear\n",
"\n", "\n",
"# Replace the following function which just runs a standard fully connected network\n", "# Replace the following function which just runs a standard fully connected network\n",
"# The flatten at the beginning is becuase we are passing in the data in a slightly different format.\n", "# The flatten at the beginning is because we are passing in the data in a slightly different format.\n",
"model = nn.Sequential(\n", "model = nn.Sequential(\n",
"nn.Flatten(),\n", "nn.Flatten(),\n",
"nn.Linear(40, 100),\n", "nn.Linear(40, 100),\n",

View File

@@ -148,7 +148,7 @@
"# 8. A flattening operation\n", "# 8. A flattening operation\n",
"# 9. A fully connected layer mapping from (whatever dimensions we are at-- find out using .shape) to 50 \n", "# 9. A fully connected layer mapping from (whatever dimensions we are at-- find out using .shape) to 50 \n",
"# 10. A ReLU\n", "# 10. A ReLU\n",
"# 11. A fully connected layer mappiing from 50 to 10 dimensions\n", "# 11. A fully connected layer mapping from 50 to 10 dimensions\n",
"# 12. A softmax function.\n", "# 12. A softmax function.\n",
"\n", "\n",
"# Replace this class which implements a minimal network (which still does okay)\n", "# Replace this class which implements a minimal network (which still does okay)\n",

View File

@@ -32,7 +32,7 @@
"source": [ "source": [
"# Gradients II: Backpropagation algorithm\n", "# Gradients II: Backpropagation algorithm\n",
"\n", "\n",
"In this practical, we'll investigate the backpropagation algoritithm. This computes the gradients of the loss with respect to all of the parameters (weights and biases) in the network. We'll use these gradients when we run stochastic gradient descent." "In this practical, we'll investigate the backpropagation algorithm. This computes the gradients of the loss with respect to all of the parameters (weights and biases) in the network. We'll use these gradients when we run stochastic gradient descent."
], ],
"metadata": { "metadata": {
"id": "L6chybAVFJW2" "id": "L6chybAVFJW2"
@@ -53,7 +53,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"First let's define a neural network. We'll just choose the weights and biaes randomly for now" "First let's define a neural network. We'll just choose the weights and biases randomly for now"
], ],
"metadata": { "metadata": {
"id": "nnUoI0m6GyjC" "id": "nnUoI0m6GyjC"
@@ -178,7 +178,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now let's define a loss function. We'll just use the least squaures loss function. We'll also write a function to compute dloss_doutpu" "Now let's define a loss function. We'll just use the least squares loss function. We'll also write a function to compute dloss_doutpu"
], ],
"metadata": { "metadata": {
"id": "SxVTKp3IcoBF" "id": "SxVTKp3IcoBF"

View File

@@ -53,7 +53,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"First let's define a neural network. We'll just choose the weights and biaes randomly for now" "First let's define a neural network. We'll just choose the weights and biases randomly for now"
], ],
"metadata": { "metadata": {
"id": "nnUoI0m6GyjC" "id": "nnUoI0m6GyjC"
@@ -204,7 +204,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now let's define a loss function. We'll just use the least squaures loss function. We'll also write a function to compute dloss_doutput\n" "Now let's define a loss function. We'll just use the least squares loss function. We'll also write a function to compute dloss_doutput\n"
], ],
"metadata": { "metadata": {
"id": "SxVTKp3IcoBF" "id": "SxVTKp3IcoBF"

View File

@@ -176,7 +176,7 @@
"# Color represents y value (brighter = higher value)\n", "# Color represents y value (brighter = higher value)\n",
"# Black = -10 or less, White = +10 or more\n", "# Black = -10 or less, White = +10 or more\n",
"# 0 = mid orange\n", "# 0 = mid orange\n",
"# Lines are conoturs where value is equal\n", "# Lines are contours where value is equal\n",
"draw_2D_function(x1,x2,y)\n", "draw_2D_function(x1,x2,y)\n",
"\n", "\n",
"# TODO\n", "# TODO\n",

View File

@@ -215,7 +215,7 @@
"# Color represents y value (brighter = higher value)\n", "# Color represents y value (brighter = higher value)\n",
"# Black = -10 or less, White = +10 or more\n", "# Black = -10 or less, White = +10 or more\n",
"# 0 = mid orange\n", "# 0 = mid orange\n",
"# Lines are conoturs where value is equal\n", "# Lines are contours where value is equal\n",
"draw_2D_function(x1,x2,y)\n", "draw_2D_function(x1,x2,y)\n",
"\n", "\n",
"# TODO\n", "# TODO\n",

View File

@@ -36,7 +36,7 @@
"\n", "\n",
"We'll compute loss functions for maximum likelihood, minimum negative log likelihood, and least squares and show that they all imply that we should use the same parameter values\n", "We'll compute loss functions for maximum likelihood, minimum negative log likelihood, and least squares and show that they all imply that we should use the same parameter values\n",
"\n", "\n",
"In part II, we'll investigate binary classification (where the output data is 0 or 1). This will be based on the Bernouilli distribution\n", "In part II, we'll investigate binary classification (where the output data is 0 or 1). This will be based on the Bernoulli distribution\n",
"\n", "\n",
"In part III we'll investigate multiclass classification (where the output data is 0,1, or, 2). This will be based on the categorical distribution." "In part III we'll investigate multiclass classification (where the output data is 0,1, or, 2). This will be based on the categorical distribution."
], ],
@@ -178,7 +178,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"The blue line i sthe mean prediction of the model and the gray area represents plus/minus two standardard deviations. This model fits okay, but could be improved. Let's compute the loss. We'll compute the the least squares error, the likelihood, the negative log likelihood." "The blue line is the mean prediction of the model and the gray area represents plus/minus two standard deviations. This model fits okay, but could be improved. Let's compute the loss. We'll compute the the least squares error, the likelihood, the negative log likelihood."
], ],
"metadata": { "metadata": {
"id": "MvVX6tl9AEXF" "id": "MvVX6tl9AEXF"
@@ -276,7 +276,7 @@
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n", "beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
"# Use our neural network to predict the mean of the Gaussian\n", "# Use our neural network to predict the mean of the Gaussian\n",
"mu_pred = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", "mu_pred = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"# Set the standard devation to something reasonable\n", "# Set the standard deviation to something reasonable\n",
"sigma = 0.2\n", "sigma = 0.2\n",
"# Compute the likelihood\n", "# Compute the likelihood\n",
"likelihood = compute_likelihood(y_train, mu_pred, sigma)\n", "likelihood = compute_likelihood(y_train, mu_pred, sigma)\n",
@@ -292,7 +292,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"You can see that this gives a very small answer, even for this small 1D dataset, and with the model fitting quite well. This is because it is the product of sveral probabilities, which are all quite small themselves.\n", "You can see that this gives a very small answer, even for this small 1D dataset, and with the model fitting quite well. This is because it is the product of several probabilities, which are all quite small themselves.\n",
"This will get out of hand pretty quickly with real datasets -- the likelihood will get so small that we can't represent it with normal finite-precision math\n", "This will get out of hand pretty quickly with real datasets -- the likelihood will get so small that we can't represent it with normal finite-precision math\n",
"\n", "\n",
"This is why we use negative log likelihood" "This is why we use negative log likelihood"
@@ -326,7 +326,7 @@
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n", "beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
"# Use our neural network to predict the mean of the Gaussian\n", "# Use our neural network to predict the mean of the Gaussian\n",
"mu_pred = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", "mu_pred = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"# Set the standard devation to something reasonable\n", "# Set the standard deviation to something reasonable\n",
"sigma = 0.2\n", "sigma = 0.2\n",
"# Compute the log likelihood\n", "# Compute the log likelihood\n",
"nll = compute_negative_log_likelihood(y_train, mu_pred, sigma)\n", "nll = compute_negative_log_likelihood(y_train, mu_pred, sigma)\n",
@@ -397,7 +397,7 @@
"source": [ "source": [
"# Define a range of values for the parameter\n", "# Define a range of values for the parameter\n",
"beta_1_vals = np.arange(0,1.0,0.01)\n", "beta_1_vals = np.arange(0,1.0,0.01)\n",
"# Create some arrays to store the likelihoods, negative log likehoos and sum of squares\n", "# Create some arrays to store the likelihoods, negative log likelihoods and sum of squares\n",
"likelihoods = np.zeros_like(beta_1_vals)\n", "likelihoods = np.zeros_like(beta_1_vals)\n",
"nlls = np.zeros_like(beta_1_vals)\n", "nlls = np.zeros_like(beta_1_vals)\n",
"sum_squares = np.zeros_like(beta_1_vals)\n", "sum_squares = np.zeros_like(beta_1_vals)\n",
@@ -482,7 +482,7 @@
"source": [ "source": [
"# Define a range of values for the parameter\n", "# Define a range of values for the parameter\n",
"sigma_vals = np.arange(0.1,0.5,0.005)\n", "sigma_vals = np.arange(0.1,0.5,0.005)\n",
"# Create some arrays to store the likelihoods, negative log likehoos and sum of squares\n", "# Create some arrays to store the likelihoods, negative log likelihoods and sum of squares\n",
"likelihoods = np.zeros_like(sigma_vals)\n", "likelihoods = np.zeros_like(sigma_vals)\n",
"nlls = np.zeros_like(sigma_vals)\n", "nlls = np.zeros_like(sigma_vals)\n",
"sum_squares = np.zeros_like(sigma_vals)\n", "sum_squares = np.zeros_like(sigma_vals)\n",

View File

@@ -34,7 +34,7 @@
"\n", "\n",
"This practical investigates loss functions. In part I we investigated univariate regression (where the output data $y$ is continuous. Our formulation was based on the normal/Gaussian distribution.\n", "This practical investigates loss functions. In part I we investigated univariate regression (where the output data $y$ is continuous. Our formulation was based on the normal/Gaussian distribution.\n",
"\n", "\n",
"In this notebook, we investigate binary classification (where the output data is 0 or 1). This will be based on the Bernouilli distribution\n", "In this notebook, we investigate binary classification (where the output data is 0 or 1). This will be based on the Bernoulli distribution\n",
"\n", "\n",
"In part III we'll investigate multiclass classification (where the outputs data can take multiple values 1,... K.\n", "In part III we'll investigate multiclass classification (where the outputs data can take multiple values 1,... K.\n",
"\n", "\n",
@@ -199,7 +199,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"The left is model output and the right is the model output after the sigmoid has been applied, so it now lies in the range [0,1] and represents the probabiilty, that y=1. The black dots show the training data. We'll compute the the likelihood and the negative log likelihood." "The left is model output and the right is the model output after the sigmoid has been applied, so it now lies in the range [0,1] and represents the probability, that y=1. The black dots show the training data. We'll compute the the likelihood and the negative log likelihood."
], ],
"metadata": { "metadata": {
"id": "MvVX6tl9AEXF" "id": "MvVX6tl9AEXF"
@@ -210,7 +210,7 @@
"source": [ "source": [
"# Return probability under Bernoulli distribution for input x\n", "# Return probability under Bernoulli distribution for input x\n",
"def bernoulli_distribution(y, lambda_param):\n", "def bernoulli_distribution(y, lambda_param):\n",
" # TODO-- write in the equation for the Bernoullid distribution \n", " # TODO-- write in the equation for the Bernoulli distribution \n",
" # Equation 5.17 from the notes (you will need np.power)\n", " # Equation 5.17 from the notes (you will need np.power)\n",
" # Replace the line below\n", " # Replace the line below\n",
" prob = np.zeros_like(y)\n", " prob = np.zeros_like(y)\n",
@@ -249,7 +249,7 @@
"source": [ "source": [
"# Return the likelihood of all of the data under the model\n", "# Return the likelihood of all of the data under the model\n",
"def compute_likelihood(y_train, lambda_param):\n", "def compute_likelihood(y_train, lambda_param):\n",
" # TODO -- compute the likelihood of the data -- the product of the Bernoullis probabilities for each data point\n", " # TODO -- compute the likelihood of the data -- the product of the Bernoulli's probabilities for each data point\n",
" # Top line of equation 5.3 in the notes\n", " # Top line of equation 5.3 in the notes\n",
" # You will need np.prod() and the bernoulli_distribution function you used above\n", " # You will need np.prod() and the bernoulli_distribution function you used above\n",
" # Replace the line below\n", " # Replace the line below\n",
@@ -284,7 +284,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"You can see that this gives a very small answer, even for this small 1D dataset, and with the model fitting quite well. This is because it is the product of sveral probabilities, which are all quite small themselves.\n", "You can see that this gives a very small answer, even for this small 1D dataset, and with the model fitting quite well. This is because it is the product of several probabilities, which are all quite small themselves.\n",
"This will get out of hand pretty quickly with real datasets -- the likelihood will get so small that we can't represent it with normal finite-precision math\n", "This will get out of hand pretty quickly with real datasets -- the likelihood will get so small that we can't represent it with normal finite-precision math\n",
"\n", "\n",
"This is why we use negative log likelihood" "This is why we use negative log likelihood"
@@ -317,7 +317,7 @@
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n", "beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
"# Use our neural network to predict the mean of the Gaussian\n", "# Use our neural network to predict the mean of the Gaussian\n",
"model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", "model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"# Set the standard devation to something reasonable\n", "# Set the standard deviation to something reasonable\n",
"lambda_train = sigmoid(model_out)\n", "lambda_train = sigmoid(model_out)\n",
"# Compute the log likelihood\n", "# Compute the log likelihood\n",
"nll = compute_negative_log_likelihood(y_train, lambda_train)\n", "nll = compute_negative_log_likelihood(y_train, lambda_train)\n",
@@ -362,7 +362,7 @@
"source": [ "source": [
"# Define a range of values for the parameter\n", "# Define a range of values for the parameter\n",
"beta_1_vals = np.arange(-2,6.0,0.1)\n", "beta_1_vals = np.arange(-2,6.0,0.1)\n",
"# Create some arrays to store the likelihoods, negative log likehoods\n", "# Create some arrays to store the likelihoods, negative log likelihoods\n",
"likelihoods = np.zeros_like(beta_1_vals)\n", "likelihoods = np.zeros_like(beta_1_vals)\n",
"nlls = np.zeros_like(beta_1_vals)\n", "nlls = np.zeros_like(beta_1_vals)\n",
"\n", "\n",

View File

@@ -33,7 +33,7 @@
"# Loss functions part III\n", "# Loss functions part III\n",
"\n", "\n",
"This practical investigates loss functions. In part I we investigated univariate regression (where the output data $y$ is continuous. Our formulation was based on the normal/Gaussian distribution.\n", "This practical investigates loss functions. In part I we investigated univariate regression (where the output data $y$ is continuous. Our formulation was based on the normal/Gaussian distribution.\n",
"In part II we investigated binary classification (where the output data is 0 or 1). This will be based on the Bernouilli distribution.<br><br>\n", "In part II we investigated binary classification (where the output data is 0 or 1). This will be based on the Bernoulli distribution.<br><br>\n",
"\n", "\n",
"Now we'll investigate multiclass classification (where the outputs data can take multiple values 1,... K, which is based on the categorical distribution\n", "Now we'll investigate multiclass classification (where the outputs data can take multiple values 1,... K, which is based on the categorical distribution\n",
"\n", "\n",
@@ -218,7 +218,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"The left is model output and the right is the model output after the softmax has been applied, so it now lies in the range [0,1] and represents the probabiilty, that y=0 (red), 1 (green) and 2 (blue) The dots at the bottom show the training data with the same color scheme. So we want the red curve to be high where there are red dots, the green curve to be high where there are green dotsmand the blue curve to be high where there are blue dots We'll compute the the likelihood and the negative log likelihood." "The left is model output and the right is the model output after the softmax has been applied, so it now lies in the range [0,1] and represents the probability, that y=0 (red), 1 (green) and 2 (blue) The dots at the bottom show the training data with the same color scheme. So we want the red curve to be high where there are red dots, the green curve to be high where there are green dotsmand the blue curve to be high where there are blue dots We'll compute the the likelihood and the negative log likelihood."
], ],
"metadata": { "metadata": {
"id": "MvVX6tl9AEXF" "id": "MvVX6tl9AEXF"
@@ -228,7 +228,7 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Return probability under Bernoulli distribution for input x\n", "# Return probability under Bernoulli distribution for input x\n",
"# Complicated code to commpute it but just take value from row k of lambda param where y =k, \n", "# Complicated code to compute it but just take value from row k of lambda param where y =k, \n",
"def categorical_distribution(y, lambda_param):\n", "def categorical_distribution(y, lambda_param):\n",
" prob = np.zeros_like(y)\n", " prob = np.zeros_like(y)\n",
" for row_index in range(lambda_param.shape[0]):\n", " for row_index in range(lambda_param.shape[0]):\n",
@@ -305,7 +305,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"You can see that this gives a very small answer, even for this small 1D dataset, and with the model fitting quite well. This is because it is the product of sveral probabilities, which are all quite small themselves.\n", "You can see that this gives a very small answer, even for this small 1D dataset, and with the model fitting quite well. This is because it is the product of several probabilities, which are all quite small themselves.\n",
"This will get out of hand pretty quickly with real datasets -- the likelihood will get so small that we can't represent it with normal finite-precision math\n", "This will get out of hand pretty quickly with real datasets -- the likelihood will get so small that we can't represent it with normal finite-precision math\n",
"\n", "\n",
"This is why we use negative log likelihood" "This is why we use negative log likelihood"
@@ -338,7 +338,7 @@
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n", "beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
"# Use our neural network to predict the mean of the Gaussian\n", "# Use our neural network to predict the mean of the Gaussian\n",
"model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", "model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"# Set the standard devation to something reasonable\n", "# Set the standard deviation to something reasonable\n",
"lambda_train = softmax(model_out)\n", "lambda_train = softmax(model_out)\n",
"# Compute the log likelihood\n", "# Compute the log likelihood\n",
"nll = compute_negative_log_likelihood(y_train, lambda_train)\n", "nll = compute_negative_log_likelihood(y_train, lambda_train)\n",
@@ -365,7 +365,7 @@
"source": [ "source": [
"# Define a range of values for the parameter\n", "# Define a range of values for the parameter\n",
"beta_1_vals = np.arange(-2,6.0,0.1)\n", "beta_1_vals = np.arange(-2,6.0,0.1)\n",
"# Create some arrays to store the likelihoods, negative log likehoods\n", "# Create some arrays to store the likelihoods, negative log likelihoods\n",
"likelihoods = np.zeros_like(beta_1_vals)\n", "likelihoods = np.zeros_like(beta_1_vals)\n",
"nlls = np.zeros_like(beta_1_vals)\n", "nlls = np.zeros_like(beta_1_vals)\n",
"\n", "\n",

View File

@@ -233,7 +233,7 @@
"# TODO\n", "# TODO\n",
"# 1. Predict what effect changing phi_0 will have on the network. \n", "# 1. Predict what effect changing phi_0 will have on the network. \n",
"# Answer:\n", "# Answer:\n",
"# 2. Predict what effect multplying phi_1, phi_2, phi_3 by 0.5 would have. Check if you are correct\n", "# 2. Predict what effect multiplying phi_1, phi_2, phi_3 by 0.5 would have. Check if you are correct\n",
"# Answer:\n", "# Answer:\n",
"# 3. Predict what effect multiplying phi_1 by -1 will have. Check if you are correct.\n", "# 3. Predict what effect multiplying phi_1 by -1 will have. Check if you are correct.\n",
"# Answer:\n", "# Answer:\n",
@@ -500,7 +500,7 @@
"print(\"Loss = %3.3f\"%(loss))\n", "print(\"Loss = %3.3f\"%(loss))\n",
"\n", "\n",
"# TODO. Manipulate the parameters (by hand!) to make the function \n", "# TODO. Manipulate the parameters (by hand!) to make the function \n",
"# fit the data better and try to reduct the loss to as small a number \n", "# fit the data better and try to reduce the loss to as small a number \n",
"# as possible. The best that I could do was 0.181\n", "# as possible. The best that I could do was 0.181\n",
"# Tip... start by manipulating phi_0.\n", "# Tip... start by manipulating phi_0.\n",
"# It's not that easy, so don't spend too much time on this!" "# It's not that easy, so don't spend too much time on this!"

View File

@@ -108,7 +108,7 @@
"source": [ "source": [
"def line_search(loss_function, thresh=.0001, max_iter = 10, draw_flag = False):\n", "def line_search(loss_function, thresh=.0001, max_iter = 10, draw_flag = False):\n",
"\n", "\n",
" # Initialize four points along the rnage we are going to search\n", " # Initialize four points along the range we are going to search\n",
" a = 0\n", " a = 0\n",
" b = 0.33\n", " b = 0.33\n",
" c = 0.66\n", " c = 0.66\n",
@@ -139,7 +139,7 @@
" # Rule #2 If point b is less than point c then\n", " # Rule #2 If point b is less than point c then\n",
" # then point d becomes point c, and\n", " # then point d becomes point c, and\n",
" # point b becomes 1/3 between a and new d\n", " # point b becomes 1/3 between a and new d\n",
" # point c beocome 2/3 between a and new d \n", " # point c becomes 2/3 between a and new d \n",
" # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n", " # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n",
" if (0):\n", " if (0):\n",
" continue;\n", " continue;\n",
@@ -147,7 +147,7 @@
" # Rule #3 If point c is less than point b then\n", " # Rule #3 If point c is less than point b then\n",
" # then point a becomes point b, and\n", " # then point a becomes point b, and\n",
" # point b becomes 1/3 between new a and d\n", " # point b becomes 1/3 between new a and d\n",
" # point c beocome 2/3 between new a and d \n", " # point c becomes 2/3 between new a and d \n",
" # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n", " # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n",
" if(0):\n", " if(0):\n",
" continue\n", " continue\n",

View File

@@ -114,7 +114,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Initialize the parmaeters and draw the model\n", "# Initialize the parameters and draw the model\n",
"phi = np.zeros((2,1))\n", "phi = np.zeros((2,1))\n",
"phi[0] = 0.6 # Intercept\n", "phi[0] = 0.6 # Intercept\n",
"phi[1] = -0.2 # Slope\n", "phi[1] = -0.2 # Slope\n",
@@ -314,7 +314,7 @@
" return compute_loss(data[0,:], data[1,:], model, phi_start+ gradient * dist_prop)\n", " return compute_loss(data[0,:], data[1,:], model, phi_start+ gradient * dist_prop)\n",
"\n", "\n",
"def line_search(data, model, phi, gradient, thresh=.00001, max_dist = 0.1, max_iter = 15, verbose=False):\n", "def line_search(data, model, phi, gradient, thresh=.00001, max_dist = 0.1, max_iter = 15, verbose=False):\n",
" # Initialize four points along the rnage we are going to search\n", " # Initialize four points along the range we are going to search\n",
" a = 0\n", " a = 0\n",
" b = 0.33 * max_dist\n", " b = 0.33 * max_dist\n",
" c = 0.66 * max_dist\n", " c = 0.66 * max_dist\n",
@@ -345,7 +345,7 @@
" # Rule #2 If point b is less than point c then\n", " # Rule #2 If point b is less than point c then\n",
" # then point d becomes point c, and\n", " # then point d becomes point c, and\n",
" # point b becomes 1/3 between a and new d\n", " # point b becomes 1/3 between a and new d\n",
" # point c beocome 2/3 between a and new d \n", " # point c becomes 2/3 between a and new d \n",
" if lossb < lossc:\n", " if lossb < lossc:\n",
" d = c\n", " d = c\n",
" b = a+ (d-a)/3\n", " b = a+ (d-a)/3\n",
@@ -355,7 +355,7 @@
" # Rule #2 If point c is less than point b then\n", " # Rule #2 If point c is less than point b then\n",
" # then point a becomes point b, and\n", " # then point a becomes point b, and\n",
" # point b becomes 1/3 between new a and d\n", " # point b becomes 1/3 between new a and d\n",
" # point c beocome 2/3 between new a and d \n", " # point c becomes 2/3 between new a and d \n",
" a = b\n", " a = b\n",
" b = a+ (d-a)/3\n", " b = a+ (d-a)/3\n",
" c = a+ 2*(d-a)/3\n", " c = a+ 2*(d-a)/3\n",

View File

@@ -340,7 +340,7 @@
" return compute_loss(data[0,:], data[1,:], model, phi_start+ gradient * dist_prop)\n", " return compute_loss(data[0,:], data[1,:], model, phi_start+ gradient * dist_prop)\n",
"\n", "\n",
"def line_search(data, model, phi, gradient, thresh=.00001, max_dist = 0.1, max_iter = 15, verbose=False):\n", "def line_search(data, model, phi, gradient, thresh=.00001, max_dist = 0.1, max_iter = 15, verbose=False):\n",
" # Initialize four points along the rnage we are going to search\n", " # Initialize four points along the range we are going to search\n",
" a = 0\n", " a = 0\n",
" b = 0.33 * max_dist\n", " b = 0.33 * max_dist\n",
" c = 0.66 * max_dist\n", " c = 0.66 * max_dist\n",
@@ -371,7 +371,7 @@
" # Rule #2 If point b is less than point c then\n", " # Rule #2 If point b is less than point c then\n",
" # then point d becomes point c, and\n", " # then point d becomes point c, and\n",
" # point b becomes 1/3 between a and new d\n", " # point b becomes 1/3 between a and new d\n",
" # point c beocome 2/3 between a and new d \n", " # point c becomes 2/3 between a and new d \n",
" if lossb < lossc:\n", " if lossb < lossc:\n",
" d = c\n", " d = c\n",
" b = a+ (d-a)/3\n", " b = a+ (d-a)/3\n",
@@ -381,7 +381,7 @@
" # Rule #2 If point c is less than point b then\n", " # Rule #2 If point c is less than point b then\n",
" # then point a becomes point b, and\n", " # then point a becomes point b, and\n",
" # point b becomes 1/3 between new a and d\n", " # point b becomes 1/3 between new a and d\n",
" # point c beocome 2/3 between new a and d \n", " # point c becomes 2/3 between new a and d \n",
" a = b\n", " a = b\n",
" b = a+ (d-a)/3\n", " b = a+ (d-a)/3\n",
" c = a+ 2*(d-a)/3\n", " c = a+ 2*(d-a)/3\n",

View File

@@ -175,7 +175,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# TODO Modify the code below by changeing the number of tokens generated and the initial sentence\n", "# TODO Modify the code below by changing the number of tokens generated and the initial sentence\n",
"# to get a feel for how well this works. Since I didn't reset the seed, it will give a different\n", "# to get a feel for how well this works. Since I didn't reset the seed, it will give a different\n",
"# answer every time that you run it.\n", "# answer every time that you run it.\n",
"\n", "\n",
@@ -253,7 +253,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# TODO Modify the code below by changeing the number of tokens generated and the initial sentence\n", "# TODO Modify the code below by changing the number of tokens generated and the initial sentence\n",
"# to get a feel for how well this works. \n", "# to get a feel for how well this works. \n",
"\n", "\n",
"# TODO Experiment with changing this line:\n", "# TODO Experiment with changing this line:\n",
@@ -471,7 +471,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# This routine reutnrs the k'th most likely next token.\n", "# This routine returns the k'th most likely next token.\n",
"# If k =0 then it returns the most likely token, if k=1 it returns the next most likely and so on\n", "# If k =0 then it returns the most likely token, if k=1 it returns the next most likely and so on\n",
"# We will need this for beam search\n", "# We will need this for beam search\n",
"def get_kth_most_likely_token(input_tokens, model, tokenizer, k):\n", "def get_kth_most_likely_token(input_tokens, model, tokenizer, k):\n",

BIN
CM20315/Data/Data.zip Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,280 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyPNASgWoh4kBvxFP0xkN/I4",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/CM20315_2023/CM20315_Coursework_I.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# Coursework I -- Model hyperparameters\n",
"\n",
"The goal of the coursework is to modify a simple bit of numpy code that trains a network and measures the performance on a validation set for the MNIST 1D dataset.\n",
"\n",
"In this coursework, you need to modify the **model hyperparameters** (only) to improve the performance over the current attempt. This could mean the number of layers, the number of hidden units per layer, or the type of activation function, or any combination of the three.\n",
"\n",
"The only constraint is that you MUST use a fully connected network (no convolutional networks for now if you have read ahead in the book).\n",
"\n",
"You must improve the performance by at least 2% to get full marks.\n",
"\n",
"You will need to upload three things to Moodle:\n",
"1. The image that this notebook saves (click the folder icon on the left on colab to download it)\n",
"2. The lines of code you changed\n",
"3. The whole notebook as a .ipynb file. You can do this on the File menu\n",
"\n",
"\n"
],
"metadata": {
"id": "t9vk9Elugvmi"
}
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import os\n",
"import torch, torch.nn as nn\n",
"from torch.utils.data import TensorDataset, DataLoader\n",
"from torch.optim.lr_scheduler import StepLR\n",
"import matplotlib.pyplot as plt\n",
"import random\n",
"import gdown"
],
"metadata": {
"id": "YrXWAH7sUWvU"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"\n",
"# Run this once to copy the train and validation data to your CoLab environment\n",
"# or download from my github to your local machine if you are doing this locally\n",
"if not os.path.exists('./Data.zip'):\n",
" !gdown 1HtnCrncY6dFCYqzgPf1HtPVAerTpwFRm\n",
" !unzip Data.zip"
],
"metadata": {
"id": "wScBGXXFVadm"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Load in the data\n",
"train_data_x = np.load('train_data_x.npy')\n",
"val_data_y = np.load('val_data_y.npy')\n",
"train_data_y = np.load('train_data_y.npy')\n",
"val_data_x = np.load('val_data_x.npy')\n",
"# Print out sizes\n",
"print(\"Train data: %d examples (columns), each of which has %d dimensions (rows)\"%((train_data_x.shape[1],train_data_x.shape[0])))\n",
"print(\"Validation data: %d examples (columns), each of which has %d dimensions (rows)\"%((val_data_x.shape[1],val_data_x.shape[0])))"
],
"metadata": {
"id": "8bKADvLHbiV5"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define the network"
],
"metadata": {
"id": "_sFvRDGrl4qe"
}
},
{
"cell_type": "code",
"source": [
"# YOU SHOULD ONLY CHANGE THIS CELL!\n",
"\n",
"# There are 40 input dimensions and 10 output dimensions for this data\n",
"# The inputs correspond to the 40 offsets in the MNIST1D template.\n",
"D_i = 40\n",
"# The outputs correspond to the 10 digits\n",
"D_o = 10\n",
"\n",
"# Number of hidden units in layers 1 and 2\n",
"D_1 = 100\n",
"D_2 = 100\n",
"\n",
"# create model with two hidden layers\n",
"model = nn.Sequential(\n",
"nn.Linear(D_i, D_1),\n",
"nn.ReLU(),\n",
"nn.Linear(D_1, D_2),\n",
"nn.ReLU(),\n",
"nn.Linear(D_2, D_o))"
],
"metadata": {
"id": "FslroPJJffrh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# He initialization of weights\n",
"def weights_init(layer_in):\n",
" if isinstance(layer_in, nn.Linear):\n",
" nn.init.kaiming_uniform_(layer_in.weight)\n",
" layer_in.bias.data.fill_(0.0)"
],
"metadata": {
"id": "YgLaex1pfhqz"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# You need all this stuff to ensure that PyTorch is deterministic\n",
"def set_seed(seed):\n",
" torch.manual_seed(seed)\n",
" torch.cuda.manual_seed_all(seed)\n",
" torch.backends.cudnn.deterministic = True\n",
" torch.backends.cudnn.benchmark = False\n",
" np.random.seed(seed)\n",
" random.seed(seed)\n",
" os.environ['PYTHONHASHSEED'] = str(seed)"
],
"metadata": {
"id": "zXRmxCQNnL_M"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Set seed so always get same result (do not change)\n",
"set_seed(1)\n",
"\n",
"# choose cross entropy loss function (equation 5.24 in the loss notes)\n",
"loss_function = nn.CrossEntropyLoss()\n",
"# construct SGD optimizer and initialize learning rate and momentum\n",
"optimizer = torch.optim.SGD(model.parameters(), lr = 0.05, momentum=0.9)\n",
"# object that decreases learning rate by half every 10 epochs\n",
"scheduler = StepLR(optimizer, step_size=10, gamma=0.5)\n",
"# create 100 dummy data points and store in data loader class\n",
"x_train = torch.tensor(train_data_x.transpose().astype('float32'))\n",
"y_train = torch.tensor(train_data_y.astype('long'))\n",
"x_val= torch.tensor(val_data_x.transpose().astype('float32'))\n",
"y_val = torch.tensor(val_data_y.astype('long'))\n",
"\n",
"# load the data into a class that creates the batches\n",
"data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n",
"\n",
"# Initialize model weights\n",
"model.apply(weights_init)\n",
"\n",
"# loop over the dataset n_epoch times\n",
"n_epoch = 50\n",
"# store the loss and the % correct at each epoch\n",
"losses_train = np.zeros((n_epoch))\n",
"errors_train = np.zeros((n_epoch))\n",
"losses_val = np.zeros((n_epoch))\n",
"errors_val = np.zeros((n_epoch))\n",
"\n",
"for epoch in range(n_epoch):\n",
" # loop over batches\n",
" for i, data in enumerate(data_loader):\n",
" # retrieve inputs and labels for this batch\n",
" x_batch, y_batch = data\n",
" # zero the parameter gradients\n",
" optimizer.zero_grad()\n",
" # forward pass -- calculate model output\n",
" pred = model(x_batch)\n",
" # compute the lss\n",
" loss = loss_function(pred, y_batch)\n",
" # backward pass\n",
" loss.backward()\n",
" # SGD update\n",
" optimizer.step()\n",
"\n",
" # Run whole dataset to get statistics -- normally wouldn't do this\n",
" pred_train = model(x_train)\n",
" pred_val = model(x_val)\n",
" _, predicted_train_class = torch.max(pred_train.data, 1)\n",
" _, predicted_val_class = torch.max(pred_val.data, 1)\n",
" errors_train[epoch] = 100 - 100 * (predicted_train_class == y_train).float().sum() / len(y_train)\n",
" errors_val[epoch]= 100 - 100 * (predicted_val_class == y_val).float().sum() / len(y_val)\n",
" losses_train[epoch] = loss_function(pred_train, y_train).item()\n",
" losses_val[epoch]= loss_function(pred_val, y_val).item()\n",
" print(f'Epoch {epoch:5d}, train loss {losses_train[epoch]:.6f}, train error {errors_train[epoch]:3.2f}, val loss {losses_val[epoch]:.6f}, percent error {errors_val[epoch]:3.2f}')\n",
"\n",
" # tell scheduler to consider updating learning rate\n",
" scheduler.step()\n",
"\n",
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
"ax.plot(errors_train,'r-',label='train')\n",
"ax.plot(errors_val,'b-',label='validation')\n",
"ax.set_ylim(0,100); ax.set_xlim(0,n_epoch)\n",
"ax.set_xlabel('Epoch'); ax.set_ylabel('Error')\n",
"ax.set_title('Part I: Validation Result %3.2f'%(errors_val[-1]))\n",
"ax.legend()\n",
"ax.plot([0,n_epoch],[37.45, 37.45],'k:') # Original results. You should be better than this!\n",
"plt.savefig('Coursework_I_Results.png',format='png')\n",
"plt.show()"
],
"metadata": {
"id": "NYw8I_3mmX5c"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Leave this all commented for now\n",
"# We'll see how well you did on the test data after the coursework is submitted\n",
"\n",
"# # I haven't given you this yet, leave commented\n",
"# test_data_x = np.load('test_data_x.npy')\n",
"# test_data_y = np.load('test_data_y.npy')\n",
"# x_test = torch.tensor(test_data_x.transpose().astype('float32'))\n",
"# y_test = torch.tensor(test_data_y.astype('long'))\n",
"# pred_test = model(x_test)\n",
"# _, predicted_test_class = torch.max(pred_test.data, 1)\n",
"# errors_test = 100 - 100 * (predicted_test_class == y_test).float().sum() / len(y_test)\n",
"# print(\"Test error = %3.3f\"%(errors_test))"
],
"metadata": {
"id": "O7nBz-R84QdJ"
},
"execution_count": null,
"outputs": []
}
]
}

View File

@@ -0,0 +1,276 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyM+iKos5DEoHUxL8+9oxA2A",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/CM20315_2023/CM20315_Coursework_II.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# Coursework II -- Training hyperparameters\n",
"\n",
"The goal of the coursework is to modify a simple bit of numpy code that trains a network and measures the performance on a validation set for the MNist 1D dataset.\n",
"\n",
"In this coursework, you need to modify the **training hyperparameters** (only) to improve the performance over the current attempt. This could mean the training algorithm, learning rate, learning rate schedule, momentum term, initialization etc. \n",
"\n",
"You must improve the performance by at least 2% to get full marks.\n",
"\n",
"You will need to upload three things to Moodle:\n",
"1. The image that this notebook saves (click the folder icon on the left on colab to download it)\n",
"2. The lines of code you changed\n",
"3. The whole notebook as a .ipynb file. You can do this on the File menu"
],
"metadata": {
"id": "t9vk9Elugvmi"
}
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import os\n",
"import torch, torch.nn as nn\n",
"from torch.utils.data import TensorDataset, DataLoader\n",
"from torch.optim.lr_scheduler import StepLR\n",
"import matplotlib.pyplot as plt\n",
"import random\n",
"import gdown"
],
"metadata": {
"id": "YrXWAH7sUWvU"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Run this once to copy the train and validation data to your CoLab environment\n",
"if not os.path.exists('./Data.zip'):\n",
" !gdown 1HtnCrncY6dFCYqzgPf1HtPVAerTpwFRm\n",
" !unzip Data.zip"
],
"metadata": {
"id": "wScBGXXFVadm"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Load in the data\n",
"train_data_x = np.load('train_data_x.npy',allow_pickle=True)\n",
"train_data_y = np.load('train_data_y.npy',allow_pickle=True)\n",
"val_data_x = np.load('val_data_x.npy',allow_pickle=True)\n",
"val_data_y = np.load('val_data_y.npy',allow_pickle=True)\n",
"# Print out sizes\n",
"print(\"Train data: %d examples (columns), each of which has %d dimensions (rows)\"%((train_data_x.shape[1],train_data_x.shape[0])))\n",
"print(\"Validation data: %d examples (columns), each of which has %d dimensions (rows)\"%((val_data_x.shape[1],val_data_x.shape[0])))"
],
"metadata": {
"id": "8bKADvLHbiV5"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define the network"
],
"metadata": {
"id": "_sFvRDGrl4qe"
}
},
{
"cell_type": "code",
"source": [
"# YOU SHOULD NOT CHANGE THIS CELL!\n",
"\n",
"# There are 40 input dimensions and 10 output dimensions for this data\n",
"# The inputs correspond to the 40 offsets in the MNIST1D template.\n",
"D_i = 40\n",
"# The outputs correspond to the 10 digits\n",
"D_o = 10\n",
"\n",
"# Number of hidden units in layers 1 and 2\n",
"D_1 = 100\n",
"D_2 = 100\n",
"\n",
"# create model with two hidden layers\n",
"model = nn.Sequential(\n",
"nn.Linear(D_i, D_1),\n",
"nn.ReLU(),\n",
"nn.Linear(D_1, D_2),\n",
"nn.ReLU(),\n",
"nn.Linear(D_2, D_o))"
],
"metadata": {
"id": "FslroPJJffrh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# He initialization of weights\n",
"def weights_init(layer_in):\n",
" if isinstance(layer_in, nn.Linear):\n",
" nn.init.kaiming_uniform_(layer_in.weight)\n",
" layer_in.bias.data.fill_(0.0)"
],
"metadata": {
"id": "YgLaex1pfhqz"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# You need all this stuff to ensure that PyTorch is deterministic\n",
"def set_seed(seed):\n",
" torch.manual_seed(seed)\n",
" torch.cuda.manual_seed_all(seed)\n",
" torch.backends.cudnn.deterministic = True\n",
" torch.backends.cudnn.benchmark = False\n",
" np.random.seed(seed)\n",
" random.seed(seed)\n",
" os.environ['PYTHONHASHSEED'] = str(seed)"
],
"metadata": {
"id": "zXRmxCQNnL_M"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Set seed so always get same result (do not change)\n",
"set_seed(1)\n",
"\n",
"# choose cross entropy loss function (equation 5.24 in the loss notes)\n",
"loss_function = nn.CrossEntropyLoss()\n",
"# construct SGD optimizer and initialize learning rate and momentum\n",
"optimizer = torch.optim.SGD(model.parameters(), lr = 0.05, momentum=0.9)\n",
"# object that decreases learning rate by half every 10 epochs\n",
"scheduler = StepLR(optimizer, step_size=10, gamma=0.5)\n",
"# create 100 dummy data points and store in data loader class\n",
"x_train = torch.tensor(train_data_x.transpose().astype('float32'))\n",
"print(x_train.shape)\n",
"y_train = torch.tensor(train_data_y.astype('long'))\n",
"print(y_train.shape)\n",
"x_val= torch.tensor(val_data_x.transpose().astype('float32'))\n",
"y_val = torch.tensor(val_data_y.astype('long'))\n",
"\n",
"# load the data into a class that creates the batches\n",
"data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n",
"\n",
"# Initialize model weights\n",
"model.apply(weights_init)\n",
"\n",
"# loop over the dataset n_epoch times\n",
"n_epoch = 50\n",
"# store the loss and the % correct at each epoch\n",
"losses_train = np.zeros((n_epoch))\n",
"errors_train = np.zeros((n_epoch))\n",
"losses_val = np.zeros((n_epoch))\n",
"errors_val = np.zeros((n_epoch))\n",
"\n",
"for epoch in range(n_epoch):\n",
" # loop over batches\n",
" for i, data in enumerate(data_loader):\n",
" # retrieve inputs and labels for this batch\n",
" x_batch, y_batch = data\n",
" # zero the parameter gradients\n",
" optimizer.zero_grad()\n",
" # forward pass -- calculate model output\n",
" pred = model(x_batch)\n",
" # compute the lss\n",
" loss = loss_function(pred, y_batch)\n",
" # backward pass\n",
" loss.backward()\n",
" # SGD update\n",
" optimizer.step()\n",
"\n",
" # Run whole dataset to get statistics -- normally wouldn't do this\n",
" pred_train = model(x_train)\n",
" pred_val = model(x_val)\n",
" _, predicted_train_class = torch.max(pred_train.data, 1)\n",
" _, predicted_val_class = torch.max(pred_val.data, 1)\n",
" errors_train[epoch] = 100 - 100 * (predicted_train_class == y_train).float().sum() / len(y_train)\n",
" errors_val[epoch]= 100 - 100 * (predicted_val_class == y_val).float().sum() / len(y_val)\n",
" losses_train[epoch] = loss_function(pred_train, y_train).item()\n",
" losses_val[epoch]= loss_function(pred_val, y_val).item()\n",
" print(f'Epoch {epoch:5d}, train loss {losses_train[epoch]:.6f}, train error {errors_train[epoch]:3.2f}, val loss {losses_val[epoch]:.6f}, percent error {errors_val[epoch]:3.2f}')\n",
"\n",
" # tell scheduler to consider updating learning rate\n",
" scheduler.step()\n",
"\n",
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
"ax.plot(errors_train,'r-',label='train')\n",
"ax.plot(errors_val,'b-',label='validation')\n",
"ax.set_ylim(0,100); ax.set_xlim(0,n_epoch)\n",
"ax.set_xlabel('Epoch'); ax.set_ylabel('Error')\n",
"ax.set_title('Part II: Validation Result %3.2f'%(errors_val[-1]))\n",
"ax.legend()\n",
"ax.plot([0,n_epoch],[37.45, 37.45],'k:') # Original results. You should be better than this!\n",
"plt.savefig('Coursework_II_Results.png',format='png')\n",
"plt.show()"
],
"metadata": {
"id": "NYw8I_3mmX5c"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Leave this all commented for now\n",
"# We'll see how well you did on the test data after the coursework is submitted\n",
"\n",
"# # I haven't given you this yet, leave commented\n",
"# test_data_x = np.load('test_data_x.npy')\n",
"# test_data_y = np.load('test_data_y.npy')\n",
"# x_test = torch.tensor(test_data_x.transpose().astype('float32'))\n",
"# y_test = torch.tensor(test_data_y.astype('long'))\n",
"# pred_test = model(x_test)\n",
"# _, predicted_test_class = torch.max(pred_test.data, 1)\n",
"# errors_test = 100 - 100 * (predicted_test_class == y_test).float().sum() / len(y_test)\n",
"# print(\"Test error = %3.3f\"%(errors_test))"
],
"metadata": {
"id": "O7nBz-R84QdJ"
},
"execution_count": null,
"outputs": []
}
]
}

View File

@@ -0,0 +1,275 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNDH1z3I76jjglu3o0LSlZc",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/CM20315_2023/CM20315_Coursework_III.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# Coursework III -- Regularization\n",
"\n",
"The goal of the coursework is to modify a simple bit of numpy code that trains a network and measures the performance on a validation set for the MNist 1D dataset.\n",
"\n",
"In this coursework, you need add **regularization** of some kind to improve the performance. Anything from chapter 9 of the book or anything else you can find is fine *except* early stopping. You must not change the model hyperparameters or the training algorithm.\n",
"\n",
"You must improve the performance by at least 2% to get full marks.\n",
"\n",
"You will need to upload three things to Moodle:\n",
"1. The image that this notebook saves (click the folder icon on the left on colab to download it)\n",
"2. The lines of code you changed\n",
"3. The whole notebook as a .ipynb file. You can do this on the File menu\n",
"\n",
"\n"
],
"metadata": {
"id": "t9vk9Elugvmi"
}
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import os\n",
"import torch, torch.nn as nn\n",
"from torch.utils.data import TensorDataset, DataLoader\n",
"from torch.optim.lr_scheduler import StepLR\n",
"import matplotlib.pyplot as plt\n",
"import random\n",
"import gdown"
],
"metadata": {
"id": "YrXWAH7sUWvU"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Run this once to copy the train and validation data to your CoLab environment\n",
"if not os.path.exists('./Data.zip'):\n",
" !gdown 1HtnCrncY6dFCYqzgPf1HtPVAerTpwFRm\n",
" !unzip Data.zip"
],
"metadata": {
"id": "wScBGXXFVadm"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Load in the data\n",
"train_data_x = np.load('train_data_x.npy')\n",
"train_data_y = np.load('train_data_y.npy')\n",
"val_data_x = np.load('val_data_x.npy')\n",
"val_data_y = np.load('val_data_y.npy')\n",
"# Print out sizes\n",
"print(\"Train data: %d examples (columns), each of which has %d dimensions (rows)\"%((train_data_x.shape[1],train_data_x.shape[0])))\n",
"print(\"Validation data: %d examples (columns), each of which has %d dimensions (rows)\"%((val_data_x.shape[1],val_data_x.shape[0])))"
],
"metadata": {
"id": "8bKADvLHbiV5"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define the network"
],
"metadata": {
"id": "_sFvRDGrl4qe"
}
},
{
"cell_type": "code",
"source": [
"# There are 40 input dimensions and 10 output dimensions for this data\n",
"# The inputs correspond to the 40 offsets in the MNIST1D template.\n",
"D_i = 40\n",
"# The outputs correspond to the 10 digits\n",
"D_o = 10\n",
"\n",
"# Number of hidden units in layers 1 and 2\n",
"D_1 = 100\n",
"D_2 = 100\n",
"\n",
"# create model with two hidden layers\n",
"model = nn.Sequential(\n",
"nn.Linear(D_i, D_1),\n",
"nn.ReLU(),\n",
"nn.Linear(D_1, D_2),\n",
"nn.ReLU(),\n",
"nn.Linear(D_2, D_o))"
],
"metadata": {
"id": "FslroPJJffrh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# He initialization of weights\n",
"def weights_init(layer_in):\n",
" if isinstance(layer_in, nn.Linear):\n",
" nn.init.kaiming_uniform_(layer_in.weight)\n",
" layer_in.bias.data.fill_(0.0)"
],
"metadata": {
"id": "YgLaex1pfhqz"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# You need all this stuff to ensure that PyTorch is deterministic\n",
"def set_seed(seed):\n",
" torch.manual_seed(seed)\n",
" torch.cuda.manual_seed_all(seed)\n",
" torch.backends.cudnn.deterministic = True\n",
" torch.backends.cudnn.benchmark = False\n",
" np.random.seed(seed)\n",
" random.seed(seed)\n",
" os.environ['PYTHONHASHSEED'] = str(seed)"
],
"metadata": {
"id": "zXRmxCQNnL_M"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Set seed so always get same result (do not change)\n",
"set_seed(1)\n",
"\n",
"# choose cross entropy loss function (equation 5.24 in the loss notes)\n",
"loss_function = nn.CrossEntropyLoss()\n",
"# construct SGD optimizer and initialize learning rate and momentum\n",
"optimizer = torch.optim.SGD(model.parameters(), lr = 0.05, momentum=0.9)\n",
"# object that decreases learning rate by half every 10 epochs\n",
"scheduler = StepLR(optimizer, step_size=10, gamma=0.5)\n",
"# create 100 dummy data points and store in data loader class\n",
"x_train = torch.tensor(train_data_x.transpose().astype('float32'))\n",
"y_train = torch.tensor(train_data_y.astype('long'))\n",
"x_val= torch.tensor(val_data_x.transpose().astype('float32'))\n",
"y_val = torch.tensor(val_data_y.astype('long'))\n",
"\n",
"# load the data into a class that creates the batches\n",
"data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n",
"\n",
"# Initialize model weights\n",
"model.apply(weights_init)\n",
"\n",
"# loop over the dataset n_epoch times\n",
"n_epoch = 50\n",
"# store the loss and the % correct at each epoch\n",
"losses_train = np.zeros((n_epoch))\n",
"errors_train = np.zeros((n_epoch))\n",
"losses_val = np.zeros((n_epoch))\n",
"errors_val = np.zeros((n_epoch))\n",
"\n",
"for epoch in range(n_epoch):\n",
" # loop over batches\n",
" for i, data in enumerate(data_loader):\n",
" # retrieve inputs and labels for this batch\n",
" x_batch, y_batch = data\n",
" # zero the parameter gradients\n",
" optimizer.zero_grad()\n",
" # forward pass -- calculate model output\n",
" pred = model(x_batch)\n",
" # compute the lss\n",
" loss = loss_function(pred, y_batch)\n",
" # backward pass\n",
" loss.backward()\n",
" # SGD update\n",
" optimizer.step()\n",
"\n",
" # Run whole dataset to get statistics -- normally wouldn't do this\n",
" pred_train = model(x_train)\n",
" pred_val = model(x_val)\n",
" _, predicted_train_class = torch.max(pred_train.data, 1)\n",
" _, predicted_val_class = torch.max(pred_val.data, 1)\n",
" errors_train[epoch] = 100 - 100 * (predicted_train_class == y_train).float().sum() / len(y_train)\n",
" errors_val[epoch]= 100 - 100 * (predicted_val_class == y_val).float().sum() / len(y_val)\n",
" losses_train[epoch] = loss_function(pred_train, y_train).item()\n",
" losses_val[epoch]= loss_function(pred_val, y_val).item()\n",
" print(f'Epoch {epoch:5d}, train loss {losses_train[epoch]:.6f}, train error {errors_train[epoch]:3.2f}, val loss {losses_val[epoch]:.6f}, percent error {errors_val[epoch]:3.2f}')\n",
"\n",
" # tell scheduler to consider updating learning rate\n",
" scheduler.step()\n",
"\n",
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
"ax.plot(errors_train,'r-',label='train')\n",
"ax.plot(errors_val,'b-',label='validation')\n",
"ax.set_ylim(0,100); ax.set_xlim(0,n_epoch)\n",
"ax.set_xlabel('Epoch'); ax.set_ylabel('Error')\n",
"ax.set_title('Part III: Validation Result %3.2f'%(errors_val[-1]))\n",
"ax.legend()\n",
"ax.plot([0,n_epoch],[37.45, 37.45],'k:') # Original results. You should be better than this!\n",
"plt.savefig('Coursework_III_Results.png',format='png')\n",
"plt.show()"
],
"metadata": {
"id": "NYw8I_3mmX5c"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Leave this all commented for now\n",
"# We'll see how well you did on the test data after the coursework is submitted\n",
"\n",
"\n",
"# # I haven't given you this yet, leave commented\n",
"# test_data_x = np.load('test_data_x.npy')\n",
"# test_data_y = np.load('test_data_y.npy')\n",
"# x_test = torch.tensor(test_data_x.transpose().astype('float32'))\n",
"# y_test = torch.tensor(test_data_y.astype('long'))\n",
"# pred_test = model(x_test)\n",
"# _, predicted_test_class = torch.max(pred_test.data, 1)\n",
"# errors_test = 100 - 100 * (predicted_test_class == y_test).float().sum() / len(y_test)\n",
"# print(\"Test error = %3.3f\"%(errors_test))"
],
"metadata": {
"id": "O7nBz-R84QdJ"
},
"execution_count": null,
"outputs": []
}
]
}

View File

@@ -0,0 +1,212 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyMrWYwQrwgJvDza1vhYK9WQ",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/CM20315_2023/CM20315_Coursework_IV.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# Coursework IV\n",
"\n",
"This coursework explores the geometry of high dimensional spaces. It doesn't behave how you would expect and all your intuitions are wrong! You will write code and it will give you three numerical answers that you need to type into Moodle."
],
"metadata": {
"id": "EjLK-kA1KnYX"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4ESMmnkYEVAb"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import scipy.special as sci"
]
},
{
"cell_type": "markdown",
"source": [
"# Part (a)\n",
"\n",
"In part (a) of the practical, we investigate how close random points are in 2D, 100D, and 1000D. In each case, we generate 1000 points and calculate the Euclidean distance between each pair. You should find that in 1000D, the furthest two points are only slightly further apart than the nearest points. Weird!"
],
"metadata": {
"id": "MonbPEitLNgN"
}
},
{
"cell_type": "code",
"source": [
"# Fix the random seed so we all have the same random numbers\n",
"np.random.seed(0)\n",
"n_data = 1000\n",
"# Create 1000 data examples (columns) each with 2 dimensions (rows)\n",
"n_dim = 2\n",
"x_2D = np.random.normal(size=(n_dim,n_data))\n",
"# Create 1000 data examples (columns) each with 100 dimensions (rows)\n",
"n_dim = 100\n",
"x_100D = np.random.normal(size=(n_dim,n_data))\n",
"# Create 1000 data examples (columns) each with 1000 dimensions (rows)\n",
"n_dim = 1000\n",
"x_1000D = np.random.normal(size=(n_dim,n_data))\n",
"\n",
"# These values should be the same, otherwise your answer will be wrong\n",
"# Get in touch if they are not!\n",
"print('Sum of your data is %3.3f, Should be %3.3f'%(np.sum(x_1000D),1036.321))"
],
"metadata": {
"id": "vZSHVmcWEk14"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def distance_ratio(x):\n",
" # TODO -- replace the two lines below to calculate the largest and smallest Euclidean distance between\n",
" # the data points in the columns of x. DO NOT include the distance between the data point\n",
" # and itself (which is obviously zero)\n",
" smallest_dist = 1.0\n",
" largest_dist = 1.0\n",
"\n",
" # Calculate the ratio and return\n",
" dist_ratio = largest_dist / smallest_dist\n",
" return dist_ratio"
],
"metadata": {
"id": "PhVmnUs8ErD9"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"print('Ratio of largest to smallest distance 2D: %3.3f'%(distance_ratio(x_2D)))\n",
"print('Ratio of largest to smallest distance 100D: %3.3f'%(distance_ratio(x_100D)))\n",
"print('Ratio of largest to smallest distance 1000D: %3.3f'%(distance_ratio(x_1000D)))\n",
"print('**Note down the last of these three numbers, you will need to submit it for your coursework**')"
],
"metadata": {
"id": "0NdPxfn5GQuJ"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Part (b)\n",
"\n",
"In part (b) of the practical we calculate the volume of a hypersphere of radius 0.5 (i.e., of diameter 1) as a function of the radius. You will find that the volume decreases to almost nothing in high dimensions. All of the volume is in the corners of the unit hypercube (which always has volume 1). Double weird.\n",
"\n",
"Note that you you can check your answer by doing the calculation for 2D using the standard formula for the area of a circle and making sure it matches."
],
"metadata": {
"id": "b2FYKV1SL4Z7"
}
},
{
"cell_type": "code",
"source": [
"def volume_of_hypersphere(diameter, dimensions):\n",
" # Formula given in Problem 8.7 of the notes\n",
" # You will need sci.gamma()\n",
" # Check out: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.gamma.html\n",
" # Also use this value for pi\n",
" pi = np.pi\n",
" # TODO replace this code with formula for the volume of a hypersphere\n",
" volume = 1.0\n",
"\n",
" return volume\n"
],
"metadata": {
"id": "CZoNhD8XJaHR"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"diameter = 1.0\n",
"for c_dim in range(1,11):\n",
" print(\"Volume of unit diameter hypersphere in %d dimensions is %3.3f\"%(c_dim, volume_of_hypersphere(diameter, c_dim)))\n",
"print('**Note down the last of these ten numbers, you will need to submit it for your coursework**')"
],
"metadata": {
"id": "fNTBlg_GPEUh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Part (c)\n",
"\n",
"In part (c) of the coursework, you will calculate what proportion of the volume of a hypersphere is in the outer 1% of the radius/diameter. Calculate the volume of a hypersphere and then the volume of a hypersphere with 0.99 of the radius and then figure out the proportion (a number between 0 and 1). You'll see that by the time we get to 300 dimensions most of the volume is in the outer 1 percent. Extremely weird!"
],
"metadata": {
"id": "GdyMeOBmoXyF"
}
},
{
"cell_type": "code",
"source": [
"def get_prop_of_volume_in_outer_1_percent(dimension):\n",
" # TODO -- replace this line\n",
" proportion = 1.0\n",
"\n",
" return proportion"
],
"metadata": {
"id": "8_CxZ2AIpQ8w"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# While we're here, let's look at how much of the volume is in the outer 1% of the radius\n",
"for c_dim in [1,2,10,20,50,100,150,200,250,300]:\n",
" print('Proportion of volume in outer 1 percent of radius in %d dimensions =%3.3f'%(c_dim, get_prop_of_volume_in_outer_1_percent(c_dim)))\n",
"print('**Note down the last of these ten numbers, you will need to submit it for your coursework**')"
],
"metadata": {
"id": "LtMDIn2qPVfJ"
},
"execution_count": null,
"outputs": []
}
]
}

View File

@@ -0,0 +1,525 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyN7KaQQ63bf52r+b5as0MkK",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/CM20315_2023/CM20315_Coursework_V_2023.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# **Coursework V: Backpropagation in Toy Model**\n",
"\n",
"This notebook computes the derivatives of a toy function similar (but different from) that in section 7.3 of the book.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions. At various points, you will get an answer that you need to copy into Moodle to be marked.\n",
"\n",
"Post to the content forum if you find any mistakes or need to clarify something."
],
"metadata": {
"id": "pOZ6Djz0dhoy"
}
},
{
"cell_type": "markdown",
"source": [
"# Problem setting\n",
"\n",
"We're going to investigate how to take the derivatives of functions where one operation is composed with another, which is composed with a third and so on. For example, consider the model:\n",
"\n",
"\\begin{equation}\n",
" \\mbox{f}[x,\\boldsymbol\\phi] = \\beta_3+\\omega_3\\cdot\\mbox{PReLU}\\Bigl[\\gamma, \\beta_2+\\omega_2\\cdot\\mbox{PReLU}\\bigl[\\gamma, \\beta_1+\\omega_1\\cdot\\mbox{PReLU}[\\gamma, \\beta_0+\\omega_0x]\\bigr]\\Bigr],\n",
"\\end{equation}\n",
"\n",
"with parameters $\\boldsymbol\\phi=\\{\\beta_0,\\omega_0,\\beta_1,\\omega_1,\\beta_2,\\omega_2,\\beta_3,\\omega_3\\}$, where\n",
"\n",
"\\begin{equation}\n",
"\\mbox{PReLU}[\\gamma, z] = \\begin{cases} \\gamma\\cdot z & \\quad z \\leq0 \\\\ z & \\quad z> 0\\end{cases}.\n",
"\\end{equation}\n",
"\n",
"Suppose that we have a binary cross-entropy loss function (equation 5.20 from the book):\n",
"\n",
"\\begin{equation*}\n",
"\\ell_i = -(1-y_{i})\\log\\Bigl[1-\\mbox{sig}[\\mbox{f}[\\mathbf{x}_i,\\boldsymbol\\phi]]\\Bigr] - y_{i}\\log\\Bigl[\\mbox{sig}[\\mbox{f}[\\mathbf{x}_i,\\boldsymbol\\phi]]\\Bigr].\n",
"\\end{equation*}\n",
"\n",
"Assume that we know the current values of $\\beta_{0},\\beta_{1},\\beta_{2},\\beta_{3},\\omega_{0},\\omega_{1},\\omega_{2},\\omega_{3}$, $\\gamma$, $x_i$ and $y_i$. We want to know how $\\ell_i$ changes when we make a small change to $\\beta_{0},\\beta_{1},\\beta_{2},\\beta_{3},\\omega_{0},\\omega_{1},\\omega_{2}$, or $\\omega_{3}$. In other words, we want to compute the eight derivatives:\n",
"\n",
"\\begin{eqnarray*}\n",
"\\frac{\\partial \\ell_i}{\\partial \\beta_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{2}}, \\quad \\frac{\\partial \\ell_i }{\\partial \\beta_{3}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{2}}, \\quad\\mbox{and} \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{3}}.\n",
"\\end{eqnarray*}"
],
"metadata": {
"id": "1DmMo2w63CmT"
}
},
{
"cell_type": "code",
"source": [
"# import library\n",
"import numpy as np"
],
"metadata": {
"id": "RIPaoVN834Lj"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Let's first define the original function and the loss term:"
],
"metadata": {
"id": "32-ufWhc3v2c"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "AakK_qen3BpU"
},
"outputs": [],
"source": [
"# Defines the activation function\n",
"def paramReLU(gamma,x):\n",
" if x > 0:\n",
" return x\n",
" else:\n",
" return x * gamma\n",
"\n",
"# Defines the main function\n",
"def fn(x, beta0, beta1, beta2, beta3, omega0, omega1, omega2, omega3, gamma):\n",
" return beta3+omega3 * paramReLU(gamma, beta2 + omega2 * paramReLU(gamma, beta1 + omega1 * paramReLU(gamma, beta0 + omega0 * x)))\n",
"\n",
"# Logistic sigmoid\n",
"def sig(z):\n",
" return 1./(1+np.exp(-z))\n",
"\n",
"# The loss function (equation 5.20 from book)\n",
"def loss(f,y):\n",
" sig_net_out = sig(f)\n",
" l = -(1-y) * np.log(1-sig_net_out) - y * np.log(sig_net_out)\n",
" return l"
]
},
{
"cell_type": "markdown",
"source": [
"Now we'll choose some values for the betas and the omegas and x and compute the output of the function:"
],
"metadata": {
"id": "y7tf0ZMt5OXt"
}
},
{
"cell_type": "code",
"source": [
"beta0 = 1.0; beta1 = -2.0; beta2 = -3.0; beta3 = 0.4\n",
"omega0 = 0.1; omega1 = -0.4; omega2 = 2.0; omega3 = -3.0\n",
"gamma = 0.2\n",
"x = 2.3; y =1.0\n",
"f_val = fn(x,beta0,beta1,beta2,beta3,omega0,omega1,omega2,omega3, gamma)\n",
"l_i_func = loss(f_val, y)\n",
"print('Loss full function = %3.3f'%l_i_func)"
],
"metadata": {
"id": "pwvOcCxr41X_"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Forward pass\n",
"\n",
"We compute a series of intermediate values $f_0, h_0, f_1, h_1, f_2, h_2, f_3$, and finally the loss $\\ell$"
],
"metadata": {
"id": "W6ZP62T5fU64"
}
},
{
"cell_type": "code",
"source": [
"x = 2.3; y =1.0\n",
"gamma = 0.2\n",
"# Compute all the f_k and h_k terms\n",
"# I've done the first two for you\n",
"f0 = beta0+omega0 * x\n",
"h1 = paramReLU(gamma, f0)\n",
"\n",
"\n",
"# TODO: Replace the code below\n",
"f1 = 0\n",
"h2 = 0\n",
"f2 = 0\n",
"h3 = 0\n",
"f3 = 0\n",
"\n",
"\n",
"# Compute the loss and print\n",
"# The answer should be the same as when we computed the full function above\n",
"l_i = loss(f3, y)\n",
"print(\"Loss forward pass = %3.3f\"%(l_i))\n"
],
"metadata": {
"id": "z-BckTpMf5PL"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Backward pass: Derivative of loss function with respect to function output\n",
"\n",
"Now, we'll compute the derivative $\\frac{dl}{df_3}$ of the loss function with respect to the network output $f_3$. In other words, we are asking how does the loss change as we make a small change in the network output.\n",
"\n",
"Since the loss it itself a function of $\\mbox{sig}[f_3]$ we'll compute this using the chain rule:\n",
"\n",
"\\begin{equation}\n",
"\\frac{dl}{df_3} = \\frac{d\\mbox{sig}[f_3]}{df_3}\\cdot \\frac{dl}{d\\mbox{sig}[f_3]}\n",
"\\end{equation}\n",
"\n",
"Your job is to compute the two quantities on the right hand side.\n"
],
"metadata": {
"id": "TbFbxz64Xz4I"
}
},
{
"cell_type": "code",
"source": [
"# Compute the derivative of the the loss with respect to the function output f_val\n",
"def dl_df(f_val,y):\n",
" # Compute sigmoid of network output\n",
" sig_f_val = sig(f_val)\n",
" # Compute the derivative of loss with respect to network output using chain rule\n",
" dl_df_val = dsig_df(f_val) * dl_dsigf(sig_f_val, y)\n",
" # Return the derivative\n",
" return dl_df_val"
],
"metadata": {
"id": "ZWKAq6HC90qV"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# MOODLE ANSWER # Notebook V 1a: Copy this code when you have finished it.\n",
"\n",
"# Compute the derivative of the logistic sigmoid function with respect to its input (as a closed form solution)\n",
"def dsig_df(f_val):\n",
" # TODO Write this function\n",
" # Replace this line:\n",
" return 1\n",
"\n",
"# Compute the derivative of the loss with respect to the logistic sigmoid (as a closed form solution)\n",
"def dl_dsigf(sig_f_val, y):\n",
" # TODO Write this function\n",
" # Replace this line:\n",
" return 1"
],
"metadata": {
"id": "lIngYAgPq-5I"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Let's run that for some f_val, y. Check previous practicals to see how you can check whether your answer is correct."
],
"metadata": {
"id": "Q-j-i8khXzbK"
}
},
{
"cell_type": "code",
"source": [
"y = 0.0\n",
"dl_df3 = dl_df(f3,y)\n",
"print(\"Moodle Answer Notebook V 1b: dldh3=%3.3f\"%(dl_df3))\n",
"\n",
"y= 1.0\n",
"dl_df3 = dl_df(f3,y)\n",
"print(\"Moodle Answer Notebook V 1c: dldh3=%3.3f\"%(dl_df3))"
],
"metadata": {
"id": "Z7Lb5BibY50H"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Backward pass: Derivative of activation function with respect to preactivations\n",
"\n",
"Write a function to compute the derivative $\\frac{\\partial h}{\\partial f}$ of the activation function (parametric ReLU) with respect to its input.\n"
],
"metadata": {
"id": "BA7QaOzejzZw"
}
},
{
"cell_type": "code",
"source": [
"# MOODLE ANSWER Notebook V 2a: Copy this code when you have finished it.\n",
"\n",
"def dh_df(gamma, f_val):\n",
" # TODO: Write this function\n",
" # Replace this line:\n",
" return 1\n"
],
"metadata": {
"id": "bBPfPg04j-Qw"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Let's run that for some values of f_val. Check previous practicals to see how you can check whether your answer is correct."
],
"metadata": {
"id": "QRNCM0EGk9-w"
}
},
{
"cell_type": "code",
"source": [
"f_val_test = 0.6\n",
"dh_df_val = dh_df(gamma, f_val_test)\n",
"print(\"Moodle Answer Notebook V 2b: dhdf=%3.3f\"%(dh_df_val))\n",
"\n",
"f_val_test = -0.4\n",
"dh_df_val = dh_df(gamma, f_val_test)\n",
"print(\"Moodle Answer Notebook V 2c: dhdf=%3.3f\"%(dh_df_val))"
],
"metadata": {
"id": "bql8VZIGk8Wy"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
" # Backward pass: Compute the derivatives of $l_i$ with respect to the intermediate quantities but in reverse order:\n",
"\n",
"\\begin{eqnarray}\n",
"\\frac{\\partial \\ell_i}{\\partial h_3}, \\quad \\frac{\\partial \\ell_i}{\\partial f_2}, \\quad\n",
"\\frac{\\partial \\ell_i}{\\partial h_2}, \\quad \\frac{\\partial \\ell_i}{\\partial f_1}, \\quad\\frac{\\partial \\ell_i}{\\partial h_1}, \\quad\\mbox{and} \\quad \\frac{\\partial \\ell_i}{\\partial f_0}.\n",
"\\end{eqnarray}\n",
"\n",
"The first of these derivatives can be calculated using the chain rule:\n",
"\n",
"\\begin{equation}\n",
"\\frac{\\partial \\ell_i}{\\partial h_{3}} =\\frac{\\partial f_{3}}{\\partial h_{3}} \\frac{\\partial \\ell_i}{\\partial f_{3}} .\n",
"\\end{equation}\n",
"\n",
"The left-hand side asks how $\\ell_i$ changes when $h_{3}$ changes. The right-hand side says we can decompose this into (i) how $\\ell_i$ changes when $f_{3}$ changes and how $f_{3}$ changes when $h_{3}$ changes. So you get a chain of events happening: $h_{3}$ changes $f_{3}$, which changes $\\ell_i$, and the derivatives represent the effects of this chain. Notice that we computed the first of these derivatives already. The second term is the derivative of $\\beta_{3} + \\omega_{3}h_{3}$ with respect to $h_3$ which is simply $\\omega_3$. \n",
"\n",
"We can continue in this way, computing the derivatives of the output with respect to these intermediate quantities:\n",
"\n",
"\\begin{eqnarray}\n",
"\\frac{\\partial \\ell_i}{\\partial f_{2}} &=& \\frac{\\partial h_{3}}{\\partial f_{2}}\\left(\n",
"\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\n",
"\\nonumber \\\\\n",
"\\frac{\\partial \\ell_i}{\\partial h_{2}} &=& \\frac{\\partial f_{2}}{\\partial h_{2}}\\left(\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}}\\right)\\nonumber \\\\\n",
"\\frac{\\partial \\ell_i}{\\partial f_{1}} &=& \\frac{\\partial h_{2}}{\\partial f_{1}}\\left( \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\\nonumber \\\\\n",
"\\frac{\\partial \\ell_i}{\\partial h_{1}} &=& \\frac{\\partial f_{1}}{\\partial h_{1}}\\left(\\frac{\\partial h_{2}}{\\partial f_{1}} \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\\nonumber \\\\\n",
"\\frac{\\partial \\ell_i}{\\partial f_{0}} &=& \\frac{\\partial h_{1}}{\\partial f_{0}}\\left(\\frac{\\partial f_{1}}{\\partial h_{1}}\\frac{\\partial h_{2}}{\\partial f_{1}} \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right).\n",
"\\end{eqnarray}\n",
"\n",
"In each case, we have already computed all of the terms except the last one in the previous step, and the last term is simple to evaluate. This is called the **backward pass**."
],
"metadata": {
"id": "jay8NYWdFHuZ"
}
},
{
"cell_type": "code",
"source": [
"x = 2.3; y =1.0\n",
"dldf3 = dl_df(f3,y)"
],
"metadata": {
"id": "RSC_2CIfKF1b"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# MOODLE ANSWER Notebook V 3a: Copy this code when you have finished it.\n",
"# TODO -- Compute the derivatives of the output with respect\n",
"# to the intermediate computations h_k and f_k (i.e, run the backward pass)\n",
"# I've done the first two for you. You replace the code below:\n",
"# Replace the code below\n",
"dldh3 = 1\n",
"dldf2 = 1\n",
"dldh2 = 1\n",
"dldf1 = 1\n",
"dldh1 = 1\n",
"dldf0 = 1"
],
"metadata": {
"id": "gCQJeI--Egdl"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Finally, we consider how the loss~$\\ell_{i}$ changes when we change the parameters $\\beta_{\\bullet}$ and $\\omega_{\\bullet}$. Once more, we apply the chain rule:\n",
"\n",
"\n",
"\n",
"\n",
"\\begin{eqnarray}\n",
"\\frac{\\partial \\ell_i}{\\partial \\beta_{k}} &=& \\frac{\\partial f_{k}}{\\partial \\beta_{k}}\\frac{\\partial \\ell_i}{\\partial f_{k}}\\nonumber \\\\\n",
"\\frac{\\partial \\ell_i}{\\partial \\omega_{k}} &=& \\frac{\\partial f_{k}}{\\partial \\omega_{k}}\\frac{\\partial \\ell_i}{\\partial f_{k}}.\n",
"\\end{eqnarray}\n",
"\n",
"\\noindent In each case, the second term on the right-hand side was computed in step 2. When $k>0$, we have~$f_{k}=\\beta_{k}+\\omega_k \\cdot h_{k}$, so:\n",
"\n",
"\\begin{eqnarray}\n",
"\\frac{\\partial f_{k}}{\\partial \\beta_{k}} = 1 \\quad\\quad\\mbox{and}\\quad \\quad \\frac{\\partial f_{k}}{\\partial \\omega_{k}} &=& h_{k}.\n",
"\\end{eqnarray}"
],
"metadata": {
"id": "FlzlThQPGpkU"
}
},
{
"cell_type": "code",
"source": [
"# MOODLE ANSWER Notebook V 3b: Copy this code when you have finished it.\n",
"# TODO -- Calculate the final derivatives with respect to the beta and omega terms\n",
"# Replace these terms\n",
"dldbeta3 = 1\n",
"dldomega3 = 1\n",
"dldbeta2 = 1\n",
"dldomega2 = 1\n",
"dldbeta1 = 1\n",
"dldomega1 = 1\n",
"dldbeta0 = 1\n",
"dldomega0 = 1"
],
"metadata": {
"id": "1I2BhqZhGMK6"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Print the last two values out (enter these into Moodle). Again, think about how you can test whether these are correct.\n",
"print('Moodle Answer Notebook V 3c: dldbeta0=%3.3f'%(dldbeta0))\n",
"print('Moodle Answer Notebook V 3d: dldOmega0=%3.3f'%(dldomega0))"
],
"metadata": {
"id": "38eiOn2aHgHI"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# Compute the derivatives of $\\ell_i$ with respect to the parmeter $\\gamma$ of the parametric ReLU function. \n",
"\n",
"In other words, compute:\n",
"\n",
"\\begin{equation}\n",
"\\frac{d\\ell_i}{d\\gamma}\n",
"\\end{equation}\n",
"\n",
"Along the way, we will need to compute derivatives\n",
"\n",
"\\begin{equation}\n",
"\\frac{dh_k(\\gamma,f_{k-1})}{d\\gamma}\n",
"\\end{equation}\n",
"\n",
"This is quite difficult and not worth many marks, so don't spend too much time on it if you are confused!"
],
"metadata": {
"id": "lhD5AoUHx3DS"
}
},
{
"cell_type": "code",
"source": [
"# Computes how an activation changes with a small change in gamma assuming preactivations are f\n",
"# MOODLE ANSWER # Notebook V 4a: Copy this code when you have finished it.\n",
"def dhdgamma(gamma, f):\n",
" # TODO -- Write this function\n",
" # Replace this line\n",
" return 1"
],
"metadata": {
"id": "yC-9MTQevliP"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Compute how the loss changes with gamma\n",
"# Replace this line:\n",
"# MOODLE ANSWER # Notebook V 4b: Copy this code when you have finished it.\n",
"dldgamma = 1"
],
"metadata": {
"id": "DiNQrveoLuHR"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"print(\"Moodle Answer Notebook V 4c: dldgamma = %3.3f\"%(dldgamma))"
],
"metadata": {
"id": "YHxmAEnxzy3O"
},
"execution_count": null,
"outputs": []
}
]
}

View File

@@ -46,11 +46,11 @@
"source": [ "source": [
"**Linear functions**<br> We will be using the term *linear equation* to mean a weighted sum of inputs plus an offset. If there is just one input $x$, then this is a straight line:\n", "**Linear functions**<br> We will be using the term *linear equation* to mean a weighted sum of inputs plus an offset. If there is just one input $x$, then this is a straight line:\n",
"\n", "\n",
"\\begin{equation}y=\\beta+\\omega x,\\end{equation} <br>\n", "\\begin{equation}y=\\beta+\\omega x,\\end{equation}\n",
"\n", "\n",
"where $\\beta$ is the y-intercept of the linear and $\\omega$ is the slope of the line. When there are two inputs $x_{1}$ and $x_{2}$, then this becomes:\n", "where $\\beta$ is the y-intercept of the linear and $\\omega$ is the slope of the line. When there are two inputs $x_{1}$ and $x_{2}$, then this becomes:\n",
"\n", "\n",
"\\begin{equation}y=\\beta+\\omega_1 x_1 + \\omega_2 x_2.\\end{equation} <br><br>\n", "\\begin{equation}y=\\beta+\\omega_1 x_1 + \\omega_2 x_2.\\end{equation}\n",
"\n", "\n",
"Any other functions are by definition **non-linear**.\n", "Any other functions are by definition **non-linear**.\n",
"\n", "\n",
@@ -83,7 +83,7 @@
"source": [ "source": [
"# Plot the 1D linear function\n", "# Plot the 1D linear function\n",
"\n", "\n",
"# Define an array of x values from 0 to 10 with increments of 0.1\n", "# Define an array of x values from 0 to 10 with increments of 0.01\n",
"# https://numpy.org/doc/stable/reference/generated/numpy.arange.html\n", "# https://numpy.org/doc/stable/reference/generated/numpy.arange.html\n",
"x = np.arange(0.0,10.0, 0.01)\n", "x = np.arange(0.0,10.0, 0.01)\n",
"# Compute y using the function you filled in above\n", "# Compute y using the function you filled in above\n",
@@ -96,7 +96,7 @@
"ax.plot(x,y,'r-')\n", "ax.plot(x,y,'r-')\n",
"ax.set_ylim([0,10]);ax.set_xlim([0,10])\n", "ax.set_ylim([0,10]);ax.set_xlim([0,10])\n",
"ax.set_xlabel('x'); ax.set_ylabel('y')\n", "ax.set_xlabel('x'); ax.set_ylabel('y')\n",
"plt.show\n", "plt.show()\n",
"\n", "\n",
"# TODO -- experiment with changing the values of beta and omega\n", "# TODO -- experiment with changing the values of beta and omega\n",
"# to understand what they do. Try to make a line\n", "# to understand what they do. Try to make a line\n",
@@ -171,7 +171,7 @@
"# Color represents y value (brighter = higher value)\n", "# Color represents y value (brighter = higher value)\n",
"# Black = -10 or less, White = +10 or more\n", "# Black = -10 or less, White = +10 or more\n",
"# 0 = mid orange\n", "# 0 = mid orange\n",
"# Lines are conoturs where value is equal\n", "# Lines are contours where value is equal\n",
"draw_2D_function(x1,x2,y)\n", "draw_2D_function(x1,x2,y)\n",
"\n", "\n",
"# TODO\n", "# TODO\n",
@@ -195,15 +195,15 @@
"source": [ "source": [
"Often we will want to compute many linear functions at the same time. For example, we might have three inputs, $x_1$, $x_2$, and $x_3$ and want to compute two linear functions giving $y_1$ and $y_2$. Of course, we could do this by just running each equation separately,<br><br>\n", "Often we will want to compute many linear functions at the same time. For example, we might have three inputs, $x_1$, $x_2$, and $x_3$ and want to compute two linear functions giving $y_1$ and $y_2$. Of course, we could do this by just running each equation separately,<br><br>\n",
"\n", "\n",
"\\begin{eqnarray}y_1 &=& \\beta_1 + \\omega_{11} x_1 + \\omega_{12} x_2 + \\omega_{13} x_3\\\\\n", "\\begin{align}y_1 &=& \\beta_1 + \\omega_{11} x_1 + \\omega_{12} x_2 + \\omega_{13} x_3\\\\\n",
"y_2 &=& \\beta_2 + \\omega_{21} x_1 + \\omega_{22} x_2 + \\omega_{23} x_3.\n", "y_2 &=& \\beta_2 + \\omega_{21} x_1 + \\omega_{22} x_2 + \\omega_{23} x_3.\n",
"\\end{eqnarray}<br>\n", "\\end{align}\n",
"\n", "\n",
"However, we can write it more compactly with vectors and matrices:\n", "However, we can write it more compactly with vectors and matrices:\n",
"\n", "\n",
"\\begin{equation}\n", "\\begin{equation}\n",
"\\begin{bmatrix} y_1\\\\ y_2 \\end{bmatrix} = \\begin{bmatrix}\\beta_{1}\\\\\\beta_{2}\\end{bmatrix}+ \\begin{bmatrix}\\omega_{11}&\\omega_{12}&\\omega_{13}\\\\\\omega_{21}&\\omega_{22}&\\omega_{23}\\end{bmatrix}\\begin{bmatrix}x_{1}\\\\x_{2}\\\\x_{3}\\end{bmatrix},\n", "\\begin{bmatrix} y_1\\\\ y_2 \\end{bmatrix} = \\begin{bmatrix}\\beta_{1}\\\\\\beta_{2}\\end{bmatrix}+ \\begin{bmatrix}\\omega_{11}&\\omega_{12}&\\omega_{13}\\\\\\omega_{21}&\\omega_{22}&\\omega_{23}\\end{bmatrix}\\begin{bmatrix}x_{1}\\\\x_{2}\\\\x_{3}\\end{bmatrix},\n",
"\\end{equation}<br>\n", "\\end{equation}\n",
"or\n", "or\n",
"\n", "\n",
"\\begin{equation}\n", "\\begin{equation}\n",
@@ -269,7 +269,7 @@
"# Compute with vector/matrix form\n", "# Compute with vector/matrix form\n",
"y_vec = beta_vec+np.matmul(omega_mat, x_vec)\n", "y_vec = beta_vec+np.matmul(omega_mat, x_vec)\n",
"print(\"Matrix/vector form\")\n", "print(\"Matrix/vector form\")\n",
"print('y1= %3.3f\\ny2 = %3.3f'%((y_vec[0],y_vec[1])))\n" "print('y1= %3.3f\\ny2 = %3.3f'%((y_vec[0][0],y_vec[1][0])))\n"
] ]
}, },
{ {
@@ -295,7 +295,7 @@
"\n", "\n",
"Throughout the book, we'll be using some special functions (see Appendix B.1.3). The most important of these are the logarithm and exponential functions. Let's investigate their properties.\n", "Throughout the book, we'll be using some special functions (see Appendix B.1.3). The most important of these are the logarithm and exponential functions. Let's investigate their properties.\n",
"\n", "\n",
"We'll start with the exponential function $y=\\mbox{exp}[x]=e^x$ which maps the real line $[-\\infty,+\\infty]$ to non-negative numbers $[0,+\\infty]$." "We'll start with the exponential function $y=\\exp[x]=e^x$ which maps the real line $[-\\infty,+\\infty]$ to non-negative numbers $[0,+\\infty]$."
] ]
}, },
{ {
@@ -308,7 +308,7 @@
"source": [ "source": [
"# Draw the exponential function\n", "# Draw the exponential function\n",
"\n", "\n",
"# Define an array of x values from -5 to 5 with increments of 0.1\n", "# Define an array of x values from -5 to 5 with increments of 0.01\n",
"x = np.arange(-5.0,5.0, 0.01)\n", "x = np.arange(-5.0,5.0, 0.01)\n",
"y = np.exp(x) ;\n", "y = np.exp(x) ;\n",
"\n", "\n",
@@ -317,7 +317,7 @@
"ax.plot(x,y,'r-')\n", "ax.plot(x,y,'r-')\n",
"ax.set_ylim([0,100]);ax.set_xlim([-5,5])\n", "ax.set_ylim([0,100]);ax.set_xlim([-5,5])\n",
"ax.set_xlabel('x'); ax.set_ylabel('exp[x]')\n", "ax.set_xlabel('x'); ax.set_ylabel('exp[x]')\n",
"plt.show" "plt.show()"
] ]
}, },
{ {
@@ -328,11 +328,11 @@
"source": [ "source": [
"# Questions\n", "# Questions\n",
"\n", "\n",
"1. What is $\\mbox{exp}[0]$? \n", "1. What is $\\exp[0]$? \n",
"2. What is $\\mbox{exp}[1]$?\n", "2. What is $\\exp[1]$?\n",
"3. What is $\\mbox{exp}[-\\infty]$?\n", "3. What is $\\exp[-\\infty]$?\n",
"4. What is $\\mbox{exp}[+\\infty]$?\n", "4. What is $\\exp[+\\infty]$?\n",
"5. A function is convex if we can draw a straight line between any two points on the function, and this line always lies above the function. Similarly, a function is concave if a straight line between any two points always lies below the function. Is the exponential function convex or concave or neither?\n" "5. A function is convex if we can draw a straight line between any two points on the function, and the line lies above the function everywhere between these two points. Similarly, a function is concave if a straight line between any two points lies below the function everywhere between these two points. Is the exponential function convex or concave or neither?\n"
] ]
}, },
{ {
@@ -354,7 +354,7 @@
"source": [ "source": [
"# Draw the logarithm function\n", "# Draw the logarithm function\n",
"\n", "\n",
"# Define an array of x values from -5 to 5 with increments of 0.1\n", "# Define an array of x values from -5 to 5 with increments of 0.01\n",
"x = np.arange(0.01,5.0, 0.01)\n", "x = np.arange(0.01,5.0, 0.01)\n",
"y = np.log(x) ;\n", "y = np.log(x) ;\n",
"\n", "\n",
@@ -363,7 +363,7 @@
"ax.plot(x,y,'r-')\n", "ax.plot(x,y,'r-')\n",
"ax.set_ylim([-5,5]);ax.set_xlim([0,5])\n", "ax.set_ylim([-5,5]);ax.set_xlim([0,5])\n",
"ax.set_xlabel('x'); ax.set_ylabel('$\\log[x]$')\n", "ax.set_xlabel('x'); ax.set_ylabel('$\\log[x]$')\n",
"plt.show" "plt.show()"
] ]
}, },
{ {
@@ -374,12 +374,12 @@
"source": [ "source": [
"# Questions\n", "# Questions\n",
"\n", "\n",
"1. What is $\\mbox{log}[0]$? \n", "1. What is $\\log[0]$? \n",
"2. What is $\\mbox{log}[1]$?\n", "2. What is $\\log[1]$?\n",
"3. What is $\\mbox{log}[e]$?\n", "3. What is $\\log[e]$?\n",
"4. What is $\\mbox{log}[\\exp[3]]$?\n", "4. What is $\\log[\\exp[3]]$?\n",
"5. What is $\\mbox{exp}[\\log[4]]$?\n", "5. What is $\\exp[\\log[4]]$?\n",
"6. What is $\\mbox{log}[-1]$?\n", "6. What is $\\log[-1]$?\n",
"7. Is the logarithm function concave or convex?\n" "7. Is the logarithm function concave or convex?\n"
] ]
} }

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyOmndC0N7dFV7W3Mh5ljOLl",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -31,7 +30,7 @@
"source": [ "source": [
"# Notebook 2.1 Supervised Learning\n", "# Notebook 2.1 Supervised Learning\n",
"\n", "\n",
"The purpose of this notebook is to explore the linear regression model dicussed in Chapter 2 of the book.\n", "The purpose of this notebook is to explore the linear regression model discussed in Chapter 2 of the book.\n",
"\n", "\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and write code to complete the functions. There are also questions interspersed in the text.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and write code to complete the functions. There are also questions interspersed in the text.\n",
"\n", "\n",
@@ -197,7 +196,7 @@
"source": [ "source": [
"# Visualizing the loss function\n", "# Visualizing the loss function\n",
"\n", "\n",
"The above process is equivalent to to descending coordinate wise on the loss function<br>\n", "The above process is equivalent to descending coordinate wise on the loss function<br>\n",
"\n", "\n",
"Now let's plot that function" "Now let's plot that function"
], ],
@@ -213,7 +212,7 @@
"\n", "\n",
"# Make a 2D array for the losses\n", "# Make a 2D array for the losses\n",
"all_losses = np.zeros_like(phi1_mesh)\n", "all_losses = np.zeros_like(phi1_mesh)\n",
"# Run throught each 2D combination of phi0, phi1 and compute loss\n", "# Run through each 2D combination of phi0, phi1 and compute loss\n",
"for indices,temp in np.ndenumerate(phi1_mesh):\n", "for indices,temp in np.ndenumerate(phi1_mesh):\n",
" all_losses[indices] = compute_loss(x,y, phi0_mesh[indices], phi1_mesh[indices])\n" " all_losses[indices] = compute_loss(x,y, phi0_mesh[indices], phi1_mesh[indices])\n"
], ],
@@ -235,8 +234,8 @@
"levels = 40\n", "levels = 40\n",
"ax.contour(phi0_mesh, phi1_mesh, all_losses ,levels, colors=['#80808080'])\n", "ax.contour(phi0_mesh, phi1_mesh, all_losses ,levels, colors=['#80808080'])\n",
"ax.set_ylim([1,-1])\n", "ax.set_ylim([1,-1])\n",
"ax.set_xlabel('Intercept, $\\phi_0$')\n", "ax.set_xlabel(r'Intercept, $\\phi_0$')\n",
"ax.set_ylabel('Slope, $\\phi_1$')\n", "ax.set_ylabel(r'Slope, $\\phi_1$')\n",
"\n", "\n",
"# Plot the position of your best fitting line on the loss function\n", "# Plot the position of your best fitting line on the loss function\n",
"# It should be close to the minimum\n", "# It should be close to the minimum\n",

File diff suppressed because one or more lines are too long

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyPD+qTkgmZCe+VessXM/kIU",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -182,7 +181,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now we'll extend this model to have two outputs $y_1$ and $y_2$, each of which can be visualized with a separate heatmap. You will now have sets of parameters $\\phi_{10}, \\phi_{11},\\phi_{12}$ and $\\phi_{2}, \\phi_{21},\\phi_{22}$ that correspond to each of these outputs." "Now we'll extend this model to have two outputs $y_1$ and $y_2$, each of which can be visualized with a separate heatmap. You will now have sets of parameters $\\phi_{10}, \\phi_{11}, \\phi_{12}, \\phi_{13}$ and $\\phi_{20}, \\phi_{21}, \\phi_{22}, \\phi_{23}$ that correspond to each of these outputs."
], ],
"metadata": { "metadata": {
"id": "Xl6LcrUyM7Lh" "id": "Xl6LcrUyM7Lh"

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyMdflMfWi9hu9ZEg/80HCd8", "authorship_tag": "ABX9TyNioITtfAcfxEfM3UOfQyb9",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -48,7 +48,7 @@
"import numpy as np\n", "import numpy as np\n",
"# Imports plotting library\n", "# Imports plotting library\n",
"import matplotlib.pyplot as plt\n", "import matplotlib.pyplot as plt\n",
"# Imports math libray\n", "# Imports math library\n",
"import math" "import math"
], ],
"metadata": { "metadata": {
@@ -79,7 +79,7 @@
"source": [ "source": [
"def number_regions(Di, D):\n", "def number_regions(Di, D):\n",
" # TODO -- implement Zaslavsky's formula\n", " # TODO -- implement Zaslavsky's formula\n",
" # You will need to use math.factorial() https://www.geeksforgeeks.org/factorial-in-python/\n", " # You can use math.comb() https://www.w3schools.com/python/ref_math_comb.asp\n",
" # Replace this code\n", " # Replace this code\n",
" N = 1;\n", " N = 1;\n",
"\n", "\n",
@@ -102,7 +102,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Calculate the number of regions for 10D input (Di=2) and 50 hidden units (D=50)\n", "# Calculate the number of regions for 10D input (Di=10) and 50 hidden units (D=50)\n",
"N = number_regions(10, 50)\n", "N = number_regions(10, 50)\n",
"print(f\"Di=10, D=50, Number of regions = {int(N)}, True value = 13432735556\")" "print(f\"Di=10, D=50, Number of regions = {int(N)}, True value = 13432735556\")"
], ],
@@ -126,7 +126,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Show that calculation fails when $D_i < D$\n", "# Depending on how you implemented it, the calculation may fail when $D_i > D$ (not to worry...)\n",
"try:\n", "try:\n",
" N = number_regions(10, 8)\n", " N = number_regions(10, 8)\n",
" print(f\"Di=10, D=8, Number of regions = {int(N)}, True value = 256\")\n", " print(f\"Di=10, D=8, Number of regions = {int(N)}, True value = 256\")\n",
@@ -191,7 +191,7 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Now let's compute and plot the number of regions as a function of the number of parameters as in figure 3.9b\n", "# Now let's compute and plot the number of regions as a function of the number of parameters as in figure 3.9b\n",
"# First let's write a function that computes the number of parameters as a function of the input dimension and number of hidden layers (assuming just one output)\n", "# First let's write a function that computes the number of parameters as a function of the input dimension and number of hidden units (assuming just one output)\n",
"\n", "\n",
"def number_parameters(D_i, D):\n", "def number_parameters(D_i, D):\n",
" # TODO -- replace this code with the proper calculation\n", " # TODO -- replace this code with the proper calculation\n",

View File

@@ -1,33 +1,22 @@
{ {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyPmra+JD+dm2M3gCqx3bMak",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [ "cells": [
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "view-in-github", "colab_type": "text",
"colab_type": "text" "id": "view-in-github"
}, },
"source": [ "source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap03/3_4_Activation_Functions.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" "<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap03/3_4_Activation_Functions.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "Mn0F56yY8ohX"
},
"source": [ "source": [
"# **Notebook 3.4 -- Activation functions**\n", "# **Notebook 3.4 -- Activation functions**\n",
"\n", "\n",
@@ -36,10 +25,7 @@
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and write code to complete the functions. There are also questions interspersed in the text.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and write code to complete the functions. There are also questions interspersed in the text.\n",
"\n", "\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions." "Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
], ]
"metadata": {
"id": "Mn0F56yY8ohX"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
@@ -57,6 +43,11 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "AeHzflFt9Tgn"
},
"outputs": [],
"source": [ "source": [
"# Plot the shallow neural network. We'll assume input in is range [0,1] and output [-1,1]\n", "# Plot the shallow neural network. We'll assume input in is range [0,1] and output [-1,1]\n",
"# If the plot_all flag is set to true, then we'll plot all the intermediate stages as in Figure 3.3\n", "# If the plot_all flag is set to true, then we'll plot all the intermediate stages as in Figure 3.3\n",
@@ -94,15 +85,15 @@
" for i in range(len(x_data)):\n", " for i in range(len(x_data)):\n",
" ax.plot(x_data[i], y_data[i],)\n", " ax.plot(x_data[i], y_data[i],)\n",
" plt.show()" " plt.show()"
], ]
"metadata": {
"id": "AeHzflFt9Tgn"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7qeIUrh19AkH"
},
"outputs": [],
"source": [ "source": [
"# Define a shallow neural network with, one input, one output, and three hidden units\n", "# Define a shallow neural network with, one input, one output, and three hidden units\n",
"def shallow_1_1_3(x, activation_fn, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31):\n", "def shallow_1_1_3(x, activation_fn, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31):\n",
@@ -123,38 +114,39 @@
"\n", "\n",
" # Return everything we have calculated\n", " # Return everything we have calculated\n",
" return y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3" " return y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3"
], ]
"metadata": {
"id": "7qeIUrh19AkH"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cwTp__Fk9YUx"
},
"outputs": [],
"source": [ "source": [
"# Define the Rectified Linear Unit (ReLU) function\n", "# Define the Rectified Linear Unit (ReLU) function\n",
"def ReLU(preactivation):\n", "def ReLU(preactivation):\n",
" activation = preactivation.clip(0.0)\n", " activation = preactivation.clip(0.0)\n",
" return activation" " return activation"
], ]
"metadata": {
"id": "cwTp__Fk9YUx"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"First, let's run the network with a ReLU functions"
],
"metadata": { "metadata": {
"id": "INQkRzyn9kVC" "id": "INQkRzyn9kVC"
} },
"source": [
"First, let's run the network with a ReLU functions"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jT9QuKou9i0_"
},
"outputs": [],
"source": [ "source": [
"# Now lets define some parameters and run the neural network\n", "# Now lets define some parameters and run the neural network\n",
"theta_10 = 0.3 ; theta_11 = -1.0\n", "theta_10 = 0.3 ; theta_11 = -1.0\n",
@@ -170,15 +162,14 @@
" shallow_1_1_3(x, ReLU, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n", " shallow_1_1_3(x, ReLU, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n",
"# And then plot it\n", "# And then plot it\n",
"plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)" "plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)"
], ]
"metadata": {
"id": "jT9QuKou9i0_"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "-I8N7r1o9HYf"
},
"source": [ "source": [
"# Sigmoid activation function\n", "# Sigmoid activation function\n",
"\n", "\n",
@@ -189,13 +180,15 @@
"\\end{equation}\n", "\\end{equation}\n",
"\n", "\n",
"(Note that the factor of 10 is not standard -- but it allow us to plot on the same axes as the ReLU examples)" "(Note that the factor of 10 is not standard -- but it allow us to plot on the same axes as the ReLU examples)"
], ]
"metadata": {
"id": "-I8N7r1o9HYf"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "hgkioNyr975Y"
},
"outputs": [],
"source": [ "source": [
"# Define the sigmoid function\n", "# Define the sigmoid function\n",
"def sigmoid(preactivation):\n", "def sigmoid(preactivation):\n",
@@ -204,15 +197,15 @@
" activation = np.zeros_like(preactivation);\n", " activation = np.zeros_like(preactivation);\n",
"\n", "\n",
" return activation" " return activation"
], ]
"metadata": {
"id": "hgkioNyr975Y"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "94HIXKJH97ve"
},
"outputs": [],
"source": [ "source": [
"# Make an array of inputs\n", "# Make an array of inputs\n",
"z = np.arange(-1,1,0.01)\n", "z = np.arange(-1,1,0.01)\n",
@@ -223,25 +216,26 @@
"ax.plot(z,sig_z,'r-')\n", "ax.plot(z,sig_z,'r-')\n",
"ax.set_xlim([-1,1]);ax.set_ylim([0,1])\n", "ax.set_xlim([-1,1]);ax.set_ylim([0,1])\n",
"ax.set_xlabel('z'); ax.set_ylabel('sig[z]')\n", "ax.set_xlabel('z'); ax.set_ylabel('sig[z]')\n",
"plt.show" "plt.show()"
], ]
"metadata": {
"id": "94HIXKJH97ve"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Let's see what happens when we use this activation function in a neural network"
],
"metadata": { "metadata": {
"id": "p3zQNXhj-J-o" "id": "p3zQNXhj-J-o"
} },
"source": [
"Let's see what happens when we use this activation function in a neural network"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "C1dASr9L-GNt"
},
"outputs": [],
"source": [ "source": [
"theta_10 = 0.3 ; theta_11 = -1.0\n", "theta_10 = 0.3 ; theta_11 = -1.0\n",
"theta_20 = -1.0 ; theta_21 = 2.0\n", "theta_20 = -1.0 ; theta_21 = 2.0\n",
@@ -256,39 +250,41 @@
" shallow_1_1_3(x, sigmoid, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n", " shallow_1_1_3(x, sigmoid, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n",
"# And then plot it\n", "# And then plot it\n",
"plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)" "plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)"
], ]
"metadata": {
"id": "C1dASr9L-GNt"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"You probably notice that this gives nice smooth curves. So why don't we use this? Aha... it's not obvious right now, but we will get to it when we learn to fit models."
],
"metadata": { "metadata": {
"id": "Uuam_DewA9fH" "id": "Uuam_DewA9fH"
} },
"source": [
"You probably notice that this gives nice smooth curves. So why don't we use this? Aha... it's not obvious right now, but we will get to it when we learn to fit models."
]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "C9WKkcMUABze"
},
"source": [ "source": [
"# Heaviside activation function\n", "# Heaviside activation function\n",
"\n", "\n",
"The Heaviside function is defined as:\n", "The Heaviside function is defined as:\n",
"\n", "\n",
"\\begin{equation}\n", "\\begin{equation}\n",
"\\mbox{heaviside}[z] = \\begin{cases} 0 & \\quad z <0 \\\\ 1 & \\quad z\\geq 0\\end{cases}\n", "\\text{heaviside}[z] = \\begin{cases} 0 & \\quad z <0 \\\\ 1 & \\quad z\\geq 0\\end{cases}\n",
"\\end{equation}" "\\end{equation}"
], ]
"metadata": {
"id": "C9WKkcMUABze"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "-1qFkdOL-NPc"
},
"outputs": [],
"source": [ "source": [
"# Define the heaviside function\n", "# Define the heaviside function\n",
"def heaviside(preactivation):\n", "def heaviside(preactivation):\n",
@@ -299,15 +295,15 @@
"\n", "\n",
"\n", "\n",
" return activation" " return activation"
], ]
"metadata": {
"id": "-1qFkdOL-NPc"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mSPyp7iA-44H"
},
"outputs": [],
"source": [ "source": [
"# Make an array of inputs\n", "# Make an array of inputs\n",
"z = np.arange(-1,1,0.01)\n", "z = np.arange(-1,1,0.01)\n",
@@ -318,16 +314,16 @@
"ax.plot(z,heav_z,'r-')\n", "ax.plot(z,heav_z,'r-')\n",
"ax.set_xlim([-1,1]);ax.set_ylim([-2,2])\n", "ax.set_xlim([-1,1]);ax.set_ylim([-2,2])\n",
"ax.set_xlabel('z'); ax.set_ylabel('heaviside[z]')\n", "ax.set_xlabel('z'); ax.set_ylabel('heaviside[z]')\n",
"plt.show" "plt.show()"
], ]
"metadata": {
"id": "mSPyp7iA-44H"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "t99K2lSl--Mq"
},
"outputs": [],
"source": [ "source": [
"theta_10 = 0.3 ; theta_11 = -1.0\n", "theta_10 = 0.3 ; theta_11 = -1.0\n",
"theta_20 = -1.0 ; theta_21 = 2.0\n", "theta_20 = -1.0 ; theta_21 = 2.0\n",
@@ -342,39 +338,41 @@
" shallow_1_1_3(x, heaviside, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n", " shallow_1_1_3(x, heaviside, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n",
"# And then plot it\n", "# And then plot it\n",
"plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)" "plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)"
], ]
"metadata": {
"id": "t99K2lSl--Mq"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"This can approximate any function, but the output is discontinuous, and there are also reasons not to use it that we will discover when we learn more about model fitting."
],
"metadata": { "metadata": {
"id": "T65MRtM-BCQA" "id": "T65MRtM-BCQA"
} },
"source": [
"This can approximate any function, but the output is discontinuous, and there are also reasons not to use it that we will discover when we learn more about model fitting."
]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "RkB-XZMLBTaR"
},
"source": [ "source": [
"# Linear activation functions\n", "# Linear activation functions\n",
"\n", "\n",
"Neural networks don't work if the activation function is linear. For example, consider what would happen if the activation function was:\n", "Neural networks don't work if the activation function is linear. For example, consider what would happen if the activation function was:\n",
"\n", "\n",
"\\begin{equation}\n", "\\begin{equation}\n",
"\\mbox{lin}[z] = a + bz\n", "\\text{lin}[z] = a + bz\n",
"\\end{equation}" "\\end{equation}"
], ]
"metadata": {
"id": "RkB-XZMLBTaR"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Q59v3saj_jq1"
},
"outputs": [],
"source": [ "source": [
"# Define the linear activation function\n", "# Define the linear activation function\n",
"def lin(preactivation):\n", "def lin(preactivation):\n",
@@ -384,15 +382,15 @@
" activation = a+b * preactivation\n", " activation = a+b * preactivation\n",
" # Return\n", " # Return\n",
" return activation" " return activation"
], ]
"metadata": {
"id": "Q59v3saj_jq1"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IwodsBr0BkDn"
},
"outputs": [],
"source": [ "source": [
"# TODO\n", "# TODO\n",
"# 1. The linear activation function above just returns the input: (0+1*z) = z\n", "# 1. The linear activation function above just returns the input: (0+1*z) = z\n",
@@ -415,12 +413,23 @@
" shallow_1_1_3(x, lin, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n", " shallow_1_1_3(x, lin, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n",
"# And then plot it\n", "# And then plot it\n",
"plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)" "plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)"
], ]
"metadata": {
"id": "IwodsBr0BkDn"
},
"execution_count": null,
"outputs": []
} }
] ],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyOmxhh3ymYWX+1HdZ91I6zU",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
} }

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyPEQEGetZqWnLRNn99Q2aaT",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -135,7 +134,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Let's define two networks. We'll put the prefixes n1_ and n2_ before all the variables to make it clear which network is which. We'll just consider the inputs and outputs over the range [-1,1]. If you set the \"plot_all\" flat to True, you can see the details of how they were created." "Let's define two networks. We'll put the prefixes n1_ and n2_ before all the variables to make it clear which network is which. We'll just consider the inputs and outputs over the range [-1,1]."
], ],
"metadata": { "metadata": {
"id": "LxBJCObC-NTY" "id": "LxBJCObC-NTY"
@@ -220,7 +219,7 @@
"source": [ "source": [
"# TODO\n", "# TODO\n",
"# Take a piece of paper and draw what you think will happen when we feed the\n", "# Take a piece of paper and draw what you think will happen when we feed the\n",
"# output of the first network into the second one now that we have changed it. Draw the relationship between\n", "# output of the first network into the modified second network. Draw the relationship between\n",
"# the input of the first network and the output of the second one." "# the input of the first network and the output of the second one."
], ],
"metadata": { "metadata": {
@@ -261,7 +260,7 @@
"source": [ "source": [
"# TODO\n", "# TODO\n",
"# Take a piece of paper and draw what you think will happen when we feed the\n", "# Take a piece of paper and draw what you think will happen when we feed the\n",
"# output of the first network now we have changed it into the original second network. Draw the relationship between\n", "# output of the modified first network into the original second network. Draw the relationship between\n",
"# the input of the first network and the output of the second one." "# the input of the first network and the output of the second one."
], ],
"metadata": { "metadata": {
@@ -302,7 +301,7 @@
"source": [ "source": [
"# TODO\n", "# TODO\n",
"# Take a piece of paper and draw what you think will happen when we feed the\n", "# Take a piece of paper and draw what you think will happen when we feed the\n",
"# output of the first network into the original second network. Draw the relationship between\n", "# output of the first network into the a copy of itself. Draw the relationship between\n",
"# the input of the first network and the output of the second one." "# the input of the first network and the output of the second one."
], ],
"metadata": { "metadata": {
@@ -350,7 +349,7 @@
"# network (blue curve above)\n", "# network (blue curve above)\n",
"\n", "\n",
"# Take away conclusion: with very few parameters, we can make A LOT of linear regions, but\n", "# Take away conclusion: with very few parameters, we can make A LOT of linear regions, but\n",
"# they depend on one another in complex ways that quickly become to difficult to understand intuitively." "# they depend on one another in complex ways that quickly become too difficult to understand intuitively."
], ],
"metadata": { "metadata": {
"id": "HqzePCLOVQK7" "id": "HqzePCLOVQK7"

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyPkFrjmRAUf0fxN07RC4xMI", "authorship_tag": "ABX9TyPZzptvvf7OPZai8erQ/0xT",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -127,26 +127,26 @@
" fig, ax = plt.subplots(3,3)\n", " fig, ax = plt.subplots(3,3)\n",
" fig.set_size_inches(8.5, 8.5)\n", " fig.set_size_inches(8.5, 8.5)\n",
" fig.tight_layout(pad=3.0)\n", " fig.tight_layout(pad=3.0)\n",
" ax[0,0].plot(x,layer2_pre_1,'r-'); ax[0,0].set_ylabel('$\\psi_{10}+\\psi_{11}h_{1}+\\psi_{12}h_{2}+\\psi_{13}h_3$')\n", " ax[0,0].plot(x,layer2_pre_1,'r-'); ax[0,0].set_ylabel(r'$\\psi_{10}+\\psi_{11}h_{1}+\\psi_{12}h_{2}+\\psi_{13}h_3$')\n",
" ax[0,1].plot(x,layer2_pre_2,'b-'); ax[0,1].set_ylabel('$\\psi_{20}+\\psi_{21}h_{1}+\\psi_{22}h_{2}+\\psi_{23}h_3$')\n", " ax[0,1].plot(x,layer2_pre_2,'b-'); ax[0,1].set_ylabel(r'$\\psi_{20}+\\psi_{21}h_{1}+\\psi_{22}h_{2}+\\psi_{23}h_3$')\n",
" ax[0,2].plot(x,layer2_pre_3,'g-'); ax[0,2].set_ylabel('$\\psi_{30}+\\psi_{31}h_{1}+\\psi_{32}h_{2}+\\psi_{33}h_3$')\n", " ax[0,2].plot(x,layer2_pre_3,'g-'); ax[0,2].set_ylabel(r'$\\psi_{30}+\\psi_{31}h_{1}+\\psi_{32}h_{2}+\\psi_{33}h_3$')\n",
" ax[1,0].plot(x,h1_prime,'r-'); ax[1,0].set_ylabel(\"$h_{1}^{'}$\")\n", " ax[1,0].plot(x,h1_prime,'r-'); ax[1,0].set_ylabel(r\"$h_{1}^{'}$\")\n",
" ax[1,1].plot(x,h2_prime,'b-'); ax[1,1].set_ylabel(\"$h_{2}^{'}$\")\n", " ax[1,1].plot(x,h2_prime,'b-'); ax[1,1].set_ylabel(r\"$h_{2}^{'}$\")\n",
" ax[1,2].plot(x,h3_prime,'g-'); ax[1,2].set_ylabel(\"$h_{3}^{'}$\")\n", " ax[1,2].plot(x,h3_prime,'g-'); ax[1,2].set_ylabel(r\"$h_{3}^{'}$\")\n",
" ax[2,0].plot(x,phi1_h1_prime,'r-'); ax[2,0].set_ylabel(\"$\\phi_1 h_{1}^{'}$\")\n", " ax[2,0].plot(x,phi1_h1_prime,'r-'); ax[2,0].set_ylabel(r\"$\\phi_1 h_{1}^{'}$\")\n",
" ax[2,1].plot(x,phi2_h2_prime,'b-'); ax[2,1].set_ylabel(\"$\\phi_2 h_{2}^{'}$\")\n", " ax[2,1].plot(x,phi2_h2_prime,'b-'); ax[2,1].set_ylabel(r\"$\\phi_2 h_{2}^{'}$\")\n",
" ax[2,2].plot(x,phi3_h3_prime,'g-'); ax[2,2].set_ylabel(\"$\\phi_3 h_{3}^{'}$\")\n", " ax[2,2].plot(x,phi3_h3_prime,'g-'); ax[2,2].set_ylabel(r\"$\\phi_3 h_{3}^{'}$\")\n",
"\n", "\n",
" for plot_y in range(3):\n", " for plot_y in range(3):\n",
" for plot_x in range(3):\n", " for plot_x in range(3):\n",
" ax[plot_y,plot_x].set_xlim([0,1]);ax[plot_x,plot_y].set_ylim([-1,1])\n", " ax[plot_y,plot_x].set_xlim([0,1]);ax[plot_x,plot_y].set_ylim([-1,1])\n",
" ax[plot_y,plot_x].set_aspect(0.5)\n", " ax[plot_y,plot_x].set_aspect(0.5)\n",
" ax[2,plot_y].set_xlabel('Input, $x$');\n", " ax[2,plot_y].set_xlabel(r'Input, $x$');\n",
" plt.show()\n", " plt.show()\n",
"\n", "\n",
" fig, ax = plt.subplots()\n", " fig, ax = plt.subplots()\n",
" ax.plot(x,y)\n", " ax.plot(x,y)\n",
" ax.set_xlabel('Input, $x$'); ax.set_ylabel('Output, $y$')\n", " ax.set_xlabel(r'Input, $x$'); ax.set_ylabel(r'Output, $y$')\n",
" ax.set_xlim([0,1]);ax.set_ylim([-1,1])\n", " ax.set_xlim([0,1]);ax.set_ylim([-1,1])\n",
" ax.set_aspect(0.5)\n", " ax.set_aspect(0.5)\n",
" plt.show()" " plt.show()"

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyMbJGN6f2+yKzzsVep/wi5U", "authorship_tag": "ABX9TyO2DaD75p+LGi7WgvTzjrk1",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -101,7 +101,6 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# # Plot the shallow neural network. We'll assume input in is range [-1,1] and output [-1,1]\n", "# # Plot the shallow neural network. We'll assume input in is range [-1,1] and output [-1,1]\n",
"# If the plot_all flag is set to true, then we'll plot all the intermediate stages as in Figure 3.3\n",
"def plot_neural(x, y):\n", "def plot_neural(x, y):\n",
" fig, ax = plt.subplots()\n", " fig, ax = plt.subplots()\n",
" ax.plot(x.T,y.T)\n", " ax.plot(x.T,y.T)\n",
@@ -119,7 +118,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Let's define a networks. We'll just consider the inputs and outputs over the range [-1,1]. If you set the \"plot_all\" flat to True, you can see the details of how it was created." "Let's define a network. We'll just consider the inputs and outputs over the range [-1,1]."
], ],
"metadata": { "metadata": {
"id": "LxBJCObC-NTY" "id": "LxBJCObC-NTY"
@@ -232,7 +231,7 @@
"beta_2 = np.zeros((1,1))\n", "beta_2 = np.zeros((1,1))\n",
"Omega_2 = np.zeros((1,3))\n", "Omega_2 = np.zeros((1,3))\n",
"\n", "\n",
"# TODO Fill in the values of the beta and Omega matrices for with the n1_theta, n1_phi, n2_theta, and n2_phi parameters\n", "# TODO Fill in the values of the beta and Omega matrices for the n1_theta, n1_phi, n2_theta, and n2_phi parameters\n",
"# that define the composition of the two networks above (see eqn 4.5 for Omega1 and beta1 albeit in different notation)\n", "# that define the composition of the two networks above (see eqn 4.5 for Omega1 and beta1 albeit in different notation)\n",
"# !!! NOTE THAT MATRICES ARE CONVENTIONALLY INDEXED WITH a_11 IN THE TOP LEFT CORNER, BUT NDARRAYS START AT [0,0] SO EVERYTHING IS OFFSET\n", "# !!! NOTE THAT MATRICES ARE CONVENTIONALLY INDEXED WITH a_11 IN THE TOP LEFT CORNER, BUT NDARRAYS START AT [0,0] SO EVERYTHING IS OFFSET\n",
"# To get you started I've filled in a few:\n", "# To get you started I've filled in a few:\n",
@@ -274,7 +273,7 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# define sizes\n", "# define sizes\n",
"D_i=4; D_1=5; D_2=2; D_3=1; D_o=1\n", "D_i=4; D_1=5; D_2=2; D_3=4; D_o=1\n",
"# We'll choose the inputs and parameters of this network randomly using np.random.normal\n", "# We'll choose the inputs and parameters of this network randomly using np.random.normal\n",
"# For example, we'll set the input using\n", "# For example, we'll set the input using\n",
"n_data = 4;\n", "n_data = 4;\n",

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyNkBMOVt5gO7Awn9JMn4N8Z",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -66,7 +65,7 @@
" return activation\n", " return activation\n",
"\n", "\n",
"# Define a shallow neural network\n", "# Define a shallow neural network\n",
"def shallow_nn(x, beta_0, omega_0, beta_1, omaga_1):\n", "def shallow_nn(x, beta_0, omega_0, beta_1, omega_1):\n",
" # Make sure that input data is (1 x n_data) array\n", " # Make sure that input data is (1 x n_data) array\n",
" n_data = x.size\n", " n_data = x.size\n",
" x = np.reshape(x,(1,n_data))\n", " x = np.reshape(x,(1,n_data))\n",
@@ -119,7 +118,7 @@
" ax.plot(x_model,y_model)\n", " ax.plot(x_model,y_model)\n",
" if sigma_model is not None:\n", " if sigma_model is not None:\n",
" ax.fill_between(x_model, y_model-2*sigma_model, y_model+2*sigma_model, color='lightgray')\n", " ax.fill_between(x_model, y_model-2*sigma_model, y_model+2*sigma_model, color='lightgray')\n",
" ax.set_xlabel('Input, $x$'); ax.set_ylabel('Output, $y$')\n", " ax.set_xlabel(r'Input, $x$'); ax.set_ylabel(r'Output, $y$')\n",
" ax.set_xlim([0,1]);ax.set_ylim([-1,1])\n", " ax.set_xlim([0,1]);ax.set_ylim([-1,1])\n",
" ax.set_aspect(0.5)\n", " ax.set_aspect(0.5)\n",
" if title is not None:\n", " if title is not None:\n",
@@ -139,7 +138,7 @@
"source": [ "source": [
"# Univariate regression\n", "# Univariate regression\n",
"\n", "\n",
"We'll investigate a simple univarite regression situation with a single input $x$ and a single output $y$ as pictured in figures 5.4 and 5.5b." "We'll investigate a simple univariate regression situation with a single input $x$ and a single output $y$ as pictured in figures 5.4 and 5.5b."
], ],
"metadata": { "metadata": {
"id": "PsgLZwsPxauP" "id": "PsgLZwsPxauP"
@@ -186,7 +185,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Return probability under normal distribution for input x\n", "# Return probability under normal distribution\n",
"def normal_distribution(y, mu, sigma):\n", "def normal_distribution(y, mu, sigma):\n",
" # TODO-- write in the equation for the normal distribution\n", " # TODO-- write in the equation for the normal distribution\n",
" # Equation 5.7 from the notes (you will need np.sqrt() and np.exp(), and math.pi)\n", " # Equation 5.7 from the notes (you will need np.sqrt() and np.exp(), and math.pi)\n",
@@ -223,7 +222,7 @@
"gauss_prob = normal_distribution(y_gauss, mu, sigma)\n", "gauss_prob = normal_distribution(y_gauss, mu, sigma)\n",
"fig, ax = plt.subplots()\n", "fig, ax = plt.subplots()\n",
"ax.plot(y_gauss, gauss_prob)\n", "ax.plot(y_gauss, gauss_prob)\n",
"ax.set_xlabel('Input, $y$'); ax.set_ylabel('Probability $Pr(y)$')\n", "ax.set_xlabel(r'Input, $y$'); ax.set_ylabel(r'Probability $Pr(y)$')\n",
"ax.set_xlim([-5,5]);ax.set_ylim([0,1.0])\n", "ax.set_xlim([-5,5]);ax.set_ylim([0,1.0])\n",
"plt.show()\n", "plt.show()\n",
"\n", "\n",
@@ -306,8 +305,9 @@
"source": [ "source": [
"# Return the negative log likelihood of the data under the model\n", "# Return the negative log likelihood of the data under the model\n",
"def compute_negative_log_likelihood(y_train, mu, sigma):\n", "def compute_negative_log_likelihood(y_train, mu, sigma):\n",
" # TODO -- compute the likelihood of the data -- don't use the likelihood function above -- compute the negative sum of the log probabilities\n", " # TODO -- compute the negative log likelihood of the data without using a product\n",
" # Bottom line of equation 5.3 in the notes\n", " # In other words, compute minus one times the sum of the log probabilities\n",
" # Equation 5.4 in the notes\n",
" # You will need np.sum(), np.log()\n", " # You will need np.sum(), np.log()\n",
" # Replace the line below\n", " # Replace the line below\n",
" nll = 0\n", " nll = 0\n",
@@ -329,7 +329,7 @@
"mu_pred = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", "mu_pred = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"# Set the standard deviation to something reasonable\n", "# Set the standard deviation to something reasonable\n",
"sigma = 0.2\n", "sigma = 0.2\n",
"# Compute the log likelihood\n", "# Compute the negative log likelihood\n",
"nll = compute_negative_log_likelihood(y_train, mu_pred, sigma)\n", "nll = compute_negative_log_likelihood(y_train, mu_pred, sigma)\n",
"# Let's double check we get the right answer before proceeding\n", "# Let's double check we get the right answer before proceeding\n",
"print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(11.452419564,nll))" "print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(11.452419564,nll))"
@@ -352,7 +352,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Return the squared distance between the predicted\n", "# Return the squared distance between the observed data (y_train) and the prediction of the model (y_pred)\n",
"def compute_sum_of_squares(y_train, y_pred):\n", "def compute_sum_of_squares(y_train, y_pred):\n",
" # TODO -- compute the sum of squared distances between the training data and the model prediction\n", " # TODO -- compute the sum of squared distances between the training data and the model prediction\n",
" # Eqn 5.10 in the notes. Make sure that you understand this, and ask questions if you don't\n", " # Eqn 5.10 in the notes. Make sure that you understand this, and ask questions if you don't\n",
@@ -372,9 +372,9 @@
"source": [ "source": [
"# Let's test this again\n", "# Let's test this again\n",
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n", "beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
"# Use our neural network to predict the mean of the Gaussian\n", "# Use our neural network to predict the mean of the Gaussian, which is out best prediction of y\n",
"y_pred = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", "y_pred = mu_pred = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"# Compute the log likelihood\n", "# Compute the sum of squares\n",
"sum_of_squares = compute_sum_of_squares(y_train, y_pred)\n", "sum_of_squares = compute_sum_of_squares(y_train, y_pred)\n",
"# Let's double check we get the right answer before proceeding\n", "# Let's double check we get the right answer before proceeding\n",
"print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(2.020992572,sum_of_squares))" "print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(2.020992572,sum_of_squares))"
@@ -388,7 +388,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now let's investigate finding the maximum likelihood / minimum log likelihood / least squares solution. For simplicity, we'll assume that all the parameters are correct except one and look at how the likelihood, log likelihood, and sum of squares change as we manipulate the last parameter. We'll start with overall y offset, beta_1 (formerly phi_0)" "Now let's investigate finding the maximum likelihood / minimum negative log likelihood / least squares solution. For simplicity, we'll assume that all the parameters are correct except one and look at how the likelihood, negative log likelihood, and sum of squares change as we manipulate the last parameter. We'll start with overall y offset, beta_1 (formerly phi_0)"
], ],
"metadata": { "metadata": {
"id": "OgcRojvPWh4V" "id": "OgcRojvPWh4V"
@@ -431,13 +431,26 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Now let's plot the likelihood, negative log likelihood, and least squares as a function the value of the offset beta1\n", "# Now let's plot the likelihood, negative log likelihood, and least squares as a function of the value of the offset beta1\n",
"fig, ax = plt.subplots(1,3)\n", "fig, ax = plt.subplots(1,2)\n",
"fig.set_size_inches(10.5, 3.5)\n", "fig.set_size_inches(10.5, 5.5)\n",
"fig.tight_layout(pad=3.0)\n", "fig.tight_layout(pad=10.0)\n",
"ax[0].plot(beta_1_vals, likelihoods); ax[0].set_xlabel('beta_1[0]$'); ax[0].set_ylabel('likelihood')\n", "likelihood_color = 'tab:red'\n",
"ax[1].plot(beta_1_vals, nlls); ax[1].set_xlabel('beta_1[0]'); ax[1].set_ylabel('negative log likelihood')\n", "nll_color = 'tab:blue'\n",
"ax[2].plot(beta_1_vals, sum_squares); ax[2].set_xlabel('beta_1[0]'); ax[2].set_ylabel('sum of squares')\n", "\n",
"ax[0].set_xlabel('beta_1[0]')\n",
"ax[0].set_ylabel('likelihood', color = likelihood_color)\n",
"ax[0].plot(beta_1_vals, likelihoods, color = likelihood_color)\n",
"ax[0].tick_params(axis='y', labelcolor=likelihood_color)\n",
"\n",
"ax00 = ax[0].twinx()\n",
"ax00.plot(beta_1_vals, nlls, color = nll_color)\n",
"ax00.set_ylabel('negative log likelihood', color = nll_color)\n",
"ax00.tick_params(axis='y', labelcolor = nll_color)\n",
"\n",
"plt.axvline(x = beta_1_vals[np.argmax(likelihoods)], linestyle='dotted')\n",
"\n",
"ax[1].plot(beta_1_vals, sum_squares); ax[1].set_xlabel('beta_1[0]'); ax[1].set_ylabel('sum of squares')\n",
"plt.show()" "plt.show()"
], ],
"metadata": { "metadata": {
@@ -517,13 +530,27 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Now let's plot the likelihood, negative log likelihood, and least squares as a function the value of the standard divation sigma\n", "# Now let's plot the likelihood, negative log likelihood, and least squares as a function of the value of the standard deviation sigma\n",
"fig, ax = plt.subplots(1,3)\n", "fig, ax = plt.subplots(1,2)\n",
"fig.set_size_inches(10.5, 3.5)\n", "fig.set_size_inches(10.5, 5.5)\n",
"fig.tight_layout(pad=3.0)\n", "fig.tight_layout(pad=10.0)\n",
"ax[0].plot(sigma_vals, likelihoods); ax[0].set_xlabel('$\\sigma$'); ax[0].set_ylabel('likelihood')\n", "likelihood_color = 'tab:red'\n",
"ax[1].plot(sigma_vals, nlls); ax[1].set_xlabel('$\\sigma$'); ax[1].set_ylabel('negative log likelihood')\n", "nll_color = 'tab:blue'\n",
"ax[2].plot(sigma_vals, sum_squares); ax[2].set_xlabel('$\\sigma$'); ax[2].set_ylabel('sum of squares')\n", "\n",
"\n",
"ax[0].set_xlabel('sigma')\n",
"ax[0].set_ylabel('likelihood', color = likelihood_color)\n",
"ax[0].plot(sigma_vals, likelihoods, color = likelihood_color)\n",
"ax[0].tick_params(axis='y', labelcolor=likelihood_color)\n",
"\n",
"ax00 = ax[0].twinx()\n",
"ax00.plot(sigma_vals, nlls, color = nll_color)\n",
"ax00.set_ylabel('negative log likelihood', color = nll_color)\n",
"ax00.tick_params(axis='y', labelcolor = nll_color)\n",
"\n",
"plt.axvline(x = sigma_vals[np.argmax(likelihoods)], linestyle='dotted')\n",
"\n",
"ax[1].plot(sigma_vals, sum_squares); ax[1].set_xlabel('sigma'); ax[1].set_ylabel('sum of squares')\n",
"plt.show()" "plt.show()"
], ],
"metadata": { "metadata": {
@@ -538,8 +565,8 @@
"# Hopefully, you can see that the maximum of the likelihood fn is at the same position as the minimum negative log likelihood\n", "# Hopefully, you can see that the maximum of the likelihood fn is at the same position as the minimum negative log likelihood\n",
"# The least squares solution does not depend on sigma, so it's just flat -- no use here.\n", "# The least squares solution does not depend on sigma, so it's just flat -- no use here.\n",
"# Let's check that:\n", "# Let's check that:\n",
"print(\"Maximum likelihood = %3.3f, at beta_1=%3.3f\"%( (likelihoods[np.argmax(likelihoods)],sigma_vals[np.argmax(likelihoods)])))\n", "print(\"Maximum likelihood = %3.3f, at sigma=%3.3f\"%( (likelihoods[np.argmax(likelihoods)],sigma_vals[np.argmax(likelihoods)])))\n",
"print(\"Minimum negative log likelihood = %3.3f, at beta_1=%3.3f\"%( (nlls[np.argmin(nlls)],sigma_vals[np.argmin(nlls)])))\n", "print(\"Minimum negative log likelihood = %3.3f, at sigma=%3.3f\"%( (nlls[np.argmin(nlls)],sigma_vals[np.argmin(nlls)])))\n",
"# Plot the best model\n", "# Plot the best model\n",
"sigma= sigma_vals[np.argmin(nlls)]\n", "sigma= sigma_vals[np.argmin(nlls)]\n",
"y_model = shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n", "y_model = shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n",
@@ -554,7 +581,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Obviously, to fit the full neural model we would vary all of the 10 parameters of the network in the $\\boldsymbol\\beta_{0},\\boldsymbol\\omega_{0},\\boldsymbol\\beta_{1},\\boldsymbol\\omega_{1}$ (and maybe $\\sigma$) until we find the combination that have the maximum likelihood / minimum negative log likelihood / least squares.<br><br>\n", "Obviously, to fit the full neural model we would vary all of the 10 parameters of the network in $\\boldsymbol\\beta_{0},\\boldsymbol\\Omega_{0},\\boldsymbol\\beta_{1},\\boldsymbol\\Omega_{1}$ (and maybe $\\sigma$) until we find the combination that have the maximum likelihood / minimum negative log likelihood / least squares.<br><br>\n",
"\n", "\n",
"Here we just varied one at a time as it is easier to see what is going on. This is known as **coordinate descent**.\n" "Here we just varied one at a time as it is easier to see what is going on. This is known as **coordinate descent**.\n"
], ],

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyOlPP7m+YTLyMPaN0WxRdrb",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -66,7 +65,7 @@
" return activation\n", " return activation\n",
"\n", "\n",
"# Define a shallow neural network\n", "# Define a shallow neural network\n",
"def shallow_nn(x, beta_0, omega_0, beta_1, omaga_1):\n", "def shallow_nn(x, beta_0, omega_0, beta_1, omega_1):\n",
" # Make sure that input data is (1 x n_data) array\n", " # Make sure that input data is (1 x n_data) array\n",
" n_data = x.size\n", " n_data = x.size\n",
" x = np.reshape(x,(1,n_data))\n", " x = np.reshape(x,(1,n_data))\n",
@@ -120,12 +119,12 @@
" fig.set_size_inches(7.0, 3.5)\n", " fig.set_size_inches(7.0, 3.5)\n",
" fig.tight_layout(pad=3.0)\n", " fig.tight_layout(pad=3.0)\n",
" ax[0].plot(x_model,out_model)\n", " ax[0].plot(x_model,out_model)\n",
" ax[0].set_xlabel('Input, $x$'); ax[0].set_ylabel('Model output')\n", " ax[0].set_xlabel(r'Input, $x$'); ax[0].set_ylabel(r'Model output')\n",
" ax[0].set_xlim([0,1]);ax[0].set_ylim([-4,4])\n", " ax[0].set_xlim([0,1]);ax[0].set_ylim([-4,4])\n",
" if title is not None:\n", " if title is not None:\n",
" ax[0].set_title(title)\n", " ax[0].set_title(title)\n",
" ax[1].plot(x_model,lambda_model)\n", " ax[1].plot(x_model,lambda_model)\n",
" ax[1].set_xlabel('Input, $x$'); ax[1].set_ylabel('$\\lambda$ or Pr(y=1|x)')\n", " ax[1].set_xlabel(r'Input, $x$'); ax[1].set_ylabel(r'$\\lambda$ or Pr(y=1|x)')\n",
" ax[1].set_xlim([0,1]);ax[1].set_ylim([-0.05,1.05])\n", " ax[1].set_xlim([0,1]);ax[1].set_ylim([-0.05,1.05])\n",
" if title is not None:\n", " if title is not None:\n",
" ax[1].set_title(title)\n", " ax[1].set_title(title)\n",
@@ -199,7 +198,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"The left is model output and the right is the model output after the sigmoid has been applied, so it now lies in the range [0,1] and represents the probability, that y=1. The black dots show the training data. We'll compute the the likelihood and the negative log likelihood." "The left is model output and the right is the model output after the sigmoid has been applied, so it now lies in the range [0,1] and represents the probability, that y=1. The black dots show the training data. We'll compute the likelihood and the negative log likelihood."
], ],
"metadata": { "metadata": {
"id": "MvVX6tl9AEXF" "id": "MvVX6tl9AEXF"
@@ -208,7 +207,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Return probability under Bernoulli distribution for input x\n", "# Return probability under Bernoulli distribution for observed class y\n",
"def bernoulli_distribution(y, lambda_param):\n", "def bernoulli_distribution(y, lambda_param):\n",
" # TODO-- write in the equation for the Bernoulli distribution\n", " # TODO-- write in the equation for the Bernoulli distribution\n",
" # Equation 5.17 from the notes (you will need np.power)\n", " # Equation 5.17 from the notes (you will need np.power)\n",
@@ -269,7 +268,7 @@
"source": [ "source": [
"# Let's test this\n", "# Let's test this\n",
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n", "beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
"# Use our neural network to predict the mean of the Gaussian\n", "# Use our neural network to predict the Bernoulli parameter lambda\n",
"model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", "model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"lambda_train = sigmoid(model_out)\n", "lambda_train = sigmoid(model_out)\n",
"# Compute the likelihood\n", "# Compute the likelihood\n",
@@ -336,7 +335,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now let's investigate finding the maximum likelihood / minimum negative log likelihood solution. For simplicity, we'll assume that all the parameters are fixed except one and look at how the likelihood and log likelihood change as we manipulate the last parameter. We'll start with overall y_offset, beta_1 (formerly phi_0)" "Now let's investigate finding the maximum likelihood / minimum negative log likelihood solution. For simplicity, we'll assume that all the parameters are fixed except one and look at how the likelihood and negative log likelihood change as we manipulate the last parameter. We'll start with overall y_offset, beta_1 (formerly phi_0)"
], ],
"metadata": { "metadata": {
"id": "OgcRojvPWh4V" "id": "OgcRojvPWh4V"
@@ -359,7 +358,7 @@
" # Run the network with new parameters\n", " # Run the network with new parameters\n",
" model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", " model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
" lambda_train = sigmoid(model_out)\n", " lambda_train = sigmoid(model_out)\n",
" # Compute and store the three values\n", " # Compute and store the two values\n",
" likelihoods[count] = compute_likelihood(y_train,lambda_train)\n", " likelihoods[count] = compute_likelihood(y_train,lambda_train)\n",
" nlls[count] = compute_negative_log_likelihood(y_train, lambda_train)\n", " nlls[count] = compute_negative_log_likelihood(y_train, lambda_train)\n",
" # Draw the model for every 20th parameter setting\n", " # Draw the model for every 20th parameter setting\n",
@@ -378,12 +377,25 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Now let's plot the likelihood, and negative log likelihoods as a function the value of the offset beta1\n", "# Now let's plot the likelihood and negative log likelihood as a function of the value of the offset beta1\n",
"fig, ax = plt.subplots(1,2)\n", "fig, ax = plt.subplots()\n",
"fig.set_size_inches(10.5, 3.5)\n", "fig.tight_layout(pad=5.0)\n",
"fig.tight_layout(pad=3.0)\n", "likelihood_color = 'tab:red'\n",
"ax[0].plot(beta_1_vals, likelihoods); ax[0].set_xlabel('beta_1[0]'); ax[0].set_ylabel('likelihood')\n", "nll_color = 'tab:blue'\n",
"ax[1].plot(beta_1_vals, nlls); ax[1].set_xlabel('beta_1[0]'); ax[1].set_ylabel('negative log likelihood')\n", "\n",
"\n",
"ax.set_xlabel('beta_1[0]')\n",
"ax.set_ylabel('likelihood', color = likelihood_color)\n",
"ax.plot(beta_1_vals, likelihoods, color = likelihood_color)\n",
"ax.tick_params(axis='y', labelcolor=likelihood_color)\n",
"\n",
"ax1 = ax.twinx()\n",
"ax1.plot(beta_1_vals, nlls, color = nll_color)\n",
"ax1.set_ylabel('negative log likelihood', color = nll_color)\n",
"ax1.tick_params(axis='y', labelcolor = nll_color)\n",
"\n",
"plt.axvline(x = beta_1_vals[np.argmax(likelihoods)], linestyle='dotted')\n",
"\n",
"plt.show()" "plt.show()"
], ],
"metadata": { "metadata": {
@@ -417,7 +429,7 @@
"source": [ "source": [
"They both give the same answer. But you can see from the likelihood above that the likelihood is very small unless the parameters are almost correct. So in practice, we would work with the negative log likelihood.<br><br>\n", "They both give the same answer. But you can see from the likelihood above that the likelihood is very small unless the parameters are almost correct. So in practice, we would work with the negative log likelihood.<br><br>\n",
"\n", "\n",
"Again, to fit the full neural model we would vary all of the 10 parameters of the network in the $\\boldsymbol\\beta_{0},\\boldsymbol\\omega_{0},\\boldsymbol\\beta_{1},\\boldsymbol\\omega_{1}$ until we find the combination that have the maximum likelihood / minimum negative log likelihood.<br><br>\n", "Again, to fit the full neural model we would vary all of the 10 parameters of the network in the $\\boldsymbol\\beta_{0},\\boldsymbol\\Omega_{0},\\boldsymbol\\beta_{1},\\boldsymbol\\Omega_{1}$ until we find the combination that have the maximum likelihood / minimum negative log likelihood.<br><br>\n",
"\n" "\n"
], ],
"metadata": { "metadata": {

View File

@@ -1,20 +1,4 @@
{ {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOVTohDBtmCCzSEqLJ4J9R/",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [ "cells": [
{ {
"cell_type": "markdown", "cell_type": "markdown",
@@ -28,6 +12,9 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "jSlFkICHwHQF"
},
"source": [ "source": [
"# **Notebook 5.3 Multiclass Cross-Entropy Loss**\n", "# **Notebook 5.3 Multiclass Cross-Entropy Loss**\n",
"\n", "\n",
@@ -36,10 +23,7 @@
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions." "Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
], ]
"metadata": {
"id": "jSlFkICHwHQF"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
@@ -61,6 +45,11 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Fv7SZR3tv7mV"
},
"outputs": [],
"source": [ "source": [
"# Define the Rectified Linear Unit (ReLU) function\n", "# Define the Rectified Linear Unit (ReLU) function\n",
"def ReLU(preactivation):\n", "def ReLU(preactivation):\n",
@@ -68,7 +57,7 @@
" return activation\n", " return activation\n",
"\n", "\n",
"# Define a shallow neural network\n", "# Define a shallow neural network\n",
"def shallow_nn(x, beta_0, omega_0, beta_1, omaga_1):\n", "def shallow_nn(x, beta_0, omega_0, beta_1, omega_1):\n",
" # Make sure that input data is (1 x n_data) array\n", " # Make sure that input data is (1 x n_data) array\n",
" n_data = x.size\n", " n_data = x.size\n",
" x = np.reshape(x,(1,n_data))\n", " x = np.reshape(x,(1,n_data))\n",
@@ -77,15 +66,15 @@
" h1 = ReLU(np.matmul(beta_0,np.ones((1,n_data))) + np.matmul(omega_0,x))\n", " h1 = ReLU(np.matmul(beta_0,np.ones((1,n_data))) + np.matmul(omega_0,x))\n",
" model_out = np.matmul(beta_1,np.ones((1,n_data))) + np.matmul(omega_1,h1)\n", " model_out = np.matmul(beta_1,np.ones((1,n_data))) + np.matmul(omega_1,h1)\n",
" return model_out" " return model_out"
], ]
"metadata": {
"id": "Fv7SZR3tv7mV"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "pUT9Ain_HRim"
},
"outputs": [],
"source": [ "source": [
"# Get parameters for model -- we can call this function to easily reset them\n", "# Get parameters for model -- we can call this function to easily reset them\n",
"def get_parameters():\n", "def get_parameters():\n",
@@ -103,15 +92,15 @@
" omega_1[2,0] = 16.0; omega_1[2,1] = -8.0; omega_1[2,2] =-8\n", " omega_1[2,0] = 16.0; omega_1[2,1] = -8.0; omega_1[2,2] =-8\n",
"\n", "\n",
" return beta_0, omega_0, beta_1, omega_1" " return beta_0, omega_0, beta_1, omega_1"
], ]
"metadata": {
"id": "pUT9Ain_HRim"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NRR67ri_1TzN"
},
"outputs": [],
"source": [ "source": [
"# Utility function for plotting data\n", "# Utility function for plotting data\n",
"def plot_multiclass_classification(x_model, out_model, lambda_model, x_data = None, y_data = None, title= None):\n", "def plot_multiclass_classification(x_model, out_model, lambda_model, x_data = None, y_data = None, title= None):\n",
@@ -148,26 +137,26 @@
" if y_data[i] ==2:\n", " if y_data[i] ==2:\n",
" ax[1].plot(x_data[i],-0.05, 'b.')\n", " ax[1].plot(x_data[i],-0.05, 'b.')\n",
" plt.show()" " plt.show()"
], ]
"metadata": {
"id": "NRR67ri_1TzN"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "PsgLZwsPxauP"
},
"source": [ "source": [
"# Multiclass classification\n", "# Multiclass classification\n",
"\n", "\n",
"For multiclass classification, the network must predict the probability of $K$ classes, using $K$ outputs. However, these probability must be non-negative and sum to one, and the network outputs can take arbitrary values. Hence, we pass the outputs through a softmax function which maps $K$ arbitrary values to $K$ non-negative values that sum to one." "For multiclass classification, the network must predict the probability of $K$ classes, using $K$ outputs. However, these probability must be non-negative and sum to one, and the network outputs can take arbitrary values. Hence, we pass the outputs through a softmax function which maps $K$ arbitrary values to $K$ non-negative values that sum to one."
], ]
"metadata": {
"id": "PsgLZwsPxauP"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "uFb8h-9IXnIe"
},
"outputs": [],
"source": [ "source": [
"# Softmax function that maps a vector of arbitrary values to a vector of values that are positive and sum to one.\n", "# Softmax function that maps a vector of arbitrary values to a vector of values that are positive and sum to one.\n",
"def softmax(model_out):\n", "def softmax(model_out):\n",
@@ -184,15 +173,15 @@
" softmax_model_out = np.ones_like(model_out)/ exp_model_out.shape[0]\n", " softmax_model_out = np.ones_like(model_out)/ exp_model_out.shape[0]\n",
"\n", "\n",
" return softmax_model_out" " return softmax_model_out"
], ]
"metadata": {
"id": "uFb8h-9IXnIe"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "VWzNOt1swFVd"
},
"outputs": [],
"source": [ "source": [
"\n", "\n",
"# Let's create some 1D training data\n", "# Let's create some 1D training data\n",
@@ -214,62 +203,62 @@
"model_out= shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n", "model_out= shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n",
"lambda_model = softmax(model_out)\n", "lambda_model = softmax(model_out)\n",
"plot_multiclass_classification(x_model, model_out, lambda_model, x_train, y_train)\n" "plot_multiclass_classification(x_model, model_out, lambda_model, x_train, y_train)\n"
], ]
"metadata": {
"id": "VWzNOt1swFVd"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"The left is model output and the right is the model output after the softmax has been applied, so it now lies in the range [0,1] and represents the probability, that y=0 (red), 1 (green) and 2 (blue) The dots at the bottom show the training data with the same color scheme. So we want the red curve to be high where there are red dots, the green curve to be high where there are green dots, and the blue curve to be high where there are blue dots We'll compute the the likelihood and the negative log likelihood."
],
"metadata": { "metadata": {
"id": "MvVX6tl9AEXF" "id": "MvVX6tl9AEXF"
} },
"source": [
"The left is model output and the right is the model output after the softmax has been applied, so it now lies in the range [0,1] and represents the probability, that y=0 (red), 1 (green) and 2 (blue). The dots at the bottom show the training data with the same color scheme. So we want the red curve to be high where there are red dots, the green curve to be high where there are green dots, and the blue curve to be high where there are blue dots We'll compute the the likelihood and the negative log likelihood."
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"# Return probability under Categorical distribution for input x\n",
"# Just take value from row k of lambda param where y =k,\n",
"def categorical_distribution(y, lambda_param):\n",
" return np.array([lambda_param[row, i] for i, row in enumerate (y)])"
],
"metadata": { "metadata": {
"id": "YaLdRlEX0FkU" "id": "YaLdRlEX0FkU"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"# Return probability under categorical distribution for observed class y\n",
"# Just take value from row k of lambda param where y =k,\n",
"def categorical_distribution(y, lambda_param):\n",
" return np.array([lambda_param[row, i] for i, row in enumerate (y)])"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4TSL14dqHHbV"
},
"outputs": [],
"source": [ "source": [
"# Let's double check we get the right answer before proceeding\n", "# Let's double check we get the right answer before proceeding\n",
"print(\"Correct answer = %3.3f, Your answer = %3.3f\"%(0.2,categorical_distribution(np.array([[0]]),np.array([[0.2],[0.5],[0.3]]))))\n", "print(\"Correct answer = %3.3f, Your answer = %3.3f\"%(0.2,categorical_distribution(np.array([[0]]),np.array([[0.2],[0.5],[0.3]]))))\n",
"print(\"Correct answer = %3.3f, Your answer = %3.3f\"%(0.5,categorical_distribution(np.array([[1]]),np.array([[0.2],[0.5],[0.3]]))))\n", "print(\"Correct answer = %3.3f, Your answer = %3.3f\"%(0.5,categorical_distribution(np.array([[1]]),np.array([[0.2],[0.5],[0.3]]))))\n",
"print(\"Correct answer = %3.3f, Your answer = %3.3f\"%(0.3,categorical_distribution(np.array([[2]]),np.array([[0.2],[0.5],[0.3]]))))\n", "print(\"Correct answer = %3.3f, Your answer = %3.3f\"%(0.3,categorical_distribution(np.array([[2]]),np.array([[0.2],[0.5],[0.3]]))))\n",
"\n" "\n"
], ]
"metadata": {
"id": "4TSL14dqHHbV"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now let's compute the likelihood using this function"
],
"metadata": { "metadata": {
"id": "R5z_0dzQMF35" "id": "R5z_0dzQMF35"
} },
"source": [
"Now let's compute the likelihood using this function"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "zpS7o6liCx7f"
},
"outputs": [],
"source": [ "source": [
"# Return the likelihood of all of the data under the model\n", "# Return the likelihood of all of the data under the model\n",
"def compute_likelihood(y_train, lambda_param):\n", "def compute_likelihood(y_train, lambda_param):\n",
@@ -280,93 +269,93 @@
" likelihood = 0\n", " likelihood = 0\n",
"\n", "\n",
" return likelihood" " return likelihood"
], ]
"metadata": {
"id": "zpS7o6liCx7f"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1hQxBLoVNlr2"
},
"outputs": [],
"source": [ "source": [
"# Let's test this\n", "# Let's test this\n",
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n", "beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
"# Use our neural network to predict the mean of the Gaussian\n", "# Use our neural network to predict the parameters of the categorical distribution\n",
"model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", "model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"lambda_train = softmax(model_out)\n", "lambda_train = softmax(model_out)\n",
"# Compute the likelihood\n", "# Compute the likelihood\n",
"likelihood = compute_likelihood(y_train, lambda_train)\n", "likelihood = compute_likelihood(y_train, lambda_train)\n",
"# Let's double check we get the right answer before proceeding\n", "# Let's double check we get the right answer before proceeding\n",
"print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(0.000000041,likelihood))" "print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(0.000000041,likelihood))"
], ]
"metadata": {
"id": "1hQxBLoVNlr2"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "HzphKgPfOvlk"
},
"source": [ "source": [
"You can see that this gives a very small answer, even for this small 1D dataset, and with the model fitting quite well. This is because it is the product of several probabilities, which are all quite small themselves.\n", "You can see that this gives a very small answer, even for this small 1D dataset, and with the model fitting quite well. This is because it is the product of several probabilities, which are all quite small themselves.\n",
"This will get out of hand pretty quickly with real datasets -- the likelihood will get so small that we can't represent it with normal finite-precision math\n", "This will get out of hand pretty quickly with real datasets -- the likelihood will get so small that we can't represent it with normal finite-precision math\n",
"\n", "\n",
"This is why we use negative log likelihood" "This is why we use negative log likelihood"
], ]
"metadata": {
"id": "HzphKgPfOvlk"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dsT0CWiKBmTV"
},
"outputs": [],
"source": [ "source": [
"# Return the negative log likelihood of the data under the model\n", "# Return the negative log likelihood of the data under the model\n",
"def compute_negative_log_likelihood(y_train, lambda_param):\n", "def compute_negative_log_likelihood(y_train, lambda_param):\n",
" # TODO -- compute the likelihood of the data -- don't use the likelihood function above -- compute the negative sum of the log probabilities\n", " # TODO -- compute the negative log likelihood of the data -- don't use the likelihood function above -- compute the negative sum of the log probabilities\n",
" # You will need np.sum(), np.log()\n", " # You will need np.sum(), np.log()\n",
" # Replace the line below\n", " # Replace the line below\n",
" nll = 0\n", " nll = 0\n",
"\n", "\n",
" return nll" " return nll"
], ]
"metadata": {
"id": "dsT0CWiKBmTV"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"# Let's test this\n",
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
"# Use our neural network to predict the mean of the Gaussian\n",
"model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"# Pass the outputs through the softmax function\n",
"lambda_train = softmax(model_out)\n",
"# Compute the log likelihood\n",
"nll = compute_negative_log_likelihood(y_train, lambda_train)\n",
"# Let's double check we get the right answer before proceeding\n",
"print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(17.015457867,nll))"
],
"metadata": { "metadata": {
"id": "nVxUXg9rQmwI" "id": "nVxUXg9rQmwI"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"# Let's test this\n",
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
"# Use our neural network to predict the parameters of the categorical distribution\n",
"model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"# Pass the outputs through the softmax function\n",
"lambda_train = softmax(model_out)\n",
"# Compute the negative log likelihood\n",
"nll = compute_negative_log_likelihood(y_train, lambda_train)\n",
"# Let's double check we get the right answer before proceeding\n",
"print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(17.015457867,nll))"
]
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now let's investigate finding the maximum likelihood / minimum log likelihood solution. For simplicity, we'll assume that all the parameters are fixed except one and look at how the likelihood and log likelihood change as we manipulate the last parameter. We'll start with overall y_offset, beta_1 (formerly phi_0)"
],
"metadata": { "metadata": {
"id": "OgcRojvPWh4V" "id": "OgcRojvPWh4V"
} },
"source": [
"Now let's investigate finding the maximum likelihood / minimum negative log likelihood solution. For simplicity, we'll assume that all the parameters are fixed except one and look at how the likelihood and negative log likelihood change as we manipulate the last parameter. We'll start with overall y_offset, $\\beta_1$ (formerly $\\phi_0$)"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "pFKtDaAeVU4U"
},
"outputs": [],
"source": [ "source": [
"# Define a range of values for the parameter\n", "# Define a range of values for the parameter\n",
"beta_1_vals = np.arange(-2,6.0,0.1)\n", "beta_1_vals = np.arange(-2,6.0,0.1)\n",
@@ -382,7 +371,7 @@
" # Run the network with new parameters\n", " # Run the network with new parameters\n",
" model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n", " model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
" lambda_train = softmax(model_out)\n", " lambda_train = softmax(model_out)\n",
" # Compute and store the three values\n", " # Compute and store the two values\n",
" likelihoods[count] = compute_likelihood(y_train,lambda_train)\n", " likelihoods[count] = compute_likelihood(y_train,lambda_train)\n",
" nlls[count] = compute_negative_log_likelihood(y_train, lambda_train)\n", " nlls[count] = compute_negative_log_likelihood(y_train, lambda_train)\n",
" # Draw the model for every 20th parameter setting\n", " # Draw the model for every 20th parameter setting\n",
@@ -391,32 +380,45 @@
" model_out = shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n", " model_out = shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n",
" lambda_model = softmax(model_out)\n", " lambda_model = softmax(model_out)\n",
" plot_multiclass_classification(x_model, model_out, lambda_model, x_train, y_train, title=\"beta1[0,0]=%3.3f\"%(beta_1[0,0]))\n" " plot_multiclass_classification(x_model, model_out, lambda_model, x_train, y_train, title=\"beta1[0,0]=%3.3f\"%(beta_1[0,0]))\n"
], ]
"metadata": {
"id": "pFKtDaAeVU4U"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"# Now let's plot the likelihood, negative log likelihood as a function the value of the offset beta1\n",
"fig, ax = plt.subplots(1,2)\n",
"fig.set_size_inches(10.5, 3.5)\n",
"fig.tight_layout(pad=3.0)\n",
"ax[0].plot(beta_1_vals, likelihoods); ax[0].set_xlabel('beta_1[0,0]'); ax[0].set_ylabel('likelihood')\n",
"ax[1].plot(beta_1_vals, nlls); ax[1].set_xlabel('beta_1[0,0]'); ax[1].set_ylabel('negative log likelihood')\n",
"plt.show()"
],
"metadata": { "metadata": {
"id": "UHXeTa9MagO6" "id": "UHXeTa9MagO6"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"# Now let's plot the likelihood and negative log likelihood as a function of the value of the offset beta1\n",
"fig, ax = plt.subplots()\n",
"fig.tight_layout(pad=5.0)\n",
"likelihood_color = 'tab:red'\n",
"nll_color = 'tab:blue'\n",
"\n",
"\n",
"ax.set_xlabel('beta_1[0, 0]')\n",
"ax.set_ylabel('likelihood', color = likelihood_color)\n",
"ax.plot(beta_1_vals, likelihoods, color = likelihood_color)\n",
"ax.tick_params(axis='y', labelcolor=likelihood_color)\n",
"\n",
"ax1 = ax.twinx()\n",
"ax1.plot(beta_1_vals, nlls, color = nll_color)\n",
"ax1.set_ylabel('negative log likelihood', color = nll_color)\n",
"ax1.tick_params(axis='y', labelcolor = nll_color)\n",
"\n",
"plt.axvline(x = beta_1_vals[np.argmax(likelihoods)], linestyle='dotted')\n",
"\n",
"plt.show()"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aDEPhddNdN4u"
},
"outputs": [],
"source": [ "source": [
"# Hopefully, you can see that the maximum of the likelihood fn is at the same position as the minimum negative log likelihood solution\n", "# Hopefully, you can see that the maximum of the likelihood fn is at the same position as the minimum negative log likelihood solution\n",
"# Let's check that:\n", "# Let's check that:\n",
@@ -428,24 +430,34 @@
"model_out = shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n", "model_out = shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n",
"lambda_model = softmax(model_out)\n", "lambda_model = softmax(model_out)\n",
"plot_multiclass_classification(x_model, model_out, lambda_model, x_train, y_train, title=\"beta1[0,0]=%3.3f\"%(beta_1[0,0]))\n" "plot_multiclass_classification(x_model, model_out, lambda_model, x_train, y_train, title=\"beta1[0,0]=%3.3f\"%(beta_1[0,0]))\n"
], ]
"metadata": {
"id": "aDEPhddNdN4u"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "771G8N1Vk5A2"
},
"source": [ "source": [
"They both give the same answer. But you can see from the likelihood above that the likelihood is very small unless the parameters are almost correct. So in practice, we would work with the negative log likelihood.<br><br>\n", "They both give the same answer. But you can see from the likelihood above that the likelihood is very small unless the parameters are almost correct. So in practice, we would work with the negative log likelihood.<br><br>\n",
"\n", "\n",
"Again, to fit the full neural model we would vary all of the 16 parameters of the network in the $\\boldsymbol\\beta_{0},\\boldsymbol\\omega_{0},\\boldsymbol\\beta_{1},\\boldsymbol\\omega_{1}$ until we find the combination that have the maximum likelihood / minimum negative log likelihood.<br><br>\n", "Again, to fit the full neural model we would vary all of the 16 parameters of the network in the $\\boldsymbol\\beta_{0},\\boldsymbol\\Omega_{0},\\boldsymbol\\beta_{1},\\boldsymbol\\Omega_{1}$ until we find the combination that have the maximum likelihood / minimum negative log likelihood.<br><br>\n",
"\n" "\n"
], ]
"metadata": {
"id": "771G8N1Vk5A2"
}
} }
] ],
"metadata": {
"colab": {
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
} }

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyOfxeJ15PMkIi4geDTRCz3c",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -67,7 +66,7 @@
" fig,ax = plt.subplots()\n", " fig,ax = plt.subplots()\n",
" ax.plot(phi_plot,loss_function(phi_plot),'r-')\n", " ax.plot(phi_plot,loss_function(phi_plot),'r-')\n",
" ax.set_xlim(0,1); ax.set_ylim(0,1)\n", " ax.set_xlim(0,1); ax.set_ylim(0,1)\n",
" ax.set_xlabel('$\\phi$'); ax.set_ylabel('$L[\\phi]$')\n", " ax.set_xlabel(r'$\\phi$'); ax.set_ylabel(r'$L[\\phi]$')\n",
" if a is not None and b is not None and c is not None and d is not None:\n", " if a is not None and b is not None and c is not None and d is not None:\n",
" plt.axvspan(a, d, facecolor='k', alpha=0.2)\n", " plt.axvspan(a, d, facecolor='k', alpha=0.2)\n",
" ax.plot([a,a],[0,1],'b-')\n", " ax.plot([a,a],[0,1],'b-')\n",
@@ -113,7 +112,7 @@
" b = 0.33\n", " b = 0.33\n",
" c = 0.66\n", " c = 0.66\n",
" d = 1.0\n", " d = 1.0\n",
" n_iter =0;\n", " n_iter = 0\n",
"\n", "\n",
" # While we haven't found the minimum closely enough\n", " # While we haven't found the minimum closely enough\n",
" while np.abs(b-c) > thresh and n_iter < max_iter:\n", " while np.abs(b-c) > thresh and n_iter < max_iter:\n",
@@ -131,23 +130,23 @@
"\n", "\n",
" print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n", " print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n",
"\n", "\n",
" # Rule #1 If point A is less than points B, C, and D then halve values of B, C, and D\n", " # Rule #1 If the HEIGHT at point A is less than the HEIGHT at points B, C, and D then halve values of B, C, and D\n",
" # i.e. bring them closer to the original point\n", " # i.e. bring them closer to the original point\n",
" # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n", " # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n",
" if (0):\n", " if (0):\n",
" continue;\n", " continue;\n",
"\n", "\n",
"\n", "\n",
" # Rule #2 If point b is less than point c then\n", " # Rule #2 If the HEIGHT at point b is less than the HEIGHT at point c then\n",
" # then point d becomes point c, and\n", " # point d becomes point c, and\n",
" # point b becomes 1/3 between a and new d\n", " # point b becomes 1/3 between a and new d\n",
" # point c becomes 2/3 between a and new d\n", " # point c becomes 2/3 between a and new d\n",
" # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n", " # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n",
" if (0):\n", " if (0):\n",
" continue;\n", " continue;\n",
"\n", "\n",
" # Rule #3 If point c is less than point b then\n", " # Rule #3 If the HEIGHT at point c is less than the HEIGHT at point b then\n",
" # then point a becomes point b, and\n", " # point a becomes point b, and\n",
" # point b becomes 1/3 between new a and d\n", " # point b becomes 1/3 between new a and d\n",
" # point c becomes 2/3 between new a and d\n", " # point c becomes 2/3 between new a and d\n",
" # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n", " # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n",

View File

@@ -1,46 +1,32 @@
{ {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyM/FIXDTd6tZYs6WRzK00hB",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [ "cells": [
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "view-in-github", "colab_type": "text",
"colab_type": "text" "id": "view-in-github"
}, },
"source": [ "source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap06/6_2_Gradient_Descent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" "<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap06/6_2_Gradient_Descent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "el8l05WQEO46"
},
"source": [ "source": [
"# **Notebook 6.2 Gradient descent**\n", "# **Notebook 6.2 Gradient descent**\n",
"\n", "\n",
"This notebook recreates the gradient descent algorithm as shon in figure 6.1.\n", "This notebook recreates the gradient descent algorithm as shown in figure 6.1.\n",
"\n", "\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n", "Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n",
"\n" "\n"
], ]
"metadata": {
"id": "el8l05WQEO46"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
@@ -59,34 +45,39 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4cRkrh9MZ58Z"
},
"outputs": [],
"source": [ "source": [
"# Let's create our training data 12 pairs {x_i, y_i}\n", "# Let's create our training data 12 pairs {x_i, y_i}\n",
"# We'll try to fit the straight line model to these data\n", "# We'll try to fit the straight line model to these data\n",
"data = np.array([[0.03,0.19,0.34,0.46,0.78,0.81,1.08,1.18,1.39,1.60,1.65,1.90],\n", "data = np.array([[0.03,0.19,0.34,0.46,0.78,0.81,1.08,1.18,1.39,1.60,1.65,1.90],\n",
" [0.67,0.85,1.05,1.00,1.40,1.50,1.30,1.54,1.55,1.68,1.73,1.60]])" " [0.67,0.85,1.05,1.00,1.40,1.50,1.30,1.54,1.55,1.68,1.73,1.60]])"
], ]
"metadata": {
"id": "4cRkrh9MZ58Z"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "WQUERmb2erAe"
},
"outputs": [],
"source": [ "source": [
"# Let's define our model -- just a straight line with intercept phi[0] and slope phi[1]\n", "# Let's define our model -- just a straight line with intercept phi[0] and slope phi[1]\n",
"def model(phi,x):\n", "def model(phi,x):\n",
" y_pred = phi[0]+phi[1] * x\n", " y_pred = phi[0]+phi[1] * x\n",
" return y_pred" " return y_pred"
], ]
"metadata": {
"id": "WQUERmb2erAe"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qFRe9POHF2le"
},
"outputs": [],
"source": [ "source": [
"# Draw model\n", "# Draw model\n",
"def draw_model(data,model,phi,title=None):\n", "def draw_model(data,model,phi,title=None):\n",
@@ -102,39 +93,40 @@
" if title is not None:\n", " if title is not None:\n",
" ax.set_title(title)\n", " ax.set_title(title)\n",
" plt.show()" " plt.show()"
], ]
"metadata": {
"id": "qFRe9POHF2le"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "TXx1Tpd1Tl-I"
},
"outputs": [],
"source": [ "source": [
"# Initialize the parameters to some arbitrary values and draw the model\n", "# Initialize the parameters to some arbitrary values and draw the model\n",
"phi = np.zeros((2,1))\n", "phi = np.zeros((2,1))\n",
"phi[0] = 0.6 # Intercept\n", "phi[0] = 0.6 # Intercept\n",
"phi[1] = -0.2 # Slope\n", "phi[1] = -0.2 # Slope\n",
"draw_model(data,model,phi, \"Initial parameters\")\n" "draw_model(data,model,phi, \"Initial parameters\")\n"
], ]
"metadata": {
"id": "TXx1Tpd1Tl-I"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now lets create compute the sum of squares loss for the training data"
],
"metadata": { "metadata": {
"id": "QU5mdGvpTtEG" "id": "QU5mdGvpTtEG"
} },
"source": [
"Now let's compute the sum of squares loss for the training data"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "I7dqTY2Gg7CR"
},
"outputs": [],
"source": [ "source": [
"def compute_loss(data_x, data_y, model, phi):\n", "def compute_loss(data_x, data_y, model, phi):\n",
" # TODO -- Write this function -- replace the line below\n", " # TODO -- Write this function -- replace the line below\n",
@@ -145,45 +137,47 @@
" loss = 0\n", " loss = 0\n",
"\n", "\n",
" return loss" " return loss"
], ]
"metadata": {
"id": "I7dqTY2Gg7CR"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Let's just test that we got that right"
],
"metadata": { "metadata": {
"id": "eB5DQvU5hYNx" "id": "eB5DQvU5hYNx"
} },
"source": [
"Let's just test that we got that right"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"loss = compute_loss(data[0,:],data[1,:],model,np.array([[0.6],[-0.2]]))\n",
"print('Your loss = %3.3f, Correct loss = %3.3f'%(loss, 12.367))"
],
"metadata": { "metadata": {
"id": "Ty05UtEEg9tc" "id": "Ty05UtEEg9tc"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"loss = compute_loss(data[0,:],data[1,:],model,np.array([[0.6],[-0.2]]))\n",
"print('Your loss = %3.3f, Correct loss = %3.3f'%(loss, 12.367))"
]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now let's plot the whole loss function"
],
"metadata": { "metadata": {
"id": "F3trnavPiHpH" "id": "F3trnavPiHpH"
} },
"source": [
"Now let's plot the whole loss function"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "K-NTHpAAHlCl"
},
"outputs": [],
"source": [ "source": [
"def draw_loss_function(compute_loss, data, model, phi_iters = None):\n", "def draw_loss_function(compute_loss, data, model, phi_iters = None):\n",
" # Define pretty colormap\n", " # Define pretty colormap\n",
@@ -210,39 +204,40 @@
" ax.set_ylim([1,-1])\n", " ax.set_ylim([1,-1])\n",
" ax.set_xlabel('Intercept $\\phi_{0}$'); ax.set_ylabel('Slope, $\\phi_{1}$')\n", " ax.set_xlabel('Intercept $\\phi_{0}$'); ax.set_ylabel('Slope, $\\phi_{1}$')\n",
" plt.show()" " plt.show()"
], ]
"metadata": {
"id": "K-NTHpAAHlCl"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"draw_loss_function(compute_loss, data, model)"
],
"metadata": { "metadata": {
"id": "l8HbvIupnTME" "id": "l8HbvIupnTME"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"draw_loss_function(compute_loss, data, model)"
]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "s9Duf05WqqSC"
},
"source": [ "source": [
"Now let's compute the gradient vector for a given set of parameters:\n", "Now let's compute the gradient vector for a given set of parameters:\n",
"\n", "\n",
"\\begin{equation}\n", "\\begin{equation}\n",
"\\frac{\\partial L}{\\partial \\boldsymbol\\phi} = \\begin{bmatrix}\\frac{\\partial L}{\\partial \\phi_0} \\\\\\frac{\\partial L}{\\partial \\phi_1} \\end{bmatrix}.\n", "\\frac{\\partial L}{\\partial \\boldsymbol\\phi} = \\begin{bmatrix}\\frac{\\partial L}{\\partial \\phi_0} \\\\\\frac{\\partial L}{\\partial \\phi_1} \\end{bmatrix}.\n",
"\\end{equation}" "\\end{equation}"
], ]
"metadata": {
"id": "s9Duf05WqqSC"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "UpswmkL2qwBT"
},
"outputs": [],
"source": [ "source": [
"# These are in the lecture slides and notes, but worth trying to calculate them yourself to\n", "# These are in the lecture slides and notes, but worth trying to calculate them yourself to\n",
"# check that you get them right. Write out the expression for the sum of squares loss and take the\n", "# check that you get them right. Write out the expression for the sum of squares loss and take the\n",
@@ -254,31 +249,32 @@
"\n", "\n",
" # Return the gradient\n", " # Return the gradient\n",
" return np.array([[dl_dphi0],[dl_dphi1]])" " return np.array([[dl_dphi0],[dl_dphi1]])"
], ]
"metadata": {
"id": "UpswmkL2qwBT"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "RS1nEcYVuEAM"
},
"source": [ "source": [
"We can check we got this right using a trick known as **finite differences**. If we evaluate the function and then change one of the parameters by a very small amount and normalize by that amount, we get an approximation to the gradient, so:\n", "We can check we got this right using a trick known as **finite differences**. If we evaluate the function and then change one of the parameters by a very small amount and normalize by that amount, we get an approximation to the gradient, so:\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
"\\frac{\\partial L}{\\partial \\phi_{0}}&\\approx & \\frac{L[\\phi_0+\\delta, \\phi_1]-L[\\phi_0, \\phi_1]}{\\delta}\\\\\n", "\\frac{\\partial L}{\\partial \\phi_{0}}&\\approx & \\frac{L[\\phi_0+\\delta, \\phi_1]-L[\\phi_0, \\phi_1]}{\\delta}\\\\\n",
"\\frac{\\partial L}{\\partial \\phi_{1}}&\\approx & \\frac{L[\\phi_0, \\phi_1+\\delta]-L[\\phi_0, \\phi_1]}{\\delta}\n", "\\frac{\\partial L}{\\partial \\phi_{1}}&\\approx & \\frac{L[\\phi_0, \\phi_1+\\delta]-L[\\phi_0, \\phi_1]}{\\delta}\n",
"\\end{eqnarray}\n", "\\end{align}\n",
"\n", "\n",
"We can't do this when there are many parameters; for a million parameters, we would have to evaluate the loss function two million times, and usually computing the gradients directly is much more efficient." "We can't do this when there are many parameters; for a million parameters, we would have to evaluate the loss function one million plus one times, and usually computing the gradients directly is much more efficient."
], ]
"metadata": {
"id": "RS1nEcYVuEAM"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QuwAHN7yt-gi"
},
"outputs": [],
"source": [ "source": [
"# Compute the gradient using your function\n", "# Compute the gradient using your function\n",
"gradient = compute_gradient(data[0,:],data[1,:], phi)\n", "gradient = compute_gradient(data[0,:],data[1,:], phi)\n",
@@ -291,28 +287,29 @@
" compute_loss(data[0,:],data[1,:],model,phi))/delta\n", " compute_loss(data[0,:],data[1,:],model,phi))/delta\n",
"print(\"Approx gradients: (%3.3f,%3.3f)\"%(dl_dphi0_est,dl_dphi1_est))\n", "print(\"Approx gradients: (%3.3f,%3.3f)\"%(dl_dphi0_est,dl_dphi1_est))\n",
"# There might be small differences in the last significant figure because finite gradients is an approximation\n" "# There might be small differences in the last significant figure because finite gradients is an approximation\n"
], ]
"metadata": {
"id": "QuwAHN7yt-gi"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now we are ready to perform gradient descent. We'll need to use our line search routine from part I, which I've reproduced here plus the helper function loss_function_1D that converts from a 2D problem to a 1D problem"
],
"metadata": { "metadata": {
"id": "5EIjMM9Fw2eT" "id": "5EIjMM9Fw2eT"
} },
"source": [
"Now we are ready to perform gradient descent. We'll need to use our line search routine from notebook 6.1, which I've reproduced here plus the helper function loss_function_1D that maps the search along the negative gradient direction in 2D space to a 1D problem (distance along this direction)"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XrJ2gQjfw1XP"
},
"outputs": [],
"source": [ "source": [
"def loss_function_1D(dist_prop, data, model, phi_start, gradient):\n", "def loss_function_1D(dist_prop, data, model, phi_start, search_direction):\n",
" # Return the loss after moving this far\n", " # Return the loss after moving this far\n",
" return compute_loss(data[0,:], data[1,:], model, phi_start+ gradient * dist_prop)\n", " return compute_loss(data[0,:], data[1,:], model, phi_start+ search_direction * dist_prop)\n",
"\n", "\n",
"def line_search(data, model, phi, gradient, thresh=.00001, max_dist = 0.1, max_iter = 15, verbose=False):\n", "def line_search(data, model, phi, gradient, thresh=.00001, max_dist = 0.1, max_iter = 15, verbose=False):\n",
" # Initialize four points along the range we are going to search\n", " # Initialize four points along the range we are going to search\n",
@@ -320,7 +317,7 @@
" b = 0.33 * max_dist\n", " b = 0.33 * max_dist\n",
" c = 0.66 * max_dist\n", " c = 0.66 * max_dist\n",
" d = 1.0 * max_dist\n", " d = 1.0 * max_dist\n",
" n_iter =0;\n", " n_iter = 0\n",
"\n", "\n",
" # While we haven't found the minimum closely enough\n", " # While we haven't found the minimum closely enough\n",
" while np.abs(b-c) > thresh and n_iter < max_iter:\n", " while np.abs(b-c) > thresh and n_iter < max_iter:\n",
@@ -344,7 +341,7 @@
" continue;\n", " continue;\n",
"\n", "\n",
" # Rule #2 If point b is less than point c then\n", " # Rule #2 If point b is less than point c then\n",
" # then point d becomes point c, and\n", " # point d becomes point c, and\n",
" # point b becomes 1/3 between a and new d\n", " # point b becomes 1/3 between a and new d\n",
" # point c becomes 2/3 between a and new d\n", " # point c becomes 2/3 between a and new d\n",
" if lossb < lossc:\n", " if lossb < lossc:\n",
@@ -354,7 +351,7 @@
" continue\n", " continue\n",
"\n", "\n",
" # Rule #2 If point c is less than point b then\n", " # Rule #2 If point c is less than point b then\n",
" # then point a becomes point b, and\n", " # point a becomes point b, and\n",
" # point b becomes 1/3 between new a and d\n", " # point b becomes 1/3 between new a and d\n",
" # point c becomes 2/3 between new a and d\n", " # point c becomes 2/3 between new a and d\n",
" a = b\n", " a = b\n",
@@ -363,32 +360,32 @@
"\n", "\n",
" # Return average of two middle points\n", " # Return average of two middle points\n",
" return (b+c)/2.0" " return (b+c)/2.0"
], ]
"metadata": {
"id": "XrJ2gQjfw1XP"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"def gradient_descent_step(phi, data, model):\n",
" # TODO -- update Phi with the gradient descent step (equation 6.3)\n",
" # 1. Compute the gradient\n",
" # 2. Find the best step size alpha (use negative gradient as going downhill)\n",
" # 3. Update the parameters phi\n",
"\n",
" return phi"
],
"metadata": { "metadata": {
"id": "YVq6rmaWRD2M" "id": "YVq6rmaWRD2M"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"def gradient_descent_step(phi, data, model):\n",
" # TODO -- update Phi with the gradient descent step (equation 6.3)\n",
" # 1. Compute the gradient (you wrote this function above)\n",
" # 2. Find the best step size alpha using line search function (above) -- use negative gradient as going downhill\n",
" # 3. Update the parameters phi based on the gradient and the step size alpha.\n",
"\n",
" return phi"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tOLd0gtdRLLS"
},
"outputs": [],
"source": [ "source": [
"# Initialize the parameters and draw the model\n", "# Initialize the parameters and draw the model\n",
"n_steps = 10\n", "n_steps = 10\n",
@@ -410,12 +407,22 @@
"\n", "\n",
"# Draw the trajectory on the loss function\n", "# Draw the trajectory on the loss function\n",
"draw_loss_function(compute_loss, data, model,phi_all)\n" "draw_loss_function(compute_loss, data, model,phi_all)\n"
], ]
"metadata": {
"id": "tOLd0gtdRLLS"
},
"execution_count": null,
"outputs": []
} }
] ],
"metadata": {
"colab": {
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
} }

View File

@@ -1,33 +1,22 @@
{ {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNk5FN4qlw3pk8BwDVWw1jN",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [ "cells": [
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "view-in-github", "colab_type": "text",
"colab_type": "text" "id": "view-in-github"
}, },
"source": [ "source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap06/6_3_Stochastic_Gradient_Descent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" "<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap06/6_3_Stochastic_Gradient_Descent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "el8l05WQEO46"
},
"source": [ "source": [
"# **Notebook 6.3: Stochastic gradient descent**\n", "# **Notebook 6.3: Stochastic gradient descent**\n",
"\n", "\n",
@@ -39,10 +28,7 @@
"\n", "\n",
"\n", "\n",
"\n" "\n"
], ]
"metadata": {
"id": "el8l05WQEO46"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
@@ -61,8 +47,13 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4cRkrh9MZ58Z"
},
"outputs": [],
"source": [ "source": [
"# Let's create our training data 30 pairs {x_i, y_i}\n", "# Let's create our training data of 30 pairs {x_i, y_i}\n",
"# We'll try to fit the Gabor model to these data\n", "# We'll try to fit the Gabor model to these data\n",
"data = np.array([[-1.920e+00,-1.422e+01,1.490e+00,-1.940e+00,-2.389e+00,-5.090e+00,\n", "data = np.array([[-1.920e+00,-1.422e+01,1.490e+00,-1.940e+00,-2.389e+00,-5.090e+00,\n",
" -8.861e+00,3.578e+00,-6.010e+00,-6.995e+00,3.634e+00,8.743e-01,\n", " -8.861e+00,3.578e+00,-6.010e+00,-6.995e+00,3.634e+00,8.743e-01,\n",
@@ -74,15 +65,15 @@
" -2.365e-02,5.098e-01,-2.777e-01,3.367e-01,1.927e-01,-2.222e-01,\n", " -2.365e-02,5.098e-01,-2.777e-01,3.367e-01,1.927e-01,-2.222e-01,\n",
" 6.352e-02,6.888e-03,3.224e-02,1.091e-02,-5.706e-01,-5.258e-02,\n", " 6.352e-02,6.888e-03,3.224e-02,1.091e-02,-5.706e-01,-5.258e-02,\n",
" -3.666e-02,1.709e-01,-4.805e-02,2.008e-01,-1.904e-01,5.952e-01]])" " -3.666e-02,1.709e-01,-4.805e-02,2.008e-01,-1.904e-01,5.952e-01]])"
], ]
"metadata": {
"id": "4cRkrh9MZ58Z"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "WQUERmb2erAe"
},
"outputs": [],
"source": [ "source": [
"# Let's define our model\n", "# Let's define our model\n",
"def model(phi,x):\n", "def model(phi,x):\n",
@@ -90,15 +81,15 @@
" gauss_component = np.exp(-(phi[0] + 0.06 * phi[1] * x) * (phi[0] + 0.06 * phi[1] * x) / 32)\n", " gauss_component = np.exp(-(phi[0] + 0.06 * phi[1] * x) * (phi[0] + 0.06 * phi[1] * x) / 32)\n",
" y_pred= sin_component * gauss_component\n", " y_pred= sin_component * gauss_component\n",
" return y_pred" " return y_pred"
], ]
"metadata": {
"id": "WQUERmb2erAe"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qFRe9POHF2le"
},
"outputs": [],
"source": [ "source": [
"# Draw model\n", "# Draw model\n",
"def draw_model(data,model,phi,title=None):\n", "def draw_model(data,model,phi,title=None):\n",
@@ -113,39 +104,40 @@
" if title is not None:\n", " if title is not None:\n",
" ax.set_title(title)\n", " ax.set_title(title)\n",
" plt.show()" " plt.show()"
], ]
"metadata": {
"id": "qFRe9POHF2le"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "TXx1Tpd1Tl-I"
},
"outputs": [],
"source": [ "source": [
"# Initialize the parmaeters and draw the model\n", "# Initialize the parameters and draw the model\n",
"phi = np.zeros((2,1))\n", "phi = np.zeros((2,1))\n",
"phi[0] = -5 # Horizontal offset\n", "phi[0] = -5 # Horizontal offset\n",
"phi[1] = 25 # Frequency\n", "phi[1] = 25 # Frequency\n",
"draw_model(data,model,phi, \"Initial parameters\")\n" "draw_model(data,model,phi, \"Initial parameters\")\n"
], ]
"metadata": {
"id": "TXx1Tpd1Tl-I"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now lets create compute the sum of squares loss for the training data"
],
"metadata": { "metadata": {
"id": "QU5mdGvpTtEG" "id": "QU5mdGvpTtEG"
} },
"source": [
"Now let's compute the sum of squares loss for the training data"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "I7dqTY2Gg7CR"
},
"outputs": [],
"source": [ "source": [
"def compute_loss(data_x, data_y, model, phi):\n", "def compute_loss(data_x, data_y, model, phi):\n",
" # TODO -- Write this function -- replace the line below\n", " # TODO -- Write this function -- replace the line below\n",
@@ -155,45 +147,47 @@
" loss = 0\n", " loss = 0\n",
"\n", "\n",
" return loss" " return loss"
], ]
"metadata": {
"id": "I7dqTY2Gg7CR"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Let's just test that we got that right"
],
"metadata": { "metadata": {
"id": "eB5DQvU5hYNx" "id": "eB5DQvU5hYNx"
} },
"source": [
"Let's just test that we got that right"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"loss = compute_loss(data[0,:],data[1,:],model,np.array([[0.6],[-0.2]]))\n",
"print('Your loss = %3.3f, Correct loss = %3.3f'%(loss, 16.419))"
],
"metadata": { "metadata": {
"id": "Ty05UtEEg9tc" "id": "Ty05UtEEg9tc"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"loss = compute_loss(data[0,:],data[1,:],model,np.array([[0.6],[-0.2]]))\n",
"print('Your loss = %3.3f, Correct loss = %3.3f'%(loss, 16.419))"
]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now let's plot the whole loss function"
],
"metadata": { "metadata": {
"id": "F3trnavPiHpH" "id": "F3trnavPiHpH"
} },
"source": [
"Now let's plot the whole loss function"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "K-NTHpAAHlCl"
},
"outputs": [],
"source": [ "source": [
"def draw_loss_function(compute_loss, data, model, phi_iters = None):\n", "def draw_loss_function(compute_loss, data, model, phi_iters = None):\n",
" # Define pretty colormap\n", " # Define pretty colormap\n",
@@ -204,7 +198,7 @@
" b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n", " b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
" my_colormap = ListedColormap(np.vstack((r,g,b)).transpose()/255.0)\n", " my_colormap = ListedColormap(np.vstack((r,g,b)).transpose()/255.0)\n",
"\n", "\n",
" # Make grid of intercept/slope values to plot\n", " # Make grid of offset/frequency values to plot\n",
" offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n", " offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n",
" loss_mesh = np.zeros_like(freqs_mesh)\n", " loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n", " # Compute loss for every set of parameters\n",
@@ -220,39 +214,40 @@
" ax.set_ylim([2.5,22.5])\n", " ax.set_ylim([2.5,22.5])\n",
" ax.set_xlabel('Offset $\\phi_{0}$'); ax.set_ylabel('Frequency, $\\phi_{1}$')\n", " ax.set_xlabel('Offset $\\phi_{0}$'); ax.set_ylabel('Frequency, $\\phi_{1}$')\n",
" plt.show()" " plt.show()"
], ]
"metadata": {
"id": "K-NTHpAAHlCl"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"draw_loss_function(compute_loss, data, model)"
],
"metadata": { "metadata": {
"id": "l8HbvIupnTME" "id": "l8HbvIupnTME"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"draw_loss_function(compute_loss, data, model)"
]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "s9Duf05WqqSC"
},
"source": [ "source": [
"Now let's compute the gradient vector for a given set of parameters:\n", "Now let's compute the gradient vector for a given set of parameters:\n",
"\n", "\n",
"\\begin{equation}\n", "\\begin{equation}\n",
"\\frac{\\partial L}{\\partial \\boldsymbol\\phi} = \\begin{bmatrix}\\frac{\\partial L}{\\partial \\phi_0} \\\\\\frac{\\partial L}{\\partial \\phi_1} \\end{bmatrix}.\n", "\\frac{\\partial L}{\\partial \\boldsymbol\\phi} = \\begin{bmatrix}\\frac{\\partial L}{\\partial \\phi_0} \\\\\\frac{\\partial L}{\\partial \\phi_1} \\end{bmatrix}.\n",
"\\end{equation}" "\\end{equation}"
], ]
"metadata": {
"id": "s9Duf05WqqSC"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "UpswmkL2qwBT"
},
"outputs": [],
"source": [ "source": [
"# These came from writing out the expression for the sum of squares loss and taking the\n", "# These came from writing out the expression for the sum of squares loss and taking the\n",
"# derivative with respect to phi0 and phi1. It was a lot of hassle to get it right!\n", "# derivative with respect to phi0 and phi1. It was a lot of hassle to get it right!\n",
@@ -281,31 +276,32 @@
" dl_dphi1 = gabor_deriv_phi1(data_x, data_y, phi[0],phi[1])\n", " dl_dphi1 = gabor_deriv_phi1(data_x, data_y, phi[0],phi[1])\n",
" # Return the gradient\n", " # Return the gradient\n",
" return np.array([[dl_dphi0],[dl_dphi1]])" " return np.array([[dl_dphi0],[dl_dphi1]])"
], ]
"metadata": {
"id": "UpswmkL2qwBT"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "RS1nEcYVuEAM"
},
"source": [ "source": [
"We can check we got this right using a trick known as **finite differences**. If we evaluate the function and then change one of the parameters by a very small amount and normalize by that amount, we get an approximation to the gradient, so:\n", "We can check we got this right using a trick known as **finite differences**. If we evaluate the function and then change one of the parameters by a very small amount and normalize by that amount, we get an approximation to the gradient, so:\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
"\\frac{\\partial L}{\\partial \\phi_{0}}&\\approx & \\frac{L[\\phi_0+\\delta, \\phi_1]-L[\\phi_0, \\phi_1]}{\\delta}\\\\\n", "\\frac{\\partial L}{\\partial \\phi_{0}}&\\approx & \\frac{L[\\phi_0+\\delta, \\phi_1]-L[\\phi_0, \\phi_1]}{\\delta}\\\\\n",
"\\frac{\\partial L}{\\partial \\phi_{1}}&\\approx & \\frac{L[\\phi_0, \\phi_1+\\delta]-L[\\phi_0, \\phi_1]}{\\delta}\n", "\\frac{\\partial L}{\\partial \\phi_{1}}&\\approx & \\frac{L[\\phi_0, \\phi_1+\\delta]-L[\\phi_0, \\phi_1]}{\\delta}\n",
"\\end{eqnarray}\n", "\\end{align}\n",
"\n", "\n",
"We can't do this when there are many parameters; for a million parameters, we would have to evaluate the loss function two million times, and usually computing the gradients directly is much more efficient." "We can't do this when there are many parameters; for a million parameters, we would have to evaluate the loss function two million times, and usually computing the gradients directly is much more efficient."
], ]
"metadata": {
"id": "RS1nEcYVuEAM"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QuwAHN7yt-gi"
},
"outputs": [],
"source": [ "source": [
"# Compute the gradient using your function\n", "# Compute the gradient using your function\n",
"gradient = compute_gradient(data[0,:],data[1,:], phi)\n", "gradient = compute_gradient(data[0,:],data[1,:], phi)\n",
@@ -317,24 +313,25 @@
"dl_dphi1_est = (compute_loss(data[0,:],data[1,:],model,phi+np.array([[0],[delta]])) - \\\n", "dl_dphi1_est = (compute_loss(data[0,:],data[1,:],model,phi+np.array([[0],[delta]])) - \\\n",
" compute_loss(data[0,:],data[1,:],model,phi))/delta\n", " compute_loss(data[0,:],data[1,:],model,phi))/delta\n",
"print(\"Approx gradients: (%3.3f,%3.3f)\"%(dl_dphi0_est,dl_dphi1_est))\n" "print(\"Approx gradients: (%3.3f,%3.3f)\"%(dl_dphi0_est,dl_dphi1_est))\n"
], ]
"metadata": {
"id": "QuwAHN7yt-gi"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now we are ready to perform gradient descent. We'll need to use our line search routine from Notebook 6.1, which I've reproduced here plus the helper function loss_function_1D that converts from a 2D problem to a 1D problem"
],
"metadata": { "metadata": {
"id": "5EIjMM9Fw2eT" "id": "5EIjMM9Fw2eT"
} },
"source": [
"Now we are ready to perform gradient descent. We'll need to use our line search routine from Notebook 6.1, which I've reproduced here plus the helper function loss_function_1D that converts from a 2D problem to a 1D problem"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XrJ2gQjfw1XP"
},
"outputs": [],
"source": [ "source": [
"def loss_function_1D(dist_prop, data, model, phi_start, gradient):\n", "def loss_function_1D(dist_prop, data, model, phi_start, gradient):\n",
" # Return the loss after moving this far\n", " # Return the loss after moving this far\n",
@@ -346,7 +343,7 @@
" b = 0.33 * max_dist\n", " b = 0.33 * max_dist\n",
" c = 0.66 * max_dist\n", " c = 0.66 * max_dist\n",
" d = 1.0 * max_dist\n", " d = 1.0 * max_dist\n",
" n_iter =0;\n", " n_iter = 0\n",
"\n", "\n",
" # While we haven't found the minimum closely enough\n", " # While we haven't found the minimum closely enough\n",
" while np.abs(b-c) > thresh and n_iter < max_iter:\n", " while np.abs(b-c) > thresh and n_iter < max_iter:\n",
@@ -370,7 +367,7 @@
" continue;\n", " continue;\n",
"\n", "\n",
" # Rule #2 If point b is less than point c then\n", " # Rule #2 If point b is less than point c then\n",
" # then point d becomes point c, and\n", " # point d becomes point c, and\n",
" # point b becomes 1/3 between a and new d\n", " # point b becomes 1/3 between a and new d\n",
" # point c becomes 2/3 between a and new d\n", " # point c becomes 2/3 between a and new d\n",
" if lossb < lossc:\n", " if lossb < lossc:\n",
@@ -380,7 +377,7 @@
" continue\n", " continue\n",
"\n", "\n",
" # Rule #2 If point c is less than point b then\n", " # Rule #2 If point c is less than point b then\n",
" # then point a becomes point b, and\n", " # point a becomes point b, and\n",
" # point b becomes 1/3 between new a and d\n", " # point b becomes 1/3 between new a and d\n",
" # point c becomes 2/3 between new a and d\n", " # point c becomes 2/3 between new a and d\n",
" a = b\n", " a = b\n",
@@ -389,15 +386,15 @@
"\n", "\n",
" # Return average of two middle points\n", " # Return average of two middle points\n",
" return (b+c)/2.0" " return (b+c)/2.0"
], ]
"metadata": {
"id": "XrJ2gQjfw1XP"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YVq6rmaWRD2M"
},
"outputs": [],
"source": [ "source": [
"def gradient_descent_step(phi, data, model):\n", "def gradient_descent_step(phi, data, model):\n",
" # Step 1: Compute the gradient\n", " # Step 1: Compute the gradient\n",
@@ -406,15 +403,15 @@
" alpha = line_search(data, model, phi, gradient*-1, max_dist = 2.0)\n", " alpha = line_search(data, model, phi, gradient*-1, max_dist = 2.0)\n",
" phi = phi - alpha * gradient\n", " phi = phi - alpha * gradient\n",
" return phi" " return phi"
], ]
"metadata": {
"id": "YVq6rmaWRD2M"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tOLd0gtdRLLS"
},
"outputs": [],
"source": [ "source": [
"# Initialize the parameters\n", "# Initialize the parameters\n",
"n_steps = 21\n", "n_steps = 21\n",
@@ -435,41 +432,41 @@
" draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n", " draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n",
"\n", "\n",
"draw_loss_function(compute_loss, data, model,phi_all)\n" "draw_loss_function(compute_loss, data, model,phi_all)\n"
], ]
"metadata": {
"id": "tOLd0gtdRLLS"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"# TODO Experiment with starting the optimization in the previous cell in different places\n",
"# and show that it heads to a local minimum if we don't start it in the right valley"
],
"metadata": { "metadata": {
"id": "Oi8ZlH0ptLqA" "id": "Oi8ZlH0ptLqA"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"# TODO Experiment with starting the optimization in the previous cell in different places\n",
"# and show that it heads to a local minimum if we don't start it in the right valley"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4l-ueLk-oAxV"
},
"outputs": [],
"source": [ "source": [
"def gradient_descent_step_fixed_learning_rate(phi, data, alpha):\n", "def gradient_descent_step_fixed_learning_rate(phi, data, alpha):\n",
" # TODO -- fill in this routine so that we take a fixed size step of size alpha without using line search\n", " # TODO -- fill in this routine so that we take a fixed size step of size alpha without using line search\n",
"\n", "\n",
" return phi" " return phi"
], ]
"metadata": {
"id": "4l-ueLk-oAxV"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oi9MX_GRpM41"
},
"outputs": [],
"source": [ "source": [
"# Initialize the parameters\n", "# Initialize the parameters\n",
"n_steps = 21\n", "n_steps = 21\n",
@@ -490,47 +487,47 @@
" draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n", " draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n",
"\n", "\n",
"draw_loss_function(compute_loss, data, model,phi_all)\n" "draw_loss_function(compute_loss, data, model,phi_all)\n"
], ]
"metadata": {
"id": "oi9MX_GRpM41"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "In6sQ5YCpMqn"
},
"outputs": [],
"source": [ "source": [
"# TODO Experiment with the learning rate, alpha.\n", "# TODO Experiment with the learning rate, alpha.\n",
"# What happens if you set it too large?\n", "# What happens if you set it too large?\n",
"# What happens if you set it too small?" "# What happens if you set it too small?"
], ]
"metadata": {
"id": "In6sQ5YCpMqn"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "VKTC9-1Gpm3N"
},
"outputs": [],
"source": [ "source": [
"def stochastic_gradient_descent_step(phi, data, alpha, batch_size):\n", "def stochastic_gradient_descent_step(phi, data, alpha, batch_size):\n",
" # TODO -- fill in this routine so that we take a fixed size step of size alpha but only using a subset (batch) of the data\n", " # TODO -- fill in this routine so that we take a fixed size step of size alpha but only using a subset (batch) of the data\n",
" # at each step\n", " # at each step\n",
" # You can use the function np.random.permutation to generate a random permutation of the n_data = data.shape[1] indices\n", " # You can use the function np.random.permutation to generate a random permutation of the n_data = data.shape[1] indices\n",
" # and then just choose the first n=batch_size of these indices. Then compute the gradient update\n", " # and then just choose the first n=batch_size of these indices. Then compute the gradient update\n",
" # from just the data with these indices. More properly, you should sample with replacement, but this will do for now.\n", " # from just the data with these indices. More properly, you should sample without replacement, but this will do for now.\n",
"\n", "\n",
"\n", "\n",
" return phi" " return phi"
], ]
"metadata": {
"id": "VKTC9-1Gpm3N"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "469OP_UHskJ4"
},
"outputs": [],
"source": [ "source": [
"# Set the random number generator so you always get same numbers (disable if you don't want this)\n", "# Set the random number generator so you always get same numbers (disable if you don't want this)\n",
"np.random.seed(1)\n", "np.random.seed(1)\n",
@@ -553,34 +550,45 @@
" draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n", " draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n",
"\n", "\n",
"draw_loss_function(compute_loss, data, model,phi_all)" "draw_loss_function(compute_loss, data, model,phi_all)"
], ]
"metadata": {
"id": "469OP_UHskJ4"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"# TODO -- Experiment with different learning rates, starting points, batch sizes, number of steps. Get a feel for this."
],
"metadata": { "metadata": {
"id": "LxE2kTa3s29p" "id": "LxE2kTa3s29p"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"# TODO -- Experiment with different learning rates, starting points, batch sizes, number of steps. Get a feel for this."
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"# TODO -- Add a learning rate schedule. Reduce the learning rate by a factor of beta every M iterations"
],
"metadata": { "metadata": {
"id": "lw4QPOaQTh5e" "id": "lw4QPOaQTh5e"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"# TODO -- Add a learning rate schedule. Reduce the learning rate by a factor of beta every M iterations"
]
} }
] ],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyNk5FN4qlw3pk8BwDVWw1jN",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
} }

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyMLS4qeqBTVHGdg9Sds9jND",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -62,7 +61,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Let's create our training data 30 pairs {x_i, y_i}\n", "# Let's create our training data of 30 pairs {x_i, y_i}\n",
"# We'll try to fit the Gabor model to these data\n", "# We'll try to fit the Gabor model to these data\n",
"data = np.array([[-1.920e+00,-1.422e+01,1.490e+00,-1.940e+00,-2.389e+00,-5.090e+00,\n", "data = np.array([[-1.920e+00,-1.422e+01,1.490e+00,-1.940e+00,-2.389e+00,-5.090e+00,\n",
" -8.861e+00,3.578e+00,-6.010e+00,-6.995e+00,3.634e+00,8.743e-01,\n", " -8.861e+00,3.578e+00,-6.010e+00,-6.995e+00,3.634e+00,8.743e-01,\n",
@@ -123,7 +122,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Initialize the parmaeters and draw the model\n", "# Initialize the parameters and draw the model\n",
"phi = np.zeros((2,1))\n", "phi = np.zeros((2,1))\n",
"phi[0] = -5 # Horizontal offset\n", "phi[0] = -5 # Horizontal offset\n",
"phi[1] = 25 # Frequency\n", "phi[1] = 25 # Frequency\n",
@@ -138,7 +137,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now lets compute the sum of squares loss for the training data and plot the loss function" "Now let's compute the sum of squares loss for the training data and plot the loss function"
], ],
"metadata": { "metadata": {
"id": "QU5mdGvpTtEG" "id": "QU5mdGvpTtEG"
@@ -161,7 +160,7 @@
" b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n", " b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
" my_colormap = ListedColormap(np.vstack((r,g,b)).transpose()/255.0)\n", " my_colormap = ListedColormap(np.vstack((r,g,b)).transpose()/255.0)\n",
"\n", "\n",
" # Make grid of intercept/slope values to plot\n", " # Make grid of offset/frequency values to plot\n",
" offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n", " offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n",
" loss_mesh = np.zeros_like(freqs_mesh)\n", " loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n", " # Compute loss for every set of parameters\n",
@@ -366,7 +365,6 @@
"\n", "\n",
" # Update the parameters\n", " # Update the parameters\n",
" phi_all[:,c_step+1:c_step+2] = phi_all[:,c_step:c_step+1] - alpha * momentum\n", " phi_all[:,c_step+1:c_step+2] = phi_all[:,c_step:c_step+1] - alpha * momentum\n",
" # Measure loss and draw model every 8th step\n",
"\n", "\n",
"loss = compute_loss(data[0,:], data[1,:], model, phi_all[:,c_step+1:c_step+2])\n", "loss = compute_loss(data[0,:], data[1,:], model, phi_all[:,c_step+1:c_step+2])\n",
"draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n", "draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n",
@@ -377,6 +375,15 @@
}, },
"execution_count": null, "execution_count": null,
"outputs": [] "outputs": []
},
{
"cell_type": "markdown",
"source": [
"Note that for this case, Nesterov momentum does not improve the result."
],
"metadata": {
"id": "F-As4hS8s2nm"
}
} }
] ]
} }

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyNFsCOnucz1nQt7PBEnKeTV",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -109,8 +108,8 @@
" ax.contour(phi0mesh, phi1mesh, loss_function, 20, colors=['#80808080'])\n", " ax.contour(phi0mesh, phi1mesh, loss_function, 20, colors=['#80808080'])\n",
" ax.plot(opt_path[0,:], opt_path[1,:],'-', color='#a0d9d3ff')\n", " ax.plot(opt_path[0,:], opt_path[1,:],'-', color='#a0d9d3ff')\n",
" ax.plot(opt_path[0,:], opt_path[1,:],'.', color='#a0d9d3ff',markersize=10)\n", " ax.plot(opt_path[0,:], opt_path[1,:],'.', color='#a0d9d3ff',markersize=10)\n",
" ax.set_xlabel(\"$\\phi_{0}$\")\n", " ax.set_xlabel(r\"$\\phi_{0}$\")\n",
" ax.set_ylabel(\"$\\phi_1}$\")\n", " ax.set_ylabel(r\"$\\phi_{1}$\")\n",
" plt.show()" " plt.show()"
], ],
"metadata": { "metadata": {
@@ -169,7 +168,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Because the function changes much faster in $\\phi_1$ than in $\\phi_0$, there is no great step size to choose. If we set the step size so that it makes sensible progress in the $\\phi_1$, then it takes many iterations to converge. If we set the step size tso that we make sensible progress in the $\\phi_{0}$ direction, then the path oscillates in the $\\phi_1$ direction. \n", "Because the function changes much faster in $\\phi_1$ than in $\\phi_0$, there is no great step size to choose. If we set the step size so that it makes sensible progress in the $\\phi_1$ direction, then it takes many iterations to converge. If we set the step size so that we make sensible progress in the $\\phi_0$ direction, then the path oscillates in the $\\phi_1$ direction. \n",
"\n", "\n",
"This motivates Adam. At the core of Adam is the idea that we should just determine which way is downhill along each axis (i.e. left/right for $\\phi_0$ or up/down for $\\phi_1$) and move a fixed distance in that direction." "This motivates Adam. At the core of Adam is the idea that we should just determine which way is downhill along each axis (i.e. left/right for $\\phi_0$ or up/down for $\\phi_1$) and move a fixed distance in that direction."
], ],
@@ -222,7 +221,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"This moves towards the minimum at a sensible speed, but we never actually converge -- the solution just bounces back and forth between the last two points. To make it converge, we add momentum to both the estimates of the gradient and the pointwise squared gradient. We also modify the statistics by a factor that depends on the time to make sure the progress is now slow to start with." "This moves towards the minimum at a sensible speed, but we never actually converge -- the solution just bounces back and forth between the last two points. To make it converge, we add momentum to both the estimates of the gradient and the pointwise squared gradient. We also modify the statistics by a factor that depends on the time to make sure the progress is not slow to start with."
], ],
"metadata": { "metadata": {
"id": "_6KoKBJdGGI4" "id": "_6KoKBJdGGI4"
@@ -248,7 +247,7 @@
" # Replace this line:\n", " # Replace this line:\n",
" v = v\n", " v = v\n",
"\n", "\n",
" # TODO -- Modify the statistics according to euation 6.16\n", " # TODO -- Modify the statistics according to equation 6.16\n",
" # You will need the function np.power\n", " # You will need the function np.power\n",
" # Replace these lines\n", " # Replace these lines\n",
" m_tilde = m\n", " m_tilde = m\n",

View File

@@ -1,33 +1,22 @@
{ {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyP5wHK5E7/el+vxU947K3q8",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [ "cells": [
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "view-in-github", "colab_type": "text",
"colab_type": "text" "id": "view-in-github"
}, },
"source": [ "source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap07/7_1_Backpropagation_in_Toy_Model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" "<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap07/7_1_Backpropagation_in_Toy_Model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "pOZ6Djz0dhoy"
},
"source": [ "source": [
"# **Notebook 7.1: Backpropagation in Toy Model**\n", "# **Notebook 7.1: Backpropagation in Toy Model**\n",
"\n", "\n",
@@ -36,64 +25,63 @@
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions." "Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
], ]
"metadata": {
"id": "pOZ6Djz0dhoy"
}
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "1DmMo2w63CmT"
},
"source": [ "source": [
"We're going to investigate how to take the derivatives of functions where one operation is composed with another, which is composed with a third and so on. For example, consider the model:\n", "We're going to investigate how to take the derivatives of functions where one operation is composed with another, which is composed with a third and so on. For example, consider the model:\n",
"\n", "\n",
"\\begin{equation}\n", "\\begin{equation}\n",
" \\mbox{f}[x,\\boldsymbol\\phi] = \\beta_3+\\omega_3\\cdot\\cos\\Bigl[\\beta_2+\\omega_2\\cdot\\exp\\bigl[\\beta_1+\\omega_1\\cdot\\sin[\\beta_0+\\omega_0x]\\bigr]\\Bigr],\n", " \\text{f}[x,\\boldsymbol\\phi] = \\beta_3+\\omega_3\\cdot\\cos\\Bigl[\\beta_2+\\omega_2\\cdot\\exp\\bigl[\\beta_1+\\omega_1\\cdot\\sin[\\beta_0+\\omega_0x]\\bigr]\\Bigr],\n",
"\\end{equation}\n", "\\end{equation}\n",
"\n", "\n",
"with parameters $\\boldsymbol\\phi=\\{\\beta_0,\\omega_0,\\beta_1,\\omega_1,\\beta_2,\\omega_2,\\beta_3,\\omega_3\\}$.<br>\n", "with parameters $\\boldsymbol\\phi=\\{\\beta_0,\\omega_0,\\beta_1,\\omega_1,\\beta_2,\\omega_2,\\beta_3,\\omega_3\\}$.<br>\n",
"\n", "\n",
"This is a composition of the functions $\\cos[\\bullet],\\exp[\\bullet],\\sin[\\bullet]$. I chose these just because you probably already know the derivatives of these functions:\n", "This is a composition of the functions $\\cos[\\bullet],\\exp[\\bullet],\\sin[\\bullet]$. I chose these just because you probably already know the derivatives of these functions:\n",
"\n", "\n",
"\\begin{eqnarray*}\n", "\\begin{align}\n",
" \\frac{\\partial \\cos[z]}{\\partial z} = -\\sin[z] \\quad\\quad \\frac{\\partial \\exp[z]}{\\partial z} = \\exp[z] \\quad\\quad \\frac{\\partial \\sin[z]}{\\partial z} = \\cos[z].\n", " \\frac{\\partial \\cos[z]}{\\partial z} = -\\sin[z] \\quad\\quad \\frac{\\partial \\exp[z]}{\\partial z} = \\exp[z] \\quad\\quad \\frac{\\partial \\sin[z]}{\\partial z} = \\cos[z].\n",
"\\end{eqnarray*}\n", "\\end{align}\n",
"\n", "\n",
"Suppose that we have a least squares loss function:\n", "Suppose that we have a least squares loss function:\n",
"\n", "\n",
"\\begin{equation*}\n", "\\begin{equation*}\n",
"\\ell_i = (\\mbox{f}[x_i,\\boldsymbol\\phi]-y_i)^2,\n", "\\ell_i = (\\text{f}[x_i,\\boldsymbol\\phi]-y_i)^2,\n",
"\\end{equation*}\n", "\\end{equation*}\n",
"\n", "\n",
"Assume that we know the current values of $\\beta_{0},\\beta_{1},\\beta_{2},\\beta_{3},\\omega_{0},\\omega_{1},\\omega_{2},\\omega_{3}$, $x_i$ and $y_i$. We could obviously calculate $\\ell_i$. But we also want to know how $\\ell_i$ changes when we make a small change to $\\beta_{0},\\beta_{1},\\beta_{2},\\beta_{3},\\omega_{0},\\omega_{1},\\omega_{2}$, or $\\omega_{3}$. In other words, we want to compute the eight derivatives:\n", "Assume that we know the current values of $\\beta_{0},\\beta_{1},\\beta_{2},\\beta_{3},\\omega_{0},\\omega_{1},\\omega_{2},\\omega_{3}$, $x_i$ and $y_i$. We could obviously calculate $\\ell_i$. But we also want to know how $\\ell_i$ changes when we make a small change to $\\beta_{0},\\beta_{1},\\beta_{2},\\beta_{3},\\omega_{0},\\omega_{1},\\omega_{2}$, or $\\omega_{3}$. In other words, we want to compute the eight derivatives:\n",
"\n", "\n",
"\\begin{eqnarray*}\n", "\\begin{align}\n",
"\\frac{\\partial \\ell_i}{\\partial \\beta_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{2}}, \\quad \\frac{\\partial \\ell_i }{\\partial \\beta_{3}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{2}}, \\quad\\mbox{and} \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{3}}.\n", "\\frac{\\partial \\ell_i}{\\partial \\beta_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{2}}, \\quad \\frac{\\partial \\ell_i }{\\partial \\beta_{3}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{2}}, \\quad\\text{and} \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{3}}.\n",
"\\end{eqnarray*}" "\\end{align}"
], ]
"metadata": {
"id": "1DmMo2w63CmT"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"# import library\n",
"import numpy as np"
],
"metadata": { "metadata": {
"id": "RIPaoVN834Lj" "id": "RIPaoVN834Lj"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"# import library\n",
"import numpy as np"
]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Let's first define the original function for $y$ and the likelihood term:"
],
"metadata": { "metadata": {
"id": "32-ufWhc3v2c" "id": "32-ufWhc3v2c"
} },
"source": [
"Let's first define the original function for $y$ and the loss term:"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
@@ -106,103 +94,135 @@
"def fn(x, beta0, beta1, beta2, beta3, omega0, omega1, omega2, omega3):\n", "def fn(x, beta0, beta1, beta2, beta3, omega0, omega1, omega2, omega3):\n",
" return beta3+omega3 * np.cos(beta2 + omega2 * np.exp(beta1 + omega1 * np.sin(beta0 + omega0 * x)))\n", " return beta3+omega3 * np.cos(beta2 + omega2 * np.exp(beta1 + omega1 * np.sin(beta0 + omega0 * x)))\n",
"\n", "\n",
"def likelihood(x, y, beta0, beta1, beta2, beta3, omega0, omega1, omega2, omega3):\n", "def loss(x, y, beta0, beta1, beta2, beta3, omega0, omega1, omega2, omega3):\n",
" diff = fn(x, beta0, beta1, beta2, beta3, omega0, omega1, omega2, omega3) - y\n", " diff = fn(x, beta0, beta1, beta2, beta3, omega0, omega1, omega2, omega3) - y\n",
" return diff * diff" " return diff * diff"
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now we'll choose some values for the betas and the omegas and x and compute the output of the function:"
],
"metadata": { "metadata": {
"id": "y7tf0ZMt5OXt" "id": "y7tf0ZMt5OXt"
} },
"source": [
"Now we'll choose some values for the betas and the omegas and x and compute the output of the function:"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "pwvOcCxr41X_",
"outputId": "9541922c-dfc4-4b2e-dfa3-3298812155ce"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"l_i=0.139\n"
]
}
],
"source": [ "source": [
"beta0 = 1.0; beta1 = 2.0; beta2 = -3.0; beta3 = 0.4\n", "beta0 = 1.0; beta1 = 2.0; beta2 = -3.0; beta3 = 0.4\n",
"omega0 = 0.1; omega1 = -0.4; omega2 = 2.0; omega3 = 3.0\n", "omega0 = 0.1; omega1 = -0.4; omega2 = 2.0; omega3 = 3.0\n",
"x = 2.3; y =2.0\n", "x = 2.3; y = 2.0\n",
"l_i_func = likelihood(x,y,beta0,beta1,beta2,beta3,omega0,omega1,omega2,omega3)\n", "l_i_func = loss(x,y,beta0,beta1,beta2,beta3,omega0,omega1,omega2,omega3)\n",
"print('l_i=%3.3f'%l_i_func)" "print('l_i=%3.3f'%l_i_func)"
], ]
"metadata": {
"id": "pwvOcCxr41X_"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "u5w69NeT64yV"
},
"source": [ "source": [
"# Computing derivatives by hand\n", "# Computing derivatives by hand\n",
"\n", "\n",
"We could compute expressions for the derivatives by hand and write code to compute them directly but some have very complex expressions, even for this relatively simple original equation. For example:\n", "We could compute expressions for the derivatives by hand and write code to compute them directly but some have very complex expressions, even for this relatively simple original equation. For example:\n",
"\n", "\n",
"\\begin{eqnarray*}\n", "\\begin{align}\n",
"\\frac{\\partial \\ell_i}{\\partial \\omega_{0}} &=& -2 \\left( \\beta_3+\\omega_3\\cdot\\cos\\Bigl[\\beta_2+\\omega_2\\cdot\\exp\\bigl[\\beta_1+\\omega_1\\cdot\\sin[\\beta_0+\\omega_0\\cdot x_i]\\bigr]\\Bigr]-y_i\\right)\\nonumber \\\\\n", "\\frac{\\partial \\ell_i}{\\partial \\omega_{0}} &=& -2 \\left( \\beta_3+\\omega_3\\cdot\\cos\\Bigl[\\beta_2+\\omega_2\\cdot\\exp\\bigl[\\beta_1+\\omega_1\\cdot\\sin[\\beta_0+\\omega_0\\cdot x_i]\\bigr]\\Bigr]-y_i\\right)\\nonumber \\\\\n",
"&&\\hspace{0.5cm}\\cdot \\omega_1\\omega_2\\omega_3\\cdot x_i\\cdot\\cos[\\beta_0+\\omega_0 \\cdot x_i]\\cdot\\exp\\Bigl[\\beta_1 + \\omega_1 \\cdot \\sin[\\beta_0+\\omega_0\\cdot x_i]\\Bigr]\\nonumber\\\\\n", "&&\\hspace{0.5cm}\\cdot \\omega_1\\omega_2\\omega_3\\cdot x_i\\cdot\\cos[\\beta_0+\\omega_0 \\cdot x_i]\\cdot\\exp\\Bigl[\\beta_1 + \\omega_1 \\cdot \\sin[\\beta_0+\\omega_0\\cdot x_i]\\Bigr]\\nonumber\\\\\n",
"&& \\hspace{1cm}\\cdot \\sin\\biggl[\\beta_2+\\omega_2\\cdot \\exp\\Bigl[\\beta_1 + \\omega_1 \\cdot \\sin[\\beta_0+\\omega_0\\cdot x_i]\\Bigr]\\biggr].\n", "&& \\hspace{1cm}\\cdot \\sin\\biggl[\\beta_2+\\omega_2\\cdot \\exp\\Bigl[\\beta_1 + \\omega_1 \\cdot \\sin[\\beta_0+\\omega_0\\cdot x_i]\\Bigr]\\biggr].\n",
"\\end{eqnarray*}" "\\end{align}"
], ]
"metadata": {
"id": "u5w69NeT64yV"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7t22hALp5zkq"
},
"outputs": [],
"source": [ "source": [
"dldbeta3_func = 2 * (beta3 +omega3 * np.cos(beta2 + omega2 * np.exp(beta1+omega1 * np.sin(beta0+omega0 * x)))-y)\n", "dldbeta3_func = 2 * (beta3 +omega3 * np.cos(beta2 + omega2 * np.exp(beta1+omega1 * np.sin(beta0+omega0 * x)))-y)\n",
"dldomega0_func = -2 *(beta3 +omega3 * np.cos(beta2 + omega2 * np.exp(beta1+omega1 * np.sin(beta0+omega0 * x)))-y) * \\\n", "dldomega0_func = -2 *(beta3 +omega3 * np.cos(beta2 + omega2 * np.exp(beta1+omega1 * np.sin(beta0+omega0 * x)))-y) * \\\n",
" omega1 * omega2 * omega3 * x * np.cos(beta0 + omega0 * x) * np.exp(beta1 +omega1 * np.sin(beta0 + omega0 * x)) *\\\n", " omega1 * omega2 * omega3 * x * np.cos(beta0 + omega0 * x) * np.exp(beta1 +omega1 * np.sin(beta0 + omega0 * x)) *\\\n",
" np.sin(beta2 + omega2 * np.exp(beta1+ omega1* np.sin(beta0+omega0 * x)))" " np.sin(beta2 + omega2 * np.exp(beta1+ omega1* np.sin(beta0+omega0 * x)))"
], ]
"metadata": {
"id": "7t22hALp5zkq"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Let's make sure this is correct using finite differences:"
],
"metadata": { "metadata": {
"id": "iRh4hnu3-H3n" "id": "iRh4hnu3-H3n"
} },
"source": [
"Let's make sure this is correct using finite differences:"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "1O3XmXMx-HlZ",
"outputId": "389ed78e-9d8d-4e8b-9e6b-5f20c21407e8"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"dydomega0: Function value = 5.246, Finite difference value = 5.246\n"
]
}
],
"source": [ "source": [
"dldomega0_fd = (likelihood(x,y,beta0,beta1,beta2,beta3,omega0+0.00001,omega1,omega2,omega3)-likelihood(x,y,beta0,beta1,beta2,beta3,omega0,omega1,omega2,omega3))/0.00001\n", "dldomega0_fd = (loss(x,y,beta0,beta1,beta2,beta3,omega0+0.00001,omega1,omega2,omega3)-loss(x,y,beta0,beta1,beta2,beta3,omega0,omega1,omega2,omega3))/0.00001\n",
"\n", "\n",
"print('dydomega0: Function value = %3.3f, Finite difference value = %3.3f'%(dldomega0_func,dldomega0_fd))" "print('dydomega0: Function value = %3.3f, Finite difference value = %3.3f'%(dldomega0_func,dldomega0_fd))"
], ]
"metadata": {
"id": "1O3XmXMx-HlZ"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"The code to calculate $\\partial l_i/ \\partial \\omega_0$ is a bit of a nightmare. It's easy to make mistakes, and you can see that some parts of it are repeated (for example, the $\\sin[\\bullet]$ term), which suggests some kind of redundancy in the calculations. The goal of this practical is to compute the derivatives in a much simpler way. There will be three steps:"
],
"metadata": { "metadata": {
"id": "wS4IPjZAKWTN" "id": "wS4IPjZAKWTN"
} },
"source": [
"The code to calculate $\\partial l_i/ \\partial \\omega_0$ is a bit of a nightmare. It's easy to make mistakes, and you can see that some parts of it are repeated (for example, the $\\sin[\\bullet]$ term), which suggests some kind of redundancy in the calculations. The goal of this practical is to compute the derivatives in a much simpler way. There will be three steps:"
]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "8UWhvDeNDudz"
},
"source": [ "source": [
"**Step 1:** Write the original equations as a series of intermediate calculations.\n", "**Step 1:** Write the original equations as a series of intermediate calculations.\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
"f_{0} &=& \\beta_{0} + \\omega_{0} x_i\\nonumber\\\\\n", "f_{0} &=& \\beta_{0} + \\omega_{0} x_i\\nonumber\\\\\n",
"h_{1} &=& \\sin[f_{0}]\\nonumber\\\\\n", "h_{1} &=& \\sin[f_{0}]\\nonumber\\\\\n",
"f_{1} &=& \\beta_{1} + \\omega_{1}h_{1}\\nonumber\\\\\n", "f_{1} &=& \\beta_{1} + \\omega_{1}h_{1}\\nonumber\\\\\n",
@@ -211,16 +231,18 @@
"h_{3} &=& \\cos[f_{2}]\\nonumber\\\\\n", "h_{3} &=& \\cos[f_{2}]\\nonumber\\\\\n",
"f_{3} &=& \\beta_{3} + \\omega_{3}h_{3}\\nonumber\\\\\n", "f_{3} &=& \\beta_{3} + \\omega_{3}h_{3}\\nonumber\\\\\n",
"l_i &=& (f_3-y_i)^2\n", "l_i &=& (f_3-y_i)^2\n",
"\\end{eqnarray}\n", "\\end{align}\n",
"\n", "\n",
"and compute and store the values of all of these intermediate values. We'll need them to compute the derivatives.<br> This is called the **forward pass**." "and compute and store the values of all of these intermediate values. We'll need them to compute the derivatives.<br> This is called the **forward pass**."
], ]
"metadata": {
"id": "8UWhvDeNDudz"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZWKAq6HC90qV"
},
"outputs": [],
"source": [ "source": [
"# TODO compute all the f_k and h_k terms\n", "# TODO compute all the f_k and h_k terms\n",
"# Replace the code below\n", "# Replace the code below\n",
@@ -233,15 +255,34 @@
"h3 = 0\n", "h3 = 0\n",
"f3 = 0\n", "f3 = 0\n",
"l_i = 0\n" "l_i = 0\n"
], ]
"metadata": {
"id": "ZWKAq6HC90qV"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ibxXw7TUW4Sx",
"outputId": "4575e3eb-2b16-4e0b-c84e-9c22b443c3ce"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"f0: true value = 1.230, your value = 0.000\n",
"h1: true value = 0.942, your value = 0.000\n",
"f1: true value = 1.623, your value = 0.000\n",
"h2: true value = 5.068, your value = 0.000\n",
"f2: true value = 7.137, your value = 0.000\n",
"h3: true value = 0.657, your value = 0.000\n",
"f3: true value = 2.372, your value = 0.000\n",
"l_i original = 0.139, l_i from forward pass = 0.000\n"
]
}
],
"source": [ "source": [
"# Let's check we got that right:\n", "# Let's check we got that right:\n",
"print(\"f0: true value = %3.3f, your value = %3.3f\"%(1.230, f0))\n", "print(\"f0: true value = %3.3f, your value = %3.3f\"%(1.230, f0))\n",
@@ -251,23 +292,22 @@
"print(\"f2: true value = %3.3f, your value = %3.3f\"%(7.137, f2))\n", "print(\"f2: true value = %3.3f, your value = %3.3f\"%(7.137, f2))\n",
"print(\"h3: true value = %3.3f, your value = %3.3f\"%(0.657, h3))\n", "print(\"h3: true value = %3.3f, your value = %3.3f\"%(0.657, h3))\n",
"print(\"f3: true value = %3.3f, your value = %3.3f\"%(2.372, f3))\n", "print(\"f3: true value = %3.3f, your value = %3.3f\"%(2.372, f3))\n",
"print(\"like original = %3.3f, like from forward pass = %3.3f\"%(l_i_func, l_i))\n" "print(\"l_i original = %3.3f, l_i from forward pass = %3.3f\"%(l_i_func, l_i))\n"
], ]
"metadata": {
"id": "ibxXw7TUW4Sx"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "jay8NYWdFHuZ"
},
"source": [ "source": [
"**Step 2:** Compute the derivatives of $y$ with respect to the intermediate quantities that we just calculated, but in reverse order:\n", "**Step 2:** Compute the derivatives of $\\ell_i$ with respect to the intermediate quantities that we just calculated, but in reverse order:\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
"\\quad \\frac{\\partial \\ell_i}{\\partial f_3}, \\quad \\frac{\\partial \\ell_i}{\\partial h_3}, \\quad \\frac{\\partial \\ell_i}{\\partial f_2}, \\quad\n", "\\quad \\frac{\\partial \\ell_i}{\\partial f_3}, \\quad \\frac{\\partial \\ell_i}{\\partial h_3}, \\quad \\frac{\\partial \\ell_i}{\\partial f_2}, \\quad\n",
"\\frac{\\partial \\ell_i}{\\partial h_2}, \\quad \\frac{\\partial \\ell_i}{\\partial f_1}, \\quad \\frac{\\partial \\ell_i}{\\partial h_1}, \\quad\\mbox{and} \\quad \\frac{\\partial \\ell_i}{\\partial f_0}.\n", "\\frac{\\partial \\ell_i}{\\partial h_2}, \\quad \\frac{\\partial \\ell_i}{\\partial f_1}, \\quad \\frac{\\partial \\ell_i}{\\partial h_1}, \\quad\\text{and} \\quad \\frac{\\partial \\ell_i}{\\partial f_0}.\n",
"\\end{eqnarray}\n", "\\end{align}\n",
"\n", "\n",
"The first of these derivatives is straightforward:\n", "The first of these derivatives is straightforward:\n",
"\n", "\n",
@@ -281,11 +321,11 @@
"\\frac{\\partial \\ell_i}{\\partial h_{3}} =\\frac{\\partial f_{3}}{\\partial h_{3}} \\frac{\\partial \\ell_i}{\\partial f_{3}} .\n", "\\frac{\\partial \\ell_i}{\\partial h_{3}} =\\frac{\\partial f_{3}}{\\partial h_{3}} \\frac{\\partial \\ell_i}{\\partial f_{3}} .\n",
"\\end{equation}\n", "\\end{equation}\n",
"\n", "\n",
"The left-hand side asks how $\\ell_i$ changes when $h_{3}$ changes. The right-hand side says we can decompose this into (i) how $ell_i$ changes when $f_{3}$ changes and how $f_{3}$ changes when $h_{3}$ changes. So you get a chain of events happening: $h_{3}$ changes $f_{3}$, which changes $\\ell_i$, and the derivatives represent the effects of this chain. Notice that we computed the first of these derivatives already and is $2 (f_3-y)$. We calculated $f_{3}$ in step 1. The second term is the derivative of $\\beta_{3} + \\omega_{3}h_{3}$ with respect to $h_3$ which is simply $\\omega_3$. \n", "The left-hand side asks how $\\ell_i$ changes when $h_{3}$ changes. The right-hand side says we can decompose this into (i) how $\\ell_i$ changes when $f_{3}$ changes and how $f_{3}$ changes when $h_{3}$ changes. So you get a chain of events happening: $h_{3}$ changes $f_{3}$, which changes $\\ell_i$, and the derivatives represent the effects of this chain. Notice that we computed the first of these derivatives already and is $2 (f_3-y)$. We calculated $f_{3}$ in step 1. The second term is the derivative of $\\beta_{3} + \\omega_{3}h_{3}$ with respect to $h_3$ which is simply $\\omega_3$. \n",
"\n", "\n",
"We can continue in this way, computing the derivatives of the output with respect to these intermediate quantities:\n", "We can continue in this way, computing the derivatives of the output with respect to these intermediate quantities:\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
"\\frac{\\partial \\ell_i}{\\partial f_{2}} &=& \\frac{\\partial h_{3}}{\\partial f_{2}}\\left(\n", "\\frac{\\partial \\ell_i}{\\partial f_{2}} &=& \\frac{\\partial h_{3}}{\\partial f_{2}}\\left(\n",
"\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\n", "\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\n",
"\\nonumber \\\\\n", "\\nonumber \\\\\n",
@@ -293,16 +333,18 @@
"\\frac{\\partial \\ell_i}{\\partial f_{1}} &=& \\frac{\\partial h_{2}}{\\partial f_{1}}\\left( \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\\nonumber \\\\\n", "\\frac{\\partial \\ell_i}{\\partial f_{1}} &=& \\frac{\\partial h_{2}}{\\partial f_{1}}\\left( \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\\nonumber \\\\\n",
"\\frac{\\partial \\ell_i}{\\partial h_{1}} &=& \\frac{\\partial f_{1}}{\\partial h_{1}}\\left(\\frac{\\partial h_{2}}{\\partial f_{1}} \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\\nonumber \\\\\n", "\\frac{\\partial \\ell_i}{\\partial h_{1}} &=& \\frac{\\partial f_{1}}{\\partial h_{1}}\\left(\\frac{\\partial h_{2}}{\\partial f_{1}} \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\\nonumber \\\\\n",
"\\frac{\\partial \\ell_i}{\\partial f_{0}} &=& \\frac{\\partial h_{1}}{\\partial f_{0}}\\left(\\frac{\\partial f_{1}}{\\partial h_{1}}\\frac{\\partial h_{2}}{\\partial f_{1}} \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right).\n", "\\frac{\\partial \\ell_i}{\\partial f_{0}} &=& \\frac{\\partial h_{1}}{\\partial f_{0}}\\left(\\frac{\\partial f_{1}}{\\partial h_{1}}\\frac{\\partial h_{2}}{\\partial f_{1}} \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right).\n",
"\\end{eqnarray}\n", "\\end{align}\n",
"\n", "\n",
"In each case, we have already computed all of the terms except the last one in the previous step, and the last term is simple to evaluate. This is called the **backward pass**." "In each case, we have already computed all of the terms except the last one in the previous step, and the last term is simple to evaluate. This is called the **backward pass**."
], ]
"metadata": {
"id": "jay8NYWdFHuZ"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gCQJeI--Egdl"
},
"outputs": [],
"source": [ "source": [
"# TODO -- Compute the derivatives of the output with respect\n", "# TODO -- Compute the derivatives of the output with respect\n",
"# to the intermediate computations h_k and f_k (i.e, run the backward pass)\n", "# to the intermediate computations h_k and f_k (i.e, run the backward pass)\n",
@@ -315,15 +357,33 @@
"dldf1 = 1\n", "dldf1 = 1\n",
"dldh1 = 1\n", "dldh1 = 1\n",
"dldf0 = 1\n" "dldf0 = 1\n"
], ]
"metadata": {
"id": "gCQJeI--Egdl"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "dS1OrLtlaFr7",
"outputId": "414f0862-ae36-4a0e-b68f-4758835b0e23"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"dldf3: true value = 0.745, your value = -4.000\n",
"dldh3: true value = 2.234, your value = -12.000\n",
"dldf2: true value = -1.683, your value = 1.000\n",
"dldh2: true value = -3.366, your value = 1.000\n",
"dldf1: true value = -17.060, your value = 1.000\n",
"dldh1: true value = 6.824, your value = 1.000\n",
"dldf0: true value = 2.281, your value = 1.000\n"
]
}
],
"source": [ "source": [
"# Let's check we got that right\n", "# Let's check we got that right\n",
"print(\"dldf3: true value = %3.3f, your value = %3.3f\"%(0.745, dldf3))\n", "print(\"dldf3: true value = %3.3f, your value = %3.3f\"%(0.745, dldf3))\n",
@@ -333,38 +393,15 @@
"print(\"dldf1: true value = %3.3f, your value = %3.3f\"%(-17.060, dldf1))\n", "print(\"dldf1: true value = %3.3f, your value = %3.3f\"%(-17.060, dldf1))\n",
"print(\"dldh1: true value = %3.3f, your value = %3.3f\"%(6.824, dldh1))\n", "print(\"dldh1: true value = %3.3f, your value = %3.3f\"%(6.824, dldh1))\n",
"print(\"dldf0: true value = %3.3f, your value = %3.3f\"%(2.281, dldf0))" "print(\"dldf0: true value = %3.3f, your value = %3.3f\"%(2.281, dldf0))"
], ]
"metadata": {
"id": "dS1OrLtlaFr7"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"**Step 3:** Finally, we consider how the loss~$\\ell_{i}$ changes when we change the parameters $\\beta_{\\bullet}$ and $\\omega_{\\bullet}$. Once more, we apply the chain rule:\n",
"\n",
"\n",
"\n",
"\n",
"\\begin{eqnarray}\n",
"\\frac{\\partial \\ell_i}{\\partial \\beta_{k}} &=& \\frac{\\partial f_{k}}{\\partial \\beta_{k}}\\frac{\\partial \\ell_i}{\\partial f_{k}}\\nonumber \\\\\n",
"\\frac{\\partial \\ell_i}{\\partial \\omega_{k}} &=& \\frac{\\partial f_{k}}{\\partial \\omega_{k}}\\frac{\\partial \\ell_i}{\\partial f_{k}}.\n",
"\\end{eqnarray}\n",
"\n",
"\\noindent In each case, the second term on the right-hand side was computed in step 2. When $k>0$, we have~$f_{k}=\\beta_{k}+\\omega_k \\cdot h_{k}$, so:\n",
"\n",
"\\begin{eqnarray}\n",
"\\frac{\\partial f_{k}}{\\partial \\beta_{k}} = 1 \\quad\\quad\\mbox{and}\\quad \\quad \\frac{\\partial f_{k}}{\\partial \\omega_{k}} &=& h_{k}.\n",
"\\end{eqnarray}"
],
"metadata": {
"id": "FlzlThQPGpkU"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1I2BhqZhGMK6"
},
"outputs": [],
"source": [ "source": [
"# TODO -- Calculate the final derivatives with respect to the beta and omega terms\n", "# TODO -- Calculate the final derivatives with respect to the beta and omega terms\n",
"\n", "\n",
@@ -376,15 +413,34 @@
"dldomega1 = 1\n", "dldomega1 = 1\n",
"dldbeta0 = 1\n", "dldbeta0 = 1\n",
"dldomega0 = 1\n" "dldomega0 = 1\n"
], ]
"metadata": {
"id": "1I2BhqZhGMK6"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "38eiOn2aHgHI",
"outputId": "1a67a636-e832-471e-e771-54824363158a"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"dldbeta3: Your value = 1.000, True value = 0.745\n",
"dldomega3: Your value = 1.000, True value = 0.489\n",
"dldbeta2: Your value = 1.000, True value = -1.683\n",
"dldomega2: Your value = 1.000, True value = -8.530\n",
"dldbeta1: Your value = 1.000, True value = -17.060\n",
"dldomega1: Your value = 1.000, True value = -16.079\n",
"dldbeta0: Your value = 1.000, True value = 2.281\n",
"dldomega0: Your value = 1.000, Function value = 5.246, Finite difference value = 5.246\n"
]
}
],
"source": [ "source": [
"# Let's check we got them right\n", "# Let's check we got them right\n",
"print('dldbeta3: Your value = %3.3f, True value = %3.3f'%(dldbeta3, 0.745))\n", "print('dldbeta3: Your value = %3.3f, True value = %3.3f'%(dldbeta3, 0.745))\n",
@@ -395,21 +451,33 @@
"print('dldomega1: Your value = %3.3f, True value = %3.3f'%(dldomega1, -16.079))\n", "print('dldomega1: Your value = %3.3f, True value = %3.3f'%(dldomega1, -16.079))\n",
"print('dldbeta0: Your value = %3.3f, True value = %3.3f'%(dldbeta0, 2.281))\n", "print('dldbeta0: Your value = %3.3f, True value = %3.3f'%(dldbeta0, 2.281))\n",
"print('dldomega0: Your value = %3.3f, Function value = %3.3f, Finite difference value = %3.3f'%(dldomega0, dldomega0_func, dldomega0_fd))" "print('dldomega0: Your value = %3.3f, Function value = %3.3f, Finite difference value = %3.3f'%(dldomega0, dldomega0_func, dldomega0_fd))"
], ]
"metadata": {
"id": "38eiOn2aHgHI"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Using this method, we can compute the derivatives quite easily without needing to compute very complicated expressions. In the next practical, we'll apply this same method to a deep neural network."
],
"metadata": { "metadata": {
"id": "N2ZhrR-2fNa1" "id": "N2ZhrR-2fNa1"
} },
"source": [
"Using this method, we can compute the derivatives quite easily without needing to compute very complicated expressions. In the next practical, we'll apply this same method to a deep neural network."
]
} }
] ],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyN7JeDgslwtZcwRCOuGuPFt",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
} }

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyN2nPVR0imZntgj4Oasyvmo", "authorship_tag": "ABX9TyM2kkHLr00J4Jeypw41sTkQ",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -115,9 +115,9 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now let's run our random network. The weight matrices $\\boldsymbol\\Omega_{1\\ldots K}$ are the entries of the list \"all_weights\" and the biases $\\boldsymbol\\beta_{1\\ldots k}$ are the entries of the list \"all_biases\"\n", "Now let's run our random network. The weight matrices $\\boldsymbol\\Omega_{1\\ldots K}$ are the entries of the list \"all_weights\" and the biases $\\boldsymbol\\beta_{1\\ldots K}$ are the entries of the list \"all_biases\"\n",
"\n", "\n",
"We know that we will need the activations $\\mathbf{f}_{0\\ldots K}$ and the activations $\\mathbf{h}_{1\\ldots K}$ for the forward pass of backpropagation, so we'll store and return these as well.\n" "We know that we will need the preactivations $\\mathbf{f}_{0\\ldots K}$ and the activations $\\mathbf{h}_{1\\ldots K}$ for the forward pass of backpropagation, so we'll store and return these as well.\n"
], ],
"metadata": { "metadata": {
"id": "5irtyxnLJSGX" "id": "5irtyxnLJSGX"
@@ -132,7 +132,7 @@
" K = len(all_weights) -1\n", " K = len(all_weights) -1\n",
"\n", "\n",
" # We'll store the pre-activations at each layer in a list \"all_f\"\n", " # We'll store the pre-activations at each layer in a list \"all_f\"\n",
" # and the activations in a second list[all_h].\n", " # and the activations in a second list \"all_h\".\n",
" all_f = [None] * (K+1)\n", " all_f = [None] * (K+1)\n",
" all_h = [None] * (K+1)\n", " all_h = [None] * (K+1)\n",
"\n", "\n",
@@ -143,7 +143,7 @@
" # Run through the layers, calculating all_f[0...K-1] and all_h[1...K]\n", " # Run through the layers, calculating all_f[0...K-1] and all_h[1...K]\n",
" for layer in range(K):\n", " for layer in range(K):\n",
" # Update preactivations and activations at this layer according to eqn 7.16\n", " # Update preactivations and activations at this layer according to eqn 7.16\n",
" # Remmember to use np.matmul for matrrix multiplications\n", " # Remember to use np.matmul for matrix multiplications\n",
" # TODO -- Replace the lines below\n", " # TODO -- Replace the lines below\n",
" all_f[layer] = all_h[layer]\n", " all_f[layer] = all_h[layer]\n",
" all_h[layer+1] = all_f[layer]\n", " all_h[layer+1] = all_f[layer]\n",
@@ -166,7 +166,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Define in input\n", "# Define input\n",
"net_input = np.ones((D_i,1)) * 1.2\n", "net_input = np.ones((D_i,1)) * 1.2\n",
"# Compute network output\n", "# Compute network output\n",
"net_output, all_f, all_h = compute_network_output(net_input,all_weights, all_biases)\n", "net_output, all_f, all_h = compute_network_output(net_input,all_weights, all_biases)\n",
@@ -244,28 +244,28 @@
" all_dl_dh = [None] * (K+1)\n", " all_dl_dh = [None] * (K+1)\n",
" # Again for convenience we'll stick with the convention that all_h[0] is the net input and all_f[k] in the net output\n", " # Again for convenience we'll stick with the convention that all_h[0] is the net input and all_f[k] in the net output\n",
"\n", "\n",
" # Compute derivatives of net output with respect to loss\n", " # Compute derivatives of the loss with respect to the network output\n",
" all_dl_df[K] = np.array(d_loss_d_output(all_f[K],y))\n", " all_dl_df[K] = np.array(d_loss_d_output(all_f[K],y))\n",
"\n", "\n",
" # Now work backwards through the network\n", " # Now work backwards through the network\n",
" for layer in range(K,-1,-1):\n", " for layer in range(K,-1,-1):\n",
" # TODO Calculate the derivatives of biases at layer this from all_dl_df[layer]. (eq 7.21)\n", " # TODO Calculate the derivatives of the loss with respect to the biases at layer from all_dl_df[layer]. (eq 7.21)\n",
" # NOTE! To take a copy of matrix X, use Z=np.array(X)\n", " # NOTE! To take a copy of matrix X, use Z=np.array(X)\n",
" # REPLACE THIS LINE\n", " # REPLACE THIS LINE\n",
" all_dl_dbiases[layer] = np.zeros_like(all_biases[layer])\n", " all_dl_dbiases[layer] = np.zeros_like(all_biases[layer])\n",
"\n", "\n",
" # TODO Calculate the derivatives of weight at layer from all_dl_df[K] and all_h[K] (eq 7.22)\n", " # TODO Calculate the derivatives of the loss with respect to the weights at layer from all_dl_df[layer] and all_h[layer] (eq 7.22)\n",
" # Don't forget to use np.matmul\n", " # Don't forget to use np.matmul\n",
" # REPLACE THIS LINE\n", " # REPLACE THIS LINE\n",
" all_dl_dweights[layer] = np.zeros_like(all_weights[layer])\n", " all_dl_dweights[layer] = np.zeros_like(all_weights[layer])\n",
"\n", "\n",
" # TODO: calculate the derivatives of activations from weight and derivatives of next preactivations (eq 7.20)\n", " # TODO: calculate the derivatives of the loss with respect to the activations from weight and derivatives of next preactivations (second part of last line of eq 7.24)\n",
" # REPLACE THIS LINE\n", " # REPLACE THIS LINE\n",
" all_dl_dh[layer] = np.zeros_like(all_h[layer])\n", " all_dl_dh[layer] = np.zeros_like(all_h[layer])\n",
"\n", "\n",
"\n", "\n",
" if layer > 0:\n", " if layer > 0:\n",
" # TODO Calculate the derivatives of the pre-activation f with respect to activation h (deriv of ReLu function)\n", " # TODO Calculate the derivatives of the loss with respect to the pre-activation f (use derivative of ReLu function, first part of last line of eq. 7.24)\n",
" # REPLACE THIS LINE\n", " # REPLACE THIS LINE\n",
" all_dl_df[layer-1] = np.zeros_like(all_f[layer-1])\n", " all_dl_df[layer-1] = np.zeros_like(all_f[layer-1])\n",
"\n", "\n",
@@ -311,10 +311,16 @@
" network_output_2, *_ = compute_network_output(net_input, all_weights, all_biases)\n", " network_output_2, *_ = compute_network_output(net_input, all_weights, all_biases)\n",
" dl_dbias[row] = (least_squares_loss(network_output_1, y) - least_squares_loss(network_output_2,y))/delta_fd\n", " dl_dbias[row] = (least_squares_loss(network_output_1, y) - least_squares_loss(network_output_2,y))/delta_fd\n",
" all_dl_dbiases_fd[layer] = np.array(dl_dbias)\n", " all_dl_dbiases_fd[layer] = np.array(dl_dbias)\n",
" print(\"-----------------------------------------------\")\n",
" print(\"Bias %d, derivatives from backprop:\"%(layer))\n", " print(\"Bias %d, derivatives from backprop:\"%(layer))\n",
" print(all_dl_dbiases[layer])\n", " print(all_dl_dbiases[layer])\n",
" print(\"Bias %d, derivatives from finite differences\"%(layer))\n", " print(\"Bias %d, derivatives from finite differences\"%(layer))\n",
" print(all_dl_dbiases_fd[layer])\n", " print(all_dl_dbiases_fd[layer])\n",
" if np.allclose(all_dl_dbiases_fd[layer],all_dl_dbiases[layer],rtol=1e-05, atol=1e-08, equal_nan=False):\n",
" print(\"Success! Derivatives match.\")\n",
" else:\n",
" print(\"Failure! Derivatives different.\")\n",
"\n",
"\n", "\n",
"\n", "\n",
"# Test the derivatives of the weights matrices\n", "# Test the derivatives of the weights matrices\n",
@@ -330,10 +336,15 @@
" network_output_2, *_ = compute_network_output(net_input, all_weights, all_biases)\n", " network_output_2, *_ = compute_network_output(net_input, all_weights, all_biases)\n",
" dl_dweight[row][col] = (least_squares_loss(network_output_1, y) - least_squares_loss(network_output_2,y))/delta_fd\n", " dl_dweight[row][col] = (least_squares_loss(network_output_1, y) - least_squares_loss(network_output_2,y))/delta_fd\n",
" all_dl_dweights_fd[layer] = np.array(dl_dweight)\n", " all_dl_dweights_fd[layer] = np.array(dl_dweight)\n",
" print(\"-----------------------------------------------\")\n",
" print(\"Weight %d, derivatives from backprop:\"%(layer))\n", " print(\"Weight %d, derivatives from backprop:\"%(layer))\n",
" print(all_dl_dweights[layer])\n", " print(all_dl_dweights[layer])\n",
" print(\"Weight %d, derivatives from finite differences\"%(layer))\n", " print(\"Weight %d, derivatives from finite differences\"%(layer))\n",
" print(all_dl_dweights_fd[layer])" " print(all_dl_dweights_fd[layer])\n",
" if np.allclose(all_dl_dweights_fd[layer],all_dl_dweights[layer],rtol=1e-05, atol=1e-08, equal_nan=False):\n",
" print(\"Success! Derivatives match.\")\n",
" else:\n",
" print(\"Failure! Derivatives different.\")"
], ],
"metadata": { "metadata": {
"id": "PK-UtE3hreAK" "id": "PK-UtE3hreAK"

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyNHLXFpiSnUzAbzhtOk+bxu",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -117,10 +116,10 @@
"def compute_network_output(net_input, all_weights, all_biases):\n", "def compute_network_output(net_input, all_weights, all_biases):\n",
"\n", "\n",
" # Retrieve number of layers\n", " # Retrieve number of layers\n",
" K = len(all_weights) -1\n", " K = len(all_weights)-1\n",
"\n", "\n",
" # We'll store the pre-activations at each layer in a list \"all_f\"\n", " # We'll store the pre-activations at each layer in a list \"all_f\"\n",
" # and the activations in a second list[all_h].\n", " # and the activations in a second list \"all_h\".\n",
" all_f = [None] * (K+1)\n", " all_f = [None] * (K+1)\n",
" all_h = [None] * (K+1)\n", " all_h = [None] * (K+1)\n",
"\n", "\n",
@@ -151,7 +150,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now let's investigate how this the size of the outputs vary as we change the initialization variance:\n" "Now let's investigate how the size of the outputs vary as we change the initialization variance:\n"
], ],
"metadata": { "metadata": {
"id": "bIUrcXnOqChl" "id": "bIUrcXnOqChl"
@@ -164,7 +163,7 @@
"K = 5\n", "K = 5\n",
"# Number of neurons per layer\n", "# Number of neurons per layer\n",
"D = 8\n", "D = 8\n",
" # Input layer\n", "# Input layer\n",
"D_i = 1\n", "D_i = 1\n",
"# Output layer\n", "# Output layer\n",
"D_o = 1\n", "D_o = 1\n",
@@ -177,7 +176,7 @@
"data_in = np.random.normal(size=(1,n_data))\n", "data_in = np.random.normal(size=(1,n_data))\n",
"net_output, all_f, all_h = compute_network_output(data_in, all_weights, all_biases)\n", "net_output, all_f, all_h = compute_network_output(data_in, all_weights, all_biases)\n",
"\n", "\n",
"for layer in range(K):\n", "for layer in range(1,K+1):\n",
" print(\"Layer %d, std of hidden units = %3.3f\"%(layer, np.std(all_h[layer])))" " print(\"Layer %d, std of hidden units = %3.3f\"%(layer, np.std(all_h[layer])))"
], ],
"metadata": { "metadata": {
@@ -196,7 +195,7 @@
"# Change this to 50 layers with 80 hidden units per layer\n", "# Change this to 50 layers with 80 hidden units per layer\n",
"\n", "\n",
"# TO DO\n", "# TO DO\n",
"# Now experiment with sigma_sq_omega to try to stop the variance of the forward computation explode" "# Now experiment with sigma_sq_omega to try to stop the variance of the forward computation exploding"
], ],
"metadata": { "metadata": {
"id": "VL_SO4tar3DC" "id": "VL_SO4tar3DC"
@@ -249,6 +248,9 @@
"\n", "\n",
"# Main backward pass routine\n", "# Main backward pass routine\n",
"def backward_pass(all_weights, all_biases, all_f, all_h, y):\n", "def backward_pass(all_weights, all_biases, all_f, all_h, y):\n",
" # Retrieve number of layers\n",
" K = len(all_weights) - 1\n",
"\n",
" # We'll store the derivatives dl_dweights and dl_dbiases in lists as well\n", " # We'll store the derivatives dl_dweights and dl_dbiases in lists as well\n",
" all_dl_dweights = [None] * (K+1)\n", " all_dl_dweights = [None] * (K+1)\n",
" all_dl_dbiases = [None] * (K+1)\n", " all_dl_dbiases = [None] * (K+1)\n",
@@ -297,7 +299,7 @@
"K = 5\n", "K = 5\n",
"# Number of neurons per layer\n", "# Number of neurons per layer\n",
"D = 8\n", "D = 8\n",
" # Input layer\n", "# Input layer\n",
"D_i = 1\n", "D_i = 1\n",
"# Output layer\n", "# Output layer\n",
"D_o = 1\n", "D_o = 1\n",
@@ -335,8 +337,8 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# You can see that the values of the hidden units are increasing on average (the variance is across all hidden units at the layer\n", "# You can see that the gradients of the hidden units are increasing on average (the standard deviation is across all hidden units at the layer\n",
"# and the 1000 training examples\n", "# and the 100 training examples\n",
"\n", "\n",
"# TO DO\n", "# TO DO\n",
"# Change this to 50 layers with 80 hidden units per layer\n", "# Change this to 50 layers with 80 hidden units per layer\n",

View File

@@ -5,7 +5,7 @@
"colab": { "colab": {
"provenance": [], "provenance": [],
"gpuType": "T4", "gpuType": "T4",
"authorship_tag": "ABX9TyNLj3HOpVB87nRu7oSLuBaU", "authorship_tag": "ABX9TyOuKMUcKfOIhIL2qTX9jJCy",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -46,8 +46,8 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n", "# Run this if you're in a Colab to install MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d" "%pip install git+https://github.com/greydanus/mnist1d"
], ],
"metadata": { "metadata": {
"id": "ifVjS4cTOqKz" "id": "ifVjS4cTOqKz"
@@ -83,8 +83,10 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"!mkdir ./sample_data\n",
"\n",
"args = mnist1d.data.get_dataset_args()\n", "args = mnist1d.data.get_dataset_args()\n",
"data = mnist1d.data.get_dataset(args, path='./mnist1d_data.pkl', download=False, regenerate=False)\n", "data = mnist1d.data.get_dataset(args, path='./sample_data/mnist1d_data.pkl', download=False, regenerate=False)\n",
"\n", "\n",
"# The training and test input and outputs are in\n", "# The training and test input and outputs are in\n",
"# data['x'], data['y'], data['x_test'], and data['y_test']\n", "# data['x'], data['y'], data['x_test'], and data['y_test']\n",
@@ -136,7 +138,6 @@
"optimizer = torch.optim.SGD(model.parameters(), lr = 0.05, momentum=0.9)\n", "optimizer = torch.optim.SGD(model.parameters(), lr = 0.05, momentum=0.9)\n",
"# object that decreases learning rate by half every 10 epochs\n", "# object that decreases learning rate by half every 10 epochs\n",
"scheduler = StepLR(optimizer, step_size=10, gamma=0.5)\n", "scheduler = StepLR(optimizer, step_size=10, gamma=0.5)\n",
"# create 100 dummy data points and store in data loader class\n",
"x_train = torch.tensor(data['x'].astype('float32'))\n", "x_train = torch.tensor(data['x'].astype('float32'))\n",
"y_train = torch.tensor(data['y'].transpose().astype('long'))\n", "y_train = torch.tensor(data['y'].transpose().astype('long'))\n",
"x_test= torch.tensor(data['x_test'].astype('float32'))\n", "x_test= torch.tensor(data['x_test'].astype('float32'))\n",

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyPz1B8kFc21JvGTDwqniloA",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -77,7 +76,7 @@
" for i in range(n_data):\n", " for i in range(n_data):\n",
" x[i] = np.random.uniform(i/n_data, (i+1)/n_data, 1)\n", " x[i] = np.random.uniform(i/n_data, (i+1)/n_data, 1)\n",
"\n", "\n",
" # y value from running through functoin and adding noise\n", " # y value from running through function and adding noise\n",
" y = np.ones(n_data)\n", " y = np.ones(n_data)\n",
" for i in range(n_data):\n", " for i in range(n_data):\n",
" y[i] = true_function(x[i])\n", " y[i] = true_function(x[i])\n",
@@ -93,7 +92,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Draw the fitted function, together win uncertainty used to generate points\n", "# Draw the fitted function, together with uncertainty used to generate points\n",
"def plot_function(x_func, y_func, x_data=None,y_data=None, x_model = None, y_model =None, sigma_func = None, sigma_model=None):\n", "def plot_function(x_func, y_func, x_data=None,y_data=None, x_model = None, y_model =None, sigma_func = None, sigma_model=None):\n",
"\n", "\n",
" fig,ax = plt.subplots()\n", " fig,ax = plt.subplots()\n",
@@ -185,10 +184,8 @@
" if A[i,j] < 0:\n", " if A[i,j] < 0:\n",
" A[i,j] = 0;\n", " A[i,j] = 0;\n",
"\n", "\n",
" ATA = np.matmul(np.transpose(A), A)\n", " beta_omega = np.linalg.lstsq(A, y, rcond=None)[0]\n",
" ATAInv = np.linalg.inv(ATA)\n", "\n",
" ATAInvAT = np.matmul(ATAInv, np.transpose(A))\n",
" beta_omega = np.matmul(ATAInvAT,y)\n",
" beta = beta_omega[0]\n", " beta = beta_omega[0]\n",
" omega = beta_omega[1:]\n", " omega = beta_omega[1:]\n",
"\n", "\n",
@@ -206,7 +203,7 @@
"# Closed form solution\n", "# Closed form solution\n",
"beta, omega = fit_model_closed_form(x_data,y_data,n_hidden=3)\n", "beta, omega = fit_model_closed_form(x_data,y_data,n_hidden=3)\n",
"\n", "\n",
"# Get prediction for model across graph grange\n", "# Get prediction for model across graph range\n",
"x_model = np.linspace(0,1,100);\n", "x_model = np.linspace(0,1,100);\n",
"y_model = network(x_model, beta, omega)\n", "y_model = network(x_model, beta, omega)\n",
"\n", "\n",
@@ -229,7 +226,7 @@
" y_model_all = np.zeros((n_datasets, x_model.shape[0]))\n", " y_model_all = np.zeros((n_datasets, x_model.shape[0]))\n",
"\n", "\n",
" for c_dataset in range(n_datasets):\n", " for c_dataset in range(n_datasets):\n",
" # TODO -- Generate n_data x,y, pairs with standard divation sigma_func\n", " # TODO -- Generate n_data x,y, pairs with standard deviation sigma_func\n",
" # Replace this line\n", " # Replace this line\n",
" x_data,y_data = np.zeros([1,n_data]),np.zeros([1,n_data])\n", " x_data,y_data = np.zeros([1,n_data]),np.zeros([1,n_data])\n",
"\n", "\n",
@@ -271,7 +268,7 @@
"mean_model, std_model = get_model_mean_variance(n_data, n_datasets, n_hidden, sigma_func) ;\n", "mean_model, std_model = get_model_mean_variance(n_data, n_datasets, n_hidden, sigma_func) ;\n",
"\n", "\n",
"# Plot the results\n", "# Plot the results\n",
"plot_function(x_func, y_func, x_data,y_data, x_model, mean_model, sigma_model=std_model)" "plot_function(x_func, y_func, x_model=x_model, y_model=mean_model, sigma_model=std_model)"
], ],
"metadata": { "metadata": {
"id": "Wxk64t2SoX9c" "id": "Wxk64t2SoX9c"
@@ -305,7 +302,7 @@
"sigma_func = 0.3\n", "sigma_func = 0.3\n",
"n_hidden = 5\n", "n_hidden = 5\n",
"\n", "\n",
"# Set random seed so that get same result every time\n", "# Set random seed so that we get the same result every time\n",
"np.random.seed(1)\n", "np.random.seed(1)\n",
"\n", "\n",
"for c_hidden in range(len(hidden_variables)):\n", "for c_hidden in range(len(hidden_variables)):\n",
@@ -316,7 +313,7 @@
"\n", "\n",
" # Compute variance -- average of the model variance (average squared deviation of fitted models around mean fitted model)\n", " # Compute variance -- average of the model variance (average squared deviation of fitted models around mean fitted model)\n",
" variance[c_hidden] = 0\n", " variance[c_hidden] = 0\n",
" # Compute bias (average squared deviaton of mean fitted model around true function)\n", " # Compute bias (average squared deviation of mean fitted model around true function)\n",
" bias[c_hidden] = 0\n", " bias[c_hidden] = 0\n",
"\n", "\n",
"# Plot the results\n", "# Plot the results\n",

View File

@@ -5,7 +5,6 @@
"colab": { "colab": {
"provenance": [], "provenance": [],
"gpuType": "T4", "gpuType": "T4",
"authorship_tag": "ABX9TyN/KUpEObCKnHZ/4Onp5sHG",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -48,8 +47,8 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n", "# Run this if you're in a Colab to install MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d" "!pip install git+https://github.com/greydanus/mnist1d"
], ],
"metadata": { "metadata": {
"id": "fn9BP5N5TguP" "id": "fn9BP5N5TguP"
@@ -124,7 +123,7 @@
" D_k = n_hidden # Hidden dimensions\n", " D_k = n_hidden # Hidden dimensions\n",
" D_o = 10 # Output dimensions\n", " D_o = 10 # Output dimensions\n",
"\n", "\n",
" # Define a model with two hidden layers of size 100\n", " # Define a model with two hidden layers\n",
" # And ReLU activations between them\n", " # And ReLU activations between them\n",
" model = nn.Sequential(\n", " model = nn.Sequential(\n",
" nn.Linear(D_i, D_k),\n", " nn.Linear(D_i, D_k),\n",
@@ -157,7 +156,6 @@
" optimizer = torch.optim.SGD(model.parameters(), lr = 0.01, momentum=0.9)\n", " optimizer = torch.optim.SGD(model.parameters(), lr = 0.01, momentum=0.9)\n",
"\n", "\n",
"\n", "\n",
" # create 100 dummy data points and store in data loader class\n",
" x_train = torch.tensor(data['x'].astype('float32'))\n", " x_train = torch.tensor(data['x'].astype('float32'))\n",
" y_train = torch.tensor(data['y'].transpose().astype('long'))\n", " y_train = torch.tensor(data['y'].transpose().astype('long'))\n",
" x_test= torch.tensor(data['x_test'].astype('float32'))\n", " x_test= torch.tensor(data['x_test'].astype('float32'))\n",

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyPXPDEQiwNw+kYhWfg4kjz6", "authorship_tag": "ABX9TyPAKqlf9VxztHXKylyJwqe8",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -145,7 +145,7 @@
"source": [ "source": [
"def volume_of_hypersphere(diameter, dimensions):\n", "def volume_of_hypersphere(diameter, dimensions):\n",
" # Formula given in Problem 8.7 of the book\n", " # Formula given in Problem 8.7 of the book\n",
" # You will need sci.special.gamma()\n", " # You will need sci.gamma()\n",
" # Check out: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.gamma.html\n", " # Check out: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.gamma.html\n",
" # Also use this value for pi\n", " # Also use this value for pi\n",
" pi = np.pi\n", " pi = np.pi\n",
@@ -224,7 +224,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"You should see see that by the time we get to 300 dimensions most of the volume is in the outer 1 percent. <br><br>\n", "You should see that by the time we get to 300 dimensions most of the volume is in the outer 1 percent. <br><br>\n",
"\n", "\n",
"The conclusion of all of this is that in high dimensions you should be sceptical of your intuitions about how things work. I have tried to visualize many things in one or two dimensions in the book, but you should also be sceptical about these visualizations!" "The conclusion of all of this is that in high dimensions you should be sceptical of your intuitions about how things work. I have tried to visualize many things in one or two dimensions in the book, but you should also be sceptical about these visualizations!"
], ],

View File

@@ -120,7 +120,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Initialize the parmaeters and draw the model\n", "# Initialize the parameters and draw the model\n",
"phi = np.zeros((2,1))\n", "phi = np.zeros((2,1))\n",
"phi[0] = -5 # Horizontal offset\n", "phi[0] = -5 # Horizontal offset\n",
"phi[1] = 25 # Frequency\n", "phi[1] = 25 # Frequency\n",
@@ -178,7 +178,7 @@
"\n", "\n",
"def draw_loss_function(compute_loss, data, model, my_colormap, phi_iters = None):\n", "def draw_loss_function(compute_loss, data, model, my_colormap, phi_iters = None):\n",
"\n", "\n",
" # Make grid of intercept/slope values to plot\n", " # Make grid of offset/frequency values to plot\n",
" offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n", " offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n",
" loss_mesh = np.zeros_like(freqs_mesh)\n", " loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n", " # Compute loss for every set of parameters\n",
@@ -304,7 +304,7 @@
"for c_step in range (n_steps):\n", "for c_step in range (n_steps):\n",
" # Do gradient descent step\n", " # Do gradient descent step\n",
" phi_all[:,c_step+1:c_step+2] = gradient_descent_step(phi_all[:,c_step:c_step+1],data, model)\n", " phi_all[:,c_step+1:c_step+2] = gradient_descent_step(phi_all[:,c_step:c_step+1],data, model)\n",
" # Measure loss and draw model every 4th step\n", " # Measure loss and draw model every 8th step\n",
" if c_step % 8 == 0:\n", " if c_step % 8 == 0:\n",
" loss = compute_loss(data[0,:], data[1,:], model, phi_all[:,c_step+1:c_step+2])\n", " loss = compute_loss(data[0,:], data[1,:], model, phi_all[:,c_step+1:c_step+2])\n",
" draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n", " draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n",
@@ -341,7 +341,7 @@
"source": [ "source": [
"# Computes the regularization term\n", "# Computes the regularization term\n",
"def compute_reg_term(phi0,phi1):\n", "def compute_reg_term(phi0,phi1):\n",
" # TODO compute the regularization term (term in large brackets in the above equstion)\n", " # TODO compute the regularization term (term in large brackets in the above equation)\n",
" # Replace this line\n", " # Replace this line\n",
" reg_term = 0.0\n", " reg_term = 0.0\n",
"\n", "\n",
@@ -369,7 +369,7 @@
"# Code to draw the regularization function\n", "# Code to draw the regularization function\n",
"def draw_reg_function():\n", "def draw_reg_function():\n",
"\n", "\n",
" # Make grid of intercept/slope values to plot\n", " # Make grid of offset/frequency values to plot\n",
" offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n", " offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n",
" loss_mesh = np.zeros_like(freqs_mesh)\n", " loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n", " # Compute loss for every set of parameters\n",
@@ -399,7 +399,7 @@
"# Code to draw loss function with regularization\n", "# Code to draw loss function with regularization\n",
"def draw_loss_function_reg(data, model, lambda_, my_colormap, phi_iters = None):\n", "def draw_loss_function_reg(data, model, lambda_, my_colormap, phi_iters = None):\n",
"\n", "\n",
" # Make grid of intercept/slope values to plot\n", " # Make grid of offset/frequency values to plot\n",
" offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n", " offsets_mesh, freqs_mesh = np.meshgrid(np.arange(-10,10.0,0.1), np.arange(2.5,22.5,0.1))\n",
" loss_mesh = np.zeros_like(freqs_mesh)\n", " loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n", " # Compute loss for every set of parameters\n",
@@ -512,7 +512,7 @@
"for c_step in range (n_steps):\n", "for c_step in range (n_steps):\n",
" # Do gradient descent step\n", " # Do gradient descent step\n",
" phi_all[:,c_step+1:c_step+2] = gradient_descent_step2(phi_all[:,c_step:c_step+1],lambda_, data, model)\n", " phi_all[:,c_step+1:c_step+2] = gradient_descent_step2(phi_all[:,c_step:c_step+1],lambda_, data, model)\n",
" # Measure loss and draw model every 4th step\n", " # Measure loss and draw model every 8th step\n",
" if c_step % 8 == 0:\n", " if c_step % 8 == 0:\n",
" loss = compute_loss2(data[0,:], data[1,:], model, phi_all[:,c_step+1:c_step+2], lambda_)\n", " loss = compute_loss2(data[0,:], data[1,:], model, phi_all[:,c_step+1:c_step+2], lambda_)\n",
" draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n", " draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n",
@@ -528,7 +528,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"You should see that the gradient descent algorithm now finds the correct minimum. By applying a tiny bit of domain knowledge (the parameter phi0 tends to be near zero and the parameters phi1 tends to be near 12.5), we get a better solution. However, the cost is that this solution is slightly biased towards this prior knowledge." "You should see that the gradient descent algorithm now finds the correct minimum. By applying a tiny bit of domain knowledge (the parameter phi0 tends to be near zero and the parameter phi1 tends to be near 12.5), we get a better solution. However, the cost is that this solution is slightly biased towards this prior knowledge."
], ],
"metadata": { "metadata": {
"id": "wrszSLrqZG4k" "id": "wrszSLrqZG4k"

File diff suppressed because one or more lines are too long

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyNuR7X+PMWRddy+WQr4gr5f", "authorship_tag": "ABX9TyOAC7YLEqN5qZhJXqRj+aHB",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -52,7 +52,7 @@
"# import libraries\n", "# import libraries\n",
"import numpy as np\n", "import numpy as np\n",
"import matplotlib.pyplot as plt\n", "import matplotlib.pyplot as plt\n",
"# Define seed so get same results each time\n", "# Define seed to get same results each time\n",
"np.random.seed(1)" "np.random.seed(1)"
] ]
}, },
@@ -80,7 +80,7 @@
" for i in range(n_data):\n", " for i in range(n_data):\n",
" x[i] = np.random.uniform(i/n_data, (i+1)/n_data, 1)\n", " x[i] = np.random.uniform(i/n_data, (i+1)/n_data, 1)\n",
"\n", "\n",
" # y value from running through functoin and adding noise\n", " # y value from running through function and adding noise\n",
" y = np.ones(n_data)\n", " y = np.ones(n_data)\n",
" for i in range(n_data):\n", " for i in range(n_data):\n",
" y[i] = true_function(x[i])\n", " y[i] = true_function(x[i])\n",
@@ -96,7 +96,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Draw the fitted function, together win uncertainty used to generate points\n", "# Draw the fitted function, together with uncertainty used to generate points\n",
"def plot_function(x_func, y_func, x_data=None,y_data=None, x_model = None, y_model =None, sigma_func = None, sigma_model=None):\n", "def plot_function(x_func, y_func, x_data=None,y_data=None, x_model = None, y_model =None, sigma_func = None, sigma_model=None):\n",
"\n", "\n",
" fig,ax = plt.subplots()\n", " fig,ax = plt.subplots()\n",
@@ -137,7 +137,7 @@
"n_data = 15\n", "n_data = 15\n",
"x_data,y_data = generate_data(n_data, sigma_func)\n", "x_data,y_data = generate_data(n_data, sigma_func)\n",
"\n", "\n",
"# Plot the functinon, data and uncertainty\n", "# Plot the function, data and uncertainty\n",
"plot_function(x_func, y_func, x_data, y_data, sigma_func=sigma_func)" "plot_function(x_func, y_func, x_data, y_data, sigma_func=sigma_func)"
], ],
"metadata": { "metadata": {
@@ -184,7 +184,9 @@
" A = np.ones((n_data, n_hidden+1))\n", " A = np.ones((n_data, n_hidden+1))\n",
" for i in range(n_data):\n", " for i in range(n_data):\n",
" for j in range(1,n_hidden+1):\n", " for j in range(1,n_hidden+1):\n",
" # Compute preactivation\n",
" A[i,j] = x[i]-(j-1)/n_hidden\n", " A[i,j] = x[i]-(j-1)/n_hidden\n",
" # Apply the ReLU function\n",
" if A[i,j] < 0:\n", " if A[i,j] < 0:\n",
" A[i,j] = 0;\n", " A[i,j] = 0;\n",
"\n", "\n",
@@ -214,7 +216,7 @@
"# Closed form solution\n", "# Closed form solution\n",
"beta, omega = fit_model_closed_form(x_data,y_data,n_hidden=14)\n", "beta, omega = fit_model_closed_form(x_data,y_data,n_hidden=14)\n",
"\n", "\n",
"# Get prediction for model across graph grange\n", "# Get prediction for model across graph range\n",
"x_model = np.linspace(0,1,100);\n", "x_model = np.linspace(0,1,100);\n",
"y_model = network(x_model, beta, omega)\n", "y_model = network(x_model, beta, omega)\n",
"\n", "\n",
@@ -295,7 +297,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Plot the median of the results\n", "# Plot the mean of the results\n",
"# TODO -- find the mean prediction\n", "# TODO -- find the mean prediction\n",
"# Replace this line\n", "# Replace this line\n",
"y_model_mean = all_y_model[0,:]\n", "y_model_mean = all_y_model[0,:]\n",

View File

@@ -1,20 +1,4 @@
{ {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyMB8B4269DVmrcLoCWrhzKF",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [ "cells": [
{ {
"cell_type": "markdown", "cell_type": "markdown",
@@ -28,6 +12,9 @@
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "el8l05WQEO46"
},
"source": [ "source": [
"# **Notebook 9.4: Bayesian approach**\n", "# **Notebook 9.4: Bayesian approach**\n",
"\n", "\n",
@@ -36,10 +23,7 @@
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n" "Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n"
], ]
"metadata": {
"id": "el8l05WQEO46"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
@@ -52,26 +36,31 @@
"# import libraries\n", "# import libraries\n",
"import numpy as np\n", "import numpy as np\n",
"import matplotlib.pyplot as plt\n", "import matplotlib.pyplot as plt\n",
"# Define seed so get same results each time\n", "# Define seed to get same results each time\n",
"np.random.seed(1)" "np.random.seed(1)"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3hpqmFyQNrbt"
},
"outputs": [],
"source": [ "source": [
"# The true function that we are trying to estimate, defined on [0,1]\n", "# The true function that we are trying to estimate, defined on [0,1]\n",
"def true_function(x):\n", "def true_function(x):\n",
" y = np.exp(np.sin(x*(2*3.1413)))\n", " y = np.exp(np.sin(x*(2*3.1413)))\n",
" return y" " return y"
], ]
"metadata": {
"id": "3hpqmFyQNrbt"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "skZMM5TbNwq4"
},
"outputs": [],
"source": [ "source": [
"# Generate some data points with or without noise\n", "# Generate some data points with or without noise\n",
"def generate_data(n_data, sigma_y=0.3):\n", "def generate_data(n_data, sigma_y=0.3):\n",
@@ -80,23 +69,23 @@
" for i in range(n_data):\n", " for i in range(n_data):\n",
" x[i] = np.random.uniform(i/n_data, (i+1)/n_data, 1)\n", " x[i] = np.random.uniform(i/n_data, (i+1)/n_data, 1)\n",
"\n", "\n",
" # y value from running through functoin and adding noise\n", " # y value from running through function and adding noise\n",
" y = np.ones(n_data)\n", " y = np.ones(n_data)\n",
" for i in range(n_data):\n", " for i in range(n_data):\n",
" y[i] = true_function(x[i])\n", " y[i] = true_function(x[i])\n",
" y[i] += np.random.normal(0, sigma_y, 1)\n", " y[i] += np.random.normal(0, sigma_y, 1)\n",
" return x,y" " return x,y"
], ]
"metadata": {
"id": "skZMM5TbNwq4"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ziwD_R7lN0DY"
},
"outputs": [],
"source": [ "source": [
"# Draw the fitted function, together win uncertainty used to generate points\n", "# Draw the fitted function, together with uncertainty used to generate points\n",
"def plot_function(x_func, y_func, x_data=None,y_data=None, x_model = None, y_model =None, sigma_func = None, sigma_model=None):\n", "def plot_function(x_func, y_func, x_data=None,y_data=None, x_model = None, y_model =None, sigma_func = None, sigma_model=None):\n",
"\n", "\n",
" fig,ax = plt.subplots()\n", " fig,ax = plt.subplots()\n",
@@ -117,15 +106,15 @@
" ax.set_xlabel('Input, $x$')\n", " ax.set_xlabel('Input, $x$')\n",
" ax.set_ylabel('Output, $y$')\n", " ax.set_ylabel('Output, $y$')\n",
" plt.show()" " plt.show()"
], ]
"metadata": {
"id": "ziwD_R7lN0DY"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2CgKanwaN3NM"
},
"outputs": [],
"source": [ "source": [
"# Generate true function\n", "# Generate true function\n",
"x_func = np.linspace(0, 1.0, 100)\n", "x_func = np.linspace(0, 1.0, 100)\n",
@@ -137,17 +126,17 @@
"n_data = 15\n", "n_data = 15\n",
"x_data,y_data = generate_data(n_data, sigma_func)\n", "x_data,y_data = generate_data(n_data, sigma_func)\n",
"\n", "\n",
"# Plot the functinon, data and uncertainty\n", "# Plot the function, data and uncertainty\n",
"plot_function(x_func, y_func, x_data, y_data, sigma_func=sigma_func)" "plot_function(x_func, y_func, x_data, y_data, sigma_func=sigma_func)"
], ]
"metadata": {
"id": "2CgKanwaN3NM"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gorZ6i97N7AR"
},
"outputs": [],
"source": [ "source": [
"# Define model -- beta is a scalar and omega has size n_hidden,1\n", "# Define model -- beta is a scalar and omega has size n_hidden,1\n",
"def network(x, beta, omega):\n", "def network(x, beta, omega):\n",
@@ -165,15 +154,13 @@
" y = y + beta\n", " y = y + beta\n",
"\n", "\n",
" return y" " return y"
], ]
"metadata": {
"id": "gorZ6i97N7AR"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "i8T_QduzeBmM"
},
"source": [ "source": [
"Now let's compute a probability distribution over the model parameters using Bayes's rule:\n", "Now let's compute a probability distribution over the model parameters using Bayes's rule:\n",
"\n", "\n",
@@ -184,69 +171,71 @@
"We'll define the prior $Pr(\\boldsymbol\\phi)$ as:\n", "We'll define the prior $Pr(\\boldsymbol\\phi)$ as:\n",
"\n", "\n",
"\\begin{equation}\n", "\\begin{equation}\n",
"Pr(\\boldsymbol\\phi) = \\mbox{Norm}_{\\boldsymbol\\phi}\\bigl[\\mathbf{0},\\sigma^2_p\\mathbf{I}\\bigr]\n", "Pr(\\boldsymbol\\phi) = \\text{Norm}_{\\boldsymbol\\phi}\\bigl[\\mathbf{0},\\sigma^2_p\\mathbf{I}\\bigr]\n",
"\\end{equation}\n", "\\end{equation}\n",
"\n", "\n",
"where $\\phi=[\\omega_1,\\omega_2\\ldots \\omega_n, \\beta]^T$ and $\\sigma^2_{p}$ is the prior variance.\n", "where $\\phi=[\\omega_1,\\omega_2\\ldots \\omega_n, \\beta]^T$ and $\\sigma^2_{p}$ is the prior variance.\n",
"\n", "\n",
"The likelihood term $\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi)$ is given by:\n", "The likelihood term $\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi)$ is given by:\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
"\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi) &=& \\prod_{i=1}^{I} \\mbox{Norm}_{y_i}\\bigl[\\mbox{f}[\\mathbf{x}_{i},\\boldsymbol\\phi],\\sigma_d^2\\bigr]\\\\\n", "\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi) &=& \\prod_{i=1}^{I} \\text{Norm}_{y_i}\\bigl[\\text{f}[\\mathbf{x}_{i},\\boldsymbol\\phi],\\sigma_d^2\\bigr]\\\\\n",
"&=& \\prod_{i=1}^{I} \\mbox{Norm}_{y_i}\\bigl[\\boldsymbol\\omega\\mathbf{h}_i+\\beta,\\sigma_d^2\\bigr]\\\\\n", "&=& \\prod_{i=1}^{I} \\text{Norm}_{y_i}\\bigl[\\boldsymbol\\omega\\mathbf{h}_i+\\beta,\\sigma_d^2\\bigr]\\\\\n",
"&=& \\mbox{Norm}_{\\mathbf{y}}\\bigl[\\mathbf{H}^T\\boldsymbol\\phi,\\sigma^2\\mathbf{I}\\bigr].\n", "&=& \\text{Norm}_{\\mathbf{y}}\\bigl[\\mathbf{H}^T\\boldsymbol\\phi,\\sigma^2\\mathbf{I}\\bigr].\n",
"\\end{eqnarray}\n", "\\end{align}\n",
"\n", "\n",
"where $\\sigma^2$ is the measurement noise and $\\mathbf{h}_{i}$ is the column vector of hidden variables for the $i^{th}$ input. Here the vector $\\mathbf{y}$ and matrix $\\mathbf{H}$ are defined as:\n", "where $\\sigma^2$ is the measurement noise and $\\mathbf{h}_{i}$ is the column vector of hidden variables for the $i^{th}$ input. Here the vector $\\mathbf{y}$ and matrix $\\mathbf{H}$ are defined as:\n",
"\n", "\n",
"\\begin{equation}\n", "\\begin{equation}\n",
"\\mathbf{y} = \\begin{bmatrix}y_1\\\\y_2\\\\\\vdots\\\\y_{I}\\end{bmatrix}\\quad\\mbox{and}\\quad \\mathbf{H} = \\begin{bmatrix}\\mathbf{h}_{1}&\\mathbf{h}_{2}&\\cdots&\\mathbf{h}_{I}\\\\1&1&\\cdots &1\\end{bmatrix}.\n", "\\mathbf{y} = \\begin{bmatrix}y_1\\\\y_2\\\\\\vdots\\\\y_{I}\\end{bmatrix}\\quad\\text{and}\\quad \\mathbf{H} = \\begin{bmatrix}\\mathbf{h}_{1}&\\mathbf{h}_{2}&\\cdots&\\mathbf{h}_{I}\\\\1&1&\\cdots &1\\end{bmatrix}.\n",
"\\end{equation}\n" "\\end{equation}\n"
], ]
"metadata": {
"id": "i8T_QduzeBmM"
}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "JojV6ueRk49G"
},
"source": [ "source": [
"To make progress we use the change of variable relation (Appendix C.3.4 of the book) to rewrite the likelihood term as a normal distribution in the parameters $\\boldsymbol\\phi$:\n", "To make progress we use the change of variable relation (Appendix C.3.4 of the book) to rewrite the likelihood term as a normal distribution in the parameters $\\boldsymbol\\phi$:\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
"\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi+\\beta)\n", "\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi+\\beta)\n",
"&=& \\mbox{Norm}_{\\mathbf{y}}\\bigl[\\mathbf{H}^T\\boldsymbol\\phi,\\sigma^2\\bigr]\\\\\n", "&=& \\text{Norm}_{\\mathbf{y}}\\bigl[\\mathbf{H}^T\\boldsymbol\\phi,\\sigma^2\\bigr]\\\\\n",
"&\\propto& \\mbox{Norm}_{\\boldsymbol\\phi}\\bigl[(\\mathbf{H}\\mathbf{H}^T)^{-1}\\mathbf{H}\\mathbf{y},\\sigma^2(\\mathbf{H}\\mathbf{H}^t)^{-1}\\bigr]\n", "&\\propto& \\text{Norm}_{\\boldsymbol\\phi}\\bigl[(\\mathbf{H}\\mathbf{H}^T)^{-1}\\mathbf{H}\\mathbf{y},\\sigma^2(\\mathbf{H}\\mathbf{H}^t)^{-1}\\bigr]\n",
"\\end{eqnarray}\n" "\\end{align}\n"
], ]
"metadata": {
"id": "JojV6ueRk49G"
}
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "YX0O_Ciwp4W1"
},
"source": [ "source": [
"Finally, we can combine the likelihood and prior terms using the product of two normal distributions relation (Appendix C.3.3).\n", "Finally, we can combine the likelihood and prior terms using the product of two normal distributions relation (Appendix C.3.3).\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
" Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) &\\propto& \\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi) Pr(\\boldsymbol\\phi)\\\\\n", " Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) &\\propto& \\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi) Pr(\\boldsymbol\\phi)\\\\\n",
" &\\propto&\\mbox{Norm}_{\\boldsymbol\\phi}\\bigl[(\\mathbf{H}\\mathbf{H}^T)^{-1}\\mathbf{H}\\mathbf{y},\\sigma^2(\\mathbf{H}\\mathbf{H}^T)^{-1}\\bigr] \\mbox{Norm}_{\\boldsymbol\\phi}\\bigl[\\mathbf{0},\\sigma^2_p\\mathbf{I}\\bigr]\\\\\n", " &\\propto&\\text{Norm}_{\\boldsymbol\\phi}\\bigl[(\\mathbf{H}\\mathbf{H}^T)^{-1}\\mathbf{H}\\mathbf{y},\\sigma^2(\\mathbf{H}\\mathbf{H}^T)^{-1}\\bigr] \\text{Norm}_{\\boldsymbol\\phi}\\bigl[\\mathbf{0},\\sigma^2_p\\mathbf{I}\\bigr]\\\\\n",
" &\\propto&\\mbox{Norm}_{\\boldsymbol\\phi}\\biggl[\\frac{1}{\\sigma^2}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y},\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\biggr].\n", " &\\propto&\\text{Norm}_{\\boldsymbol\\phi}\\biggl[\\frac{1}{\\sigma^2}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y},\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\biggr].\n",
"\\end{eqnarray}\n", "\\end{align}\n",
"\n", "\n",
"In fact, since this already a normal distribution, the constant of proportionality must be one and we can write\n", "In fact, since this is already a normal distribution, the constant of proportionality must be one and we can write\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
" Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) &=& \\mbox{Norm}_{\\boldsymbol\\phi}\\biggl[\\frac{1}{\\sigma^2}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y},\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\biggr].\n", " Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) &=& \\text{Norm}_{\\boldsymbol\\phi}\\biggl[\\frac{1}{\\sigma^2}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y},\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\biggr].\n",
"\\end{eqnarray}\n", "\\end{align}\n",
"\n", "\n",
"TODO -- On a piece of paper, use the relations in Appendix C.3.3 and C.3.4 to fill in the missing steps and establish that this is the correct formula for the posterior." "TODO -- On a piece of paper, use the relations in Appendix C.3.3 and C.3.4 to fill in the missing steps and establish that this is the correct formula for the posterior."
], ]
"metadata": {
"id": "YX0O_Ciwp4W1"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nF1AcgNDwm4t"
},
"outputs": [],
"source": [ "source": [
"def compute_H(x_data, n_hidden):\n", "def compute_H(x_data, n_hidden):\n",
" psi1 = np.ones((n_hidden+1,1));\n", " psi1 = np.ones((n_hidden+1,1));\n",
@@ -280,24 +269,24 @@
"\n", "\n",
"\n", "\n",
" return phi_mean, phi_covar" " return phi_mean, phi_covar"
], ]
"metadata": {
"id": "nF1AcgNDwm4t"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now we can draw samples from this distribution"
],
"metadata": { "metadata": {
"id": "GjPnlG4q0UFK" "id": "GjPnlG4q0UFK"
} },
"source": [
"Now we can draw samples from this distribution"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "K4vYc82D0BMq"
},
"outputs": [],
"source": [ "source": [
"# Define parameters\n", "# Define parameters\n",
"n_hidden = 5\n", "n_hidden = 5\n",
@@ -313,15 +302,15 @@
"x_model = x_func\n", "x_model = x_func\n",
"y_model_mean = network(x_model, phi_mean[-1], phi_mean[0:n_hidden])\n", "y_model_mean = network(x_model, phi_mean[-1], phi_mean[0:n_hidden])\n",
"plot_function(x_func, y_func, x_data, y_data, x_model, y_model_mean)" "plot_function(x_func, y_func, x_data, y_data, x_model, y_model_mean)"
], ]
"metadata": {
"id": "K4vYc82D0BMq"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "TVIjhubkSw-R"
},
"outputs": [],
"source": [ "source": [
"# TODO Draw two samples from the normal distribution over the parameters\n", "# TODO Draw two samples from the normal distribution over the parameters\n",
"# Replace these lines\n", "# Replace these lines\n",
@@ -336,37 +325,40 @@
"# Draw the two models\n", "# Draw the two models\n",
"plot_function(x_func, y_func, x_data, y_data, x_model, y_model_sample1)\n", "plot_function(x_func, y_func, x_data, y_data, x_model, y_model_sample1)\n",
"plot_function(x_func, y_func, x_data, y_data, x_model, y_model_sample2)" "plot_function(x_func, y_func, x_data, y_data, x_model, y_model_sample2)"
], ]
"metadata": {
"id": "TVIjhubkSw-R"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "GiNg5EroUiUb"
},
"source": [ "source": [
"Now we need to perform inference for a new data points $\\mathbf{x}^*$ with corresponding hidden values $\\mathbf{h}^*$. Instead of having a single estimate of the parameters, we have a distribution over the possible parameters. So we marginalize (integrate) over this distribution to account for all possible values:\n", "Now we need to perform inference for a new data points $\\mathbf{x}^*$ with corresponding hidden values $\\mathbf{h}^*$. Instead of having a single estimate of the parameters, we have a distribution over the possible parameters. So we marginalize (integrate) over this distribution to account for all possible values:\n",
"\n", "\n",
"\\begin{eqnarray}\n", "\\begin{align}\n",
"Pr(y^*|\\mathbf{x}^*) &=& \\int Pr(y^{*}|\\mathbf{x}^*,\\boldsymbol\\phi)Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) d\\boldsymbol\\phi\\\\\n", "Pr(y^*|\\mathbf{x}^*) &= \\int Pr(y^{*}|\\mathbf{x}^*,\\boldsymbol\\phi)Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) d\\boldsymbol\\phi\\\\\n",
"&=& \\int \\mbox{Norm}_{y^*}\\bigl[\\begin{bmatrix}\\mathbf{h}^{*T}&1\\end{bmatrix}\\boldsymbol\\phi,\\sigma^2]\\cdot\\mbox{Norm}_{\\boldsymbol\\phi}\\biggl[\\frac{1}{\\sigma^2}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y},\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\biggr]d\\boldsymbol\\phi\\\\\n", "&= \\int \\text{Norm}_{y^*}\\bigl[[\\mathbf{h}^{*T},1]\\boldsymbol\\phi,\\sigma^2\\bigr]\\cdot\\text{Norm}_{\\boldsymbol\\phi}\\biggl[\\frac{1}{\\sigma^2}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y},\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\biggr]d\\boldsymbol\\phi\\\\\n",
"&=& \\mbox{Norm}_{y^*}\\biggl[\\frac{1}{\\sigma^2} \\begin{bmatrix}\\mathbf{h}^{*T}&1\\end{bmatrix}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y}, \\begin{bmatrix}\\mathbf{h}^{*T}&1\\end{bmatrix}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\n", "&= \\text{Norm}_{y^*}\\biggl[\\frac{1}{\\sigma^2} [\\mathbf{h}^{*T},1]\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y}, [\\mathbf{h}^{*T},1]\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\n",
"\\begin{bmatrix}\\mathbf{h}^*\\\\1\\end{bmatrix}\\biggr]\n", "[\\mathbf{h}^*;1]\\biggr],\n",
"\\end{eqnarray}\n", "\\end{align}\n",
"\n", "\n",
"To compute this, we reformulated the integrand using the relations from appendices\n", "where the notation $[\\mathbf{h}^{*T},1]$ is a row vector containing $\\mathbf{h}^{T}$ with a one appended to the end and $[\\mathbf{h};1 ]$ is a column vector containing $\\mathbf{h}$ with a one appended to the end.\n",
"C.3.3 and C.3.4 as the product of a normal distribution in $\\boldsymbol\\phi$ and a constant with respect\n",
"to $\\boldsymbol\\phi$. The integral of the normal distribution must be one, and so the finnal result is just the constant. This constant is itself a normal distribution in $y^*$. <br>\n",
"\n", "\n",
"If you feel so inclined you can work through the math of this yourself." "\n",
], "To compute this, we reformulated the integrand using the relations from appendices C.3.3 and C.3.4 as the product of a normal distribution in $\\boldsymbol\\phi$ and a constant with respect\n",
"metadata": { "to $\\boldsymbol\\phi$. The integral of the normal distribution must be one, and so the final result is just the constant. This constant is itself a normal distribution in $y^*$. <br>\n",
"id": "GiNg5EroUiUb" "\n",
} "If you feel so inclined you can work through the math of this yourself.\n",
"\n"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ILxT4EfW2lUm"
},
"outputs": [],
"source": [ "source": [
"# Predict mean and variance of y_star from x_star\n", "# Predict mean and variance of y_star from x_star\n",
"def inference(x_star, x_data, y_data, sigma_sq, sigma_p_sq, n_hidden):\n", "def inference(x_star, x_data, y_data, sigma_sq, sigma_p_sq, n_hidden):\n",
@@ -381,15 +373,15 @@
" y_star_var = 1\n", " y_star_var = 1\n",
"\n", "\n",
" return y_star_mean, y_star_var" " return y_star_mean, y_star_var"
], ]
"metadata": {
"id": "ILxT4EfW2lUm"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "87cjUjMaixHZ"
},
"outputs": [],
"source": [ "source": [
"x_model = x_func\n", "x_model = x_func\n",
"y_model = np.zeros_like(x_model)\n", "y_model = np.zeros_like(x_model)\n",
@@ -401,24 +393,34 @@
"\n", "\n",
"# Draw the model\n", "# Draw the model\n",
"plot_function(x_func, y_func, x_data, y_data, x_model, y_model, sigma_model=y_model_std)\n" "plot_function(x_func, y_func, x_data, y_data, x_model, y_model, sigma_model=y_model_std)\n"
], ]
"metadata": {
"id": "87cjUjMaixHZ"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "8Hcbe_16sK0F"
},
"source": [ "source": [
"TODO:\n", "TODO:\n",
"\n", "\n",
"1. Experiment running this again with different numbers of hidden units. Make a prediction for what will happen when you increase / decrease them.\n", "1. Experiment running this again with different numbers of hidden units. Make a prediction for what will happen when you increase / decrease them.\n",
"2. Experiment with what happens if you make the prior variance $\\sigma^2_p$ to a smaller value like 1. How do you explain the results?" "2. Experiment with what happens if you make the prior variance $\\sigma^2_p$ to a smaller value like 1. How do you explain the results?"
], ]
"metadata": {
"id": "8Hcbe_16sK0F"
}
} }
] ],
"metadata": {
"colab": {
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
} }

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyM3wq9CHLjekkIXIgXRxueE",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -44,8 +43,8 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n", "# Run this if you're in a Colab to install MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d" "!pip install git+https://github.com/greydanus/mnist1d"
], ],
"metadata": { "metadata": {
"id": "syvgxgRr3myY" "id": "syvgxgRr3myY"
@@ -95,7 +94,7 @@
"D_k = 200 # Hidden dimensions\n", "D_k = 200 # Hidden dimensions\n",
"D_o = 10 # Output dimensions\n", "D_o = 10 # Output dimensions\n",
"\n", "\n",
"# Define a model with two hidden layers of size 100\n", "# Define a model with two hidden layers of size 200\n",
"# And ReLU activations between them\n", "# And ReLU activations between them\n",
"model = nn.Sequential(\n", "model = nn.Sequential(\n",
"nn.Linear(D_i, D_k),\n", "nn.Linear(D_i, D_k),\n",
@@ -186,7 +185,7 @@
"ax.plot(errors_test,'b-',label='test')\n", "ax.plot(errors_test,'b-',label='test')\n",
"ax.set_ylim(0,100); ax.set_xlim(0,n_epoch)\n", "ax.set_ylim(0,100); ax.set_xlim(0,n_epoch)\n",
"ax.set_xlabel('Epoch'); ax.set_ylabel('Error')\n", "ax.set_xlabel('Epoch'); ax.set_ylabel('Error')\n",
"ax.set_title('TrainError %3.2f, Test Error %3.2f'%(errors_train[-1],errors_test[-1]))\n", "ax.set_title('Train Error %3.2f, Test Error %3.2f'%(errors_train[-1],errors_test[-1]))\n",
"ax.legend()\n", "ax.legend()\n",
"plt.show()" "plt.show()"
], ],
@@ -208,14 +207,14 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"def augment(data_in):\n", "def augment(input_vector):\n",
" # Create output vector\n", " # Create output vector\n",
" data_out = np.zeros_like(data_in)\n", " data_out = np.zeros_like(input_vector)\n",
"\n", "\n",
" # TODO: Shift the input data by a random offset\n", " # TODO: Shift the input data by a random offset\n",
" # (rotating, so points that would go off the end, are added back to the beginning)\n", " # (rotating, so points that would go off the end, are added back to the beginning)\n",
" # Replace this line:\n", " # Replace this line:\n",
" data_out = np.zeros_like(data_in) ;\n", " data_out = np.zeros_like(input_vector) ;\n",
"\n", "\n",
" # TODO: # Randomly scale the data by a factor drawn from a uniform distribution over [0.8,1.2]\n", " # TODO: # Randomly scale the data by a factor drawn from a uniform distribution over [0.8,1.2]\n",
" # Replace this line:\n", " # Replace this line:\n",
@@ -233,7 +232,7 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"n_data_orig = data['x'].shape[0]\n", "n_data_orig = data['x'].shape[0]\n",
"# We'll double the amount o fdata\n", "# We'll double the amount of data\n",
"n_data_augment = n_data_orig+4000\n", "n_data_augment = n_data_orig+4000\n",
"augmented_x = np.zeros((n_data_augment, D_i))\n", "augmented_x = np.zeros((n_data_augment, D_i))\n",
"augmented_y = np.zeros(n_data_augment)\n", "augmented_y = np.zeros(n_data_augment)\n",

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyPHUNRkJMI5LujaxIXNV60m", "authorship_tag": "ABX9TyML7rfAGE4gvmNUEiK5x3PS",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -41,6 +41,17 @@
"id": "el8l05WQEO46" "id": "el8l05WQEO46"
} }
}, },
{
"cell_type": "markdown",
"source": [
"NOTE!!\n",
"\n",
"If you have the first edition of the printed book, it mistakenly refers to a convolutional filter with no spaces between the elements (i.e. a normal filter without dilation) as having dilation zero. Actually, the convention is (weirdly) that this has dilation one. And when there is one space between the elements, this is dilation two. This notebook reflects the correct convention and so will be out of sync with the printed book. If this is confusing, check the [errata](https://github.com/udlbook/udlbook/blob/main/UDL_Errata.pdf) document."
],
"metadata": {
"id": "ggQrHkFZcUiV"
}
},
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
@@ -50,7 +61,7 @@
"metadata": { "metadata": {
"id": "nw7k5yCtOzoK" "id": "nw7k5yCtOzoK"
}, },
"execution_count": null, "execution_count": 1,
"outputs": [] "outputs": []
}, },
{ {
@@ -85,10 +96,10 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Now let's define a zero-padded convolution operation\n", "# Now let's define a zero-padded convolution operation\n",
"# with a convolution kernel size of 3, a stride of 1, and a dilation of 0\n", "# with a convolution kernel size of 3, a stride of 1, and a dilation of 1\n",
"# as in figure 10.2a-c. Write it yourself, don't call a library routine!\n", "# as in figure 10.2a-c. Write it yourself, don't call a library routine!\n",
"# Don't forget that Python arrays are indexed from zero, not from 1 as in the book figures\n", "# Don't forget that Python arrays are indexed from zero, not from 1 as in the book figures\n",
"def conv_3_1_0_zp(x_in, omega):\n", "def conv_3_1_1_zp(x_in, omega):\n",
" x_out = np.zeros_like(x_in)\n", " x_out = np.zeros_like(x_in)\n",
" # TODO -- write this function\n", " # TODO -- write this function\n",
" # replace this line\n", " # replace this line\n",
@@ -119,7 +130,7 @@
"source": [ "source": [
"\n", "\n",
"omega = [0.33,0.33,0.33]\n", "omega = [0.33,0.33,0.33]\n",
"h = conv_3_1_0_zp(x, omega)\n", "h = conv_3_1_1_zp(x, omega)\n",
"\n", "\n",
"# Check that you have computed this correctly\n", "# Check that you have computed this correctly\n",
"print(f\"Sum of output is {np.sum(h):3.3}, should be 71.1\")\n", "print(f\"Sum of output is {np.sum(h):3.3}, should be 71.1\")\n",
@@ -155,7 +166,7 @@
"source": [ "source": [
"\n", "\n",
"omega = [-0.5,0,0.5]\n", "omega = [-0.5,0,0.5]\n",
"h2 = conv_3_1_0_zp(x, omega)\n", "h2 = conv_3_1_1_zp(x, omega)\n",
"\n", "\n",
"# Draw the signal\n", "# Draw the signal\n",
"fig,ax = plt.subplots()\n", "fig,ax = plt.subplots()\n",
@@ -187,9 +198,9 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Now let's define a zero-padded convolution operation\n", "# Now let's define a zero-padded convolution operation\n",
"# with a convolution kernel size of 3, a stride of 2, and a dilation of 0\n", "# with a convolution kernel size of 3, a stride of 2, and a dilation of 1\n",
"# as in figure 10.2a-c. Write it yourself, don't call a library routine!\n", "# as in figure 10.3a-b. Write it yourself, don't call a library routine!\n",
"def conv_3_2_0_zp(x_in, omega):\n", "def conv_3_2_1_zp(x_in, omega):\n",
" x_out = np.zeros(int(np.ceil(len(x_in)/2)))\n", " x_out = np.zeros(int(np.ceil(len(x_in)/2)))\n",
" # TODO -- write this function\n", " # TODO -- write this function\n",
" # replace this line\n", " # replace this line\n",
@@ -209,7 +220,7 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"omega = [0.33,0.33,0.33]\n", "omega = [0.33,0.33,0.33]\n",
"h3 = conv_3_2_0_zp(x, omega)\n", "h3 = conv_3_2_1_zp(x, omega)\n",
"\n", "\n",
"# If you have done this right, the output length should be six and it should\n", "# If you have done this right, the output length should be six and it should\n",
"# contain every other value from the original convolution with stride 1\n", "# contain every other value from the original convolution with stride 1\n",
@@ -226,9 +237,9 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Now let's define a zero-padded convolution operation\n", "# Now let's define a zero-padded convolution operation\n",
"# with a convolution kernel size of 5, a stride of 1, and a dilation of 0\n", "# with a convolution kernel size of 5, a stride of 1, and a dilation of 1\n",
"# as in figure 10.2a-c. Write it yourself, don't call a library routine!\n", "# as in figure 10.3c. Write it yourself, don't call a library routine!\n",
"def conv_5_1_0_zp(x_in, omega):\n", "def conv_5_1_1_zp(x_in, omega):\n",
" x_out = np.zeros_like(x_in)\n", " x_out = np.zeros_like(x_in)\n",
" # TODO -- write this function\n", " # TODO -- write this function\n",
" # replace this line\n", " # replace this line\n",
@@ -249,7 +260,7 @@
"source": [ "source": [
"\n", "\n",
"omega2 = [0.2, 0.2, 0.2, 0.2, 0.2]\n", "omega2 = [0.2, 0.2, 0.2, 0.2, 0.2]\n",
"h4 = conv_5_1_0_zp(x, omega2)\n", "h4 = conv_5_1_1_zp(x, omega2)\n",
"\n", "\n",
"# Check that you have computed this correctly\n", "# Check that you have computed this correctly\n",
"print(f\"Sum of output is {np.sum(h4):3.3}, should be 69.6\")\n", "print(f\"Sum of output is {np.sum(h4):3.3}, should be 69.6\")\n",
@@ -273,10 +284,10 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Finally let's define a zero-padded convolution operation\n", "# Finally let's define a zero-padded convolution operation\n",
"# with a convolution kernel size of 3, a stride of 1, and a dilation of 1\n", "# with a convolution kernel size of 3, a stride of 1, and a dilation of 2\n",
"# as in figure 10.2a-c. Write it yourself, don't call a library routine!\n", "# as in figure 10.3d. Write it yourself, don't call a library routine!\n",
"# Don't forget that Python arrays are indexed from zero, not from 1 as in the book figures\n", "# Don't forget that Python arrays are indexed from zero, not from 1 as in the book figures\n",
"def conv_3_1_1_zp(x_in, omega):\n", "def conv_3_1_2_zp(x_in, omega):\n",
" x_out = np.zeros_like(x_in)\n", " x_out = np.zeros_like(x_in)\n",
" # TODO -- write this function\n", " # TODO -- write this function\n",
" # replace this line\n", " # replace this line\n",
@@ -295,7 +306,7 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"omega = [0.33,0.33,0.33]\n", "omega = [0.33,0.33,0.33]\n",
"h5 = conv_3_1_1_zp(x, omega)\n", "h5 = conv_3_1_2_zp(x, omega)\n",
"\n", "\n",
"# Check that you have computed this correctly\n", "# Check that you have computed this correctly\n",
"print(f\"Sum of output is {np.sum(h5):3.3}, should be 68.3\")\n", "print(f\"Sum of output is {np.sum(h5):3.3}, should be 68.3\")\n",
@@ -328,9 +339,9 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Compute matrix in figure 10.4 d\n", "# Compute matrix in figure 10.4 d\n",
"def get_conv_mat_3_1_0_zp(n_out, omega):\n", "def get_conv_mat_3_1_1_zp(n_out, omega):\n",
" omega_mat = np.zeros((n_out,n_out))\n", " omega_mat = np.zeros((n_out,n_out))\n",
" # TODO Fill in this matix\n", " # TODO Fill in this matrix\n",
" # Replace this line:\n", " # Replace this line:\n",
" omega_mat = omega_mat\n", " omega_mat = omega_mat\n",
"\n", "\n",
@@ -349,11 +360,11 @@
"source": [ "source": [
"# Run original convolution\n", "# Run original convolution\n",
"omega = np.array([-1.0,0.5,-0.2])\n", "omega = np.array([-1.0,0.5,-0.2])\n",
"h6 = conv_3_1_0_zp(x, omega)\n", "h6 = conv_3_1_1_zp(x, omega)\n",
"print(h6)\n", "print(h6)\n",
"\n", "\n",
"# If you have done this right, you should get the same answer\n", "# If you have done this right, you should get the same answer\n",
"omega_mat = get_conv_mat_3_1_0_zp(len(x), omega)\n", "omega_mat = get_conv_mat_3_1_1_zp(len(x), omega)\n",
"h7 = np.matmul(omega_mat, x)\n", "h7 = np.matmul(omega_mat, x)\n",
"print(h7)\n" "print(h7)\n"
], ],

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyOgDisWDe/zHpfTGCH8AZ3i", "authorship_tag": "ABX9TyNb46PJB/CC1pcHGfjpUUZg",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -45,8 +45,8 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n", "# Run this if you're in a Colab to install MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d" "!pip install git+https://github.com/greydanus/mnist1d"
], ],
"metadata": { "metadata": {
"id": "D5yLObtZCi9J" "id": "D5yLObtZCi9J"
@@ -128,11 +128,11 @@
"\n", "\n",
"\n", "\n",
"# TODO Create a model with the following layers\n", "# TODO Create a model with the following layers\n",
"# 1. Convolutional layer, (input=length 40 and 1 channel, kernel size 3x3, stride 2, padding=\"valid\", 15 output channels )\n", "# 1. Convolutional layer, (input=length 40 and 1 channel, kernel size 3, stride 2, padding=\"valid\", 15 output channels )\n",
"# 2. ReLU\n", "# 2. ReLU\n",
"# 3. Convolutional layer, (input=length 19 and 15 channels, kernel size 3x3, stride 2, padding=\"valid\", 15 output channels )\n", "# 3. Convolutional layer, (input=length 19 and 15 channels, kernel size 3, stride 2, padding=\"valid\", 15 output channels )\n",
"# 4. ReLU\n", "# 4. ReLU\n",
"# 5. Convolutional layer, (input=length 9 and 15 channels, kernel size 3x3, stride 2, padding=\"valid\", 15 output channels)\n", "# 5. Convolutional layer, (input=length 9 and 15 channels, kernel size 3, stride 2, padding=\"valid\", 15 output channels)\n",
"# 6. ReLU\n", "# 6. ReLU\n",
"# 7. Flatten (converts 4x15) to length 60\n", "# 7. Flatten (converts 4x15) to length 60\n",
"# 8. Linear layer (input size = 60, output size = 10)\n", "# 8. Linear layer (input size = 60, output size = 10)\n",
@@ -141,6 +141,9 @@
"# https://pytorch.org/docs/stable/generated/torch.nn.Flatten.html\n", "# https://pytorch.org/docs/stable/generated/torch.nn.Flatten.html\n",
"# https://pytorch.org/docs/1.13/generated/torch.nn.Linear.html?highlight=linear#torch.nn.Linear\n", "# https://pytorch.org/docs/1.13/generated/torch.nn.Linear.html?highlight=linear#torch.nn.Linear\n",
"\n", "\n",
"# NOTE THAT THE CONVOLUTIONAL LAYERS NEED TO TAKE THE NUMBER OF INPUT CHANNELS AS A PARAMETER\n",
"# AND NOT THE INPUT SIZE.\n",
"\n",
"# Replace the following function:\n", "# Replace the following function:\n",
"model = nn.Sequential(\n", "model = nn.Sequential(\n",
"nn.Flatten(),\n", "nn.Flatten(),\n",
@@ -185,9 +188,9 @@
"scheduler = StepLR(optimizer, step_size=20, gamma=0.5)\n", "scheduler = StepLR(optimizer, step_size=20, gamma=0.5)\n",
"# create 100 dummy data points and store in data loader class\n", "# create 100 dummy data points and store in data loader class\n",
"x_train = torch.tensor(train_data_x.transpose().astype('float32'))\n", "x_train = torch.tensor(train_data_x.transpose().astype('float32'))\n",
"y_train = torch.tensor(train_data_y.astype('long'))\n", "y_train = torch.tensor(train_data_y.astype('long')).long()\n",
"x_val= torch.tensor(val_data_x.transpose().astype('float32'))\n", "x_val= torch.tensor(val_data_x.transpose().astype('float32'))\n",
"y_val = torch.tensor(val_data_y.astype('long'))\n", "y_val = torch.tensor(val_data_y.astype('long')).long()\n",
"\n", "\n",
"# load the data into a class that creates the batches\n", "# load the data into a class that creates the batches\n",
"data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n", "data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n",

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyMmbD0cKYvIHXbKX4AupA1x", "authorship_tag": "ABX9TyNDaU2KKZDyY9Ea7vm/fNxo",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -114,6 +114,11 @@
" # Create output\n", " # Create output\n",
" out = np.zeros((batchSize, channelsOut, imageHeightOut, imageWidthOut), dtype=np.float32)\n", " out = np.zeros((batchSize, channelsOut, imageHeightOut, imageWidthOut), dtype=np.float32)\n",
"\n", "\n",
" # !!!!!! NOTE THERE IS A SUBTLETY HERE !!!!!!!!\n",
" # I have padded the image with zeros above, so it is surrouned by a \"ring\" of zeros\n",
" # That means that the image indexes are all off by one\n",
" # This actually makes your code simpler\n",
"\n",
" for c_y in range(imageHeightOut):\n", " for c_y in range(imageHeightOut):\n",
" for c_x in range(imageWidthOut):\n", " for c_x in range(imageWidthOut):\n",
" for c_kernel_y in range(kernelHeight):\n", " for c_kernel_y in range(kernelHeight):\n",

View File

@@ -301,7 +301,7 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Define 2 by 2 original patch\n", "# Define 2 by 2 original patch\n",
"orig_2_2 = np.array([[2, 4], [4,8]])\n", "orig_2_2 = np.array([[6, 8], [8,4]])\n",
"print(orig_2_2)" "print(orig_2_2)"
], ],
"metadata": { "metadata": {

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyMrF4rB2hTKq7XzLuYsURdL", "authorship_tag": "ABX9TyP3VmRg51U+7NCfSYjRRrgv",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -235,7 +235,7 @@
"# Finite difference calculation\n", "# Finite difference calculation\n",
"dydx_fd = (y2-y1)/delta\n", "dydx_fd = (y2-y1)/delta\n",
"\n", "\n",
"print(\"Gradient calculation=%f, Finite difference gradient=%f\"%(dydx,dydx_fd))\n" "print(\"Gradient calculation=%f, Finite difference gradient=%f\"%(dydx.squeeze(),dydx_fd.squeeze()))\n"
], ],
"metadata": { "metadata": {
"id": "KJpQPVd36Haq" "id": "KJpQPVd36Haq"
@@ -267,8 +267,8 @@
" fig,ax = plt.subplots()\n", " fig,ax = plt.subplots()\n",
" ax.plot(np.squeeze(x_in), np.squeeze(dydx), 'b-')\n", " ax.plot(np.squeeze(x_in), np.squeeze(dydx), 'b-')\n",
" ax.set_xlim(-2,2)\n", " ax.set_xlim(-2,2)\n",
" ax.set_xlabel('Input, $x$')\n", " ax.set_xlabel(r'Input, $x$')\n",
" ax.set_ylabel('Gradient, $dy/dx$')\n", " ax.set_ylabel(r'Gradient, $dy/dx$')\n",
" ax.set_title('No layers = %d'%(K))\n", " ax.set_title('No layers = %d'%(K))\n",
" plt.show()" " plt.show()"
], ],

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyObut1y9atNUuowPT6dMY+I", "authorship_tag": "ABX9TyNIY8tswL9e48d5D53aSmHO",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -45,8 +45,8 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n", "# Run this if you're in a Colab to install MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d" "!pip install git+https://github.com/greydanus/mnist1d"
], ],
"metadata": { "metadata": {
"id": "D5yLObtZCi9J" "id": "D5yLObtZCi9J"
@@ -144,10 +144,10 @@
" def count_params(self):\n", " def count_params(self):\n",
" return sum([p.view(-1).shape[0] for p in self.parameters()])\n", " return sum([p.view(-1).shape[0] for p in self.parameters()])\n",
"\n", "\n",
"# # TODO -- Add residual connections to this model\n", "# TODO -- Add residual connections to this model\n",
"# # The order of operations should similar to figure 11.5b\n", "# The order of operations within each block should similar to figure 11.5b\n",
"# # linear1 first, ReLU+linear2 in first residual block, ReLU+linear3 in second residual block), linear4 at end\n", "# ie., linear1 first, ReLU+linear2 in first residual block, ReLU+linear3 in second residual block), linear4 at end\n",
"# # Replace this function\n", "# Replace this function\n",
" def forward(self, x):\n", " def forward(self, x):\n",
" h1 = self.linear1(x).relu()\n", " h1 = self.linear1(x).relu()\n",
" h2 = self.linear2(h1).relu()\n", " h2 = self.linear2(h1).relu()\n",

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyOoGS+lY+EhGthebSO4smpj", "authorship_tag": "ABX9TyPx2mM2zTHmDJeKeiE1RymT",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -45,8 +45,8 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n", "# Run this if you're in a Colab to install MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d" "!pip install git+https://github.com/greydanus/mnist1d"
], ],
"metadata": { "metadata": {
"id": "D5yLObtZCi9J" "id": "D5yLObtZCi9J"
@@ -205,7 +205,8 @@
" self.linear3 = nn.Linear(hidden_size, hidden_size)\n", " self.linear3 = nn.Linear(hidden_size, hidden_size)\n",
" self.linear4 = nn.Linear(hidden_size, hidden_size)\n", " self.linear4 = nn.Linear(hidden_size, hidden_size)\n",
" self.linear5 = nn.Linear(hidden_size, hidden_size)\n", " self.linear5 = nn.Linear(hidden_size, hidden_size)\n",
" self.linear6 = nn.Linear(hidden_size, output_size)\n", " self.linear6 = nn.Linear(hidden_size, hidden_size)\n",
" self.linear7 = nn.Linear(hidden_size, output_size)\n",
"\n", "\n",
" def count_params(self):\n", " def count_params(self):\n",
" return sum([p.view(-1).shape[0] for p in self.parameters()])\n", " return sum([p.view(-1).shape[0] for p in self.parameters()])\n",
@@ -220,11 +221,11 @@
" print_variance(\"After second residual connection\",res2)\n", " print_variance(\"After second residual connection\",res2)\n",
" res3 = res2 + self.linear4(res2.relu())\n", " res3 = res2 + self.linear4(res2.relu())\n",
" print_variance(\"After third residual connection\",res3)\n", " print_variance(\"After third residual connection\",res3)\n",
" res4 = res3 + self.linear4(res3.relu())\n", " res4 = res3 + self.linear5(res3.relu())\n",
" print_variance(\"After fourth residual connection\",res4)\n", " print_variance(\"After fourth residual connection\",res4)\n",
" res5 = res4 + self.linear4(res4.relu())\n", " res5 = res4 + self.linear6(res4.relu())\n",
" print_variance(\"After fifth residual connection\",res5)\n", " print_variance(\"After fifth residual connection\",res5)\n",
" return self.linear6(res5)" " return self.linear7(res5)"
], ],
"metadata": { "metadata": {
"id": "FslroPJJffrh" "id": "FslroPJJffrh"
@@ -272,7 +273,8 @@
" self.linear3 = nn.Linear(hidden_size, hidden_size)\n", " self.linear3 = nn.Linear(hidden_size, hidden_size)\n",
" self.linear4 = nn.Linear(hidden_size, hidden_size)\n", " self.linear4 = nn.Linear(hidden_size, hidden_size)\n",
" self.linear5 = nn.Linear(hidden_size, hidden_size)\n", " self.linear5 = nn.Linear(hidden_size, hidden_size)\n",
" self.linear6 = nn.Linear(hidden_size, output_size)\n", " self.linear6 = nn.Linear(hidden_size, hidden_size)\n",
" self.linear7 = nn.Linear(hidden_size, output_size)\n",
"\n", "\n",
" def count_params(self):\n", " def count_params(self):\n",
" return sum([p.view(-1).shape[0] for p in self.parameters()])\n", " return sum([p.view(-1).shape[0] for p in self.parameters()])\n",
@@ -287,11 +289,11 @@
" print_variance(\"After second residual connection\",res2)\n", " print_variance(\"After second residual connection\",res2)\n",
" res3 = res2 + self.linear4(res2.relu())\n", " res3 = res2 + self.linear4(res2.relu())\n",
" print_variance(\"After third residual connection\",res3)\n", " print_variance(\"After third residual connection\",res3)\n",
" res4 = res3 + self.linear4(res3.relu())\n", " res4 = res3 + self.linear5(res3.relu())\n",
" print_variance(\"After fourth residual connection\",res4)\n", " print_variance(\"After fourth residual connection\",res4)\n",
" res5 = res4 + self.linear4(res4.relu())\n", " res5 = res4 + self.linear6(res4.relu())\n",
" print_variance(\"After fifth residual connection\",res5)\n", " print_variance(\"After fifth residual connection\",res5)\n",
" return self.linear6(res5)" " return self.linear7(res5)"
], ],
"metadata": { "metadata": {
"id": "5JvMmaRITKGd" "id": "5JvMmaRITKGd"

View File

@@ -31,7 +31,7 @@
"source": [ "source": [
"# **Notebook 12.1: Self Attention**\n", "# **Notebook 12.1: Self Attention**\n",
"\n", "\n",
"This notebook builds a self-attnetion mechanism from scratch, as discussed in section 12.2 of the book.\n", "This notebook builds a self-attention mechanism from scratch, as discussed in section 12.2 of the book.\n",
"\n", "\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
@@ -153,7 +153,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"We'll need a softmax function (equation 12.5) -- here, it will take a list of arbirtrary numbers and return a list where the elements are non-negative and sum to one\n" "We'll need a softmax function (equation 12.5) -- here, it will take a list of arbitrary numbers and return a list where the elements are non-negative and sum to one\n"
], ],
"metadata": { "metadata": {
"id": "Se7DK6PGPSUk" "id": "Se7DK6PGPSUk"
@@ -364,7 +364,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"TODO -- Investigate whether the self-attention mechanism is covariant with respect to permulation.\n", "TODO -- Investigate whether the self-attention mechanism is covariant with respect to permutation.\n",
"If it is, when we permute the columns of the input matrix $\\mathbf{X}$, the columns of the output matrix $\\mathbf{X}'$ will also be permuted.\n" "If it is, when we permute the columns of the input matrix $\\mathbf{X}$, the columns of the output matrix $\\mathbf{X}'$ will also be permuted.\n"
], ],
"metadata": { "metadata": {

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyMSk8qTqDYqFnRJVZKlsue0",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -29,9 +28,9 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"# **Notebook 12.1: Multhead Self-Attention**\n", "# **Notebook 12.1: Multihead Self-Attention**\n",
"\n", "\n",
"This notebook builds a multihead self-attentionm mechanism as in figure 12.6\n", "This notebook builds a multihead self-attention mechanism as in figure 12.6\n",
"\n", "\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
@@ -147,9 +146,7 @@
" exp_values = np.exp(data_in) ;\n", " exp_values = np.exp(data_in) ;\n",
" # Sum over columns\n", " # Sum over columns\n",
" denom = np.sum(exp_values, axis = 0);\n", " denom = np.sum(exp_values, axis = 0);\n",
" # Replicate denominator to N rows\n", " # Compute softmax (numpy broadcasts denominator to all rows automatically)\n",
" denom = np.matmul(np.ones((data_in.shape[0],1)), denom[np.newaxis,:])\n",
" # Compute softmax\n",
" softmax = exp_values / denom\n", " softmax = exp_values / denom\n",
" # return the answer\n", " # return the answer\n",
" return softmax" " return softmax"

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyNPrHfkLWjy3NfDHRhGG3IE", "authorship_tag": "ABX9TyPsZjfqVeHYh95Hzt+hCIO7",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -409,7 +409,7 @@
" print(\"Choosing from %d tokens\"%(thresh_index))\n", " print(\"Choosing from %d tokens\"%(thresh_index))\n",
" # TODO: Find the probability value to threshold\n", " # TODO: Find the probability value to threshold\n",
" # Replace this line:\n", " # Replace this line:\n",
" thresh_prob = sorted_probs_decreasing[thresh_index]\n", " thresh_prob = 0.5\n",
"\n", "\n",
"\n", "\n",
"\n", "\n",

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyOMSGUFWT+YN0fwYHpMmHJM",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -57,7 +56,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Let's build a model that maps a chemical structure to a binary decision. This model might be used to predict whether a chemical is liquid at room temparature or not. We'll start by drawing the chemical structure." "Let's build a model that maps a chemical structure to a binary decision. This model might be used to predict whether a chemical is liquid at room temperature or not. We'll start by drawing the chemical structure."
], ],
"metadata": { "metadata": {
"id": "UNleESc7k5uB" "id": "UNleESc7k5uB"
@@ -99,7 +98,7 @@
"\n", "\n",
"# TODO -- Define node matrix\n", "# TODO -- Define node matrix\n",
"# There will be 9 nodes and 118 possible chemical elements\n", "# There will be 9 nodes and 118 possible chemical elements\n",
"# so we'll define a 9x118 matrix. Each column represents one\n", "# so we'll define a 118x9 matrix. Each column represents one\n",
"# node and is a one-hot vector (i.e. all zeros, except a single one at the\n", "# node and is a one-hot vector (i.e. all zeros, except a single one at the\n",
"# chemical number of the element).\n", "# chemical number of the element).\n",
"# Chemical numbers: Hydrogen-->1, Carbon-->6, Oxygen-->8\n", "# Chemical numbers: Hydrogen-->1, Carbon-->6, Oxygen-->8\n",
@@ -191,7 +190,7 @@
"source": [ "source": [
"# Let's test this network\n", "# Let's test this network\n",
"f = graph_neural_network(A,X, Omega0, beta0, Omega1, beta1, Omega2, beta2, omega3, beta3)\n", "f = graph_neural_network(A,X, Omega0, beta0, Omega1, beta1, Omega2, beta2, omega3, beta3)\n",
"print(\"Your value is %3f: \"%(f[0,0]), \"True value of f: 0.498010\")" "print(\"Your value is %3f: \"%(f[0,0]), \"True value of f: 0.310843\")"
], ],
"metadata": { "metadata": {
"id": "X7gYgOu6uIAt" "id": "X7gYgOu6uIAt"
@@ -221,7 +220,7 @@
"X_permuted = np.copy(X)\n", "X_permuted = np.copy(X)\n",
"\n", "\n",
"f = graph_neural_network(A_permuted,X_permuted, Omega0, beta0, Omega1, beta1, Omega2, beta2, omega3, beta3)\n", "f = graph_neural_network(A_permuted,X_permuted, Omega0, beta0, Omega1, beta1, Omega2, beta2, omega3, beta3)\n",
"print(\"Your value is %3f: \"%(f[0,0]), \"True value of f: 0.498010\")" "print(\"Your value is %3f: \"%(f[0,0]), \"True value of f: 0.310843\")"
], ],
"metadata": { "metadata": {
"id": "F0zc3U_UuR5K" "id": "F0zc3U_UuR5K"

View File

@@ -268,7 +268,7 @@
"source": [ "source": [
"# TODO Find the nodes in hidden layer 1 that connect to the nodes in hidden layer 2\n", "# TODO Find the nodes in hidden layer 1 that connect to the nodes in hidden layer 2\n",
"# using the adjacency matrix. Then sample n_sample of these nodes randomly without\n", "# using the adjacency matrix. Then sample n_sample of these nodes randomly without\n",
"# replacement. Make sure not to sample nodes that were already included in hidden layer 2 our the ouput layer.\n", "# replacement. Make sure not to sample nodes that were already included in hidden layer 2 our the output layer.\n",
"# The nodes at hidden layer 1 are the union of these nodes and the nodes in hidden layer 2\n", "# The nodes at hidden layer 1 are the union of these nodes and the nodes in hidden layer 2\n",
"\n", "\n",
"# Replace this line:\n", "# Replace this line:\n",

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyOdSkjfQnSZXnffGsZVM7r5", "authorship_tag": "ABX9TyO/wJ4N9w01f04mmrs/ZSHY",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -185,10 +185,10 @@
"np.set_printoptions(precision=3)\n", "np.set_printoptions(precision=3)\n",
"output = graph_attention(X, omega, beta, phi, A);\n", "output = graph_attention(X, omega, beta, phi, A);\n",
"print(\"Correct answer is:\")\n", "print(\"Correct answer is:\")\n",
"print(\"[[1.796 1.346 0.569 1.703 1.298 1.224 1.24 1.234]\")\n", "print(\"[[0. 0.028 0.37 0. 0.97 0. 0. 0.698]\")\n",
"print(\" [0.768 0.672 0. 0.529 3.841 4.749 5.376 4.761]\")\n", "print(\" [0. 0. 0. 0. 1.184 0. 2.654 0. ]\")\n",
"print(\" [0.305 0.129 0. 0.341 0.785 1.014 1.113 1.024]\")\n", "print(\" [1.13 0.564 0. 1.298 0.268 0. 0. 0.779]\")\n",
"print(\" [0. 0. 0. 0. 0.35 0.864 1.098 0.871]]]\")\n", "print(\" [0.825 0. 0. 1.175 0. 0. 0. 0. ]]]\")\n",
"\n", "\n",
"\n", "\n",
"print(\"Your answer is:\")\n", "print(\"Your answer is:\")\n",

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyM0StKV3FIZ3MZqfflqC0Rv",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -31,7 +30,7 @@
"source": [ "source": [
"# **Notebook 15.1: GAN Toy example**\n", "# **Notebook 15.1: GAN Toy example**\n",
"\n", "\n",
"This notebook investigates the GAN toy example as illustred in figure 15.1 in the book.\n", "This notebook investigates the GAN toy example as illustrated in figure 15.1 in the book.\n",
"\n", "\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
@@ -101,7 +100,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now, we define our disriminator. This is a simple logistic regression model (1D linear model passed through sigmoid) that returns the probability that the data is real" "Now, we define our discriminator. This is a simple logistic regression model (1D linear model passed through sigmoid) that returns the probability that the data is real"
], ],
"metadata": { "metadata": {
"id": "Xrzd8aehYAYR" "id": "Xrzd8aehYAYR"
@@ -339,7 +338,7 @@
" print(\"Initial generator loss = \", compute_generator_loss(z, theta, phi0, phi1))\n", " print(\"Initial generator loss = \", compute_generator_loss(z, theta, phi0, phi1))\n",
" for iter in range(n_iter):\n", " for iter in range(n_iter):\n",
" # Get gradient\n", " # Get gradient\n",
" dl_dtheta = compute_generator_gradient(x_real, x_syn, phi0, phi1)\n", " dl_dtheta = compute_generator_gradient(z, theta, phi0, phi1)\n",
" # Take a gradient step (uphill, since we are trying to make synthesized data less well classified by discriminator)\n", " # Take a gradient step (uphill, since we are trying to make synthesized data less well classified by discriminator)\n",
" theta = theta + alpha * dl_dtheta ;\n", " theta = theta + alpha * dl_dtheta ;\n",
"\n", "\n",
@@ -387,7 +386,7 @@
"print(\"Final parameters (phi0,phi1)\", phi0, phi1)\n", "print(\"Final parameters (phi0,phi1)\", phi0, phi1)\n",
"for c_gan_iter in range(5):\n", "for c_gan_iter in range(5):\n",
"\n", "\n",
" # Run generator to product syntehsized data\n", " # Run generator to product synthesized data\n",
" x_syn = generator(z, theta)\n", " x_syn = generator(z, theta)\n",
" draw_data_model(x_real, x_syn, phi0, phi1)\n", " draw_data_model(x_real, x_syn, phi0, phi1)\n",
"\n", "\n",

View File

@@ -4,7 +4,6 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyNyLnpoXgKN+RGCuTUszCAZ",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -29,9 +28,9 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"# **Notebook 15.2: Wassserstein Distance**\n", "# **Notebook 15.2: Wasserstein Distance**\n",
"\n", "\n",
"This notebook investigates the GAN toy example as illustred in figure 15.1 in the book.\n", "This notebook investigates the GAN toy example as illustrated in figure 15.1 in the book.\n",
"\n", "\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
@@ -129,7 +128,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"draw_2D_heatmap(dist_mat,'Distance $|i-j|$', my_colormap)" "draw_2D_heatmap(dist_mat,r'Distance $|i-j|$', my_colormap)"
], ],
"metadata": { "metadata": {
"id": "G0HFPBXyHT6V" "id": "G0HFPBXyHT6V"
@@ -153,9 +152,9 @@
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# TODO: Now construct the matrix A that has the initial distribution constraints\n", "# TODO: Now construct the matrix A that has the initial distribution constraints\n",
"# so that Ap=b where p is the transport plan P vectorized rows first so p = np.flatten(P)\n", "# so that A @ TPFlat=b where TPFlat is the transport plan TP vectorized rows first so TPFlat = np.flatten(TP)\n",
"# Replace this line:\n", "# Replace this line:\n",
"A = np.zeros((20,100))\n" "A = np.zeros((20,100))"
], ],
"metadata": { "metadata": {
"id": "7KrybL96IuNW" "id": "7KrybL96IuNW"
@@ -197,8 +196,8 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"P = np.array(opt.x).reshape(10,10)\n", "TP = np.array(opt.x).reshape(10,10)\n",
"draw_2D_heatmap(P,'Transport plan $\\mathbf{P}$', my_colormap)" "draw_2D_heatmap(TP,r'Transport plan $\\mathbf{P}$', my_colormap)"
], ],
"metadata": { "metadata": {
"id": "nZGfkrbRV_D0" "id": "nZGfkrbRV_D0"
@@ -218,8 +217,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"was = np.sum(P * dist_mat)\n", "was = np.sum(TP * dist_mat)\n",
"print(\"Wasserstein distance = \", was)" "print(\"Your Wasserstein distance = \", was)\n",
"print(\"Correct answer = 0.15148578811369506\")"
], ],
"metadata": { "metadata": {
"id": "yiQ_8j-Raq3c" "id": "yiQ_8j-Raq3c"

View File

@@ -65,7 +65,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"# First let's make the 1D piecewise linear mapping as illustated in figure 16.5\n", "# First let's make the 1D piecewise linear mapping as illustrated in figure 16.5\n",
"def g(h, phi):\n", "def g(h, phi):\n",
" # TODO -- write this function (equation 16.12)\n", " # TODO -- write this function (equation 16.12)\n",
" # Note: If you have the first printing of the book, there is a mistake in equation 16.12\n", " # Note: If you have the first printing of the book, there is a mistake in equation 16.12\n",
@@ -156,7 +156,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Now let's define an autogressive flow. Let's switch to looking at figure 16.7.# We'll assume that our piecewise function will use five parameters phi1,phi2,phi3,phi4,phi5" "Now let's define an autoregressive flow. Let's switch to looking at figure 16.7.# We'll assume that our piecewise function will use five parameters phi1,phi2,phi3,phi4,phi5"
], ],
"metadata": { "metadata": {
"id": "t8XPxipfd7hz" "id": "t8XPxipfd7hz"
@@ -175,7 +175,7 @@
" x = x/ np.sum(x) ;\n", " x = x/ np.sum(x) ;\n",
" return x\n", " return x\n",
"\n", "\n",
"# Return value of phi that doesn't depend on any of the iputs\n", "# Return value of phi that doesn't depend on any of the inputs\n",
"def get_phi():\n", "def get_phi():\n",
" return np.array([0.2, 0.1, 0.4, 0.05, 0.25])\n", " return np.array([0.2, 0.1, 0.4, 0.05, 0.25])\n",
"\n", "\n",

View File

@@ -1,33 +1,22 @@
{ {
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNeCWINUqqUGKMcxsqPFTAh",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [ "cells": [
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "view-in-github", "colab_type": "text",
"colab_type": "text" "id": "view-in-github"
}, },
"source": [ "source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap16/16_3_Contraction_Mappings.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" "<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap16/16_3_Contraction_Mappings.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [ "source": [
"# **Notebook 16.3: Contraction mappings**\n", "# **Notebook 16.3: Contraction mappings**\n",
"\n", "\n",
@@ -36,38 +25,40 @@
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions." "Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
], ]
"metadata": {
"id": "t9vk9Elugvmi"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"import numpy as np\n",
"import matplotlib.pyplot as plt"
],
"metadata": { "metadata": {
"id": "OLComQyvCIJ7" "id": "OLComQyvCIJ7"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4Pfz2KSghdVI"
},
"outputs": [],
"source": [ "source": [
"# Define a function that is a contraction mapping\n", "# Define a function that is a contraction mapping\n",
"def f(z):\n", "def f(z):\n",
" return 0.3 + 0.5 *z + 0.02 * np.sin(z*15)" " return 0.3 + 0.5 *z + 0.02 * np.sin(z*15)"
], ]
"metadata": {
"id": "4Pfz2KSghdVI"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "zEwCbIx0hpAI"
},
"outputs": [],
"source": [ "source": [
"def draw_function(f, fixed_point=None):\n", "def draw_function(f, fixed_point=None):\n",
" z = np.arange(0,1,0.01)\n", " z = np.arange(0,1,0.01)\n",
@@ -84,35 +75,36 @@
" ax.set_xlabel('Input, $z$')\n", " ax.set_xlabel('Input, $z$')\n",
" ax.set_ylabel('Output, f$[z]$')\n", " ax.set_ylabel('Output, f$[z]$')\n",
" plt.show()" " plt.show()"
], ]
"metadata": {
"id": "zEwCbIx0hpAI"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"draw_function(f)"
],
"metadata": { "metadata": {
"id": "k4e5Yu0fl8bz" "id": "k4e5Yu0fl8bz"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"draw_function(f)"
]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now let's find where $\\mbox{f}[z]=z$ using fixed point iteration"
],
"metadata": { "metadata": {
"id": "DfgKrpCAjnol" "id": "DfgKrpCAjnol"
} },
"source": [
"Now let's find where $\\text{f}[z]=z$ using fixed point iteration"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bAOBvZT-j3lv"
},
"outputs": [],
"source": [ "source": [
"# Takes a function f and a starting point z\n", "# Takes a function f and a starting point z\n",
"def fixed_point_iteration(f, z0):\n", "def fixed_point_iteration(f, z0):\n",
@@ -125,115 +117,117 @@
"\n", "\n",
"\n", "\n",
" return z_out" " return z_out"
], ]
"metadata": {
"id": "bAOBvZT-j3lv"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Now let's test that and plot the solution"
],
"metadata": { "metadata": {
"id": "CAS0lgIomAa0" "id": "CAS0lgIomAa0"
} },
"source": [
"Now let's test that and plot the solution"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EYQZJdNPk8Lg"
},
"outputs": [],
"source": [ "source": [
"# Now let's test that\n", "# Now let's test that\n",
"z = fixed_point_iteration(f, 0.2)\n", "z = fixed_point_iteration(f, 0.2)\n",
"draw_function(f, z)" "draw_function(f, z)"
], ]
"metadata": {
"id": "EYQZJdNPk8Lg"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4DipPiqVlnwJ"
},
"outputs": [],
"source": [ "source": [
"# Let's define another function\n", "# Let's define another function\n",
"def f2(z):\n", "def f2(z):\n",
" return 0.7 + -0.6 *z + 0.03 * np.sin(z*15)\n", " return 0.7 + -0.6 *z + 0.03 * np.sin(z*15)\n",
"draw_function(f2)" "draw_function(f2)"
], ]
"metadata": {
"id": "4DipPiqVlnwJ"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tYOdbWcomdEE"
},
"outputs": [],
"source": [ "source": [
"# Now let's test that\n", "# Now let's test that\n",
"# TODO Before running this code, predict what you think will happen\n", "# TODO Before running this code, predict what you think will happen\n",
"z = fixed_point_iteration(f2, 0.9)\n", "z = fixed_point_iteration(f2, 0.9)\n",
"draw_function(f2, z)" "draw_function(f2, z)"
], ]
"metadata": {
"id": "tYOdbWcomdEE"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Mni37RUpmrIu"
},
"outputs": [],
"source": [ "source": [
"# Let's define another function\n", "# Let's define another function\n",
"# Define a function that is a contraction mapping\n", "# Define a function that is a contraction mapping\n",
"def f3(z):\n", "def f3(z):\n",
" return -0.2 + 1.5 *z + 0.1 * np.sin(z*15)\n", " return -0.2 + 1.5 *z + 0.1 * np.sin(z*15)\n",
"draw_function(f3)" "draw_function(f3)"
], ]
"metadata": {
"id": "Mni37RUpmrIu"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "agt5mfJrnM1O"
},
"outputs": [],
"source": [ "source": [
"# Now let's test that\n", "# Now let's test that\n",
"# TODO Before running this code, predict what you think will happen\n", "# TODO Before running this code, predict what you think will happen\n",
"z = fixed_point_iteration(f3, 0.7)\n", "z = fixed_point_iteration(f3, 0.7)\n",
"draw_function(f3, z)" "draw_function(f3, z)"
], ]
"metadata": {
"id": "agt5mfJrnM1O"
},
"execution_count": null,
"outputs": []
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"source": [
"Finally, let's invert a problem of the form $y = z+ f[z]$ for a given value of $y$. What is the $z$ that maps to it?"
],
"metadata": { "metadata": {
"id": "n6GI46-ZoQz6" "id": "n6GI46-ZoQz6"
} },
"source": [
"Finally, let's invert a problem of the form $y = z+ f[z]$ for a given value of $y$. What is the $z$ that maps to it?"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"def f4(z):\n",
" return -0.3 + 0.5 *z + 0.02 * np.sin(z*15)"
],
"metadata": { "metadata": {
"id": "dy6r3jr9rjPf" "id": "dy6r3jr9rjPf"
}, },
"execution_count": null, "outputs": [],
"outputs": [] "source": [
"def f4(z):\n",
" return -0.3 + 0.5 *z + 0.02 * np.sin(z*15)"
]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "GMX64Iz0nl-B"
},
"outputs": [],
"source": [ "source": [
"def fixed_point_iteration_z_plus_f(f, y, z0):\n", "def fixed_point_iteration_z_plus_f(f, y, z0):\n",
" # TODO -- write this function\n", " # TODO -- write this function\n",
@@ -241,15 +235,15 @@
" z_out = 1\n", " z_out = 1\n",
"\n", "\n",
" return z_out" " return z_out"
], ]
"metadata": {
"id": "GMX64Iz0nl-B"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "uXxKHad5qT8Y"
},
"outputs": [],
"source": [ "source": [
"def draw_function2(f, y, fixed_point=None):\n", "def draw_function2(f, y, fixed_point=None):\n",
" z = np.arange(0,1,0.01)\n", " z = np.arange(0,1,0.01)\n",
@@ -267,15 +261,15 @@
" ax.set_xlabel('Input, $z$')\n", " ax.set_xlabel('Input, $z$')\n",
" ax.set_ylabel('Output, z+f$[z]$')\n", " ax.set_ylabel('Output, z+f$[z]$')\n",
" plt.show()" " plt.show()"
], ]
"metadata": {
"id": "uXxKHad5qT8Y"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mNEBXC3Aqd_1"
},
"outputs": [],
"source": [ "source": [
"# Test this out and draw\n", "# Test this out and draw\n",
"y = 0.8\n", "y = 0.8\n",
@@ -283,12 +277,23 @@
"draw_function2(f4,y,z)\n", "draw_function2(f4,y,z)\n",
"# If you have done this correctly, the red dot should be\n", "# If you have done this correctly, the red dot should be\n",
"# where the cyan curve has a y value of 0.8" "# where the cyan curve has a y value of 0.8"
], ]
"metadata": {
"id": "mNEBXC3Aqd_1"
},
"execution_count": null,
"outputs": []
} }
] ],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyNeCWINUqqUGKMcxsqPFTAh",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
} }

View File

@@ -0,0 +1,405 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap17/17_1_Latent_Variable_Models.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 17.1: Latent variable models**\n",
"\n",
"This notebook investigates a non-linear latent variable model similar to that in figures 17.2 and 17.3 of the book.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import scipy\n",
"from matplotlib.colors import ListedColormap\n",
"from matplotlib import cm"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "IyVn-Gi-p7wf"
},
"source": [
"We'll assume that our base distribution over the latent variables is a 1D standard normal so that\n",
"\n",
"\\begin{equation}\n",
"Pr(z) = \\text{Norm}_{z}[0,1]\n",
"\\end{equation}\n",
"\n",
"As in figure 17.2, we'll assume that the output is two dimensional, we we need to define a function that maps from the 1D latent variable to two dimensions. Usually, we would use a neural network, but in this case, we'll just define an arbitrary relationship.\n",
"\n",
"\\begin{align}\n",
"x_{1} &=& 0.5\\cdot\\exp\\Bigl[\\sin\\bigl[2+ 3.675 z \\bigr]\\Bigr]\\\\\n",
"x_{2} &=& \\sin\\bigl[2+ 2.85 z \\bigr]\n",
"\\end{align}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZIfQwhd-AV6L"
},
"outputs": [],
"source": [
"# The function that maps z to x1 and x2\n",
"def f(z):\n",
" x_1 = np.exp(np.sin(2+z*3.675)) * 0.5\n",
" x_2 = np.cos(2+z*2.85)\n",
" return x_1, x_2"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "KB9FU34onW1j"
},
"source": [
"Let's plot the 3D relation between the two observed variables $x_{1}$ and $x_{2}$ and the latent variables $z$ as in figure 17.2 of the book. We'll use the opacity to represent the prior probability $Pr(z)$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "lW08xqAgnP4q"
},
"outputs": [],
"source": [
"def draw_3d_projection(z,pr_z, x1,x2):\n",
" alpha = pr_z / np.max(pr_z)\n",
" ax = plt.axes(projection='3d')\n",
" fig = plt.gcf()\n",
" fig.set_size_inches(18.5, 10.5)\n",
" for i in range(len(z)-1):\n",
" ax.plot([z[i],z[i+1]],[x1[i],x1[i+1]],[x2[i],x2[i+1]],'r-', alpha=pr_z[i])\n",
" ax.set_xlabel('$z$',)\n",
" ax.set_ylabel('$x_1$')\n",
" ax.set_zlabel('$x_2$')\n",
" ax.set_xlim(-3,3)\n",
" ax.set_ylim(0,2)\n",
" ax.set_zlim(-1,1)\n",
" ax.set_box_aspect((3,1,1))\n",
" plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9DUTauMi6tPk"
},
"outputs": [],
"source": [
"# Compute the prior\n",
"def get_prior(z):\n",
" return scipy.stats.multivariate_normal.pdf(z)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PAzHq461VqvF"
},
"outputs": [],
"source": [
"# Define the latent variable values\n",
"z = np.arange(-3.0,3.0,0.01)\n",
"# Find the probability distribution over z\n",
"pr_z = get_prior(z)\n",
"# Compute x1 and x2 for each z\n",
"x1,x2 = f(z)\n",
"# Plot the function\n",
"draw_3d_projection(z,pr_z, x1,x2)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "sQg2gKR5zMrF"
},
"source": [
"The likelihood is defined as:\n",
"\\begin{align}\n",
" Pr(x_1,x_2|z) &=& \\text{Norm}_{[x_1,x_2]}\\Bigl[\\mathbf{f}[z],\\sigma^{2}\\mathbf{I}\\Bigr]\n",
"\\end{align}\n",
"\n",
"so we will also need to define the noise level $\\sigma^2$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "In_Vg4_0nva3"
},
"outputs": [],
"source": [
"sigma_sq = 0.04"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6P6d-AgAqxXZ"
},
"outputs": [],
"source": [
"# Draws a heatmap to represent a probability distribution, possibly with samples overlaed\n",
"def plot_heatmap(x1_mesh,x2_mesh,y_mesh, x1_samples=None, x2_samples=None, title=None):\n",
" # Define pretty colormap\n",
" my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
" my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
" r = np.floor(my_colormap_vals_dec/(256*256))\n",
" g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
" b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
" my_colormap = ListedColormap(np.vstack((r,g,b)).transpose()/255.0)\n",
"\n",
" fig,ax = plt.subplots()\n",
" fig.set_size_inches(8,8)\n",
" ax.contourf(x1_mesh,x2_mesh,y_mesh,256,cmap=my_colormap)\n",
" ax.contour(x1_mesh,x2_mesh,y_mesh,8,colors=['#80808080'])\n",
" if title is not None:\n",
" ax.set_title(title);\n",
" if x1_samples is not None:\n",
" ax.plot(x1_samples, x2_samples, 'c.')\n",
" ax.set_xlim([-0.5,2.5])\n",
" ax.set_ylim([-1.5,1.5])\n",
" ax.set_xlabel('$x_1$'); ax.set_ylabel('$x_2$')\n",
" plt.show()\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "diYKb7_ZgjlJ"
},
"outputs": [],
"source": [
"# Returns the likelihood\n",
"def get_likelihood(x1_mesh, x2_mesh, z_val):\n",
" # Find the corresponding x1 and x2 values\n",
" x1,x2 = f(z_val)\n",
"\n",
" # Calculate the probability for a mesh of x1,x2 values.\n",
" mn = scipy.stats.multivariate_normal([x1, x2], [[sigma_sq, 0], [0, sigma_sq]])\n",
" pr_x1_x2_given_z_val = mn.pdf(np.dstack((x1_mesh, x2_mesh)))\n",
" return pr_x1_x2_given_z_val"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "0X4NwixzqxtZ"
},
"source": [
"Now let's plot the likelihood $Pr(x_1,x_2|z)$ as in fig 17.3b in the book."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "hWfqK-Oz5_DT"
},
"outputs": [],
"source": [
"# Choose some z value\n",
"z_val = 1.8\n",
"\n",
"# Compute the conditional distribution on a grid\n",
"x1_mesh, x2_mesh = np.meshgrid(np.arange(-0.5,2.5,0.01), np.arange(-1.5,1.5,0.01))\n",
"pr_x1_x2_given_z_val = get_likelihood(x1_mesh,x2_mesh, z_val)\n",
"\n",
"# Plot the result\n",
"plot_heatmap(x1_mesh, x2_mesh, pr_x1_x2_given_z_val, title=\"Conditional distribution $Pr(x_1,x_2|z)$\")\n",
"\n",
"# TODO -- Experiment with different values of z and make sure that you understand the what is happening."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "25xqXnmFo-PH"
},
"source": [
"The data density is found by marginalizing over the latent variables $z$:\n",
"\n",
"\\begin{align}\n",
" Pr(x_1,x_2) &=& \\int Pr(x_1,x_2, z) dz \\nonumber \\\\\n",
" &=& \\int Pr(x_1,x_2 | z) \\cdot Pr(z)dz\\nonumber \\\\\n",
" &=& \\int \\text{Norm}_{[x_1,x_2]}\\Bigl[\\mathbf{f}[z],\\sigma^{2}\\mathbf{I}\\Bigr]\\cdot \\text{Norm}_{z}\\left[\\mathbf{0},\\mathbf{I}\\right]dz.\n",
"\\end{align}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "H0Ijce9VzeCO"
},
"outputs": [],
"source": [
"# TODO Compute the data density\n",
"# We can't integrate this function in closed form\n",
"# So let's approximate it as a sum over the z values (z = np.arange(-3,3,0.01))\n",
"# You will need the functions get_likelihood() and get_prior()\n",
"# To make this a valid probability distribution, you need to divide\n",
"# By the z-increment (0.01)\n",
"# Replace this line\n",
"pr_x1_x2 = np.zeros_like(x1_mesh)\n",
"\n",
"\n",
"# Plot the result\n",
"plot_heatmap(x1_mesh, x2_mesh, pr_x1_x2, title=\"Data density $Pr(x_1,x_2)$\")\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "W264N7By_h9y"
},
"source": [
"Now let's draw some samples from the model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Li3mK_I48k0k"
},
"outputs": [],
"source": [
"def draw_samples(n_sample):\n",
" # TODO Write this routine to draw n_sample samples from the model\n",
" # First draw a random value of z from the prior (a standard normal distribution)\n",
" # Then draw a sample from Pr(x1,x2|z)\n",
" # Replace this line\n",
" x1_samples=0; x2_samples = 0;\n",
"\n",
" return x1_samples, x2_samples"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "D7N7oqLe-eJO"
},
"source": [
"Let's plot those samples on top of the heat map."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XRmWv99B-BWO"
},
"outputs": [],
"source": [
"x1_samples, x2_samples = draw_samples(500)\n",
"# Plot the result\n",
"plot_heatmap(x1_mesh, x2_mesh, pr_x1_x2, x1_samples, x2_samples, title=\"Data density $Pr(x_1,x_2)$\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PwOjzPD5_1OF"
},
"outputs": [],
"source": [
"# Return the posterior distribution\n",
"def get_posterior(x1,x2):\n",
" z = np.arange(-3,3, 0.01)\n",
" # TODO -- write this function\n",
" # Again, we can't integrate, but we can sum\n",
" # We don't know the constant in the denominator of equation 17.19, but we can just normalize\n",
" # by the sum of the numerators for all values of z\n",
" # Replace this line:\n",
" pr_z_given_x1_x2 = np.ones_like(z)\n",
"\n",
"\n",
" return z, pr_z_given_x1_x2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PKFUY42K-Tp7"
},
"outputs": [],
"source": [
"x1 = 0.9; x2 = -0.9\n",
"z, pr_z_given_x1_x2 = get_posterior(x1,x2)\n",
"\n",
"\n",
"fig, ax = plt.subplots()\n",
"ax.plot(z, pr_z_given_x1_x2, 'r-')\n",
"ax.set_xlabel(\"Latent variable $z$\")\n",
"ax.set_ylabel(\"Posterior probability $Pr(z|x_{1},x_{2})$\")\n",
"ax.set_xlim([-3,3])\n",
"ax.set_ylim([0,1.5 * np.max(pr_z_given_x1_x2)])\n",
"plt.show()"
]
}
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyOSEQVqxE5KrXmsZVh9M3gq",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -0,0 +1,422 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap17/17_2_Reparameterization_Trick.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 17.2: Reparameterization trick**\n",
"\n",
"This notebook investigates the reparameterization trick as described in section 17.7 of the book.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "paLz5RukZP1J"
},
"source": [
"The reparameterization trick computes the derivative of an expectation of a function $\\text{f}[x]$:\n",
"\n",
"\\begin{equation}\n",
"\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\bigl[\\text{f}[x]\\bigr],\n",
"\\end{equation}\n",
"\n",
"with respect to the parameters $\\boldsymbol\\phi$ of the distribution $Pr(x|\\boldsymbol\\phi)$ that the expectation is over.\n",
"\n",
"Let's consider a simple concrete example, where:\n",
"\n",
"\\begin{equation}\n",
"Pr(x|\\phi) = \\text{Norm}_{x}\\Bigl[\\mu, \\sigma^2\\Bigr]=\\text{Norm}_{x}\\Bigl[\\phi^3,(\\exp[\\phi])^2\\Bigr]\n",
"\\end{equation}\n",
"\n",
"and\n",
"\n",
"\\begin{equation}\n",
"\\text{f}[x] = x^2+\\sin[x]\n",
"\\end{equation}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FdEbMnDBY0i9"
},
"outputs": [],
"source": [
"# Let's approximate this expectation for a particular value of phi\n",
"def compute_expectation(phi, n_samples):\n",
" # TODO complete this function\n",
" # 1. Compute the mean of the normal distribution, mu\n",
" # 2. Compute the standard deviation of the normal distribution, sigma\n",
" # 3. Draw n_samples samples using np.random.normal(mu, sigma, size=(n_samples, 1))\n",
" # 4. Compute f[x] for each of these samples\n",
" # 4. Approximate the expectation by taking the average of the values of f[x]\n",
" # Replace this line\n",
" expected_f_given_phi = 0\n",
"\n",
"\n",
" return expected_f_given_phi"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FTh7LJ0llNJZ"
},
"outputs": [],
"source": [
"# Set the seed so the random numbers are all the same\n",
"np.random.seed(0)\n",
"\n",
"# Compute the expectation for two values of phi\n",
"phi1 = 0.5\n",
"n_samples = 10000000\n",
"expected_f_given_phi1 = compute_expectation(phi1, n_samples)\n",
"print(\"Your value: \", expected_f_given_phi1, \", True value: 2.7650801613563116\")\n",
"\n",
"phi2 = -0.1\n",
"n_samples = 10000000\n",
"expected_f_given_phi2 = compute_expectation(phi2, n_samples)\n",
"print(\"Your value: \", expected_f_given_phi2, \", True value: 0.8176793102849222\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "r5Hl2QkimWx9"
},
"source": [
"Le't plot this expectation as a function of phi"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "05XxVLJxmkER"
},
"outputs": [],
"source": [
"phi_vals = np.arange(-1.5,1.5, 0.05)\n",
"expected_vals = np.zeros_like(phi_vals)\n",
"n_samples = 1000000\n",
"for i in range(len(phi_vals)):\n",
" expected_vals[i] = compute_expectation(phi_vals[i], n_samples)\n",
"\n",
"fig,ax = plt.subplots()\n",
"ax.plot(phi_vals, expected_vals,'r-')\n",
"ax.set_xlabel(r'Parameter $\\phi$')\n",
"ax.set_ylabel(r'$\\mathbb{E}_{Pr(x|\\phi)}[f[x]]$')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zTCykVeWqj_O"
},
"source": [
"It's this curve that we want to find the derivative of (so for example, we could run gradient descent and find the minimum.\n",
"\n",
"This is tricky though -- if you look at the computation that you performed, then there is a sampling step in the procedure (step 3). How do we compute the derivative of this?\n",
"\n",
"The answer is the reparameterization trick. We note that:\n",
"\n",
"\\begin{equation}\n",
"\\text{Norm}_{x}\\Bigl[\\mu, \\sigma^2\\Bigr]=\\text{Norm}_{x}\\Bigl[0, 1\\Bigr] \\times \\sigma + \\mu\n",
"\\end{equation}\n",
"\n",
"and so:\n",
"\n",
"\\begin{equation}\n",
"\\text{Norm}_{x}\\Bigl[\\phi^3,(\\exp[\\phi])^2\\Bigr] = \\text{Norm}_{x}\\Bigl[0, 1\\Bigr] \\times \\exp[\\phi]+ \\phi^3\n",
"\\end{equation}\n",
"\n",
"So, if we draw a sample $\\epsilon^*$ from $\\text{Norm}_{\\epsilon}[0, 1]$, then we can compute a sample $x^*$ as:\n",
"\n",
"\\begin{align}\n",
"x^* &=& \\epsilon^* \\times \\sigma + \\mu \\\\\n",
"&=& \\epsilon^* \\times \\exp[\\phi]+ \\phi^3\n",
"\\end{align}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "w13HVpi9q8nF"
},
"outputs": [],
"source": [
"def compute_df_dx_star(x_star):\n",
" # TODO Compute this derivative (function defined at the top)\n",
" # Replace this line:\n",
" deriv = 0;\n",
"\n",
"\n",
"\n",
" return deriv\n",
"\n",
"def compute_dx_star_dphi(epsilon_star, phi):\n",
" # TODO Compute this derivative\n",
" # Replace this line:\n",
" deriv = 0;\n",
"\n",
"\n",
"\n",
" return deriv\n",
"\n",
"def compute_derivative_of_expectation(phi, n_samples):\n",
" # Generate the random values of epsilon\n",
" epsilon_star= np.random.normal(size=(n_samples,1))\n",
" # TODO -- write\n",
" # 1. Compute dx*/dphi using the function defined above\n",
" # 2. Compute x*\n",
" # 3. Compute df/dx* using the function you wrote above\n",
" # 4. Compute df/dphi = df/x* * dx*dphi\n",
" # 5. Average the samples of df/dphi to get the expectation.\n",
" # Replace this line:\n",
" df_dphi = 0\n",
"\n",
"\n",
"\n",
" return df_dphi"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ntQT4An79kAl"
},
"outputs": [],
"source": [
"# Set the seed so the random numbers are all the same\n",
"np.random.seed(0)\n",
"\n",
"# Compute the expectation for two values of phi\n",
"phi1 = 0.5\n",
"n_samples = 10000000\n",
"\n",
"deriv = compute_derivative_of_expectation(phi1, n_samples)\n",
"print(\"Your value: \", deriv, \", True value: 5.726338035051403\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "t0Jqd_IN_lMU"
},
"outputs": [],
"source": [
"phi_vals = np.arange(-1.5,1.5, 0.05)\n",
"deriv_vals = np.zeros_like(phi_vals)\n",
"n_samples = 1000000\n",
"for i in range(len(phi_vals)):\n",
" deriv_vals[i] = compute_derivative_of_expectation(phi_vals[i], n_samples)\n",
"\n",
"fig,ax = plt.subplots()\n",
"ax.plot(phi_vals, deriv_vals,'r-')\n",
"ax.set_xlabel(r'Parameter $\\phi$')\n",
"ax.set_ylabel(r'$\\partial/\\partial\\phi\\mathbb{E}_{Pr(x|\\phi)}[f[x]]$')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ASu4yKSwAEYI"
},
"source": [
"This should look plausibly like the derivative of the function we plotted above!"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xoFR1wifc8-b"
},
"source": [
"The reparameterization trick computes the derivative of an expectation of a function $\\text{f}[x]$:\n",
"\n",
"\\begin{equation}\n",
"\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\bigl[\\text{f}[x]\\bigr],\n",
"\\end{equation}\n",
"\n",
"with respect to the parameters $\\boldsymbol\\phi$ of the distribution $Pr(x|\\boldsymbol\\phi)$ that the expectation is over. This derivative can also be computed as:\n",
"\n",
"\\begin{align}\n",
"\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\bigl[\\text{f}[x]\\bigr] &=& \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\left[\\text{f}[x]\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\log\\bigl[ Pr(x|\\boldsymbol\\phi)\\bigr]\\right]\\nonumber \\\\\n",
"&\\approx & \\frac{1}{I}\\sum_{i=1}^{I}\\text{f}[x_i]\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\log\\bigl[ Pr(x_i|\\boldsymbol\\phi)\\bigr].\n",
"\\end{align}\n",
"\n",
"This method is known as the REINFORCE algorithm or score function estimator. Problem 17.5 asks you to prove this relation. Let's use this method to compute the gradient and compare.\n",
"\n",
"Recall that the expression for a univariate Gaussian is:\n",
"\n",
"\\begin{equation}\n",
" Pr(x|\\mu,\\sigma^2) = \\frac{1}{\\sqrt{2\\pi\\sigma^{2}}}\\exp\\left[-\\frac{(x-\\mu)^{2}}{2\\sigma^{2}}\\right].\n",
"\\end{equation}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4TUaxiWvASla"
},
"outputs": [],
"source": [
"def d_log_pr_x_given_phi(x,phi):\n",
" # TODO -- fill in this function\n",
" # Compute the derivative of log[Pr(x|phi)]\n",
" # Replace this line:\n",
" deriv =0;\n",
"\n",
"\n",
" return deriv\n",
"\n",
"\n",
"def compute_derivative_of_expectation_score_function(phi, n_samples):\n",
" # TODO -- Compute this function\n",
" # 1. Calculate mu from phi\n",
" # 2. Calculate sigma from phi\n",
" # 3. Generate n_sample random samples of x using np.random.normal\n",
" # 4. Calculate f[x] for all of the samples\n",
" # 5. Multiply f[x] by d_log_pr_x_given_phi\n",
" # 6. Take the average of the samples\n",
" # Replace this line:\n",
" deriv = 0\n",
"\n",
"\n",
"\n",
" return deriv"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0RSN32Rna_C_"
},
"outputs": [],
"source": [
"# Set the seed so the random numbers are all the same\n",
"np.random.seed(0)\n",
"\n",
"# Compute the expectation for two values of phi\n",
"phi1 = 0.5\n",
"n_samples = 100000000\n",
"\n",
"deriv = compute_derivative_of_expectation_score_function(phi1, n_samples)\n",
"print(\"Your value: \", deriv, \", True value: 5.724609927313369\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "EM_i5zoyElHR"
},
"outputs": [],
"source": [
"phi_vals = np.arange(-1.5,1.5, 0.05)\n",
"deriv_vals = np.zeros_like(phi_vals)\n",
"n_samples = 1000000\n",
"for i in range(len(phi_vals)):\n",
" deriv_vals[i] = compute_derivative_of_expectation_score_function(phi_vals[i], n_samples)\n",
"\n",
"fig,ax = plt.subplots()\n",
"ax.plot(phi_vals, deriv_vals,'r-')\n",
"ax.set_xlabel(r'Parameter $\\phi$')\n",
"ax.set_ylabel(r'$\\partial/\\partial\\phi\\mathbb{E}_{Pr(x|\\phi)}[f[x]]$')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1TWBiUC7bQSw"
},
"source": [
"This should look the same as the derivative that we computed with the reparameterization trick. So, is there any advantage to one way or the other? Let's compare the variances of the estimates\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vV_Jx5bCbQGs"
},
"outputs": [],
"source": [
"n_estimate = 100\n",
"n_sample = 1000\n",
"phi = 0.3\n",
"reparam_estimates = np.zeros((n_estimate,1))\n",
"score_function_estimates = np.zeros((n_estimate,1))\n",
"for i in range(n_estimate):\n",
" reparam_estimates[i]= compute_derivative_of_expectation(phi, n_samples)\n",
" score_function_estimates[i] = compute_derivative_of_expectation_score_function(phi, n_samples)\n",
"\n",
"print(\"Variance of reparameterization estimator\", np.var(reparam_estimates))\n",
"print(\"Variance of score function estimator\", np.var(score_function_estimates))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d-0tntSYdKPR"
},
"source": [
"The variance of the reparameterization estimator should be quite a bit lower than the score function estimator which is why it is preferred in this situation."
]
}
],
"metadata": {
"colab": {
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -0,0 +1,507 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap17/17_3_Importance_Sampling.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 17.3: Importance sampling**\n",
"\n",
"This notebook investigates importance sampling as described in section 17.8.1 of the book.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "f7a6xqKjkmvT"
},
"source": [
"Let's approximate the expectation\n",
"\n",
"\\begin{equation}\n",
"\\mathbb{E}_{y}\\Bigl[\\exp\\bigl[- (y-1)^4\\bigr]\\Bigr] = \\int \\exp\\bigl[- (y-1)^4\\bigr] Pr(y) dy,\n",
"\\end{equation}\n",
"\n",
"where\n",
"\n",
"\\begin{equation}\n",
"Pr(y)=\\text{Norm}_y[0,1]\n",
"\\end{equation}\n",
"\n",
"by drawing $I$ samples $y_i$ and using the formula:\n",
"\n",
"\\begin{equation}\n",
"\\mathbb{E}_{y}\\Bigl[\\exp\\bigl[- (y-1)^4\\bigr]\\Bigr] \\approx \\frac{1}{I} \\sum_{i=1}^I \\exp\\bigl[-(y_i-1)^4 \\bigr]\n",
"\\end{equation}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "VjkzRr8o2ksg"
},
"outputs": [],
"source": [
"def f(y):\n",
" return np.exp(-(y-1) *(y-1) *(y-1) * (y-1))\n",
"\n",
"\n",
"def pr_y(y):\n",
" return (1/np.sqrt(2*np.pi)) * np.exp(-0.5 * y * y)\n",
"\n",
"fig,ax = plt.subplots()\n",
"y = np.arange(-10,10,0.01)\n",
"ax.plot(y, f(y), 'r-', label='f$[y]$');\n",
"ax.plot(y, pr_y(y),'b-',label='$Pr(y)$')\n",
"ax.set_xlabel(\"$y$\")\n",
"ax.legend()\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LGAKHjUJnWmy"
},
"outputs": [],
"source": [
"def compute_expectation(n_samples):\n",
" # TODO -- compute this expectation\n",
" # 1. Generate samples y_i using np.random.normal\n",
" # 2. Approximate the expectation of f[y]\n",
" # Replace this line\n",
" expectation = 0\n",
"\n",
"\n",
" return expectation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nmvixMqgodIP"
},
"outputs": [],
"source": [
"# Set the seed so the random numbers are all the same\n",
"np.random.seed(0)\n",
"\n",
"# Compute the expectation with a very large number of samples (good estimate)\n",
"n_samples = 100000000\n",
"expected_f= compute_expectation(n_samples)\n",
"print(\"Your value: \", expected_f, \", True value: 0.43160702267383166\")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "Jr4UPcqmnXCS"
},
"source": [
"Let's investigate how the variance of this approximation decreases as we increase the number of samples $N$.\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "yrDp1ILUo08j"
},
"outputs": [],
"source": [
"def compute_mean_variance(n_sample):\n",
" n_estimate = 10000\n",
" estimates = np.zeros((n_estimate,1))\n",
" for i in range(n_estimate):\n",
" estimates[i] = compute_expectation(n_sample.astype(int))\n",
" return np.mean(estimates), np.var(estimates)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "BcUVsodtqdey"
},
"outputs": [],
"source": [
"# Compute the mean and variance for 1,2,... 20 samples\n",
"n_sample_all = np.array([1.,2,3,4,5,6,7,8,9,10,15,20,25,30,45,50,60,70,80,90,100,150,200,250,300,350,400,450,500])\n",
"mean_all = np.zeros_like(n_sample_all)\n",
"variance_all = np.zeros_like(n_sample_all)\n",
"for i in range(len(n_sample_all)):\n",
" print(\"Computing mean and variance for expectation with %d samples\"%(n_sample_all[i]))\n",
" mean_all[i],variance_all[i] = compute_mean_variance(n_sample_all[i])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "feXmyk0krpUi"
},
"outputs": [],
"source": [
"fig,ax = plt.subplots()\n",
"ax.semilogx(n_sample_all, mean_all,'r-',label='mean estimate')\n",
"ax.fill_between(n_sample_all, mean_all-2*np.sqrt(variance_all), mean_all+2*np.sqrt(variance_all))\n",
"ax.set_xlabel(\"Number of samples\")\n",
"ax.set_ylabel(\"Mean of estimate\")\n",
"ax.plot([0,500],[0.43160702267383166,0.43160702267383166],'k--',label='true value')\n",
"ax.legend()\n",
"plt.show()\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "XTUpxFlSuOl7"
},
"source": [
"As you might expect, the more samples that we use to compute the approximate estimate, the lower the variance of the estimate."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "6hxsl3Pxo1TT"
},
"source": [
" Now consider the function\n",
" \\begin{equation}\n",
" \\mbox{f}[y]= 20.446\\exp\\left[-(y-3)^4\\right],\n",
" \\end{equation}\n",
"\n",
"which decreases rapidly as we move away from the position $y=3$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "znydVPW7sL4P"
},
"outputs": [],
"source": [
"def f2(y):\n",
" return 20.446*np.exp(- (y-3) *(y-3) *(y-3) * (y-3))\n",
"\n",
"fig,ax = plt.subplots()\n",
"y = np.arange(-10,10,0.01)\n",
"ax.plot(y, f2(y), 'r-', label='f$[y]$');\n",
"ax.plot(y, pr_y(y),'b-',label='$Pr(y)$')\n",
"ax.set_xlabel(\"$y$\")\n",
"ax.legend()\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "G9Xxo0OJsIqD"
},
"source": [
"Let's again, compute the expectation:\n",
"\n",
"\\begin{align}\n",
"\\mathbb{E}_{y}\\left[\\text{f}[y]\\right] &=& \\int \\text{f}[y] Pr(y) dy\\\\\n",
"&\\approx& \\frac{1}{I} \\text{f}[y]\n",
"\\end{align}\n",
"\n",
"where $Pr(y)=\\text{Norm}_y[0,1]$ by approximating with samples $y_{i}$.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "l8ZtmkA2vH4y"
},
"outputs": [],
"source": [
"def compute_expectation2(n_samples):\n",
" y = np.random.normal(size=(n_samples,1))\n",
" expectation = np.mean(f2(y))\n",
"\n",
" return expectation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dfUQyJ-svZ6F"
},
"outputs": [],
"source": [
"# Set the seed so the random numbers are all the same\n",
"np.random.seed(0)\n",
"\n",
"# Compute the expectation with a very large number of samples (good estimate)\n",
"n_samples = 100000000\n",
"expected_f2= compute_expectation2(n_samples)\n",
"print(\"Expected value: \", expected_f2)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "2sVDqP0BvxqM"
},
"source": [
"I deliberately chose this function, because it's expectation is roughly the same as for the previous function.\n",
"\n",
"Again, let's look at the mean and the variance of the estimates"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mHnILRkOv0Ir"
},
"outputs": [],
"source": [
"def compute_mean_variance2(n_sample):\n",
" n_estimate = 10000\n",
" estimates = np.zeros((n_estimate,1))\n",
" for i in range(n_estimate):\n",
" estimates[i] = compute_expectation2(n_sample.astype(int))\n",
" return np.mean(estimates), np.var(estimates)\n",
"\n",
"# Compute the variance for 1,2,... 20 samples\n",
"mean_all2 = np.zeros_like(n_sample_all)\n",
"variance_all2 = np.zeros_like(n_sample_all)\n",
"for i in range(len(n_sample_all)):\n",
" print(\"Computing variance for expectation with %d samples\"%(n_sample_all[i]))\n",
" mean_all2[i], variance_all2[i] = compute_mean_variance2(n_sample_all[i])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FkCX-hxxAnsw"
},
"outputs": [],
"source": [
"fig,ax1 = plt.subplots()\n",
"ax1.semilogx(n_sample_all, mean_all,'r-',label='mean estimate')\n",
"ax1.fill_between(n_sample_all, mean_all-2*np.sqrt(variance_all), mean_all+2*np.sqrt(variance_all))\n",
"ax1.set_xlabel(\"Number of samples\")\n",
"ax1.set_ylabel(\"Mean of estimate\")\n",
"ax1.plot([1,500],[0.43160702267383166,0.43160702267383166],'k--',label='true value')\n",
"ax1.set_ylim(-5,6)\n",
"ax1.set_title(\"First function\")\n",
"ax1.legend()\n",
"\n",
"fig2,ax2 = plt.subplots()\n",
"ax2.semilogx(n_sample_all, mean_all2,'r-',label='mean estimate')\n",
"ax2.fill_between(n_sample_all, mean_all2-2*np.sqrt(variance_all2), mean_all2+2*np.sqrt(variance_all2))\n",
"ax2.set_xlabel(\"Number of samples\")\n",
"ax2.set_ylabel(\"Mean of estimate\")\n",
"ax2.plot([0,500],[0.43160428638892556,0.43160428638892556],'k--',label='true value')\n",
"ax2.set_ylim(-5,6)\n",
"ax2.set_title(\"Second function\")\n",
"ax2.legend()\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "EtBP6NeLwZqz"
},
"source": [
"You can see that the variance of the estimate of the second function is considerably worse than the estimate of the variance of estimate of the first function\n",
"\n",
"TODO: Think about why this is."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "_wuF-NoQu1--"
},
"source": [
" Now let's repeat this experiment with the second function, but this time use importance sampling with auxiliary distribution:\n",
"\n",
" \\begin{equation}\n",
" q(y)=\\text{Norm}_{y}[3,1]\n",
" \\end{equation}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jPm0AVYVIDnn"
},
"outputs": [],
"source": [
"def q_y(y):\n",
" return (1/np.sqrt(2*np.pi)) * np.exp(-0.5 * (y-3) * (y-3))\n",
"\n",
"def compute_expectation2b(n_samples):\n",
" # TODO -- complete this function\n",
" # 1. Draw n_samples from auxiliary distribution\n",
" # 2. Compute f2[y] for those samples\n",
" # 3. Scale the results by pr_y / q_y\n",
" # 4. Compute the mean of these weighted samples\n",
" # Replace this line\n",
" expectation = 0\n",
"\n",
" return expectation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "No2ByVvOM2yQ"
},
"outputs": [],
"source": [
"# Set the seed so the random numbers are all the same\n",
"np.random.seed(0)\n",
"\n",
"# Compute the expectation with a very large number of samples (good estimate)\n",
"n_samples = 100000000\n",
"expected_f2= compute_expectation2b(n_samples)\n",
"print(\"Your value: \", expected_f2,\", True value: 0.43163734204459125 \")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6v8Jc7z4M3Mk"
},
"outputs": [],
"source": [
"def compute_mean_variance2b(n_sample):\n",
" n_estimate = 10000\n",
" estimates = np.zeros((n_estimate,1))\n",
" for i in range(n_estimate):\n",
" estimates[i] = compute_expectation2b(n_sample.astype(int))\n",
" return np.mean(estimates), np.var(estimates)\n",
"\n",
"# Compute the variance for 1,2,... 20 samples\n",
"mean_all2b = np.zeros_like(n_sample_all)\n",
"variance_all2b = np.zeros_like(n_sample_all)\n",
"for i in range(len(n_sample_all)):\n",
" print(\"Computing variance for expectation with %d samples\"%(n_sample_all[i]))\n",
" mean_all2b[i], variance_all2b[i] = compute_mean_variance2b(n_sample_all[i])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "C0beD4sNNM3L"
},
"outputs": [],
"source": [
"fig,ax1 = plt.subplots()\n",
"ax1.semilogx(n_sample_all, mean_all,'r-',label='mean estimate')\n",
"ax1.fill_between(n_sample_all, mean_all-2*np.sqrt(variance_all), mean_all+2*np.sqrt(variance_all))\n",
"ax1.set_xlabel(\"Number of samples\")\n",
"ax1.set_ylabel(\"Mean of estimate\")\n",
"ax1.plot([1,500],[0.43160702267383166,0.43160702267383166],'k--',label='true value')\n",
"ax1.set_ylim(-5,6)\n",
"ax1.set_title(\"First function\")\n",
"ax1.legend()\n",
"\n",
"fig2,ax2 = plt.subplots()\n",
"ax2.semilogx(n_sample_all, mean_all2,'r-',label='mean estimate')\n",
"ax2.fill_between(n_sample_all, mean_all2-2*np.sqrt(variance_all2), mean_all2+2*np.sqrt(variance_all2))\n",
"ax2.set_xlabel(\"Number of samples\")\n",
"ax2.set_ylabel(\"Mean of estimate\")\n",
"ax2.plot([0,500],[0.43160428638892556,0.43160428638892556],'k--',label='true value')\n",
"ax2.set_ylim(-5,6)\n",
"ax2.set_title(\"Second function\")\n",
"ax2.legend()\n",
"plt.show()\n",
"\n",
"fig2,ax2 = plt.subplots()\n",
"ax2.semilogx(n_sample_all, mean_all2b,'r-',label='mean estimate')\n",
"ax2.fill_between(n_sample_all, mean_all2b-2*np.sqrt(variance_all2b), mean_all2b+2*np.sqrt(variance_all2b))\n",
"ax2.set_xlabel(\"Number of samples\")\n",
"ax2.set_ylabel(\"Mean of estimate\")\n",
"ax2.plot([0,500],[ 0.43163734204459125, 0.43163734204459125],'k--',label='true value')\n",
"ax2.set_ylim(-5,6)\n",
"ax2.set_title(\"Second function with importance sampling\")\n",
"ax2.legend()\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "y8rgge9MNiOc"
},
"source": [
"You can see that the importance sampling technique has reduced the amount of variance for any given number of samples."
]
}
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyNecz9/CDOggPSmy1LjT/Dv",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -0,0 +1,470 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap18/18_1_Diffusion_Encoder.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 18.1: Diffusion Encoder**\n",
"\n",
"This notebook investigates the diffusion encoder as described in section 18.2 of the book.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib.colors import ListedColormap\n",
"from operator import itemgetter"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4PM8bf6lO0VE"
},
"outputs": [],
"source": [
"#Create pretty colormap as in book\n",
"my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
"my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
"r = np.floor(my_colormap_vals_dec/(256*256))\n",
"g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
"b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
"my_colormap_vals = np.vstack((r,g,b)).transpose()/255.0\n",
"my_colormap = ListedColormap(my_colormap_vals)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ONGRaQscfIOo"
},
"outputs": [],
"source": [
"# Probability distribution for normal\n",
"def norm_pdf(x, mu, sigma):\n",
" return np.exp(-0.5 * (x-mu) * (x-mu) / (sigma * sigma)) / np.sqrt(2*np.pi*sigma*sigma)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gZvG0MKhfY8Y"
},
"outputs": [],
"source": [
"# True distribution is a mixture of four Gaussians\n",
"class TrueDataDistribution:\n",
" # Constructor initializes parameters\n",
" def __init__(self):\n",
" self.mu = [1.5, -0.216, 0.45, -1.875]\n",
" self.sigma = [0.3, 0.15, 0.525, 0.075]\n",
" self.w = [0.2, 0.3, 0.35, 0.15]\n",
"\n",
" # Return PDF\n",
" def pdf(self, x):\n",
" return(self.w[0] *norm_pdf(x,self.mu[0],self.sigma[0]) + self.w[1] *norm_pdf(x,self.mu[1],self.sigma[1]) + self.w[2] *norm_pdf(x,self.mu[2],self.sigma[2]) + self.w[3] *norm_pdf(x,self.mu[3],self.sigma[3]))\n",
"\n",
" # Draw samples\n",
" def sample(self, n):\n",
" hidden = np.random.choice(4, n, p=self.w)\n",
" epsilon = np.random.normal(size=(n))\n",
" mu_list = list(itemgetter(*hidden)(self.mu))\n",
" sigma_list = list(itemgetter(*hidden)(self.sigma))\n",
" return mu_list + sigma_list * epsilon"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qXmej3TUuQyp"
},
"outputs": [],
"source": [
"# Define ground truth probability distribution that we will model\n",
"true_dist = TrueDataDistribution()\n",
"# Let's visualize this\n",
"x_vals = np.arange(-3,3,0.01)\n",
"pr_x_true = true_dist.pdf(x_vals)\n",
"fig,ax = plt.subplots()\n",
"ax.plot(x_vals, pr_x_true, 'r-')\n",
"ax.set_xlabel(\"$x$\")\n",
"ax.set_ylabel(\"$Pr(x)$\")\n",
"ax.set_ylim(0,1.0)\n",
"ax.set_xlim(-3,3)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XHdtfRP47YLy"
},
"source": [
"Let's first implement the forward process"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "hkApJ2VJlQuk"
},
"outputs": [],
"source": [
"# Do one step of diffusion (equation 18.1)\n",
"def diffuse_one_step(z_t_minus_1, beta_t):\n",
" # TODO -- Implement this function\n",
" # Use np.random.normal to generate the samples epsilon\n",
" # Replace this line\n",
" z_t = np.zeros_like(z_t_minus_1)\n",
"\n",
" return z_t"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ECAUfHNi9NVW"
},
"source": [
"Now let's run the diffusion process for a whole bunch of samples"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "M-TY5w9Q8LYW"
},
"outputs": [],
"source": [
"# Generate some samples\n",
"n_sample = 10000\n",
"np.random.seed(6)\n",
"x = true_dist.sample(n_sample)\n",
"\n",
"# Number of time steps\n",
"T = 100\n",
"# Noise schedule has same value at every time step\n",
"beta = 0.01511\n",
"\n",
"# We'll store the diffused samples in an array\n",
"samples = np.zeros((T+1, n_sample))\n",
"samples[0,:] = x\n",
"\n",
"for t in range(T):\n",
" samples[t+1,:] = diffuse_one_step(samples[t,:], beta)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jYrAW6tN-gJ4"
},
"source": [
"Let's, plot the evolution of a few paths as in figure 18.2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4XU6CDZC_kFo"
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"t_vals = np.arange(0,101,1)\n",
"ax.plot(samples[:,0],t_vals,'r-')\n",
"ax.plot(samples[:,1],t_vals,'g-')\n",
"ax.plot(samples[:,2],t_vals,'b-')\n",
"ax.plot(samples[:,3],t_vals,'c-')\n",
"ax.plot(samples[:,4],t_vals,'m-')\n",
"ax.set_xlim([-3,3])\n",
"ax.set_ylim([101, 0])\n",
"ax.set_xlabel('value')\n",
"ax.set_ylabel('z_{t}')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SGTYGGevAktz"
},
"source": [
"Notice that the samples have a tendency to move toward the center. Now let's look at the histogram of the samples at each stage"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bn5E5NzL-evM"
},
"outputs": [],
"source": [
"def draw_hist(z_t,title=''):\n",
" fig, ax = plt.subplots()\n",
" fig.set_size_inches(8,2.5)\n",
" plt.hist(z_t , bins=np.arange(-3,3, 0.1), density = True)\n",
" ax.set_xlim([-3,3])\n",
" ax.set_ylim([0,1.0])\n",
" ax.set_title(title)\n",
" plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "pn_XD-EhBlwk"
},
"outputs": [],
"source": [
"draw_hist(samples[0,:],'Original data')\n",
"draw_hist(samples[5,:],'Time step 5')\n",
"draw_hist(samples[10,:],'Time step 10')\n",
"draw_hist(samples[20,:],'Time step 20')\n",
"draw_hist(samples[40,:],'Time step 40')\n",
"draw_hist(samples[80,:],'Time step 80')\n",
"draw_hist(samples[100,:],'Time step 100')"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "skuLfGl5Czf4"
},
"source": [
"You can clearly see that as the diffusion process continues, the data becomes more Gaussian."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "s37CBSzzK7wh"
},
"source": [
"Now let's investigate the diffusion kernel as in figure 18.3 of the book.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vL62Iym0LEtY"
},
"outputs": [],
"source": [
"def diffusion_kernel(x, t, beta):\n",
" # TODO -- write this function\n",
" # Replace this line:\n",
" dk_mean = 0.0 ; dk_std = 1.0\n",
"\n",
" return dk_mean, dk_std"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KtP1KF8wMh8o"
},
"outputs": [],
"source": [
"def draw_prob_dist(x_plot_vals, prob_dist, title=''):\n",
" fig, ax = plt.subplots()\n",
" fig.set_size_inches(8,2.5)\n",
" ax.plot(x_plot_vals, prob_dist, 'b-')\n",
" ax.set_xlim([-3,3])\n",
" ax.set_ylim([0,1.0])\n",
" ax.set_title(title)\n",
" plt.show()\n",
"\n",
"def compute_and_plot_diffusion_kernels(x, T, beta, my_colormap):\n",
" x_plot_vals = np.arange(-3,3,0.01)\n",
" diffusion_kernels = np.zeros((T+1,len(x_plot_vals)))\n",
" dk_mean_all = np.ones((T+1,1))*x\n",
" dk_std_all = np.zeros((T+1,1))\n",
" for t in range(T):\n",
" dk_mean_all[t+1], dk_std_all[t+1] = diffusion_kernel(x,t+1,beta)\n",
" diffusion_kernels[t+1,:] = norm_pdf(x_plot_vals, dk_mean_all[t+1], dk_std_all[t+1])\n",
"\n",
" samples = np.ones((T+1, 5))\n",
" samples[0,:] = x\n",
"\n",
" for t in range(T):\n",
" samples[t+1,:] = diffuse_one_step(samples[t,:], beta)\n",
"\n",
" fig, ax = plt.subplots()\n",
" fig.set_size_inches(6,6)\n",
"\n",
" # Plot the image containing all the kernels\n",
" plt.imshow(diffusion_kernels, cmap=my_colormap, interpolation='nearest')\n",
"\n",
" # Plot +/- 2 standard deviations\n",
" ax.plot((dk_mean_all -2 * dk_std_all)/0.01 + len(x_plot_vals)/2, np.arange(0,101,1),'y--')\n",
" ax.plot((dk_mean_all +2 * dk_std_all)/0.01 + len(x_plot_vals)/2, np.arange(0,101,1),'y--')\n",
"\n",
" # Plot a few trajectories\n",
" ax.plot(samples[:,0]/0.01 + + len(x_plot_vals)/2, np.arange(0,101,1), 'r-')\n",
" ax.plot(samples[:,1]/0.01 + + len(x_plot_vals)/2, np.arange(0,101,1), 'g-')\n",
" ax.plot(samples[:,2]/0.01 + + len(x_plot_vals)/2, np.arange(0,101,1), 'b-')\n",
" ax.plot(samples[:,3]/0.01 + + len(x_plot_vals)/2, np.arange(0,101,1), 'c-')\n",
" ax.plot(samples[:,4]/0.01 + + len(x_plot_vals)/2, np.arange(0,101,1), 'm-')\n",
"\n",
" # Tidy up and plot\n",
" ax.set_ylabel(\"$Pr(z_{t}|x)$\")\n",
" ax.get_xaxis().set_visible(False)\n",
" ax.set_xlim([0,601])\n",
" ax.set_aspect(601/T)\n",
" plt.show()\n",
"\n",
"\n",
" draw_prob_dist(x_plot_vals, diffusion_kernels[20,:],'$q(z_{20}|x)$')\n",
" draw_prob_dist(x_plot_vals, diffusion_kernels[40,:],'$q(z_{40}|x)$')\n",
" draw_prob_dist(x_plot_vals, diffusion_kernels[80,:],'$q(z_{80}|x)$')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "g8TcI5wtRQsx"
},
"outputs": [],
"source": [
"x = -2\n",
"compute_and_plot_diffusion_kernels(x, T, beta, my_colormap)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-RuN2lR28-hK"
},
"source": [
"TODO -- Run this for different version of $x$ and check that you understand how the graphs change"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "n-x6Whz2J_zy"
},
"source": [
"Finally, let's estimate the marginal distributions empirically and visualize them as in figure 18.4 of the book. This is only tractable because the data is in one dimension and we know the original distribution.\n",
"\n",
"The marginal distribution at time t is the sum of the diffusion kernels for each position x, weighted by the probability of seeing that value of x in the true distribution."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YzN5duYpg7C-"
},
"outputs": [],
"source": [
"def diffusion_marginal(x_plot_vals, pr_x_true, t, beta):\n",
" # If time is zero then marginal is just original distribution\n",
" if t == 0:\n",
" return pr_x_true\n",
"\n",
" # The thing we are computing\n",
" marginal_at_time_t = np.zeros_like(pr_x_true);\n",
"\n",
"\n",
" # TODO Write this function\n",
" # 1. For each x (value in x_plot_vals):\n",
" # 2. Compute the mean and variance of the diffusion kernel at time t\n",
" # 3. Compute pdf of this Gaussian at every x_plot_val\n",
" # 4. Weight Gaussian by probability at position x and by 0.01 to componensate for bin size\n",
" # 5. Accumulate weighted Gaussian in marginal at time t.\n",
"\n",
" # Replace this line:\n",
" marginal_at_time_t = marginal_at_time_t\n",
"\n",
"\n",
"\n",
" return marginal_at_time_t"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OgEU9sxjRaeO"
},
"outputs": [],
"source": [
"x_plot_vals = np.arange(-3,3,0.01)\n",
"marginal_distributions = np.zeros((T+1,len(x_plot_vals)))\n",
"\n",
"for t in range(T+1):\n",
" marginal_distributions[t,:] = diffusion_marginal(x_plot_vals, pr_x_true , t, beta)\n",
"\n",
"fig, ax = plt.subplots()\n",
"fig.set_size_inches(6,6)\n",
"\n",
"# Plot the image containing all the kernels\n",
"plt.imshow(marginal_distributions, cmap=my_colormap, interpolation='nearest')\n",
"\n",
"# Tidy up and plot\n",
"ax.set_ylabel(\"$Pr(z_{t})$\")\n",
"ax.get_xaxis().set_visible(False)\n",
"ax.set_xlim([0,601])\n",
"ax.set_aspect(601/T)\n",
"plt.show()\n",
"\n",
"\n",
"draw_prob_dist(x_plot_vals, marginal_distributions[0,:],'$q(z_{0})$')\n",
"draw_prob_dist(x_plot_vals, marginal_distributions[20,:],'$q(z_{20})$')\n",
"draw_prob_dist(x_plot_vals, marginal_distributions[60,:],'$q(z_{60})$')"
]
}
],
"metadata": {
"colab": {
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -0,0 +1,388 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap18/18_2_1D_Diffusion_Model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 18.2: 1D Diffusion Model**\n",
"\n",
"This notebook investigates the diffusion encoder as described in section 18.3 and 18.4 of the book.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib.colors import ListedColormap\n",
"from operator import itemgetter\n",
"from scipy import stats\n",
"from IPython.display import display, clear_output"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4PM8bf6lO0VE"
},
"outputs": [],
"source": [
"#Create pretty colormap as in book\n",
"my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
"my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
"r = np.floor(my_colormap_vals_dec/(256*256))\n",
"g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
"b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
"my_colormap_vals = np.vstack((r,g,b)).transpose()/255.0\n",
"my_colormap = ListedColormap(my_colormap_vals)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ONGRaQscfIOo"
},
"outputs": [],
"source": [
"# Probability distribution for normal\n",
"def norm_pdf(x, mu, sigma):\n",
" return np.exp(-0.5 * (x-mu) * (x-mu) / (sigma * sigma)) / np.sqrt(2*np.pi*sigma*sigma)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gZvG0MKhfY8Y"
},
"outputs": [],
"source": [
"# True distribution is a mixture of four Gaussians\n",
"class TrueDataDistribution:\n",
" # Constructor initializes parameters\n",
" def __init__(self):\n",
" self.mu = [1.5, -0.216, 0.45, -1.875]\n",
" self.sigma = [0.3, 0.15, 0.525, 0.075]\n",
" self.w = [0.2, 0.3, 0.35, 0.15]\n",
"\n",
" # Return PDF\n",
" def pdf(self, x):\n",
" return(self.w[0] *norm_pdf(x,self.mu[0],self.sigma[0]) + self.w[1] *norm_pdf(x,self.mu[1],self.sigma[1]) + self.w[2] *norm_pdf(x,self.mu[2],self.sigma[2]) + self.w[3] *norm_pdf(x,self.mu[3],self.sigma[3]))\n",
"\n",
" # Draw samples\n",
" def sample(self, n):\n",
" hidden = np.random.choice(4, n, p=self.w)\n",
" epsilon = np.random.normal(size=(n))\n",
" mu_list = list(itemgetter(*hidden)(self.mu))\n",
" sigma_list = list(itemgetter(*hidden)(self.sigma))\n",
" return mu_list + sigma_list * epsilon"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "iJu_uBiaeUVv"
},
"outputs": [],
"source": [
"# Define ground truth probability distribution that we will model\n",
"true_dist = TrueDataDistribution()\n",
"# Let's visualize this\n",
"x_vals = np.arange(-3,3,0.01)\n",
"pr_x_true = true_dist.pdf(x_vals)\n",
"fig,ax = plt.subplots()\n",
"fig.set_size_inches(8,2.5)\n",
"ax.plot(x_vals, pr_x_true, 'r-')\n",
"ax.set_xlabel(\"$x$\")\n",
"ax.set_ylabel(\"$Pr(x)$\")\n",
"ax.set_ylim(0,1.0)\n",
"ax.set_xlim(-3,3)\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "DRHUG_41i4t_"
},
"source": [
"To train the model to describe this distribution, we'll need to generate pairs of samples drawn from $Pr(z_t|x)$ (diffusion kernel) and $q(z_{t-1}|z_{t},x)$ (equation 18.15).\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "x6B8t72Ukscd"
},
"outputs": [],
"source": [
"# The diffusion kernel returns the parameters of Pr(z_{t}|x)\n",
"def diffusion_kernel(x, t, beta):\n",
" alpha = np.power(1-beta,t)\n",
" dk_mean = x * np.sqrt(alpha)\n",
" dk_std = np.sqrt(1-alpha)\n",
" return dk_mean, dk_std\n",
"\n",
"# Compute mean and variance q(z_{t-1}|z_{t},x)\n",
"def conditional_diffusion_distribution(x,z_t,t,beta):\n",
" # TODO -- Implement this function\n",
" # Replace this line\n",
" cd_mean = 0; cd_std = 1\n",
"\n",
" return cd_mean, cd_std\n",
"\n",
"def get_data_pairs(x_train,t,beta):\n",
" # Find diffusion kernel for every x_train and draw samples\n",
" dk_mean, dk_std = diffusion_kernel(x_train, t, beta)\n",
" z_t = np.random.normal(size=x_train.shape) * dk_std + dk_mean\n",
" # Find conditional diffusion distribution for each x_train, z pair and draw samples\n",
" cd_mean, cd_std = conditional_diffusion_distribution(x_train,z_t,t,beta)\n",
" if t == 1:\n",
" z_tminus1 = x_train\n",
" else:\n",
" z_tminus1 = np.random.normal(size=x_train.shape) * cd_std + cd_mean\n",
"\n",
" return z_t, z_tminus1"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "aSG_4uA8_zZ-"
},
"source": [
"We also need models $\\text{f}_t[z_{t},\\phi_{t}]$ that map from $z_{t}$ to the mean of the distribution at time $z_{t-1}$. We're just going to use a very hacky non-parametric model (basically a lookup table) that tells you the result based on the (quantized) input."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZHViC0pL_yy5"
},
"outputs": [],
"source": [
"# This code is really ugly! Don't look too closely at it!\n",
"# All you need to know is that it is a model that trains from pairs zt, zt_minus1\n",
"# And can then predict zt\n",
"class NonParametricModel():\n",
" # Constructor initializes parameters\n",
" def __init__(self):\n",
"\n",
" self.inc = 0.01\n",
" self.max_val = 3.0\n",
" self.model = []\n",
"\n",
" # Learns a model that predicts z_t_minus1 given z_t\n",
" def train(self, zt, zt_minus1):\n",
" zt = np.clip(zt,-self.max_val,self.max_val)\n",
" zt_minus1 = np.clip(zt_minus1,-self.max_val,self.max_val)\n",
" bins = np.arange(-self.max_val,self.max_val+self.inc,self.inc)\n",
" numerator, *_ = stats.binned_statistic(zt, zt_minus1-zt, statistic='sum',bins=bins)\n",
" denominator, *_ = stats.binned_statistic(zt, zt_minus1-zt, statistic='count',bins=bins)\n",
" self.model = numerator / (denominator + 1)\n",
"\n",
" def predict(self, zt):\n",
" bin_index = np.floor((zt+self.max_val)/self.inc)\n",
" bin_index = np.clip(bin_index,0, len(self.model)-1).astype('uint32')\n",
" return zt + self.model[bin_index]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CzVFybWoBygu"
},
"outputs": [],
"source": [
"# Sample data from distribution (this would usually be our collected training set)\n",
"n_sample = 100000\n",
"x_train = true_dist.sample(n_sample)\n",
"\n",
"# Define model parameters\n",
"T = 100\n",
"beta = 0.01511\n",
"\n",
"all_models = []\n",
"for t in range(0,T):\n",
" clear_output(wait=True)\n",
" display(\"Training timestep %d\"%(t))\n",
" zt,zt_minus1 = get_data_pairs(x_train,t+1,beta)\n",
" all_models.append(NonParametricModel())\n",
" # The model at index t maps data from z_{t+1} to z_{t}\n",
" all_models[t].train(zt,zt_minus1)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ZPc9SEvtl14U"
},
"source": [
"Now that we've learned the model, let's draw some samples from it. We start at $z_{100}$ and use the model to predict $z_{99}$, then $z_{98}$ and so on until finally we get to $z_{1}$ and then $x$ (represented as $z_{0}$ here). We'll store all of the intermediate stages as well, so we can plot the trajectories. See equations 18.16."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "A-ZMFOvACIOw"
},
"outputs": [],
"source": [
"def sample(model, T, sigma_t, n_samples):\n",
" # Create the output array\n",
" # Each row represents a time step, first row will be sampled data\n",
" # Each column represents a different sample\n",
" samples = np.zeros((T+1,n_samples))\n",
"\n",
" # TODO -- Initialize the samples z_{T} at samples[T,:] from standard normal distribution\n",
" # Replace this line\n",
" samples[T,:] = np.zeros((1,n_samples))\n",
"\n",
"\n",
" # For t=100...99..98... ...0\n",
" for t in range(T,0,-1):\n",
" clear_output(wait=True)\n",
" display(\"Predicting z_{%d} from z_{%d}\"%(t-1,t))\n",
" # TODO Predict samples[t-1,:] from samples[t,:] using the appropriate model\n",
" # Replace this line:\n",
" samples[t-1,:] = np.zeros((1,n_samples))\n",
"\n",
"\n",
" # If not the last time step\n",
" if t>0:\n",
" # TODO Add noise to the samples at z_t-1 we just generated with mean zero, standard deviation sigma_t\n",
" # Replace this line\n",
" samples[t-1,:] = samples[t-1,:]\n",
"\n",
" return samples"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ECAUfHNi9NVW"
},
"source": [
"Now let's run the diffusion process for a whole bunch of samples"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "M-TY5w9Q8LYW"
},
"outputs": [],
"source": [
"sigma_t=0.12288\n",
"n_samples = 100000\n",
"samples = sample(all_models, T, sigma_t, n_samples)\n",
"\n",
"\n",
"# Plot the data\n",
"sampled_data = samples[0,:]\n",
"bins = np.arange(-3,3.05,0.05)\n",
"\n",
"fig,ax = plt.subplots()\n",
"fig.set_size_inches(8,2.5)\n",
"ax.set_xlim([-3,3])\n",
"plt.hist(sampled_data, bins=bins, density =True)\n",
"ax.set_ylim(0, 0.8)\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "jYrAW6tN-gJ4"
},
"source": [
"Let's, plot the evolution of a few of the paths as in figure 18.7 (paths are from bottom to top now)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4XU6CDZC_kFo"
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"t_vals = np.arange(0,101,1)\n",
"ax.plot(samples[:,0],t_vals,'r-')\n",
"ax.plot(samples[:,1],t_vals,'g-')\n",
"ax.plot(samples[:,2],t_vals,'b-')\n",
"ax.plot(samples[:,3],t_vals,'c-')\n",
"ax.plot(samples[:,4],t_vals,'m-')\n",
"ax.set_xlim([-3,3])\n",
"ax.set_ylim([101, 0])\n",
"ax.set_xlabel('value')\n",
"ax.set_ylabel('z_{t}')\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "SGTYGGevAktz"
},
"source": [
"Notice that the samples have a tendency to move from positions that are near the center at time 100 to positions that are high in the true probability distribution at time 0"
]
}
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyM4DdZDGoP1xGst+Nn+rwvt",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -0,0 +1,370 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap18/18_3_Reparameterized_Model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 18.3: 1D Reparameterized model**\n",
"\n",
"This notebook investigates the reparameterized model as described in section 18.5 of the book and implements algorithms 18.1 and 18.2.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib.colors import ListedColormap\n",
"from operator import itemgetter\n",
"from scipy import stats\n",
"from IPython.display import display, clear_output"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4PM8bf6lO0VE"
},
"outputs": [],
"source": [
"#Create pretty colormap as in book\n",
"my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
"my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
"r = np.floor(my_colormap_vals_dec/(256*256))\n",
"g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
"b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
"my_colormap_vals = np.vstack((r,g,b)).transpose()/255.0\n",
"my_colormap = ListedColormap(my_colormap_vals)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ONGRaQscfIOo"
},
"outputs": [],
"source": [
"# Probability distribution for normal\n",
"def norm_pdf(x, mu, sigma):\n",
" return np.exp(-0.5 * (x-mu) * (x-mu) / (sigma * sigma)) / np.sqrt(2*np.pi*sigma*sigma)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gZvG0MKhfY8Y"
},
"outputs": [],
"source": [
"# True distribution is a mixture of four Gaussians\n",
"class TrueDataDistribution:\n",
" # Constructor initializes parameters\n",
" def __init__(self):\n",
" self.mu = [1.5, -0.216, 0.45, -1.875]\n",
" self.sigma = [0.3, 0.15, 0.525, 0.075]\n",
" self.w = [0.2, 0.3, 0.35, 0.15]\n",
"\n",
" # Return PDF\n",
" def pdf(self, x):\n",
" return(self.w[0] *norm_pdf(x,self.mu[0],self.sigma[0]) + self.w[1] *norm_pdf(x,self.mu[1],self.sigma[1]) + self.w[2] *norm_pdf(x,self.mu[2],self.sigma[2]) + self.w[3] *norm_pdf(x,self.mu[3],self.sigma[3]))\n",
"\n",
" # Draw samples\n",
" def sample(self, n):\n",
" hidden = np.random.choice(4, n, p=self.w)\n",
" epsilon = np.random.normal(size=(n))\n",
" mu_list = list(itemgetter(*hidden)(self.mu))\n",
" sigma_list = list(itemgetter(*hidden)(self.sigma))\n",
" return mu_list + sigma_list * epsilon"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "iJu_uBiaeUVv"
},
"outputs": [],
"source": [
"# Define ground truth probability distribution that we will model\n",
"true_dist = TrueDataDistribution()\n",
"# Let's visualize this\n",
"x_vals = np.arange(-3,3,0.01)\n",
"pr_x_true = true_dist.pdf(x_vals)\n",
"fig,ax = plt.subplots()\n",
"fig.set_size_inches(8,2.5)\n",
"ax.plot(x_vals, pr_x_true, 'r-')\n",
"ax.set_xlabel(\"$x$\")\n",
"ax.set_ylabel(\"$Pr(x)$\")\n",
"ax.set_ylim(0,1.0)\n",
"ax.set_xlim(-3,3)\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "DRHUG_41i4t_"
},
"source": [
"To train the model to describe this distribution, we'll need to generate pairs of samples drawn from $Pr(z_t|x)$ (diffusion kernel) and $q(z_{t-1}|z_{t},x)$ (equation 18.15).\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "x6B8t72Ukscd"
},
"outputs": [],
"source": [
"# Return z_t (the argument of g_{t}[] in the loss function in algorithm 18.1) and epsilon\n",
"def get_data_pairs(x_train,t,beta):\n",
" # TODO -- write this function\n",
" # Replace these lines\n",
" epsilon = np.ones_like(x_train)\n",
" z_t = np.ones_like(x_train)\n",
"\n",
" return z_t, epsilon"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "aSG_4uA8_zZ-"
},
"source": [
"We also need models $\\text{g}_t[z_{t},\\phi_{t}]$ that map from $z_{t}$ to the noise $\\epsilon$ that was added. We're just going to use a very hacky non-parametric model (basically a lookup table) that tells you the result based on the (quantized) input."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZHViC0pL_yy5"
},
"outputs": [],
"source": [
"# This code is really ugly! Don't look too closely at it!\n",
"# All you need to know is that it is a model that trains from pairs zt, zt_minus1\n",
"# And can then predict zt\n",
"class NonParametricModel():\n",
" # Constructor initializes parameters\n",
" def __init__(self):\n",
"\n",
" self.inc = 0.01\n",
" self.max_val = 3.0\n",
" self.model = []\n",
"\n",
" # Learns a model that predicts epsilon given z_t\n",
" def train(self, zt, epsilon):\n",
" zt = np.clip(zt,-self.max_val,self.max_val)\n",
" epsilon = np.clip(epsilon,-self.max_val,self.max_val)\n",
" bins = np.arange(-self.max_val,self.max_val+self.inc,self.inc)\n",
" numerator, *_ = stats.binned_statistic(zt, epsilon, statistic='sum',bins=bins)\n",
" denominator, *_ = stats.binned_statistic(zt, epsilon, statistic='count',bins=bins)\n",
" self.model = numerator / (denominator + 1)\n",
"\n",
" def predict(self, zt):\n",
" bin_index = np.floor((zt+self.max_val)/self.inc)\n",
" bin_index = np.clip(bin_index,0, len(self.model)-1).astype('uint32')\n",
" return self.model[bin_index]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CzVFybWoBygu"
},
"outputs": [],
"source": [
"# Sample data from distribution (this would usually be our collected training set)\n",
"n_sample = 100000\n",
"x_train = true_dist.sample(n_sample)\n",
"\n",
"# Define model parameters\n",
"T = 100\n",
"beta = 0.01511\n",
"\n",
"all_models = []\n",
"for t in range(0,T):\n",
" clear_output(wait=True)\n",
" display(\"Training timestep %d\"%(t))\n",
" zt,epsilon= get_data_pairs(x_train,t,beta)\n",
" all_models.append(NonParametricModel())\n",
" # The model at index t maps data from z_{t+1} to epsilon\n",
" all_models[t].train(zt,epsilon)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ZPc9SEvtl14U"
},
"source": [
"Now that we've learned the model, let's draw some samples from it. We start at $z_{100}$ and use the model to predict $z_{99}$, then $z_{98}$ and so on until finally we get to $z_{1}$ and then $x$ (represented as $z_{0}$ here). We'll store all of the intermediate stages as well, so we can plot the trajectories. See algorithm 18.2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "A-ZMFOvACIOw"
},
"outputs": [],
"source": [
"def sample(model, T, sigma_t, n_samples):\n",
" # Create the output array\n",
" # Each row represents a time step, first row will be sampled data\n",
" # Each column represents a different sample\n",
" samples = np.zeros((T+1,n_samples))\n",
"\n",
" # TODO -- Initialize the samples z_{T} at samples[T,:] from standard normal distribution\n",
" # Replace this line\n",
" samples[T,:] = np.zeros((1,n_samples))\n",
"\n",
"\n",
"\n",
" # For t=100...99..98... ...0\n",
" for t in range(T,0,-1):\n",
" clear_output(wait=True)\n",
" display(\"Predicting z_{%d} from z_{%d}\"%(t-1,t))\n",
" # TODO Predict samples[t-1,:] from samples[t,:] using the appropriate model\n",
" # Replace this line:\n",
" samples[t-1,:] = np.zeros((1,n_samples))\n",
"\n",
"\n",
" # If not the last time step\n",
" if t>0:\n",
" # TODO Add noise to the samples at z_t-1 we just generated with mean zero, standard deviation sigma_t\n",
" # Replace this line\n",
" samples[t-1,:] = samples[t-1,:]\n",
"\n",
" return samples"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ECAUfHNi9NVW"
},
"source": [
"Now let's run the diffusion process for a whole bunch of samples"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "M-TY5w9Q8LYW"
},
"outputs": [],
"source": [
"sigma_t=0.12288\n",
"n_samples = 100000\n",
"samples = sample(all_models, T, sigma_t, n_samples)\n",
"\n",
"\n",
"# Plot the data\n",
"sampled_data = samples[0,:]\n",
"bins = np.arange(-3,3.05,0.05)\n",
"\n",
"fig,ax = plt.subplots()\n",
"fig.set_size_inches(8,2.5)\n",
"ax.set_xlim([-3,3])\n",
"plt.hist(sampled_data, bins=bins, density =True)\n",
"ax.set_ylim(0, 0.8)\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "jYrAW6tN-gJ4"
},
"source": [
"Let's, plot the evolution of a few of the paths as in figure 18.7 (paths are from bottom to top now)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4XU6CDZC_kFo"
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"t_vals = np.arange(0,101,1)\n",
"ax.plot(samples[:,0],t_vals,'r-')\n",
"ax.plot(samples[:,1],t_vals,'g-')\n",
"ax.plot(samples[:,2],t_vals,'b-')\n",
"ax.plot(samples[:,3],t_vals,'c-')\n",
"ax.plot(samples[:,4],t_vals,'m-')\n",
"ax.set_xlim([-3,3])\n",
"ax.set_ylim([101, 0])\n",
"ax.set_xlabel('value')\n",
"ax.set_ylabel('z_{t}')\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "SGTYGGevAktz"
},
"source": [
"Notice that the samples have a tendency to move from positions that are near the center at time 100 to positions that are high in the true probability distribution at time 0"
]
}
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyNd+D0/IVWXtU2GKsofyk2d",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -0,0 +1,494 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap18/18_4_Families_of_Diffusion_Models.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 18.4: Families of diffusion models**\n",
"\n",
"This notebook investigates the reparameterized model as described in section 18.5 of the book and computers the results shown in figure 18.10c-f. These models are based on the paper \"Denoising diffusion implicit models\" which can be found [here](https://arxiv.org/pdf/2010.02502.pdf).\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib.colors import ListedColormap\n",
"from operator import itemgetter\n",
"from scipy import stats\n",
"from IPython.display import display, clear_output"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4PM8bf6lO0VE"
},
"outputs": [],
"source": [
"#Create pretty colormap as in book\n",
"my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
"my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
"r = np.floor(my_colormap_vals_dec/(256*256))\n",
"g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
"b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
"my_colormap_vals = np.vstack((r,g,b)).transpose()/255.0\n",
"my_colormap = ListedColormap(my_colormap_vals)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ONGRaQscfIOo"
},
"outputs": [],
"source": [
"# Probability distribution for normal\n",
"def norm_pdf(x, mu, sigma):\n",
" return np.exp(-0.5 * (x-mu) * (x-mu) / (sigma * sigma)) / np.sqrt(2*np.pi*sigma*sigma)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gZvG0MKhfY8Y"
},
"outputs": [],
"source": [
"# True distribution is a mixture of four Gaussians\n",
"class TrueDataDistribution:\n",
" # Constructor initializes parameters\n",
" def __init__(self):\n",
" self.mu = [1.5, -0.216, 0.45, -1.875]\n",
" self.sigma = [0.3, 0.15, 0.525, 0.075]\n",
" self.w = [0.2, 0.3, 0.35, 0.15]\n",
"\n",
" # Return PDF\n",
" def pdf(self, x):\n",
" return(self.w[0] *norm_pdf(x,self.mu[0],self.sigma[0]) + self.w[1] *norm_pdf(x,self.mu[1],self.sigma[1]) + self.w[2] *norm_pdf(x,self.mu[2],self.sigma[2]) + self.w[3] *norm_pdf(x,self.mu[3],self.sigma[3]))\n",
"\n",
" # Draw samples\n",
" def sample(self, n):\n",
" hidden = np.random.choice(4, n, p=self.w)\n",
" epsilon = np.random.normal(size=(n))\n",
" mu_list = list(itemgetter(*hidden)(self.mu))\n",
" sigma_list = list(itemgetter(*hidden)(self.sigma))\n",
" return mu_list + sigma_list * epsilon"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "iJu_uBiaeUVv"
},
"outputs": [],
"source": [
"# Define ground truth probability distribution that we will model\n",
"true_dist = TrueDataDistribution()\n",
"# Let's visualize this\n",
"x_vals = np.arange(-3,3,0.01)\n",
"pr_x_true = true_dist.pdf(x_vals)\n",
"fig,ax = plt.subplots()\n",
"fig.set_size_inches(8,2.5)\n",
"ax.plot(x_vals, pr_x_true, 'r-')\n",
"ax.set_xlabel(\"$x$\")\n",
"ax.set_ylabel(\"$Pr(x)$\")\n",
"ax.set_ylim(0,1.0)\n",
"ax.set_xlim(-3,3)\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "DRHUG_41i4t_"
},
"source": [
"To train the model to describe this distribution, we'll need to generate pairs of samples drawn from $Pr(z_t|x)$ (diffusion kernel) and $q(z_{t-1}|z_{t},x)$ (equation 18.15).\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "x6B8t72Ukscd"
},
"outputs": [],
"source": [
"# Return z_t (the argument of g_{t}[] in the loss function in algorithm 18.1) and epsilon\n",
"def get_data_pairs(x_train,t,beta):\n",
"\n",
" epsilon = np.random.standard_normal(x_train.shape)\n",
" alpha_t = np.power(1-beta,t)\n",
" z_t = x_train * np.sqrt(alpha_t) + np.sqrt(1-alpha_t) * epsilon\n",
"\n",
" return z_t, epsilon"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "aSG_4uA8_zZ-"
},
"source": [
"We also need models $\\text{g}_t[z_{t},\\phi_{t}]$ that map from $z_{t}$ to the noise $\\epsilon$ that was added. We're just going to use a very hacky non-parametric model (basically a lookup table) that tells you the result based on the (quantized) input."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZHViC0pL_yy5"
},
"outputs": [],
"source": [
"# This code is really ugly! Don't look too closely at it!\n",
"# All you need to know is that it is a model that trains from pairs zt, zt_minus1\n",
"# And can then predict zt\n",
"class NonParametricModel():\n",
" # Constructor initializes parameters\n",
" def __init__(self):\n",
"\n",
" self.inc = 0.01\n",
" self.max_val = 3.0\n",
" self.model = []\n",
"\n",
" # Learns a model that predicts epsilon given z_t\n",
" def train(self, zt, epsilon):\n",
" zt = np.clip(zt,-self.max_val,self.max_val)\n",
" epsilon = np.clip(epsilon,-self.max_val,self.max_val)\n",
" bins = np.arange(-self.max_val,self.max_val+self.inc,self.inc)\n",
" numerator, *_ = stats.binned_statistic(zt, epsilon, statistic='sum',bins=bins)\n",
" denominator, *_ = stats.binned_statistic(zt, epsilon, statistic='count',bins=bins)\n",
" self.model = numerator / (denominator + 1)\n",
"\n",
" def predict(self, zt):\n",
" bin_index = np.floor((zt+self.max_val)/self.inc)\n",
" bin_index = np.clip(bin_index,0, len(self.model)-1).astype('uint32')\n",
" return self.model[bin_index]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CzVFybWoBygu"
},
"outputs": [],
"source": [
"# Sample data from distribution (this would usually be our collected training set)\n",
"n_sample = 100000\n",
"x_train = true_dist.sample(n_sample)\n",
"\n",
"# Define model parameters\n",
"T = 100\n",
"beta = 0.01511\n",
"\n",
"all_models = []\n",
"for t in range(0,T):\n",
" clear_output(wait=True)\n",
" display(\"Training timestep %d\"%(t))\n",
" zt,epsilon= get_data_pairs(x_train,t,beta)\n",
" all_models.append(NonParametricModel())\n",
" # The model at index t maps data from z_{t+1} to epsilon\n",
" all_models[t].train(zt,epsilon)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ZPc9SEvtl14U"
},
"source": [
"Now that we've learned the model, let's draw some samples from it. We start at $z_{100}$ and use the model to predict $z_{99}$, then $z_{98}$ and so on until finally we get to $z_{1}$ and then $x$ (represented as $z_{0}$ here). We'll store all of the intermediate stages as well, so we can plot the trajectories.\n",
"\n",
"This is the same model we learned last time. The whole point of this is that it is compatible with any forward process with the same diffusion kernel.\n",
"\n",
"One such model is the denoising diffusion implicit model, which has a sampling step:\n",
"\n",
"\\begin{equation}\n",
"\\mathbf{z}_{t-1} = \\sqrt{\\alpha_{t-1}}\\left(\\frac{\\mathbf{z}_{t}-\\sqrt{1-\\alpha_{t}}\\text{g}_t[\\mathbf{z}_{t},\\boldsymbol\\phi]}{\\sqrt{\\alpha_{t}}}\\right) + \\sqrt{1-\\alpha_{t-1}-\\sigma^2}\\text{g}_t[\\mathbf{z}_{t},\\boldsymbol\\phi]+\\sigma\\epsilon\n",
"\\end{equation}\n",
"\n",
"(see equation 12 of the denoising [diffusion implicit models paper ](https://arxiv.org/pdf/2010.02502.pdf).\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "A-ZMFOvACIOw"
},
"outputs": [],
"source": [
"def sample_ddim(model, T, sigma_t, n_samples):\n",
" # Create the output array\n",
" # Each row represents a time step, first row will be sampled data\n",
" # Each column represents a different sample\n",
" samples = np.zeros((T+1,n_samples))\n",
" samples[T,:] = np.random.standard_normal(n_samples)\n",
"\n",
" # For t=100...99..98... ...0\n",
" for t in range(T,0,-1):\n",
" clear_output(wait=True)\n",
" display(\"Predicting z_{%d} from z_{%d}\"%(t-1,t))\n",
"\n",
" alpha_t = np.power(1-beta,t+1)\n",
" alpha_t_minus1 = np.power(1-beta,t)\n",
"\n",
" # TODO -- implement the DDIM sampling step\n",
" # Note the final noise term is already added in the \"if\" statement below\n",
" # Replace this line:\n",
" samples[t-1,:] = samples[t-1,:]\n",
"\n",
" # If not the last time step\n",
" if t>0:\n",
" samples[t-1,:] = samples[t-1,:]+ np.random.standard_normal(n_samples) * sigma_t\n",
" return samples"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ECAUfHNi9NVW"
},
"source": [
"Now let's run the diffusion process for a whole bunch of samples"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "M-TY5w9Q8LYW"
},
"outputs": [],
"source": [
"# Now we'll set the noise to a MUCH smaller level\n",
"sigma_t=0.001\n",
"n_samples = 100000\n",
"samples_low_noise = sample_ddim(all_models, T, sigma_t, n_samples)\n",
"\n",
"\n",
"# Plot the data\n",
"sampled_data = samples_low_noise[0,:]\n",
"bins = np.arange(-3,3.05,0.05)\n",
"\n",
"fig,ax = plt.subplots()\n",
"fig.set_size_inches(8,2.5)\n",
"ax.set_xlim([-3,3])\n",
"plt.hist(sampled_data, bins=bins, density =True)\n",
"ax.set_ylim(0, 0.8)\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "jYrAW6tN-gJ4"
},
"source": [
"Let's, plot the evolution of a few of the paths as in figure 18.7 (paths are from bottom to top now)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4XU6CDZC_kFo"
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"t_vals = np.arange(0,101,1)\n",
"ax.plot(samples_low_noise[:,0],t_vals,'r-')\n",
"ax.plot(samples_low_noise[:,1],t_vals,'g-')\n",
"ax.plot(samples_low_noise[:,2],t_vals,'b-')\n",
"ax.plot(samples_low_noise[:,3],t_vals,'c-')\n",
"ax.plot(samples_low_noise[:,4],t_vals,'m-')\n",
"ax.set_xlim([-3,3])\n",
"ax.set_ylim([101, 0])\n",
"ax.set_xlabel('value')\n",
"ax.set_ylabel('z_{t}')\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "SGTYGGevAktz"
},
"source": [
"The samples have a tendency to move from positions that are near the center at time 100 to positions that are high in the true probability distribution at time 0"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "Z-LZp_fMXxRt"
},
"source": [
"Let's now sample from the accelerated model, that requires fewer models. Again, we don't need to learn anything new -- this is just the reverse process that corresponds to a different forward process that is compatible with the same diffusion kernel.\n",
"\n",
"There's nothing to do here except read the code. It uses the same DDIM model as you just implemented in the previous step, but it jumps timesteps five at a time."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3Z0erjGbYj1u"
},
"outputs": [],
"source": [
"def sample_accelerated(model, T, sigma_t, n_steps, n_samples):\n",
" # Create the output array\n",
" # Each row represents a sample (i.e. fewer than the time steps), first row will be sampled data\n",
" # Each column represents a different sample\n",
" samples = np.zeros((n_steps+1,n_samples))\n",
" samples[n_steps,:] = np.random.standard_normal(n_samples)\n",
"\n",
" # For each sampling step\n",
" for c_step in range(n_steps,0,-1):\n",
" # Find the corresponding time step and previous time step\n",
" t= int(T * c_step/n_steps)\n",
" tminus1 = int(T * (c_step-1)/n_steps)\n",
" display(\"Predicting z_{%d} from z_{%d}\"%(tminus1,t))\n",
"\n",
" alpha_t = np.power(1-beta,t+1)\n",
" alpha_t_minus1 = np.power(1-beta,tminus1+1)\n",
" epsilon_est = all_models[t-1].predict(samples[c_step,:])\n",
"\n",
" samples[c_step-1,:]=np.sqrt(alpha_t_minus1)*(samples[c_step,:]-np.sqrt(1-alpha_t) * epsilon_est)/np.sqrt(alpha_t) \\\n",
" + np.sqrt(1-alpha_t_minus1 - sigma_t*sigma_t) * epsilon_est\n",
" # If not the last time step\n",
" if t>0:\n",
" samples[c_step-1,:] = samples[c_step-1,:]+ np.random.standard_normal(n_samples) * sigma_t\n",
" return samples"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "D3Sm_WYrcuED"
},
"source": [
"Now let's draw a bunch of samples from the model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "UB45c7VMcGy-"
},
"outputs": [],
"source": [
"sigma_t=0.11\n",
"n_samples = 100000\n",
"n_steps = 20 # i.e. sample 5 times as fast as before -- should be a divisor of 100\n",
"samples_accelerated = sample_accelerated(all_models, T, sigma_t, n_steps, n_samples)\n",
"\n",
"\n",
"# Plot the data\n",
"sampled_data = samples_accelerated[0,:]\n",
"bins = np.arange(-3,3.05,0.05)\n",
"\n",
"fig,ax = plt.subplots()\n",
"fig.set_size_inches(8,2.5)\n",
"ax.set_xlim([-3,3])\n",
"plt.hist(sampled_data, bins=bins, density =True)\n",
"ax.set_ylim(0, 0.9)\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Luv-6w84c_qO"
},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"step_increment = 100/ n_steps\n",
"t_vals = np.arange(0,101,5)\n",
"\n",
"for i in range(len(t_vals)-1):\n",
" ax.plot( (samples_accelerated[i,0],samples_accelerated[i+1,0]), (t_vals[i], t_vals[i+1]),'r.-')\n",
" ax.plot( (samples_accelerated[i,1],samples_accelerated[i+1,1]), (t_vals[i], t_vals[i+1]),'g.-')\n",
" ax.plot( (samples_accelerated[i,2],samples_accelerated[i+1,2]), (t_vals[i], t_vals[i+1]),'b.-')\n",
" ax.plot( (samples_accelerated[i,3],samples_accelerated[i+1,3]), (t_vals[i], t_vals[i+1]),'c.-')\n",
" ax.plot( (samples_accelerated[i,4],samples_accelerated[i+1,4]), (t_vals[i], t_vals[i+1]),'m.-')\n",
"\n",
"ax.set_xlim([-3,3])\n",
"ax.set_ylim([101, 0])\n",
"ax.set_xlabel('value')\n",
"ax.set_ylabel('z_{t}')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LSJi72f0kw_e"
},
"outputs": [],
"source": []
}
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyNFSvISBXo/Z1l+onknF2Gw",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -0,0 +1,736 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyPg3umHnqmIXX6jGe809Nxf",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap19/19_1_Markov_Decision_Processes.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# **Notebook 19.1: Markov Decision Processes**\n",
"\n",
"This notebook investigates Markov decision processes as described in section 19.1 of the book.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
],
"metadata": {
"id": "t9vk9Elugvmi"
}
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image"
],
"metadata": {
"id": "OLComQyvCIJ7"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Get local copies of components of images\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Empty.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Hole.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Fish.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Penguin.png"
],
"metadata": {
"id": "ZsvrUszPLyEG"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Ugly class that takes care of drawing pictures like in the book.\n",
"# You can totally ignore this code!\n",
"class DrawMDP:\n",
" # Constructor initializes parameters\n",
" def __init__(self, n_row, n_col):\n",
" self.empty_image = np.asarray(Image.open('Empty.png'))\n",
" self.hole_image = np.asarray(Image.open('Hole.png'))\n",
" self.fish_image = np.asarray(Image.open('Fish.png'))\n",
" self.penguin_image = np.asarray(Image.open('Penguin.png'))\n",
" self.fig,self.ax = plt.subplots()\n",
" self.n_row = n_row\n",
" self.n_col = n_col\n",
"\n",
" my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
" my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
" r = np.floor(my_colormap_vals_dec/(256*256))\n",
" g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
" b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
" self.colormap = np.vstack((r,g,b)).transpose()/255.0\n",
"\n",
"\n",
" def draw_text(self, text, row, col, position, color):\n",
" if position == 'bc':\n",
" self.ax.text( 83*col+41,83 * (row+1) -10, text, horizontalalignment=\"center\", color=color, fontweight='bold')\n",
" if position == 'tl':\n",
" self.ax.text( 83*col+5,83 * row +5, text, verticalalignment = 'top', horizontalalignment=\"left\", color=color, fontweight='bold')\n",
"\n",
" # Draws a set of states\n",
" def draw_path(self, path, color1, color2):\n",
" for i in range(len(path)-1):\n",
" row_start = np.floor(path[i]/self.n_col)\n",
" row_end = np.floor(path[i+1]/self.n_col)\n",
" col_start = path[i] - row_start * self.n_col\n",
" col_end = path[i+1] - row_end * self.n_col\n",
"\n",
" color_index = int(np.floor(255 * i/(len(path)-1.)))\n",
" self.ax.plot([col_start * 83+41 + i, col_end * 83+41 + i ],[row_start * 83+41 + i, row_end * 83+41 + i ], color=(self.colormap[color_index,0],self.colormap[color_index,1],self.colormap[color_index,2]))\n",
"\n",
"\n",
" # Draw deterministic policy\n",
" def draw_deterministic_policy(self,i, action):\n",
" row = np.floor(i/self.n_col)\n",
" col = i - row * self.n_col\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 10\n",
" arrow_height = 15\n",
" # Draw arrow pointing upward\n",
" if action ==0:\n",
" triangle_indices = np.array([[center_x, center_y-arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y+arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y+arrow_height/2]])\n",
" # Draw arrow pointing right\n",
" if action ==1:\n",
" triangle_indices = np.array([[center_x + arrow_height/2, center_y],\n",
" [center_x - arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x - arrow_height/2, center_y+arrow_base_width/2]])\n",
" # Draw arrow pointing downward\n",
" if action ==2:\n",
" triangle_indices = np.array([[center_x, center_y+arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y-arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y-arrow_height/2]])\n",
" # Draw arrow pointing left\n",
" if action ==3:\n",
" triangle_indices = np.array([[center_x - arrow_height/2, center_y],\n",
" [center_x + arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x + arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw stochastic policy\n",
" def draw_stochastic_policy(self,i, action_probs):\n",
" row = np.floor(i/self.n_col)\n",
" col = i - row * self.n_col\n",
" offset = 20\n",
" # Draw arrow pointing upward\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41 - offset\n",
" arrow_base_width = 15 * action_probs[0]\n",
" arrow_height = 20 * action_probs[0]\n",
" triangle_indices = np.array([[center_x, center_y-arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y+arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y+arrow_height/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing right\n",
" center_x = 83 * col + 41 + offset\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 15 * action_probs[1]\n",
" arrow_height = 20 * action_probs[1]\n",
" triangle_indices = np.array([[center_x + arrow_height/2, center_y],\n",
" [center_x - arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x - arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing downward\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41 +offset\n",
" arrow_base_width = 15 * action_probs[2]\n",
" arrow_height = 20 * action_probs[2]\n",
" triangle_indices = np.array([[center_x, center_y+arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y-arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y-arrow_height/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing left\n",
" center_x = 83 * col + 41 -offset\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 15 * action_probs[3]\n",
" arrow_height = 20 * action_probs[3]\n",
" triangle_indices = np.array([[center_x - arrow_height/2, center_y],\n",
" [center_x + arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x + arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
"\n",
"\n",
"\n",
" def draw(self, layout, state, draw_state_index= False, rewards=None, policy=None, state_values=None, action_values=None,path1=None, path2 = None):\n",
" # Construct the image\n",
" image_out = np.zeros((self.n_row * 83, self.n_col * 83, 4),dtype='uint8')\n",
" for c_row in range (self.n_row):\n",
" for c_col in range(self.n_col):\n",
" if layout[c_row * self.n_col + c_col]==0:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.empty_image\n",
" elif layout[c_row * self.n_col + c_col]==1:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.hole_image\n",
" else:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.fish_image\n",
" if state == c_row * self.n_col + c_col:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.penguin_image\n",
"\n",
" # Draw the image\n",
" plt.imshow(image_out)\n",
" self.ax.get_xaxis().set_visible(False)\n",
" self.ax.get_yaxis().set_visible(False)\n",
" self.ax.spines['top'].set_visible(False)\n",
" self.ax.spines['right'].set_visible(False)\n",
" self.ax.spines['bottom'].set_visible(False)\n",
" self.ax.spines['left'].set_visible(False)\n",
"\n",
" if draw_state_index:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%d\"%(c_cell), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'tl','k')\n",
"\n",
" # Draw the policy as triangles\n",
" if policy is not None:\n",
" # If the policy is deterministic\n",
" if len(policy) == len(layout):\n",
" for i in range(len(layout)):\n",
" self.draw_deterministic_policy(i, policy[i])\n",
" # Else it is stochastic\n",
" else:\n",
" for i in range(len(layout)):\n",
" self.draw_stochastic_policy(i,policy[:,i])\n",
"\n",
"\n",
" if path1 is not None:\n",
" # self.draw_path(path1, np.array([0.81, 0.51, 0.38]), np.array([1.0, 0.2, 0.5]))\n",
" self.draw_path(path1, np.array([1.0, 0.0, 0.0]), np.array([0.0, 1.0, 1.0]))\n",
"\n",
"\n",
" plt.show()"
],
"metadata": {
"id": "Gq1HfJsHN3SB"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Let's draw the initial situation with the penguin in top right\n",
"n_rows = 4; n_cols = 4\n",
"layout = np.zeros(n_rows * n_cols)\n",
"initial_state = 0\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = initial_state, draw_state_index = True)"
],
"metadata": {
"id": "eBQ7lTpJQBSe"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Note that the states are indexed from 0 rather than 1 as in the book to make\n",
"the code neater."
],
"metadata": {
"id": "P7P40UyMunKb"
}
},
{
"cell_type": "code",
"source": [
"# Define the state probabilities\n",
"transition_probabilities = np.array( \\\n",
"[[0.00 , 0.33, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.33, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.33, 0.00, 0.50, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.34, 0.00, 0.00, 0.33, 0.00, 0.25, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.34, 0.00, 0.00, 0.25, 0.00, 0.33, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.50, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.33, 0.00, 0.25, 0.00, 0.00, 0.33, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.25, 0.00, 0.33, 0.00, 0.00, 0.33, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.50, 0.00, 0.33, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.34, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.34, 0.00 ],\n",
"])\n",
"initial_state = 0"
],
"metadata": {
"id": "wgFcIi4YQJWI"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define a step from the Markov process"
],
"metadata": {
"id": "axllRDDuDDLS"
}
},
{
"cell_type": "code",
"source": [
"def markov_process_step(state, transition_probabilities):\n",
" # TODO -- update the state according to the appropriate transition probabilities\n",
" # One way to do this is to use np.random.choice\n",
" # Replace this line:\n",
" new_state = 0\n",
"\n",
"\n",
" return new_state"
],
"metadata": {
"id": "FrSZrS67sdbN"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Run the Markov process for 10 steps and visualise the results"
],
"metadata": {
"id": "uTj7rN6LDFXd"
}
},
{
"cell_type": "code",
"source": [
"np.random.seed(0)\n",
"T = 10\n",
"states = np.zeros(T, dtype='uint8')\n",
"states[0] = 0\n",
"for t in range(T-1):\n",
" states[t+1] = markov_process_step(states[t], transition_probabilities)\n",
"\n",
"\n",
"\n",
"print(\"Your States:\", states)\n",
"print(\"True States: [ 0 4 8 9 10 9 10 9 13 14]\")\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = states[0], path1=states, draw_state_index = True)"
],
"metadata": {
"id": "lRIdjagCwP62"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define a Markov one step of a reward process."
],
"metadata": {
"id": "QLyjyBjjDMin"
}
},
{
"cell_type": "code",
"source": [
"def markov_reward_process_step(state, transition_probabilities, reward_structure):\n",
"\n",
" # TODO -- write this function\n",
" # Update the state. Return a reward of +1 if the Penguin lands on the fish\n",
" # or zero otherwise.\n",
" # Replace this line\n",
" new_state = 0; reward = 0\n",
"\n",
"\n",
" return new_state, reward"
],
"metadata": {
"id": "YPHSJRKx-pgO"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Run the Markov reward process for 10 steps and visualise the results"
],
"metadata": {
"id": "AIz8QEiRFoCm"
}
},
{
"cell_type": "code",
"source": [
"# Set up the reward structure so it matches figure 19.2\n",
"reward_structure = np.zeros((16,1))\n",
"reward_structure[3] = 1; reward_structure[8] = 1; reward_structure[10] = 1\n",
"\n",
"# Initialize random numbers\n",
"np.random.seed(0)\n",
"T = 10\n",
"# Set up the states, so the fish are in the same positions as figure 19.2\n",
"states = np.zeros(T, dtype='uint8')\n",
"rewards = np.zeros(T, dtype='uint8')\n",
"\n",
"states[0] = 0\n",
"for t in range(T-1):\n",
" states[t+1],rewards[t+1] = markov_reward_process_step(states[t], transition_probabilities, reward_structure)\n",
"\n",
"print(\"Your States:\", states)\n",
"print(\"Your Rewards:\", rewards)\n",
"print(\"True Rewards: [0 0 1 0 1 0 1 0 0 0]\")\n",
"\n",
"\n",
"# Draw the figure\n",
"layout = np.zeros(n_rows * n_cols)\n",
"layout[3] = 2; layout[8] = 2 ; layout[10] = 2\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = states[0], path1=states, draw_state_index = True)"
],
"metadata": {
"id": "0p1gCpGoFn4M"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Now let's calculate the return -- the sum of discounted future rewards"
],
"metadata": {
"id": "lyz47NWrITfj"
}
},
{
"cell_type": "code",
"source": [
"def calculate_return(rewards, gamma):\n",
" # TODO -- you write this function\n",
" # It should compute one return for the start of the sequence (i.e. G_1)\n",
" # Replace this line\n",
" return_val = 0.0\n",
"\n",
"\n",
" return return_val"
],
"metadata": {
"id": "4fEuBRPnFm_N"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"gamma = 0.9\n",
"for t in range(len(states)):\n",
" print(\"Return at time %d = %3.3f\"%(t, calculate_return(rewards[t:],gamma)))\n",
"\n",
"# Reality check!\n",
"print(\"True return at time 0: 1.998\")"
],
"metadata": {
"id": "o19lQgM3JrOz"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Now let's define the state transition function $Pr(s_{t+1}|s_{t},a)$ in full where $a$ is the actions. Here $a=0$ means try to go upward, $a=1$, right, $a=2$ down and $a=3$ right. However, the ice is slippery, so we don't always go the direction we want to.\n",
"\n",
"Note that as for the states, we've indexed the actions from zero (unlike in the book, so they map to the indices of arrays better)"
],
"metadata": {
"id": "Fhc6DzZNOjiC"
}
},
{
"cell_type": "code",
"source": [
"transition_probabilities_given_action1 = np.array(\\\n",
"[[0.00 , 0.33, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.33, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.33, 0.00, 0.50, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.34, 0.00, 0.00, 0.25, 0.00, 0.17, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.34, 0.00, 0.00, 0.17, 0.00, 0.25, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.50, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.75, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.25, 0.00, 0.17, 0.00, 0.00, 0.50, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.17, 0.00, 0.25, 0.00, 0.00, 0.50, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.75 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.25, 0.00, 0.25, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.25, 0.00, 0.25 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.25, 0.00 ],\n",
"])\n",
"\n",
"transition_probabilities_given_action2 = np.array(\\\n",
"[[0.00 , 0.25, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.75 , 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.50, 0.00, 0.50, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.25 , 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.25, 0.00, 0.00, 0.50, 0.00, 0.17, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.25, 0.00, 0.00, 0.50, 0.00, 0.33, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.50, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.50, 0.00, 0.17, 0.00, 0.00, 0.25, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.50, 0.00, 0.33, 0.00, 0.00, 0.25, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.75, 0.00, 0.25, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.50, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.50, 0.00 ],\n",
"])\n",
"\n",
"transition_probabilities_given_action3 = np.array(\\\n",
"[[0.00 , 0.25, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.25 , 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.25, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.75 , 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.50, 0.00, 0.00, 0.25, 0.00, 0.17, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.50, 0.00, 0.00, 0.16, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.75, 0.00, 0.00, 0.16, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.25, 0.00, 0.17, 0.00, 0.00, 0.33, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.16, 0.00, 0.25, 0.00, 0.00, 0.33, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.16, 0.00, 0.00, 0.00, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.50, 0.00, 0.33, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.34, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.34, 0.00 ],\n",
"])\n",
"\n",
"transition_probabilities_given_action4 = np.array(\\\n",
"[[0.00 , 0.25, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.50, 0.00, 0.75, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.25, 0.00, 0.00, 0.33, 0.00, 0.50, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.50, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.33, 0.00, 0.50, 0.00, 0.00, 0.25, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.17, 0.00, 0.50, 0.00, 0.00, 0.25, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.25 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.50, 0.00, 0.50, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.25, 0.00, 0.75 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.25, 0.00 ],\n",
"])\n",
"\n",
"# Store all of these in a three dimension array\n",
"# Pr(s_{t+1}=2|s_{t}=1, a_{t}=3] is stored at position [2,1,3]\n",
"transition_probabilities_given_action = np.concatenate((np.expand_dims(transition_probabilities_given_action1,2),\n",
" np.expand_dims(transition_probabilities_given_action2,2),\n",
" np.expand_dims(transition_probabilities_given_action3,2),\n",
" np.expand_dims(transition_probabilities_given_action4,2)),axis=2)"
],
"metadata": {
"id": "l7rT78BbOgTi"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Now we need a policy. Let's start with the deterministic policy in figure 19.5a:\n",
"policy = [2,2,1,1, 2,1,1,1, 1,1,0,2, 1,0,1,1]\n",
"\n",
"# Let's draw the policy first\n",
"layout = np.zeros(n_rows * n_cols)\n",
"layout[15] = 2\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = states[0], policy = policy, draw_state_index = True)"
],
"metadata": {
"id": "8jWhDlkaKj7Q"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def markov_decision_process_step_deterministic(state, transition_probabilities_given_action, reward_structure, policy):\n",
" # TODO -- complete this function.\n",
" # For each state, there's is a corresponding action.\n",
" # Draw the next state based on the current state and that action\n",
" # and calculate the reward\n",
" # Replace this line:\n",
" new_state = 0; reward = 0;\n",
"\n",
" return new_state, reward\n"
],
"metadata": {
"id": "dueNbS2SUVUK"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Set up the reward structure so it matches figure 19.2\n",
"reward_structure = np.zeros((16,1))\n",
"reward_structure[15] = 1\n",
"\n",
"# Initialize random number seed\n",
"np.random.seed(3)\n",
"T = 10\n",
"# Set up the states, so the fish are in the same positions as figure 19.5\n",
"states = np.zeros(T, dtype='uint8')\n",
"rewards = np.zeros(T, dtype='uint8')\n",
"\n",
"states[0] = 0\n",
"for t in range(T-1):\n",
" states[t+1],rewards[t+1] = markov_decision_process_step_deterministic(states[t], transition_probabilities_given_action, reward_structure, policy)\n",
"\n",
"print(\"Your States:\", states)\n",
"print(\"True States: [ 0 4 8 9 13 14 15 11 7 3]\")\n",
"print(\"Your Rewards:\", rewards)\n",
"print(\"True Rewards: [0 0 0 0 0 0 1 0 0 0]\")\n",
"\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = states[0], path1=states, policy = policy, draw_state_index = True)"
],
"metadata": {
"id": "4Du5aUfd2Lci"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"You can see that the Penguin usually follows the policy, (heads in the direction of the cyan arrows (when it can). But sometimes, the penguin \"slips\" to a different neighboring state\n",
"\n",
"Now let's investigate a stochastic policy"
],
"metadata": {
"id": "bLEd8xug33b-"
}
},
{
"cell_type": "code",
"source": [
"np.random.seed(0)\n",
"# Let's now choose a random policy. We'll generate a set of random numbers and pass\n",
"# them through a softmax function\n",
"stochastic_policy = np.random.normal(size=(4,n_rows*n_cols))\n",
"stochastic_policy = np.exp(stochastic_policy) / (np.ones((4,1))@ np.expand_dims(np.sum(np.exp(stochastic_policy), axis=0),0))\n",
"np.set_printoptions(precision=2)\n",
"print(stochastic_policy)\n",
"\n",
"# Let's draw the policy first\n",
"layout = np.zeros(n_rows * n_cols)\n",
"layout[15] = 2\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = states[0], path1=states, policy = stochastic_policy, draw_state_index = True)"
],
"metadata": {
"id": "o7T0b3tyilDc"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def markov_decision_process_step_stochastic(state, transition_probabilities_given_action, reward_structure, stochastic_policy):\n",
" # TODO -- complete this function.\n",
" # For each state, there's is a corresponding distribution over actions\n",
" # Draw a sample from that distribution to get the action\n",
" # Draw the next state based on the current state and that action\n",
" # and calculate the reward\n",
" # Replace this line:\n",
" new_state = 0; reward = 0;action = 0\n",
"\n",
"\n",
"\n",
" return new_state, reward, action"
],
"metadata": {
"id": "T68mTZSe6A3w"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Set up the reward structure so it matches figure 19.2\n",
"reward_structure = np.zeros((16,1))\n",
"reward_structure[15] = 1\n",
"\n",
"# Initialize random number seed\n",
"np.random.seed(0)\n",
"T = 10\n",
"# Set up the states, so the fish are in the same positions as figure 19.5\n",
"states = np.zeros(T, dtype='uint8')\n",
"rewards = np.zeros(T, dtype='uint8')\n",
"actions = np.zeros(T-1, dtype='uint8')\n",
"\n",
"states[0] = 0\n",
"for t in range(T-1):\n",
" states[t+1],rewards[t+1],actions[t] = markov_decision_process_step_stochastic(states[t], transition_probabilities_given_action, reward_structure, stochastic_policy)\n",
"\n",
"print(\"Actions\", actions)\n",
"print(\"Your States:\", states)\n",
"print(\"Your Rewards:\", rewards)\n",
"\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = states[0], path1=states, policy = stochastic_policy, draw_state_index = True)"
],
"metadata": {
"id": "hMRVYX2HtqMg"
},
"execution_count": null,
"outputs": []
}
]
}

View File

@@ -0,0 +1,530 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOlD6kmCxX3SKKuh3oJikKA",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap19/19_2_Dynamic_Programming.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# **Notebook 19.2: Dynamic programming**\n",
"\n",
"This notebook investigates the dynamic programming approach to tabular reinforcement learning as described in figure 19.10 of the book.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
],
"metadata": {
"id": "t9vk9Elugvmi"
}
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image"
],
"metadata": {
"id": "OLComQyvCIJ7"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Get local copies of components of images\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Empty.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Hole.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Fish.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Penguin.png"
],
"metadata": {
"id": "ZsvrUszPLyEG"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Ugly class that takes care of drawing pictures like in the book.\n",
"# You can totally ignore this code!\n",
"class DrawMDP:\n",
" # Constructor initializes parameters\n",
" def __init__(self, n_row, n_col):\n",
" self.empty_image = np.asarray(Image.open('Empty.png'))\n",
" self.hole_image = np.asarray(Image.open('Hole.png'))\n",
" self.fish_image = np.asarray(Image.open('Fish.png'))\n",
" self.penguin_image = np.asarray(Image.open('Penguin.png'))\n",
" self.fig,self.ax = plt.subplots()\n",
" self.n_row = n_row\n",
" self.n_col = n_col\n",
"\n",
" my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
" my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
" r = np.floor(my_colormap_vals_dec/(256*256))\n",
" g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
" b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
" self.colormap = np.vstack((r,g,b)).transpose()/255.0\n",
"\n",
"\n",
" def draw_text(self, text, row, col, position, color):\n",
" if position == 'bc':\n",
" self.ax.text( 83*col+41,83 * (row+1) -10, text, horizontalalignment=\"center\", color=color, fontweight='bold')\n",
" if position == 'tl':\n",
" self.ax.text( 83*col+5,83 * row +5, text, verticalalignment = 'top', horizontalalignment=\"left\", color=color, fontweight='bold')\n",
" if position == 'tr':\n",
" self.ax.text( 83*(col+1)-5, 83 * row +5, text, verticalalignment = 'top', horizontalalignment=\"right\", color=color, fontweight='bold')\n",
"\n",
" # Draws a set of states\n",
" def draw_path(self, path, color1, color2):\n",
" for i in range(len(path)-1):\n",
" row_start = np.floor(path[i]/self.n_col)\n",
" row_end = np.floor(path[i+1]/self.n_col)\n",
" col_start = path[i] - row_start * self.n_col\n",
" col_end = path[i+1] - row_end * self.n_col\n",
"\n",
" color_index = int(np.floor(255 * i/(len(path)-1.)))\n",
" self.ax.plot([col_start * 83+41 + i, col_end * 83+41 + i ],[row_start * 83+41 + i, row_end * 83+41 + i ], color=(self.colormap[color_index,0],self.colormap[color_index,1],self.colormap[color_index,2]))\n",
"\n",
"\n",
" # Draw deterministic policy\n",
" def draw_deterministic_policy(self,i, action):\n",
" row = np.floor(i/self.n_col)\n",
" col = i - row * self.n_col\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 10\n",
" arrow_height = 15\n",
" # Draw arrow pointing upward\n",
" if action ==0:\n",
" triangle_indices = np.array([[center_x, center_y-arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y+arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y+arrow_height/2]])\n",
" # Draw arrow pointing right\n",
" if action ==1:\n",
" triangle_indices = np.array([[center_x + arrow_height/2, center_y],\n",
" [center_x - arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x - arrow_height/2, center_y+arrow_base_width/2]])\n",
" # Draw arrow pointing downward\n",
" if action ==2:\n",
" triangle_indices = np.array([[center_x, center_y+arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y-arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y-arrow_height/2]])\n",
" # Draw arrow pointing left\n",
" if action ==3:\n",
" triangle_indices = np.array([[center_x - arrow_height/2, center_y],\n",
" [center_x + arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x + arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw stochastic policy\n",
" def draw_stochastic_policy(self,i, action_probs):\n",
" row = np.floor(i/self.n_col)\n",
" col = i - row * self.n_col\n",
" offset = 20\n",
" # Draw arrow pointing upward\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41 - offset\n",
" arrow_base_width = 15 * action_probs[0]\n",
" arrow_height = 20 * action_probs[0]\n",
" triangle_indices = np.array([[center_x, center_y-arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y+arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y+arrow_height/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing right\n",
" center_x = 83 * col + 41 + offset\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 15 * action_probs[1]\n",
" arrow_height = 20 * action_probs[1]\n",
" triangle_indices = np.array([[center_x + arrow_height/2, center_y],\n",
" [center_x - arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x - arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing downward\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41 +offset\n",
" arrow_base_width = 15 * action_probs[2]\n",
" arrow_height = 20 * action_probs[2]\n",
" triangle_indices = np.array([[center_x, center_y+arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y-arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y-arrow_height/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing left\n",
" center_x = 83 * col + 41 -offset\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 15 * action_probs[3]\n",
" arrow_height = 20 * action_probs[3]\n",
" triangle_indices = np.array([[center_x - arrow_height/2, center_y],\n",
" [center_x + arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x + arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
"\n",
" def draw(self, layout, state=None, draw_state_index= False, rewards=None, policy=None, state_values=None, action_values=None,path1=None, path2 = None):\n",
" # Construct the image\n",
" image_out = np.zeros((self.n_row * 83, self.n_col * 83, 4),dtype='uint8')\n",
" for c_row in range (self.n_row):\n",
" for c_col in range(self.n_col):\n",
" if layout[c_row * self.n_col + c_col]==0:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.empty_image\n",
" elif layout[c_row * self.n_col + c_col]==1:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.hole_image\n",
" else:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.fish_image\n",
" if state is not None and state == c_row * self.n_col + c_col:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.penguin_image\n",
"\n",
" # Draw the image\n",
" plt.imshow(image_out)\n",
" self.ax.get_xaxis().set_visible(False)\n",
" self.ax.get_yaxis().set_visible(False)\n",
" self.ax.spines['top'].set_visible(False)\n",
" self.ax.spines['right'].set_visible(False)\n",
" self.ax.spines['bottom'].set_visible(False)\n",
" self.ax.spines['left'].set_visible(False)\n",
"\n",
" if draw_state_index:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%d\"%(c_cell), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'tl','k')\n",
"\n",
" # Draw the policy as triangles\n",
" if policy is not None:\n",
" # If the policy is deterministic\n",
" if len(policy) == len(layout):\n",
" for i in range(len(layout)):\n",
" self.draw_deterministic_policy(i, policy[i])\n",
" # Else it is stochastic\n",
" else:\n",
" for i in range(len(layout)):\n",
" self.draw_stochastic_policy(i,policy[:,i])\n",
"\n",
"\n",
" if path1 is not None:\n",
" self.draw_path(path1, np.array([1.0, 0.0, 0.0]), np.array([0.0, 1.0, 1.0]))\n",
"\n",
" if rewards is not None:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%d\"%(rewards[c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'tr','r')\n",
"\n",
" if state_values is not None:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%2.2f\"%(state_values[c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'bc','hotpink')\n",
"\n",
"\n",
" plt.show()"
],
"metadata": {
"id": "Gq1HfJsHN3SB"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# We're going to work on the problem depicted in figure 19.10a\n",
"n_rows = 4; n_cols = 4\n",
"layout = np.zeros(n_rows * n_cols)\n",
"rewards = np.zeros(n_rows * n_cols)\n",
"layout[9] = 1 ; rewards[9] = -2\n",
"layout[10] = 1; rewards[10] = -2\n",
"layout[14] = 1; rewards[14] = -2\n",
"layout[15] = 2; rewards[15] = 3\n",
"initial_state = 0\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = initial_state, rewards=rewards, draw_state_index = True)"
],
"metadata": {
"id": "eBQ7lTpJQBSe"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"For clarity, the black numbers are the state number and the red numbers are the reward for being in that state. Note that the states are indexed from 0 rather than 1 as in the book to make the code neater."
],
"metadata": {
"id": "6Vku6v_se2IG"
}
},
{
"cell_type": "markdown",
"source": [
"Define a step from the Markov process"
],
"metadata": {
"id": "axllRDDuDDLS"
}
},
{
"cell_type": "markdown",
"source": [
"Now let's define the state transition function $Pr(s_{t+1}|s_{t},a)$ in full where $a$ is the actions. Here $a=0$ means try to go upward, $a=1$, right, $a=2$ down and $a=3$ right. However, the ice is slippery, so we don't always go the direction we want to.\n",
"\n",
"Note that as for the states, we've indexed the actions from zero (unlike in the book) so they map to the indices of arrays better"
],
"metadata": {
"id": "Fhc6DzZNOjiC"
}
},
{
"cell_type": "code",
"source": [
"transition_probabilities_given_action0 = np.array(\\\n",
"[[0.00 , 0.33, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.33, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.33, 0.00, 0.50, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.34, 0.00, 0.00, 0.25, 0.00, 0.17, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.34, 0.00, 0.00, 0.17, 0.00, 0.25, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.50, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.75, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.25, 0.00, 0.17, 0.00, 0.00, 0.50, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.17, 0.00, 0.25, 0.00, 0.00, 0.50, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.75 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.25, 0.00, 0.25, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.25, 0.00, 0.25 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.25, 0.00 ],\n",
"])\n",
"\n",
"transition_probabilities_given_action1 = np.array(\\\n",
"[[0.00 , 0.25, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.75 , 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.50, 0.00, 0.50, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.25 , 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.25, 0.00, 0.00, 0.50, 0.00, 0.17, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.25, 0.00, 0.00, 0.50, 0.00, 0.33, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.50, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.50, 0.00, 0.17, 0.00, 0.00, 0.25, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.50, 0.00, 0.33, 0.00, 0.00, 0.25, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.75, 0.00, 0.25, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.50, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.50, 0.00 ],\n",
"])\n",
"\n",
"transition_probabilities_given_action2 = np.array(\\\n",
"[[0.00 , 0.25, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.25 , 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.25, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.75 , 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.50, 0.00, 0.00, 0.25, 0.00, 0.17, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.50, 0.00, 0.00, 0.16, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.75, 0.00, 0.00, 0.16, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.17, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.25, 0.00, 0.17, 0.00, 0.00, 0.33, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.16, 0.00, 0.25, 0.00, 0.00, 0.33, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.16, 0.00, 0.00, 0.00, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.33, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.50, 0.00, 0.33, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.34, 0.00, 0.50 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.34, 0.00 ],\n",
"])\n",
"\n",
"transition_probabilities_given_action3 = np.array(\\\n",
"[[0.00 , 0.25, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.50, 0.00, 0.75, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.50, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.50 , 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.33, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.25, 0.00, 0.00, 0.33, 0.00, 0.50, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.50, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00, 0.50, 0.00, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.33, 0.00, 0.50, 0.00, 0.00, 0.25, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.17, 0.00, 0.50, 0.00, 0.00, 0.25, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.17, 0.00, 0.00, 0.00, 0.00, 0.25 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.34, 0.00, 0.00, 0.00, 0.00, 0.50, 0.00, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.50, 0.00, 0.50, 0.00 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.16, 0.00, 0.00, 0.25, 0.00, 0.75 ],\n",
" [0.00 , 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.25, 0.00, 0.00, 0.25, 0.00 ],\n",
"])\n",
"\n",
"# Store all of these in a three dimension array\n",
"# Pr(s_{t+1}=2|s_{t}=1, a_{t}=3] is stored at position [2,1,3]\n",
"transition_probabilities_given_action = np.concatenate((np.expand_dims(transition_probabilities_given_action0,2),\n",
" np.expand_dims(transition_probabilities_given_action1,2),\n",
" np.expand_dims(transition_probabilities_given_action2,2),\n",
" np.expand_dims(transition_probabilities_given_action3,2)),axis=2)"
],
"metadata": {
"id": "l7rT78BbOgTi"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Update the state values for the current policy, by making the values at at adjacent\n",
"# states compatible with the Bellman equation (equation 19.11)\n",
"def policy_evaluation(policy, state_values, rewards, transition_probabilities_given_action, gamma):\n",
"\n",
" n_state = len(state_values)\n",
" state_values_new = np.zeros_like(state_values)\n",
"\n",
" for state in range(n_state):\n",
" # Special case -- bottom right is terminating state, always just rewards 3.0\n",
" if state == 15:\n",
" state_values_new[state] = 3.0\n",
" break\n",
"\n",
" return state_values_new\n",
"\n",
"# Greedily choose the action that maximizes the value for each state.\n",
"def policy_improvement(state_values, rewards, transition_probabilities_given_action, gamma):\n",
" policy = np.zeros_like(state_values, dtype='uint8')\n",
" for state in range(15):\n",
" # TODO -- Write this function (from equation 19.12)\n",
" # Replace this line\n",
" policy[state] = 1\n",
"\n",
"\n",
" return policy\n",
"\n",
"\n",
"# Main routine -- alternately call policy evaluation and policy improvement\n",
"def dynamic_programming(policy, state_values, rewards, transition_probabilities_given_action, gamma, n_iter, verbose = False):\n",
"\n",
" for c_iter in range(n_iter):\n",
" print(\"Iteration %d\"%(c_iter))\n",
"\n",
" state_values = policy_evaluation(policy, state_values, rewards, transition_probabilities_given_action, gamma)\n",
"\n",
" if verbose:\n",
" print(\"Updated state values\")\n",
" print(\"Policy: \", policy)\n",
" print(\"State values:\", state_values)\n",
" mdp_drawer = DrawMDP(n_rows, n_cols)\n",
" mdp_drawer.draw(layout, policy = policy, state_values=state_values)\n",
"\n",
" policy = policy_improvement(state_values, rewards, transition_probabilities_given_action, gamma)\n",
"\n",
" if verbose:\n",
" print(\"Updated policy values\")\n",
" print(\"Policy:\", policy)\n",
" print(\"State_values\", state_values)\n",
" mdp_drawer = DrawMDP(n_rows, n_cols)\n",
" mdp_drawer.draw(layout, policy = policy, state_values=state_values)\n",
"\n",
" return policy, state_values\n"
],
"metadata": {
"id": "bFYvF9nAloIA"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Set seed so random numbers always the same\n",
"np.random.seed(0)\n",
"\n",
"# Let's start with by setting the policy randomly\n",
"policy = np.random.choice(size= n_rows * n_cols, a=np.arange(0,4,1))\n",
"state_values = np.zeros(n_rows* n_cols)\n",
"\n",
"# Let's draw the policy first\n",
"print(\"Initial state\")\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, rewards = rewards, state_values=state_values, draw_state_index = True)\n",
"\n",
"n_iter = 2\n",
"gamma = 0.9\n",
"policy, state_values = dynamic_programming(policy, state_values, rewards, transition_probabilities_given_action, gamma, n_iter, verbose=True)\n",
"\n",
"print(\"Your state values=\", state_values)\n",
"print(\"True values= [ 0. 0. 0. 0. 0. -0.288 -0.288 0. -0.45 -2.288 -2.594 0.9 0. -0.9 -1.1 3. ] \", )"
],
"metadata": {
"id": "8jWhDlkaKj7Q"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Now let's run it for a series of iterations without drawing."
],
"metadata": {
"id": "wdcecFKlx97N"
}
},
{
"cell_type": "code",
"source": [
"# Set seed so random numbers always the same\n",
"np.random.seed(0)\n",
"\n",
"# Let's start with by setting the policy randomly\n",
"policy = np.random.choice(size= n_rows * n_cols, a=np.arange(0,4,1))\n",
"state_values = np.zeros(n_rows* n_cols)\n",
"\n",
"# Let's draw the policy first\n",
"print(\"Initial state\")\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, rewards = rewards, state_values=state_values, draw_state_index = True)\n",
"\n",
"n_iter = 20\n",
"gamma = 0.9\n",
"policy, state_values = dynamic_programming(policy, state_values, rewards, transition_probabilities_given_action, gamma, n_iter, verbose=False)\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, rewards = rewards, state_values=state_values, draw_state_index = True)\n",
"\n"
],
"metadata": {
"id": "rtsLUwi6ZEWL"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"You should see that if we start at state 13, the actions have been selected to go all the way around the holes in the ice (keeping a wide berth to avoid slipping into them) and eventually converge on the fish."
],
"metadata": {
"id": "tvXOs9VhyWnh"
}
}
]
}

View File

@@ -0,0 +1,749 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap19/19_3_Monte_Carlo_Methods.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 19.3: Monte-Carlo methods**\n",
"\n",
"This notebook investigates Monte Carlo methods for tabular reinforcement learning as described in section 19.3.2 of the book\n",
"\n",
"NOTE! There is a mistake in Figure 19.11 in the first printing of the book, so check the errata to avoid becoming confused. Apologies!\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n",
"\n",
"Thanks to [Akshil Patel](https://www.akshilpatel.com) and [Jessica Nicholson](https://jessicanicholson1.github.io) for their help in preparing this notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image\n",
"\n",
"from IPython.display import clear_output\n",
"from time import sleep"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZsvrUszPLyEG"
},
"outputs": [],
"source": [
"# Get local copies of components of images\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Empty.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Hole.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Fish.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Penguin.png"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Gq1HfJsHN3SB"
},
"outputs": [],
"source": [
"# Ugly class that takes care of drawing pictures like in the book.\n",
"# You can totally ignore this code!\n",
"class DrawMDP:\n",
" # Constructor initializes parameters\n",
" def __init__(self, n_row, n_col):\n",
" self.empty_image = np.asarray(Image.open('Empty.png'))\n",
" self.hole_image = np.asarray(Image.open('Hole.png'))\n",
" self.fish_image = np.asarray(Image.open('Fish.png'))\n",
" self.penguin_image = np.asarray(Image.open('Penguin.png'))\n",
" self.fig,self.ax = plt.subplots()\n",
" self.n_row = n_row\n",
" self.n_col = n_col\n",
"\n",
" my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
" my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
" r = np.floor(my_colormap_vals_dec/(256*256))\n",
" g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
" b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
" self.colormap = np.vstack((r,g,b)).transpose()/255.0\n",
"\n",
"\n",
" def draw_text(self, text, row, col, position, color):\n",
" if position == 'bc':\n",
" self.ax.text( 83*col+41,83 * (row+1) -5, text, horizontalalignment=\"center\", color=color, fontweight='bold')\n",
" if position == 'tc':\n",
" self.ax.text( 83*col+41,83 * (row) +10, text, horizontalalignment=\"center\", color=color, fontweight='bold')\n",
" if position == 'lc':\n",
" self.ax.text( 83*col+2,83 * (row) +41, text, verticalalignment=\"center\", color=color, fontweight='bold', rotation=90)\n",
" if position == 'rc':\n",
" self.ax.text( 83*(col+1)-5,83 * (row) +41, text, horizontalalignment=\"right\", verticalalignment=\"center\", color=color, fontweight='bold', rotation=-90)\n",
" if position == 'tl':\n",
" self.ax.text( 83*col+5,83 * row +5, text, verticalalignment = 'top', horizontalalignment=\"left\", color=color, fontweight='bold')\n",
" if position == 'tr':\n",
" self.ax.text( 83*(col+1)-5, 83 * row +5, text, verticalalignment = 'top', horizontalalignment=\"right\", color=color, fontweight='bold')\n",
"\n",
" # Draws a set of states\n",
" def draw_path(self, path, color1, color2):\n",
" for i in range(len(path)-1):\n",
" row_start = np.floor(path[i]/self.n_col)\n",
" row_end = np.floor(path[i+1]/self.n_col)\n",
" col_start = path[i] - row_start * self.n_col\n",
" col_end = path[i+1] - row_end * self.n_col\n",
"\n",
" color_index = int(np.floor(255 * i/(len(path)-1.)))\n",
" self.ax.plot([col_start * 83+41 + i, col_end * 83+41 + i ],[row_start * 83+41 + i, row_end * 83+41 + i ], color=(self.colormap[color_index,0],self.colormap[color_index,1],self.colormap[color_index,2]))\n",
"\n",
"\n",
" # Draw deterministic policy\n",
" def draw_deterministic_policy(self,i, action):\n",
" row = np.floor(i/self.n_col)\n",
" col = i - row * self.n_col\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 10\n",
" arrow_height = 15\n",
" # Draw arrow pointing upward\n",
" if action ==0:\n",
" triangle_indices = np.array([[center_x, center_y-arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y+arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y+arrow_height/2]])\n",
" # Draw arrow pointing right\n",
" if action ==1:\n",
" triangle_indices = np.array([[center_x + arrow_height/2, center_y],\n",
" [center_x - arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x - arrow_height/2, center_y+arrow_base_width/2]])\n",
" # Draw arrow pointing downward\n",
" if action ==2:\n",
" triangle_indices = np.array([[center_x, center_y+arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y-arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y-arrow_height/2]])\n",
" # Draw arrow pointing left\n",
" if action ==3:\n",
" triangle_indices = np.array([[center_x - arrow_height/2, center_y],\n",
" [center_x + arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x + arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw stochastic policy\n",
" def draw_stochastic_policy(self,i, action_probs):\n",
" row = np.floor(i/self.n_col)\n",
" col = i - row * self.n_col\n",
" offset = 20\n",
" # Draw arrow pointing upward\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41 - offset\n",
" arrow_base_width = 15 * action_probs[0]\n",
" arrow_height = 20 * action_probs[0]\n",
" triangle_indices = np.array([[center_x, center_y-arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y+arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y+arrow_height/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing right\n",
" center_x = 83 * col + 41 + offset\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 15 * action_probs[1]\n",
" arrow_height = 20 * action_probs[1]\n",
" triangle_indices = np.array([[center_x + arrow_height/2, center_y],\n",
" [center_x - arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x - arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing downward\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41 +offset\n",
" arrow_base_width = 15 * action_probs[2]\n",
" arrow_height = 20 * action_probs[2]\n",
" triangle_indices = np.array([[center_x, center_y+arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y-arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y-arrow_height/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing left\n",
" center_x = 83 * col + 41 -offset\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 15 * action_probs[3]\n",
" arrow_height = 20 * action_probs[3]\n",
" triangle_indices = np.array([[center_x - arrow_height/2, center_y],\n",
" [center_x + arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x + arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
"\n",
" def draw(self, layout, state=None, draw_state_index= False, rewards=None, policy=None, state_values=None, state_action_values=None,path1=None, path2 = None):\n",
" # Construct the image\n",
" image_out = np.zeros((self.n_row * 83, self.n_col * 83, 4),dtype='uint8')\n",
" for c_row in range (self.n_row):\n",
" for c_col in range(self.n_col):\n",
" if layout[c_row * self.n_col + c_col]==0:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.empty_image\n",
" elif layout[c_row * self.n_col + c_col]==1:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.hole_image\n",
" else:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.fish_image\n",
" if state is not None and state == c_row * self.n_col + c_col:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.penguin_image\n",
"\n",
" # Draw the image\n",
" plt.imshow(image_out)\n",
" self.ax.get_xaxis().set_visible(False)\n",
" self.ax.get_yaxis().set_visible(False)\n",
" self.ax.spines['top'].set_visible(False)\n",
" self.ax.spines['right'].set_visible(False)\n",
" self.ax.spines['bottom'].set_visible(False)\n",
" self.ax.spines['left'].set_visible(False)\n",
"\n",
" if draw_state_index:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%d\"%(c_cell), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'tl','k')\n",
"\n",
" # Draw the policy as triangles\n",
" if policy is not None:\n",
" # If the policy is deterministic\n",
" if len(policy) == len(layout):\n",
" for i in range(len(layout)):\n",
" self.draw_deterministic_policy(i, policy[i])\n",
" # Else it is stochastic\n",
" else:\n",
" for i in range(len(layout)):\n",
" self.draw_stochastic_policy(i,policy[:,i])\n",
"\n",
"\n",
" if path1 is not None:\n",
" self.draw_path(path1, np.array([1.0, 0.0, 0.0]), np.array([0.0, 1.0, 1.0]))\n",
"\n",
" if rewards is not None:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%d\"%(rewards[c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'tr','r')\n",
"\n",
" if state_values is not None:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%2.2f\"%(state_values[c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'bc','black')\n",
"\n",
" if state_action_values is not None:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%2.2f\"%(state_action_values[0, c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'tc','black')\n",
" self.draw_text(\"%2.2f\"%(state_action_values[1, c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'rc','black')\n",
" self.draw_text(\"%2.2f\"%(state_action_values[2, c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'bc','black')\n",
" self.draw_text(\"%2.2f\"%(state_action_values[3, c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'lc','black')\n",
"\n",
"\n",
"\n",
" plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eBQ7lTpJQBSe"
},
"outputs": [],
"source": [
"# We're going to work on the problem depicted in figure 19.10a\n",
"n_rows = 4; n_cols = 4\n",
"layout = np.zeros(n_rows * n_cols)\n",
"reward_structure = np.zeros(n_rows * n_cols)\n",
"layout[9] = 1 ; reward_structure[9] = -2 # Hole\n",
"layout[10] = 1; reward_structure[10] = -2 # Hole\n",
"layout[14] = 1; reward_structure[14] = -2 # Hole\n",
"layout[15] = 2; reward_structure[15] = 3 # Fish\n",
"initial_state = 0\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = initial_state, rewards=reward_structure, draw_state_index = True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6Vku6v_se2IG"
},
"source": [
"For clarity, the black numbers are the state number and the red numbers are the reward for being in that state. Note that the states are indexed from 0 rather than 1 as in the book to make the code neater."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Fhc6DzZNOjiC"
},
"source": [
"Now let's define the state transition function $Pr(s_{t+1}|s_{t},a)$ in full where $a$ is the actions. Here $a=0$ means try to go upward, $a=1$, right, $a=2$ down and $a=3$ right. However, the ice is slippery, so we don't always go the direction we want to.\n",
"\n",
"Note that as for the states, we've indexed the actions from zero (unlike in the book) so they map to the indices of arrays better"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "l7rT78BbOgTi"
},
"outputs": [],
"source": [
"transition_probabilities_given_action0 = np.array(\\\n",
"[[0.90, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.85, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.85, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.90, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.10, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00]])\n",
"\n",
"\n",
"transition_probabilities_given_action1 = np.array(\\\n",
"[[0.10, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.85, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.85, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.85, 0.90, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.85, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.85, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.10, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.05, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00]])\n",
"\n",
"\n",
"transition_probabilities_given_action2 = np.array(\\\n",
"[[0.10, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.10, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.85, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.90, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.85, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.85, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00]])\n",
"\n",
"transition_probabilities_given_action3 = np.array(\\\n",
"[[0.90, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.05, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.05, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.10, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.00, 0.00, 0.00, 0.85, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.85, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.90, 0.85, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.85, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00]])\n",
"\n",
"\n",
"\n",
"# Store all of these in a three dimension array\n",
"# Pr(s_{t+1}=2|s_{t}=1, a_{t}=3] is stored at position [2,1,3]\n",
"transition_probabilities_given_action = np.concatenate((np.expand_dims(transition_probabilities_given_action0,2),\n",
" np.expand_dims(transition_probabilities_given_action1,2),\n",
" np.expand_dims(transition_probabilities_given_action2,2),\n",
" np.expand_dims(transition_probabilities_given_action3,2)),axis=2)\n",
"\n",
"print('Grid Size:', len(transition_probabilities_given_action[0]))\n",
"print()\n",
"print('Transition Probabilities for when next state = 2:')\n",
"print(transition_probabilities_given_action[2])\n",
"print()\n",
"print('Transitions Probabilities for when next state = 2 and current state = 1')\n",
"print(transition_probabilities_given_action[2][1])\n",
"print()\n",
"print('Transitions Probabilities for when next state = 2 and current state = 1 and action = 3 (Left):')\n",
"print(transition_probabilities_given_action[2][1][3])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BHWjp6Qq4tBF"
},
"source": [
"## Implementation Details\n",
"\n",
"We provide the following methods:\n",
"\n",
"- **`markov_decision_process_step_stochastic`** - this function selects an action based on the stochastic policy for the current state, updates the state based on the transition probabilities associated with the chosen action, and returns the new state, the reward obtained for the new state, the chosen action, and whether the episode terminates.\n",
"\n",
"- **`get_one_episode`** - this function simulates an episode of agent-environment interaction. It returns the states, rewards, and actions seen in that episode, which we can then use to update the agent.\n",
"\n",
"- **`calculate_returns`** - this function calls on the **`calculate_return`** function that computes the discounted sum of rewards from a specific step, in a sequence of rewards.\n",
"\n",
"You have to implement the following methods:\n",
"\n",
"- **`deterministic_policy_to_epsilon_greedy`** - given a deterministic policy, where one action is chosen per state, this function computes the $\\epsilon$-greedy version of that policy, where each of the four actions has some nonzero probability of being selected per state. In each state, the probability of selecting each of the actions should sum to 1.\n",
"\n",
"- **`update_policy_mc`** - this function updates the action-value function using the Monte Carlo method. We use the rollout trajectories collected using `get_one_episode` to calculate the returns. Then update the action values towards the Monte Carlo estimate of the return for each state."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "akjrncMF-FkU"
},
"outputs": [],
"source": [
"# This takes a single step from an MDP\n",
"def markov_decision_process_step_stochastic(state, transition_probabilities_given_action, reward_structure, terminal_states, stochastic_policy):\n",
" # Pick action\n",
" action = np.random.choice(a=np.arange(0,4,1),p=stochastic_policy[:,state])\n",
"\n",
" # Update the state\n",
" new_state = np.random.choice(a=np.arange(0,transition_probabilities_given_action.shape[0]),p = transition_probabilities_given_action[:,state,action])\n",
" # Return the reward\n",
" reward = reward_structure[new_state]\n",
" is_terminal = new_state in [terminal_states]\n",
"\n",
" return new_state, reward, action, is_terminal"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bFYvF9nAloIA"
},
"outputs": [],
"source": [
"# Run one episode and return actions, rewards, returns\n",
"def get_one_episode(initial_state, transition_probabilities_given_action, reward_structure, terminal_states, stochastic_policy):\n",
"\n",
" states = []\n",
" rewards = []\n",
" actions = []\n",
"\n",
" states.append(initial_state)\n",
" state = initial_state\n",
"\n",
" is_terminal = False\n",
" # While we haven't reached a terminal state\n",
" while not is_terminal:\n",
" # Keep stepping through MDP\n",
" state, reward, action, is_terminal = markov_decision_process_step_stochastic(state,\n",
" transition_probabilities_given_action,\n",
" reward_structure,\n",
" terminal_states,\n",
" stochastic_policy)\n",
" states.append(state)\n",
" rewards.append(reward)\n",
" actions.append(action)\n",
"\n",
" states = np.array(states, dtype=\"uint8\")\n",
" rewards = np.array(rewards)\n",
" actions = np.array(actions, dtype=\"uint8\")\n",
"\n",
" # If the episode was terminated early, we need to compute the return differently using r_{t+1} + gamma*V(s_{t+1})\n",
" return states, rewards, actions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qJhOrIId4tBF"
},
"outputs": [],
"source": [
"def visualize_one_episode(states, actions):\n",
" # Define actions for visualization\n",
" acts = ['up', 'right', 'down', 'left']\n",
"\n",
" # Iterate over the states and actions\n",
" for i in range(len(states)):\n",
"\n",
" if i == 0:\n",
" print('Starting State:', states[i])\n",
"\n",
" elif i == len(states)-1:\n",
" print('Episode Done:', states[i])\n",
"\n",
" else:\n",
" print('State', states[i-1])\n",
" a = actions[i]\n",
" print('Action:', acts[a])\n",
" print('Next State:', states[i])\n",
"\n",
" # Visualize the current state using the MDP drawer\n",
" mdp_drawer.draw(layout, state=states[i], rewards=reward_structure, draw_state_index=True)\n",
" clear_output(True)\n",
"\n",
" # Pause for a short duration to allow observation\n",
" sleep(1.5)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_AKwdtQQHzIK"
},
"outputs": [],
"source": [
"# Convert deterministic policy (1x16) to an epsilon greedy stochastic policy (4x16)\n",
"def deterministic_policy_to_epsilon_greedy(policy, epsilon=0.2):\n",
" # TODO -- write this function\n",
" # You should wind up with a 4x16 matrix, with epsilon/3 in every position except the real policy\n",
" # The columns should sum to one\n",
" # Replace this line:\n",
" stochastic_policy = np.ones((4,16)) * 0.25\n",
"\n",
"\n",
" return stochastic_policy"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OhVXw2Favo-w"
},
"source": [
"Let's try generating an episode"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5zQ1Oh9Zvnwt"
},
"outputs": [],
"source": [
"# Set seed so random numbers always the same\n",
"np.random.seed(6)\n",
"# Print in compact form\n",
"np.set_printoptions(precision=3)\n",
"\n",
"# Let's start with by setting the policy randomly\n",
"policy = np.random.choice(size= n_rows * n_cols, a=np.arange(0,4,1))\n",
"\n",
"# Convert deterministic policy to stochastic\n",
"stochastic_policy = deterministic_policy_to_epsilon_greedy(policy)\n",
"\n",
"print(\"Initial Penguin Policy:\")\n",
"print(policy)\n",
"print()\n",
"print('Stochastic Penguin Policy:')\n",
"print(stochastic_policy)\n",
"print()\n",
"\n",
"initial_state = 5\n",
"terminal_states=[15]\n",
"states, rewards, actions = get_one_episode(initial_state,transition_probabilities_given_action, reward_structure, terminal_states, stochastic_policy)\n",
"\n",
"print('Initial Penguin Position:')\n",
"mdp_drawer.draw(layout, state = initial_state, rewards=reward_structure, draw_state_index = True)\n",
"\n",
"print('Total steps to termination:', len(states))\n",
"print('Final Reward:', np.sum(rewards))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KJH-UGKk4tBF"
},
"outputs": [],
"source": [
"#this visualizes the complete episode\n",
"visualize_one_episode(states, actions)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nl6rtNffwhcU"
},
"source": [
"We'll need to calculate the returns (discounted cumulative reward) for each state action pair"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FxrItqGPLTq7"
},
"outputs": [],
"source": [
"def calculate_returns(rewards, gamma):\n",
" returns = np.zeros(len(rewards))\n",
" for c_return in range(len(returns)):\n",
" returns[c_return] = calculate_return(rewards[c_return:], gamma)\n",
" return returns\n",
"\n",
"def calculate_return(rewards, gamma):\n",
" return_val = 0.0\n",
" for i in range(len(rewards)):\n",
" return_val += rewards[i] * np.power(gamma, i)\n",
" return return_val"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DX1KfHRhzUOU"
},
"source": [
"This routine does the main work of the on-policy Monte Carlo method. We repeatedly rollout episods, calculate the returns. Then we figure out the average return for each state action pair, and choose the next policy as the action that has greatest state action value at each state."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "hCghcKlOJXSM"
},
"outputs": [],
"source": [
"def update_policy_mc(initial_state, transition_probabilities_given_action, reward_structure, terminal_states, stochastic_policy, gamma, n_rollouts=1):\n",
" # Create two matrices to store total returns for each action/state pair and the\n",
" # number of times we observed that action/state pair\n",
" n_state = transition_probabilities_given_action.shape[0]\n",
" n_action = transition_probabilities_given_action.shape[2]\n",
" # Contains the total returns seen for taking this action at this state\n",
" state_action_returns_total = np.zeros((n_action, n_state))\n",
" # Contains the number of times we have taken this action in this state\n",
" state_action_count = np.zeros((n_action,n_state))\n",
"\n",
" # For each rollout\n",
" for c_rollout in range(n_rollouts):\n",
" # TODO -- Complete this function\n",
" # 1. Draw a random state from 0 to 14\n",
" # 2. Get one episode starting at that state\n",
" # 3. Compute the returns\n",
" # 4. For each position in the trajectory, update state_action_returns_total and state_action_count\n",
" # Replace these two lines\n",
" state_action_returns_total[0,1] = state_action_returns_total[0,1]\n",
" state_action_count[0,1] = state_action_count[0,1]\n",
"\n",
"\n",
" # Normalize -- add small number to denominator to avoid divide by zero\n",
" state_action_values = state_action_returns_total/( state_action_count+0.00001)\n",
" policy = np.argmax(state_action_values, axis=0).astype(int)\n",
" return policy, state_action_values\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8jWhDlkaKj7Q"
},
"outputs": [],
"source": [
"# Set seed so random numbers always the same\n",
"np.random.seed(0)\n",
"# Print in compact form\n",
"np.set_printoptions(precision=3)\n",
"\n",
"# Let's start with by setting the policy randomly\n",
"policy = np.random.choice(size= n_rows * n_cols, a=np.arange(0,4,1))\n",
"gamma = 0.9\n",
"print(\"Initial policy:\")\n",
"print(policy)\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, rewards = reward_structure)\n",
"\n",
"terminal_states = [15]\n",
"# Track all the policies so we can visualize them later\n",
"all_policies = []\n",
"n_policy_update = 2000\n",
"for c_policy_update in range(n_policy_update):\n",
" # Convert policy to stochastic\n",
" stochastic_policy = deterministic_policy_to_epsilon_greedy(policy)\n",
" # Update policy by Monte Carlo method\n",
" policy, state_action_values = update_policy_mc(initial_state, transition_probabilities_given_action, reward_structure, terminal_states, stochastic_policy, gamma, n_rollouts=100)\n",
" all_policies.append(policy)\n",
"\n",
" # Print out 10 snapshots of progress\n",
" if (c_policy_update % (n_policy_update//10) == 0) or c_policy_update == n_policy_update - 1:\n",
" print(\"Updated policy\")\n",
" print(policy)\n",
" mdp_drawer = DrawMDP(n_rows, n_cols)\n",
" mdp_drawer.draw(layout, policy = policy, rewards = reward_structure, state_action_values=state_action_values)\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "j7Ny47kTEMzH"
},
"source": [
"You can see a definite improvement to the policy"
]
}
],
"metadata": {
"colab": {
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -0,0 +1,762 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap19/19_4_Temporal_Difference_Methods.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 19.4: Temporal difference methods**\n",
"\n",
"This notebook investigates temporal difference methods for tabular reinforcement learning as described in section 19.3.3 of the book\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n",
"\n",
"Thanks to [Akshil Patel](https://www.akshilpatel.com) and [Jessica Nicholson](https://jessicanicholson1.github.io) for their help in preparing this notebook."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image\n",
"from IPython.display import clear_output\n",
"from time import sleep\n",
"from copy import deepcopy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZsvrUszPLyEG"
},
"outputs": [],
"source": [
"# Get local copies of components of images\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Empty.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Hole.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Fish.png\n",
"!wget https://raw.githubusercontent.com/udlbook/udlbook/main/Notebooks/Chap19/Penguin.png"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Gq1HfJsHN3SB"
},
"outputs": [],
"source": [
"# Ugly class that takes care of drawing pictures like in the book.\n",
"# You can totally ignore this code!\n",
"class DrawMDP:\n",
" # Constructor initializes parameters\n",
" def __init__(self, n_row, n_col):\n",
" self.empty_image = np.asarray(Image.open('Empty.png'))\n",
" self.hole_image = np.asarray(Image.open('Hole.png'))\n",
" self.fish_image = np.asarray(Image.open('Fish.png'))\n",
" self.penguin_image = np.asarray(Image.open('Penguin.png'))\n",
" self.fig,self.ax = plt.subplots()\n",
" self.n_row = n_row\n",
" self.n_col = n_col\n",
"\n",
" my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
" my_colormap_vals_dec = np.array([int(element,base=16) for element in my_colormap_vals_hex])\n",
" r = np.floor(my_colormap_vals_dec/(256*256))\n",
" g = np.floor((my_colormap_vals_dec - r *256 *256)/256)\n",
" b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
" self.colormap = np.vstack((r,g,b)).transpose()/255.0\n",
"\n",
"\n",
" def draw_text(self, text, row, col, position, color):\n",
" if position == 'bc':\n",
" self.ax.text( 83*col+41,83 * (row+1) -5, text, horizontalalignment=\"center\", color=color, fontweight='bold')\n",
" if position == 'tc':\n",
" self.ax.text( 83*col+41,83 * (row) +10, text, horizontalalignment=\"center\", color=color, fontweight='bold')\n",
" if position == 'lc':\n",
" self.ax.text( 83*col+2,83 * (row) +41, text, verticalalignment=\"center\", color=color, fontweight='bold', rotation=90)\n",
" if position == 'rc':\n",
" self.ax.text( 83*(col+1)-5,83 * (row) +41, text, horizontalalignment=\"right\", verticalalignment=\"center\", color=color, fontweight='bold', rotation=-90)\n",
" if position == 'tl':\n",
" self.ax.text( 83*col+5,83 * row +5, text, verticalalignment = 'top', horizontalalignment=\"left\", color=color, fontweight='bold')\n",
" if position == 'tr':\n",
" self.ax.text( 83*(col+1)-5, 83 * row +5, text, verticalalignment = 'top', horizontalalignment=\"right\", color=color, fontweight='bold')\n",
"\n",
" # Draws a set of states\n",
" def draw_path(self, path, color1, color2):\n",
" for i in range(len(path)-1):\n",
" row_start = np.floor(path[i]/self.n_col)\n",
" row_end = np.floor(path[i+1]/self.n_col)\n",
" col_start = path[i] - row_start * self.n_col\n",
" col_end = path[i+1] - row_end * self.n_col\n",
"\n",
" color_index = int(np.floor(255 * i/(len(path)-1.)))\n",
" self.ax.plot([col_start * 83+41 + i, col_end * 83+41 + i ],[row_start * 83+41 + i, row_end * 83+41 + i ], color=(self.colormap[color_index,0],self.colormap[color_index,1],self.colormap[color_index,2]))\n",
"\n",
"\n",
" # Draw deterministic policy\n",
" def draw_deterministic_policy(self,i, action):\n",
" row = np.floor(i/self.n_col)\n",
" col = i - row * self.n_col\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 10\n",
" arrow_height = 15\n",
" # Draw arrow pointing upward\n",
" if action ==0:\n",
" triangle_indices = np.array([[center_x, center_y-arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y+arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y+arrow_height/2]])\n",
" # Draw arrow pointing right\n",
" if action ==1:\n",
" triangle_indices = np.array([[center_x + arrow_height/2, center_y],\n",
" [center_x - arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x - arrow_height/2, center_y+arrow_base_width/2]])\n",
" # Draw arrow pointing downward\n",
" if action ==2:\n",
" triangle_indices = np.array([[center_x, center_y+arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y-arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y-arrow_height/2]])\n",
" # Draw arrow pointing left\n",
" if action ==3:\n",
" triangle_indices = np.array([[center_x - arrow_height/2, center_y],\n",
" [center_x + arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x + arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw stochastic policy\n",
" def draw_stochastic_policy(self,i, action_probs):\n",
" row = np.floor(i/self.n_col)\n",
" col = i - row * self.n_col\n",
" offset = 20\n",
" # Draw arrow pointing upward\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41 - offset\n",
" arrow_base_width = 15 * action_probs[0]\n",
" arrow_height = 20 * action_probs[0]\n",
" triangle_indices = np.array([[center_x, center_y-arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y+arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y+arrow_height/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing right\n",
" center_x = 83 * col + 41 + offset\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 15 * action_probs[1]\n",
" arrow_height = 20 * action_probs[1]\n",
" triangle_indices = np.array([[center_x + arrow_height/2, center_y],\n",
" [center_x - arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x - arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing downward\n",
" center_x = 83 * col + 41\n",
" center_y = 83 * row + 41 +offset\n",
" arrow_base_width = 15 * action_probs[2]\n",
" arrow_height = 20 * action_probs[2]\n",
" triangle_indices = np.array([[center_x, center_y+arrow_height/2],\n",
" [center_x - arrow_base_width/2, center_y-arrow_height/2],\n",
" [center_x + arrow_base_width/2, center_y-arrow_height/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
" # Draw arrow pointing left\n",
" center_x = 83 * col + 41 -offset\n",
" center_y = 83 * row + 41\n",
" arrow_base_width = 15 * action_probs[3]\n",
" arrow_height = 20 * action_probs[3]\n",
" triangle_indices = np.array([[center_x - arrow_height/2, center_y],\n",
" [center_x + arrow_height/2, center_y-arrow_base_width/2],\n",
" [center_x + arrow_height/2, center_y+arrow_base_width/2]])\n",
" self.ax.fill(triangle_indices[:,0], triangle_indices[:,1],facecolor='cyan', edgecolor='darkcyan', linewidth=1)\n",
"\n",
"\n",
" def draw(self, layout, state=None, draw_state_index= False, rewards=None, policy=None, state_values=None, state_action_values=None,path1=None, path2 = None):\n",
" # Construct the image\n",
" image_out = np.zeros((self.n_row * 83, self.n_col * 83, 4),dtype='uint8')\n",
" for c_row in range (self.n_row):\n",
" for c_col in range(self.n_col):\n",
" if layout[c_row * self.n_col + c_col]==0:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.empty_image\n",
" elif layout[c_row * self.n_col + c_col]==1:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.hole_image\n",
" else:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.fish_image\n",
" if state is not None and state == c_row * self.n_col + c_col:\n",
" image_out[c_row*83:c_row*83+83, c_col*83:c_col*83+83,:] = self.penguin_image\n",
"\n",
" # Draw the image\n",
" plt.imshow(image_out)\n",
" self.ax.get_xaxis().set_visible(False)\n",
" self.ax.get_yaxis().set_visible(False)\n",
" self.ax.spines['top'].set_visible(False)\n",
" self.ax.spines['right'].set_visible(False)\n",
" self.ax.spines['bottom'].set_visible(False)\n",
" self.ax.spines['left'].set_visible(False)\n",
"\n",
" if draw_state_index:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%d\"%(c_cell), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'tl','k')\n",
"\n",
" # Draw the policy as triangles\n",
" if policy is not None:\n",
" # If the policy is deterministic\n",
" if len(policy) == len(layout):\n",
" for i in range(len(layout)):\n",
" self.draw_deterministic_policy(i, policy[i])\n",
" # Else it is stochastic\n",
" else:\n",
" for i in range(len(layout)):\n",
" self.draw_stochastic_policy(i,policy[:,i])\n",
"\n",
"\n",
" if path1 is not None:\n",
" self.draw_path(path1, np.array([1.0, 0.0, 0.0]), np.array([0.0, 1.0, 1.0]))\n",
"\n",
" if rewards is not None:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%d\"%(rewards[c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'tr','r')\n",
"\n",
" if state_values is not None:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%2.2f\"%(state_values[c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'bc','black')\n",
"\n",
" if state_action_values is not None:\n",
" for c_cell in range(layout.size):\n",
" self.draw_text(\"%2.2f\"%(state_action_values[0, c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'tc','black')\n",
" self.draw_text(\"%2.2f\"%(state_action_values[1, c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'rc','black')\n",
" self.draw_text(\"%2.2f\"%(state_action_values[2, c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'bc','black')\n",
" self.draw_text(\"%2.2f\"%(state_action_values[3, c_cell]), np.floor(c_cell/self.n_col), c_cell-np.floor(c_cell/self.n_col)*self.n_col,'lc','black')\n",
"\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JU8gX59o76xM"
},
"source": [
"# Penguin Ice Environment\n",
"\n",
"In this implementation we have designed an icy gridworld that a penguin has to traverse to reach the fish found in the bottom right corner.\n",
"\n",
"## Environment Description\n",
"\n",
"Consider having to cross an icy surface to reach the yummy fish. In order to achieve this task as quickly as possible, the penguin needs to waddle along as fast as it can whilst simultaneously avoiding falling into the holes.\n",
"\n",
"In this icy environment the penguin is at one of the discrete cells in the gridworld. The agent starts each episode on a randomly chosen cell. The environment state dynamics are captured by the transition probabilities $Pr(s_{t+1} |s_t, a_t)$ where $s_t$ is the current state, $a_t$ is the action chosen, and $s_{t+1}$ is the next state at decision stage t. At each decision stage, the penguin can move in one of four directions: $a=0$ means try to go upward, $a=1$, right, $a=2$ down and $a=3$ left.\n",
"\n",
"However, the ice is slippery, so we don't always go the direction we want to: every time the agent chooses an action, with 0.25 probability, the environment changes the action taken to a differenct action, which is uniformly sampled from the other available actions.\n",
"\n",
"The rewards are deterministic; the penguin will receive a reward of +3 if it reaches the fish, -2 if it slips into a hole and 0 otherwise.\n",
"\n",
"Note that as for the states, we've indexed the actions from zero (unlike in the book) so they map to the indices of arrays better"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eBQ7lTpJQBSe"
},
"outputs": [],
"source": [
"# We're going to work on the problem depicted in figure 19.10a\n",
"n_rows = 4; n_cols = 4\n",
"layout = np.zeros(n_rows * n_cols)\n",
"reward_structure = np.zeros(n_rows * n_cols)\n",
"layout[9] = 1 ; reward_structure[9] = -2 # Hole\n",
"layout[10] = 1; reward_structure[10] = -2 # Hole\n",
"layout[14] = 1; reward_structure[14] = -2 # Hole\n",
"layout[15] = 2; reward_structure[15] = 3 # Fish\n",
"initial_state = 0\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, state = initial_state, rewards=reward_structure, draw_state_index = True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6Vku6v_se2IG"
},
"source": [
"For clarity, the black numbers are the state number and the red numbers are the reward for being in that state. Note that the states are indexed from 0 rather than 1 as in the book to make the code neater."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Fhc6DzZNOjiC"
},
"source": [
"Now let's define the state transition function $Pr(s_{t+1}|s_{t},a)$ in full where $a$ is the actions. Here $a=0$ means try to go upward, $a=1$, right, $a=2$ down and $a=3$ right. However, the ice is slippery, so we don't always go the direction we want to.\n",
"\n",
"Note that as for the states, we've indexed the actions from zero (unlike in the book) so they map to the indices of arrays better"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wROjgnqh76xN"
},
"outputs": [],
"source": [
"transition_probabilities_given_action0 = np.array(\\\n",
"[[0.90, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.85, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.85, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.90, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.10, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00]])\n",
"\n",
"\n",
"transition_probabilities_given_action1 = np.array(\\\n",
"[[0.10, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.85, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.85, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.85, 0.90, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.85, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.85, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.10, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.05, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.85, 0.00]])\n",
"\n",
"\n",
"transition_probabilities_given_action2 = np.array(\\\n",
"[[0.10, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.10, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.85, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.00, 0.90, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.85, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.85, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00]])\n",
"\n",
"transition_probabilities_given_action3 = np.array(\\\n",
"[[0.90, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.05, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.05, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.10, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.05, 0.00, 0.00, 0.00, 0.85, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.85, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00, 0.85, 0.00, 0.00, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00, 0.00, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.00, 0.90, 0.85, 0.00, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.85, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.05, 0.00],\n",
" [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.00, 0.00, 0.05, 0.00]])\n",
"\n",
"\n",
"\n",
"# Store all of these in a three dimension array\n",
"# Pr(s_{t+1}=2|s_{t}=1, a_{t}=3] is stored at position [2,1,3]\n",
"transition_probabilities_given_action = np.concatenate((np.expand_dims(transition_probabilities_given_action0,2),\n",
" np.expand_dims(transition_probabilities_given_action1,2),\n",
" np.expand_dims(transition_probabilities_given_action2,2),\n",
" np.expand_dims(transition_probabilities_given_action3,2)),axis=2)\n",
"\n",
"print('Grid Size:', len(transition_probabilities_given_action[0]))\n",
"print()\n",
"print('Transition Probabilities for when next state = 2:')\n",
"print(transition_probabilities_given_action[2])\n",
"print()\n",
"print('Transitions Probabilities for when next state = 2 and current state = 1')\n",
"print(transition_probabilities_given_action[2][1])\n",
"print()\n",
"print('Transitions Probabilities for when next state = 2 and current state = 1 and action = 3 (Left):')\n",
"print(transition_probabilities_given_action[2][1][3])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eblSQ6xZ76xN"
},
"source": [
"## Implementation Details\n",
"\n",
"We provide the following methods:\n",
"- **`markov_decision_process_step`** - this function simulates $Pr(s_{t+1} | s_{t}, a_{t})$. It randomly selects an action, updates the state based on the transition probabilities associated with the chosen action, and returns the new state, the reward obtained for leaving the current state, and the chosen action. The randomness in action selection and state transitions reflects a random exploration process and the stochastic nature of the MDP, respectively.\n",
"\n",
"- **`get_policy`** - this function computes a policy that acts greedily with respect to the state-action values. The policy is computed for all states and the action that maximizes the state-action value is chosen for each state. When there are multiple optimal actions, one is chosen at random.\n",
"\n",
"\n",
"You have to implement the following method:\n",
"\n",
"- **`q_learning_step`** - this function implements a single step of the Q-learning algorithm for reinforcement learning as shown below. The update follows the Q-learning formula and is controlled by parameters such as the learning rate (alpha) and the discount factor $(\\gamma)$. The function returns the updated state-action values matrix.\n",
"\n",
"$Q(s, a) \\leftarrow (1 - \\alpha) \\cdot Q(s, a) + \\alpha \\cdot \\left(r + \\gamma \\cdot \\max_{a'} Q(s', a')\\right)$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cKLn4Iam76xN"
},
"outputs": [],
"source": [
"def get_policy(state_action_values):\n",
" policy = np.zeros(state_action_values.shape[1]) # One action for each state\n",
" for state in range(state_action_values.shape[1]):\n",
" # Break ties for maximising actions randomly\n",
" policy[state] = np.random.choice(np.flatnonzero(state_action_values[:, state] == max(state_action_values[:, state])))\n",
" return policy"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "akjrncMF-FkU"
},
"outputs": [],
"source": [
"def markov_decision_process_step(state, transition_probabilities_given_action, reward_structure, terminal_states, action=None):\n",
" # Pick action\n",
" if action is None:\n",
" action = np.random.randint(4)\n",
" # Update the state\n",
" new_state = np.random.choice(a=range(transition_probabilities_given_action.shape[0]), p = transition_probabilities_given_action[:, state,action])\n",
"\n",
" # Return the reward -- here the reward is for arriving at the state\n",
" reward = reward_structure[new_state]\n",
" is_terminal = new_state in [terminal_states]\n",
"\n",
" return new_state, reward, action, is_terminal"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5pO6-9ACWhiV"
},
"outputs": [],
"source": [
"def q_learning_step(state_action_values, reward, state, new_state, action, is_terminal, gamma, alpha = 0.1):\n",
" # TODO -- write this function\n",
" # Replace this line\n",
" state_action_values_after = np.copy(state_action_values)\n",
"\n",
" return state_action_values_after"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "u4OHTTk176xO"
},
"source": [
"Lets run this for a single Q-learning step"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Fu5_VjvbSwfJ"
},
"outputs": [],
"source": [
"# Initialize the state-action values to random numbers\n",
"np.random.seed(0)\n",
"n_state = transition_probabilities_given_action.shape[0]\n",
"n_action = transition_probabilities_given_action.shape[2]\n",
"terminal_states=[15]\n",
"state_action_values = np.random.normal(size=(n_action, n_state))\n",
"# Hard code value of termination state of finding fish to 0\n",
"state_action_values[:, terminal_states] = 0\n",
"gamma = 0.9\n",
"\n",
"policy = get_policy(state_action_values)\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, state_action_values = state_action_values, rewards = reward_structure)\n",
"\n",
"# Now let's simulate a single Q-learning step\n",
"initial_state = 9\n",
"print(\"Initial state =\",initial_state)\n",
"new_state, reward, action, is_terminal = markov_decision_process_step(initial_state, transition_probabilities_given_action, reward_structure, terminal_states)\n",
"print(\"Action =\",action)\n",
"print(\"New state =\",new_state)\n",
"print(\"Reward =\", reward)\n",
"\n",
"state_action_values_after = q_learning_step(state_action_values, reward, initial_state, new_state, action, is_terminal, gamma)\n",
"print(\"Your value:\",state_action_values_after[action, initial_state])\n",
"print(\"True value: 0.3024718977397814\")\n",
"\n",
"policy = get_policy(state_action_values)\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, state_action_values = state_action_values_after, rewards = reward_structure)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ogh0qucmb68J"
},
"source": [
"Now let's run this for a while (20000) steps and watch the policy improve"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "N6gFYifh76xO"
},
"outputs": [],
"source": [
"# Initialize the state-action values to random numbers\n",
"np.random.seed(0)\n",
"n_state = transition_probabilities_given_action.shape[0]\n",
"n_action = transition_probabilities_given_action.shape[2]\n",
"state_action_values = np.random.normal(size=(n_action, n_state))\n",
"\n",
"# Hard code value of termination state of finding fish to 0\n",
"terminal_states = [15]\n",
"state_action_values[:, terminal_states] = 0\n",
"gamma = 0.9\n",
"\n",
"# Draw the initial setup\n",
"print('Initial Policy:')\n",
"policy = get_policy(state_action_values)\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, state_action_values = state_action_values, rewards = reward_structure)\n",
"\n",
"state = np.random.randint(n_state-1)\n",
"\n",
"# Run for a number of iterations\n",
"for c_iter in range(20000):\n",
" new_state, reward, action, is_terminal = markov_decision_process_step(state, transition_probabilities_given_action, reward_structure, terminal_states)\n",
" state_action_values_after = q_learning_step(state_action_values, reward, state, new_state, action, is_terminal, gamma)\n",
"\n",
" # If in termination state, reset state randomly\n",
" if is_terminal:\n",
" state = np.random.randint(n_state-1)\n",
" else:\n",
" state = new_state\n",
"\n",
" # Update the policy\n",
" state_action_values = deepcopy(state_action_values_after)\n",
" policy = get_policy(state_action_values_after)\n",
"\n",
"print('Final Optimal Policy:')\n",
"# Draw the final situation\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, state_action_values = state_action_values, rewards = reward_structure)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "djPTKuDk76xO"
},
"source": [
"Finally, lets run this for a **single** episode and visualize the penguin's actions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "pWObQf2h76xO"
},
"outputs": [],
"source": [
"def get_one_episode(n_state, state_action_values, terminal_states, gamma):\n",
"\n",
" state = np.random.randint(n_state-1)\n",
"\n",
" # Create lists to store all the states seen and actions taken throughout the single episode\n",
" all_states = []\n",
" all_actions = []\n",
"\n",
" # Initalize episode termination flag\n",
" done = False\n",
" # Initialize counter for steps in the episode\n",
" steps = 0\n",
"\n",
" all_states.append(state)\n",
"\n",
" while not done:\n",
" steps += 1\n",
"\n",
" new_state, reward, action, is_terminal = markov_decision_process_step(state, transition_probabilities_given_action, reward_structure, terminal_states)\n",
" all_states.append(new_state)\n",
" all_actions.append(action)\n",
"\n",
" state_action_values_after = q_learning_step(state_action_values, reward, state, new_state, action, is_terminal, gamma)\n",
"\n",
" # If in termination state, reset state randomly\n",
" if is_terminal:\n",
" state = np.random.randint(n_state-1)\n",
" print(f'Episode Terminated at {steps} Steps')\n",
" # Set episode termination flag\n",
" done = True\n",
" else:\n",
" state = new_state\n",
"\n",
" # Update the policy\n",
" state_action_values = deepcopy(state_action_values_after)\n",
" policy = get_policy(state_action_values_after)\n",
"\n",
" return all_states, all_actions, policy, state_action_values\n",
""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "P7cbCGT176xO"
},
"outputs": [],
"source": [
"def visualize_one_episode(states, actions):\n",
" # Define actions for visualization\n",
" acts = ['up', 'right', 'down', 'left']\n",
"\n",
" # Iterate over the states and actions\n",
" for i in range(len(states)):\n",
"\n",
" if i == 0:\n",
" print('Starting State:', states[i])\n",
"\n",
" elif i == len(states)-1:\n",
" print('Episode Done:', states[i])\n",
"\n",
" else:\n",
" print('State', states[i-1])\n",
" a = actions[i]\n",
" print('Action:', acts[a])\n",
" print('Next State:', states[i])\n",
"\n",
" # Visualize the current state using the MDP drawer\n",
" mdp_drawer.draw(layout, state=states[i], rewards=reward_structure, draw_state_index=True)\n",
" clear_output(True)\n",
"\n",
" # Pause for a short duration to allow observation\n",
" sleep(1.5)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cr98F8PT76xP"
},
"outputs": [],
"source": [
"# Initialize the state-action values to random numbers\n",
"np.random.seed(2)\n",
"n_state = transition_probabilities_given_action.shape[0]\n",
"n_action = transition_probabilities_given_action.shape[2]\n",
"state_action_values = np.random.normal(size=(n_action, n_state))\n",
"\n",
"# Hard code value of termination state of finding fish to 0\n",
"terminal_states = [15]\n",
"state_action_values[:, terminal_states] = 0\n",
"gamma = 0.9\n",
"\n",
"# Draw the initial setup\n",
"print('Initial Policy:')\n",
"policy = get_policy(state_action_values)\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, state_action_values = state_action_values, rewards = reward_structure)\n",
"\n",
"states, actions, policy, state_action_values = get_one_episode(n_state, state_action_values, terminal_states, gamma)\n",
"\n",
"print()\n",
"print('Final Optimal Policy:')\n",
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, state_action_values = state_action_values, rewards = reward_structure)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "5zBu1g3776xP"
},
"outputs": [],
"source": [
"visualize_one_episode(states, actions)"
]
}
],
"metadata": {
"colab": {
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -0,0 +1,170 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyO6CLgMIO5bUVAMkzPT3z4y",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap19/19_5_Control_Variates.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# **Notebook 19.5: Control variates**\n",
"\n",
"This notebook investigates the method of control variates as described in figure 19.16\n",
"\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
],
"metadata": {
"id": "t9vk9Elugvmi"
}
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt"
],
"metadata": {
"id": "OLComQyvCIJ7"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Generate from our two variables, $a$ and $b$. We are interested in estimating the mean of $a$, but we can use $b$$ to improve our estimates if it is correlated"
],
"metadata": {
"id": "uwmhcAZBzTRO"
}
},
{
"cell_type": "code",
"source": [
"# Sample from two variables with mean zero, standard deviation one, and a given correlation coefficient\n",
"def get_samples(n_samples, correlation_coeff=0.8):\n",
" a = np.random.normal(size=(1,n_samples))\n",
" temp = np.random.normal(size=(1, n_samples))\n",
" b = correlation_coeff * a + np.sqrt(1-correlation_coeff * correlation_coeff) * temp\n",
" return a, b"
],
"metadata": {
"id": "bC8MBXPawQJ3"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"N = 10000000\n",
"a,b, = get_samples(N)\n",
"\n",
"# Verify that these two variables have zero mean and unit standard deviation\n",
"print(\"Mean of a = %3.3f, Std of a = %3.3f\"%(np.mean(a),np.std(a)))\n",
"print(\"Mean of b = %3.3f, Std of b = %3.3f\"%(np.mean(b),np.std(b)))"
],
"metadata": {
"id": "1cT66nbRyW34"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Now let's samples $N=10$ examples from $a$ and estimate their mean $\\mathbb{E}[a]$. We'll do this 1000000 times and then compute the variance of those estimates."
],
"metadata": {
"id": "PWoYRpjS0Nlf"
}
},
{
"cell_type": "code",
"source": [
"n_estimate = 1000000\n",
"\n",
"N = 5\n",
"\n",
"# TODO -- sample N examples of variable $a$\n",
"# Compute the mean of each\n",
"# Compute the mean and variance of these estimates of the mean\n",
"# Replace this line\n",
"mean_of_estimator_1 = -1; std_of_estimator_1 = -1\n",
"\n",
"print(\"Standard estimator mean = %3.3f, Standard estimator variance = %3.3f\"%(mean_of_estimator_1, std_of_estimator_1))"
],
"metadata": {
"id": "n6Uem2aYzBp7"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Now let's estimate the mean $\\mathbf{E}[a]$ of $a$ by computing $a-b$ where $b$ is correlated with $a$"
],
"metadata": {
"id": "F-af86z13TFc"
}
},
{
"cell_type": "code",
"source": [
"n_estimate = 1000000\n",
"\n",
"N = 5\n",
"\n",
"# TODO -- sample N examples of variables $a$ and $b$\n",
"# Compute $c=a-b$ for each and then compute the mean of $c$\n",
"# Compute the mean and variance of these estimates of the mean of $c$\n",
"# Replace this line\n",
"mean_of_estimator_2 = -1; std_of_estimator_2 = -1\n",
"\n",
"print(\"Control variate estimator mean = %3.3f, Control variate estimator variance = %3.3f\"%(mean_of_estimator_2, std_of_estimator_2))"
],
"metadata": {
"id": "MrEVDggY0IGU"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Note that they both have a very similar mean, but the second estimator has a lower variance. \n",
"\n",
"TODO -- Experiment with different samples sizes $N$ and correlation coefficients."
],
"metadata": {
"id": "Jklzkca14ofS"
}
}
]
}

BIN
Notebooks/Chap19/Empty.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
Notebooks/Chap19/Fish.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
Notebooks/Chap19/Hole.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -0,0 +1,305 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNgBRvfIlngVobKuLE6leM+",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap20/20_1_Random_Data.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# **Notebook 20.1: Random Data**\n",
"\n",
"This notebook investigates training the network with random data, as illustrated in figure 20.1.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n",
"\n"
],
"metadata": {
"id": "t9vk9Elugvmi"
}
},
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to install MNIST 1D repository\n",
"!pip install git+https://github.com/greydanus/mnist1d"
],
"metadata": {
"id": "D5yLObtZCi9J"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import os\n",
"import torch, torch.nn as nn\n",
"from torch.utils.data import TensorDataset, DataLoader\n",
"from torch.optim.lr_scheduler import StepLR\n",
"import matplotlib.pyplot as plt\n",
"import mnist1d\n",
"import random\n",
"from IPython.display import display, clear_output"
],
"metadata": {
"id": "YrXWAH7sUWvU"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"args = mnist1d.data.get_dataset_args()\n",
"data = mnist1d.data.get_dataset(args, path='./mnist1d_data.pkl', download=False, regenerate=False)\n",
"\n",
"# The training and test input and outputs are in\n",
"# data['x'], data['y'], data['x_test'], and data['y_test']\n",
"print(\"Examples in training set: {}\".format(len(data['y'])))\n",
"print(\"Examples in test set: {}\".format(len(data['y_test'])))\n",
"print(\"Length of each example: {}\".format(data['x'].shape[-1]))"
],
"metadata": {
"id": "twI72ZCrCt5z"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define the network"
],
"metadata": {
"id": "_sFvRDGrl4qe"
}
},
{
"cell_type": "code",
"source": [
"D_i = 40 # Input dimensions\n",
"D_k = 300 # Hidden dimensions\n",
"D_o = 10 # Output dimensions\n",
"\n",
"model = nn.Sequential(\n",
"nn.Linear(D_i, D_k),\n",
"nn.ReLU(),\n",
"nn.Linear(D_k, D_k),\n",
"nn.ReLU(),\n",
"nn.Linear(D_k, D_k),\n",
"nn.ReLU(),\n",
"nn.Linear(D_k, D_k),\n",
"nn.ReLU(),\n",
"nn.Linear(D_k, D_o))"
],
"metadata": {
"id": "FslroPJJffrh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# He initialization of weights\n",
"def weights_init(layer_in):\n",
" if isinstance(layer_in, nn.Linear):\n",
" nn.init.kaiming_uniform_(layer_in.weight)\n",
" layer_in.bias.data.fill_(0.0)"
],
"metadata": {
"id": "YgLaex1pfhqz"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def train_model(train_data_x, train_data_y, n_epoch):\n",
" # choose cross entropy loss function (equation 5.24 in the loss notes)\n",
" loss_function = nn.CrossEntropyLoss()\n",
" # construct SGD optimizer and initialize learning rate and momentum\n",
" optimizer = torch.optim.SGD(model.parameters(), lr = 0.02, momentum=0.9)\n",
" # object that decreases learning rate by half every 20 epochs\n",
" scheduler = StepLR(optimizer, step_size=20, gamma=0.5)\n",
" # create 100 dummy data points and store in data loader class\n",
" x_train = torch.tensor(train_data_x.transpose().astype('float32'))\n",
" y_train = torch.tensor(train_data_y.astype('long'))\n",
"\n",
" # load the data into a class that creates the batches\n",
" data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n",
"\n",
" # Initialize model weights\n",
" model.apply(weights_init)\n",
"\n",
" # store the loss and the % correct at each epoch\n",
" losses_train = np.zeros((n_epoch))\n",
"\n",
" for epoch in range(n_epoch):\n",
" # loop over batches\n",
" for i, data in enumerate(data_loader):\n",
" # retrieve inputs and labels for this batch\n",
" x_batch, y_batch = data\n",
" # zero the parameter gradients\n",
" optimizer.zero_grad()\n",
" # forward pass -- calculate model output\n",
" pred = model(x_batch)\n",
" # compute the loss\n",
" loss = loss_function(pred, y_batch)\n",
" # backward pass\n",
" loss.backward()\n",
" # SGD update\n",
" optimizer.step()\n",
"\n",
" # Run whole dataset to get statistics -- normally wouldn't do this\n",
" pred_train = model(x_train)\n",
" _, predicted_train_class = torch.max(pred_train.data, 1)\n",
" losses_train[epoch] = loss_function(pred_train, y_train).item()\n",
" if epoch % 5 == 0:\n",
" clear_output(wait=True)\n",
" display(\"Epoch %d, train loss %3.3f\"%(epoch, losses_train[epoch]))\n",
"\n",
" # tell scheduler to consider updating learning rate\n",
" scheduler.step()\n",
"\n",
" return losses_train"
],
"metadata": {
"id": "NYw8I_3mmX5c"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Load in the data\n",
"train_data_x = data['x'].transpose()\n",
"train_data_y = data['y']\n",
"# Print out sizes\n",
"print(\"Train data: %d examples (columns), each of which has %d dimensions (rows)\"%((train_data_x.shape[1],train_data_x.shape[0])))"
],
"metadata": {
"id": "4FE3HQ_vedXO"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Compute loss for proper data and plot\n",
"n_epoch = 60\n",
"loss_true_labels = train_model(train_data_x, train_data_y, n_epoch)\n",
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
"ax.plot(loss_true_labels,'r-',label='true_labels')\n",
"# ax.set_ylim(0,0.7); ax.set_xlim(0,n_epoch)\n",
"ax.set_xlabel('Epoch'); ax.set_ylabel('Loss')\n",
"ax.legend()\n",
"plt.show()"
],
"metadata": {
"id": "b56wdODqemF1"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# TODO -- Randomize the input data (train_data_x), but retain overall mean and variance\n",
"# Replace this line\n",
"train_data_x_randomized = np.copy(train_data_x)"
],
"metadata": {
"id": "SbPCiiUKgTLw"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Compute loss for true labels and plot\n",
"n_epoch = 60\n",
"loss_randomized_data = train_model(train_data_x_randomized, train_data_y, n_epoch)\n",
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
"ax.plot(loss_true_labels,'r-',label='true_labels')\n",
"ax.plot(loss_randomized_data,'b-',label='random_data')\n",
"# ax.set_ylim(0,0.7); ax.set_xlim(0,n_epoch)\n",
"ax.set_xlabel('Epoch'); ax.set_ylabel('Loss')\n",
"ax.legend()\n",
"plt.show()"
],
"metadata": {
"id": "y7CcCJvvjLnn"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# TODO -- Permute the labels\n",
"# Replace this line:\n",
"train_data_y_permuted = np.copy(train_data_y)"
],
"metadata": {
"id": "ojaMTrzKj_74"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Compute loss for true labels and plot\n",
"n_epoch = 60\n",
"loss_permuted_labels = train_model(train_data_x, train_data_y_permuted, n_epoch)\n",
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
"ax.plot(loss_true_labels,'r-',label='true_labels')\n",
"ax.plot(loss_randomized_data,'b-',label='random_data')\n",
"ax.plot(loss_permuted_labels,'g-',label='random_labels')\n",
"# ax.set_ylim(0,0.7); ax.set_xlim(0,n_epoch)\n",
"ax.set_xlabel('Epoch'); ax.set_ylabel('Loss')\n",
"ax.legend()\n",
"plt.show()"
],
"metadata": {
"id": "LaYCSjyMo9LQ"
},
"execution_count": null,
"outputs": []
}
]
}

View File

@@ -0,0 +1,296 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyO6xuszaG4nNAcWy/3juLkn",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap20/20_2_Full_Batch_Gradient_Descent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# **Notebook 20.2: Full Batch Gradient Descent**\n",
"\n",
"This notebook investigates training a network with full batch gradient descent as in figure 20.2. There is also a version (notebook takes a long time to run), but this didn't speed it up much for me. If you run out of CoLab time, you'll need to download the Python file and run locally.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
],
"metadata": {
"id": "t9vk9Elugvmi"
}
},
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to install MNIST 1D repository\n",
"!pip install git+https://github.com/greydanus/mnist1d"
],
"metadata": {
"id": "D5yLObtZCi9J"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import os\n",
"import torch, torch.nn as nn\n",
"from torch.utils.data import TensorDataset, DataLoader\n",
"from torch.optim.lr_scheduler import StepLR\n",
"import matplotlib.pyplot as plt\n",
"import mnist1d\n",
"import random\n",
"from IPython.display import display, clear_output"
],
"metadata": {
"id": "YrXWAH7sUWvU"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"args = mnist1d.data.get_dataset_args()\n",
"data = mnist1d.data.get_dataset(args, path='./mnist1d_data.pkl', download=False, regenerate=False)\n",
"\n",
"# The training and test input and outputs are in\n",
"# data['x'], data['y']\n",
"print(\"Examples in training set: {}\".format(len(data['y'])))\n",
"print(\"Length of each example: {}\".format(data['x'].shape[-1]))"
],
"metadata": {
"id": "twI72ZCrCt5z"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define the network"
],
"metadata": {
"id": "_sFvRDGrl4qe"
}
},
{
"cell_type": "code",
"source": [
"# Data is length forty, and there are 10 classes\n",
"D_i = 40\n",
"D_o = 10\n",
"\n",
"# create model with one hidden layer and 298 hidden units\n",
"model_1_layer = nn.Sequential(\n",
"nn.Linear(D_i, 298),\n",
"nn.ReLU(),\n",
"nn.Linear(298, D_o))\n",
"\n",
"\n",
"# TODO -- create model with three hidden layers and 100 hidden units per layer\n",
"# Replace this line\n",
"model_2_layer = nn.Sequential(nn.Linear(D_i, D_o))\n",
"\n",
"\n",
"\n",
"# TODO -- Create model with three hidden layers and 75 hidden units per layer\n",
"# Replace this line\n",
"model_3_layer = nn.Sequential(nn.Linear(D_i, D_o))\n",
"\n",
"\n",
"\n",
"# TODO create model with four hidden layers and 63 hidden units per layer\n",
"# Replace this line\n",
"model_4_layer = nn.Sequential(nn.Linear(D_i, D_o))\n",
"\n"
],
"metadata": {
"id": "FslroPJJffrh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# He initialization of weights\n",
"def weights_init(layer_in):\n",
" if isinstance(layer_in, nn.Linear):\n",
" nn.init.kaiming_uniform_(layer_in.weight)\n",
" layer_in.bias.data.fill_(0.0)"
],
"metadata": {
"id": "YgLaex1pfhqz"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def train_model(model, train_data_x, train_data_y, n_epoch):\n",
" print(\"This is going to take a long time!\")\n",
" # choose cross entropy loss function (equation 5.24 in the loss notes)\n",
" loss_function = nn.CrossEntropyLoss()\n",
" # construct SGD optimizer and initialize learning rate to small value and momentum to 0\n",
" optimizer = torch.optim.SGD(model.parameters(), lr = 0.0025, momentum=0.0)\n",
" # create 100 dummy data points and store in data loader class\n",
" x_train = torch.tensor(train_data_x.transpose().astype('float32'))\n",
" y_train = torch.tensor(train_data_y.astype('long'))\n",
"\n",
" # load the data into a class that creates the batches -- full batch as there are 4000 examples\n",
" data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=4000, shuffle=False, worker_init_fn=np.random.seed(1))\n",
"\n",
" # Initialize model weights\n",
" model.apply(weights_init)\n",
"\n",
" # store the errors percentage at each point\n",
" errors_train = np.zeros((n_epoch))\n",
"\n",
" for epoch in range(n_epoch):\n",
" # loop over batches\n",
" for i, data in enumerate(data_loader):\n",
" # retrieve inputs and labels for this batch\n",
" x_batch, y_batch = data\n",
" # zero the parameter gradients\n",
" optimizer.zero_grad()\n",
" # forward pass -- calculate model output\n",
" pred = model(x_batch)\n",
" # compute the loss\n",
" loss = loss_function(pred, y_batch)\n",
" # Store the errors\n",
" _, predicted_train_class = torch.max(pred.data, 1)\n",
" errors_train[epoch] = 100 - 100 * (predicted_train_class == y_train).float().sum() / len(y_train)\n",
" # backward pass\n",
" loss.backward()\n",
" # SGD update\n",
" optimizer.step()\n",
"\n",
" if epoch % 10 == 0:\n",
" clear_output(wait=True)\n",
" display(\"Epoch %d, errors_train %3.3f\"%(epoch, errors_train[epoch]))\n",
"\n",
" return errors_train"
],
"metadata": {
"id": "NYw8I_3mmX5c"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Load in the data\n",
"train_data_x = data['x'].transpose()\n",
"train_data_y = data['y']\n",
"# Print out sizes\n",
"print(\"Train data: %d examples (columns), each of which has %d dimensions (rows)\"%((train_data_x.shape[1],train_data_x.shape[0])))"
],
"metadata": {
"id": "4FE3HQ_vedXO"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Train the models\n",
"errors_four_layers = train_model(model_4_layer, train_data_x, train_data_y, n_epoch=200000)"
],
"metadata": {
"id": "b56wdODqemF1"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"errors_three_layers = train_model(model_3_layer, train_data_x, train_data_y, n_epoch=200000)\n"
],
"metadata": {
"id": "hqY-MJVPnCBV"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"errors_two_layers = train_model(model_2_layer, train_data_x, train_data_y, n_epoch=200000)\n"
],
"metadata": {
"id": "T61jfpNGnDGj"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"errors_one_layer = train_model(model_1_layer, train_data_x, train_data_y, n_epoch=500000)"
],
"metadata": {
"id": "HO8ZFgYqnEQe"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
"ax.plot(errors_one_layer,'r-',label='one layer')\n",
"ax.plot(errors_two_layers,'g-',label='two layers')\n",
"ax.plot(errors_three_layers,'b-',label='three layers')\n",
"ax.plot(errors_four_layers,'m-',label='four layers')\n",
"ax.set_ylim(0,100)\n",
"ax.set_xlabel('Epoch'); ax.set_ylabel('Percent error')\n",
"ax.legend()\n",
"plt.show()"
],
"metadata": {
"id": "pYL0YMI5oNSR"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "wJerga3M7eDw"
},
"execution_count": null,
"outputs": []
}
]
}

View File

@@ -0,0 +1,303 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"gpuType": "T4",
"authorship_tag": "ABX9TyOG/5A+P053/x1IfFg52z4V",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap20/20_2_Full_Batch_Gradient_Descent_GPU.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"source": [
"# **Notebook 20.2: Full Batch Gradient Descent**\n",
"\n",
"This notebook investigates training a network with full batch gradient descent as in figure 20.2. This is the GPU version (notebook takes a long time to run). If you are using Colab then you need to go change the runtime type to GPU on the Runtime menu. Even then, you may run out of time. If that's the case, you'll need to download the Python file and run locally.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n",
"\n"
],
"metadata": {
"id": "t9vk9Elugvmi"
}
},
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to install MNIST 1D repository\n",
"!pip install git+https://github.com/greydanus/mnist1d"
],
"metadata": {
"id": "D5yLObtZCi9J"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import os\n",
"import torch, torch.nn as nn\n",
"from torch.utils.data import TensorDataset, DataLoader\n",
"from torch.optim.lr_scheduler import StepLR\n",
"import matplotlib.pyplot as plt\n",
"import mnist1d\n",
"import random\n",
"from IPython.display import display, clear_output\n",
"\n",
"\n",
"# Try attaching to GPU\n",
"DEVICE = str(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))\n",
"print('Using:', DEVICE)"
],
"metadata": {
"id": "YrXWAH7sUWvU"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"args = mnist1d.data.get_dataset_args()\n",
"data = mnist1d.data.get_dataset(args, path='./mnist1d_data.pkl', download=False, regenerate=False)\n",
"\n",
"# The training and test input and outputs are in\n",
"# data['x'], data['y']\n",
"print(\"Examples in training set: {}\".format(len(data['y'])))\n",
"print(\"Length of each example: {}\".format(data['x'].shape[-1]))"
],
"metadata": {
"id": "twI72ZCrCt5z"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"Define the network"
],
"metadata": {
"id": "_sFvRDGrl4qe"
}
},
{
"cell_type": "code",
"source": [
"# Data is length forty, and there are 10 classes\n",
"D_i = 40\n",
"D_o = 10\n",
"\n",
"# create model with one hidden layer and 298 hidden units\n",
"model_1_layer = nn.Sequential(\n",
"nn.Linear(D_i, 298),\n",
"nn.ReLU(),\n",
"nn.Linear(298, D_o))\n",
"\n",
"\n",
"# TODO -- create model with three hidden layers and 100 hidden units per layer\n",
"# Replace this line\n",
"model_2_layer = nn.Sequential(nn.Linear(D_i, D_o))\n",
"\n",
"# TODO -- Create model with three hidden layers and 75 hidden units per layer\n",
"# Replace this line\n",
"model_3_layer = nn.Sequential(nn.Linear(D_i, D_o))\n",
"\n",
"# TODO create model with four hidden layers and 63 hidden units per layer\n",
"# Replace this line\n",
"model_4_layer = nn.Sequential(nn.Linear(D_i, D_o))\n"
],
"metadata": {
"id": "FslroPJJffrh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# He initialization of weights\n",
"def weights_init(layer_in):\n",
" if isinstance(layer_in, nn.Linear):\n",
" nn.init.kaiming_uniform_(layer_in.weight)\n",
" layer_in.bias.data.fill_(0.0)"
],
"metadata": {
"id": "YgLaex1pfhqz"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def train_model(model, train_data_x, train_data_y, n_epoch, DEVICE):\n",
" print(\"This is going to take a long time!\")\n",
" # choose cross entropy loss function (equation 5.24 in the loss notes)\n",
" loss_function = nn.CrossEntropyLoss()\n",
" # construct SGD optimizer and initialize learning rate to small value and momentum to 0\n",
" optimizer = torch.optim.SGD(model.parameters(), lr = 0.0025, momentum=0.0)\n",
" # create 100 dummy data points and store in data loader class\n",
" x_train = torch.tensor(train_data_x.transpose(), dtype=torch.float32, device=DEVICE)\n",
" y_train = torch.tensor(train_data_y, dtype=torch.long, device=DEVICE)\n",
"\n",
" # load the data into a class that creates the batches -- full batch as there are 4000 examples\n",
" data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=4000, shuffle=False, worker_init_fn=np.random.seed(1))\n",
"\n",
" # Initialize model weights\n",
" model.apply(weights_init)\n",
"\n",
" # store the errors percentage at each point\n",
" errors_train = np.zeros((n_epoch))\n",
"\n",
" for epoch in range(n_epoch):\n",
" # loop over batches\n",
" for i, data in enumerate(data_loader):\n",
" # retrieve inputs and labels for this batch\n",
" x_batch, y_batch = data\n",
" # zero the parameter gradients\n",
" optimizer.zero_grad()\n",
" # forward pass -- calculate model output\n",
" pred = model(x_batch)\n",
" # compute the loss\n",
" loss = loss_function(pred, y_batch)\n",
" # Store the errors\n",
" _, predicted_train_class = torch.max(pred.data, 1)\n",
" errors_train[epoch] = 100 - 100 * (predicted_train_class == y_train).float().sum() / len(y_train)\n",
" # backward pass\n",
" loss.backward()\n",
" # SGD update\n",
" optimizer.step()\n",
"\n",
" if epoch % 10 == 0:\n",
" clear_output(wait=True)\n",
" display(\"Epoch %d, errors_train %3.3f\"%(epoch, errors_train[epoch]))\n",
"\n",
" return errors_train"
],
"metadata": {
"id": "NYw8I_3mmX5c"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Load in the data\n",
"train_data_x = data['x'].transpose()\n",
"train_data_y = data['y']\n",
"# Print out sizes\n",
"print(\"Train data: %d examples (columns), each of which has %d dimensions (rows)\"%((train_data_x.shape[1],train_data_x.shape[0])))"
],
"metadata": {
"id": "4FE3HQ_vedXO"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Train the four models\n",
"model_4_layer = model_4_layer.to(DEVICE)\n",
"errors_four_layers = train_model(model_4_layer, train_data_x, train_data_y, n_epoch=200000, DEVICE=DEVICE)\n"
],
"metadata": {
"id": "b56wdODqemF1"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"model_3_layer = model_3_layer.to(DEVICE)\n",
"errors_three_layers = train_model(model_3_layer, train_data_x, train_data_y, n_epoch=200000, DEVICE=DEVICE)\n"
],
"metadata": {
"id": "63WsEgDCmbB4"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"model_2_layer = model_2_layer.to(DEVICE)\n",
"errors_two_layers = train_model(model_2_layer, train_data_x, train_data_y, n_epoch=200000, DEVICE=DEVICE)\n"
],
"metadata": {
"id": "3TfS5DaZmdCN"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"model_1_layer = model_1_layer.to(DEVICE)\n",
"errors_one_layer = train_model(model_1_layer, train_data_x, train_data_y, n_epoch=500000, DEVICE=DEVICE)"
],
"metadata": {
"id": "3f9Z6Mh4meeA"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
"ax.plot(errors_one_layer,'r-',label='one layer')\n",
"ax.plot(errors_two_layers,'g-',label='two layers')\n",
"ax.plot(errors_three_layers,'b-',label='three layers')\n",
"ax.plot(errors_four_layers,'m-',label='four layers')\n",
"ax.set_ylim(0,100)\n",
"ax.set_xlabel('Epoch'); ax.set_ylabel('Percent error')\n",
"ax.legend()\n",
"plt.show()"
],
"metadata": {
"id": "pYL0YMI5oNSR"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "iJem05Y03mZB"
},
"execution_count": null,
"outputs": []
}
]
}

Some files were not shown because too many files have changed in this diff Show More