Compare commits

...

298 Commits

Author SHA1 Message Date
udlbook
5302b32929 Created using Colab 2025-05-22 13:04:04 -04:00
udlbook
d5586e57fc Created using Colab 2025-05-22 12:12:42 -04:00
udlbook
d0acc42d81 Created using Colab 2025-05-22 12:11:38 -04:00
udlbook
f3188ac35a Created using Colab 2025-05-16 15:45:18 -04:00
udlbook
ad1b6a558b Created using Colab 2025-05-16 15:39:03 -04:00
udlbook
7eadd56eaa Created using Colab 2025-05-16 15:32:56 -04:00
udlbook
53c1357df7 Created using Colab 2025-05-16 15:21:19 -04:00
udlbook
8d862ede26 Created using Colab 2025-05-16 12:20:43 -04:00
udlbook
44bbfbed91 Created using Colab 2025-04-20 10:42:09 -04:00
udlbook
f65f0b1ddf Created using Colab 2025-04-20 10:25:38 -04:00
udlbook
1d6d6b6fbe Update SAT_Sudoku.ipynb 2025-04-20 10:24:02 -04:00
udlbook
62779ec260 Created using Colab 2025-04-20 10:23:27 -04:00
udlbook
be3edb60f9 Created using Colab 2025-04-19 16:35:23 -04:00
udlbook
b9403e091b Created using Colab 2025-04-19 16:35:10 -04:00
udlbook
2c916d9a87 Created using Colab 2025-04-19 16:30:00 -04:00
udlbook
310b71e203 Created using Colab 2025-04-19 12:48:29 -04:00
udlbook
fcb1333aed Created using Colab 2025-04-19 12:44:38 -04:00
udlbook
c39267b3b4 Created using Colab 2025-04-19 12:43:00 -04:00
udlbook
4291ed453c Created using Colab 2025-04-19 12:19:24 -04:00
udlbook
ab2ff3177a Add files via upload 2025-04-09 12:58:10 -04:00
udlbook
c2a4d40da3 Created using Colab 2025-04-04 15:15:23 -04:00
udlbook
aa75d3ad73 Created using Colab 2025-04-03 17:11:57 -04:00
udlbook
1f0c224a7d Created using Colab 2025-04-03 17:05:24 -04:00
udlbook
eb29a28284 Created using Colab 2025-04-03 16:48:48 -04:00
udlbook
7648203767 Created using Colab 2025-04-03 16:35:24 -04:00
udlbook
64e1d82d04 Created using Colab 2025-03-31 18:10:24 -04:00
udlbook
f7450d1875 Created using Colab 2025-03-31 18:07:05 -04:00
Simon Prince
884a7e358b Merge branch 'main' of https://github.com/udlbook/udlbook
commit.
2025-03-28 14:45:38 -04:00
Simon Prince
2016977f30 New release 2025-03-28 14:44:01 -04:00
udlbook
f88127c0d2 Created using Colab 2025-03-27 17:56:09 -04:00
udlbook
a637eec888 Created using Colab 2025-03-27 17:52:22 -04:00
udlbook
ddd6bf9149 Created using Colab 2025-03-27 17:47:29 -04:00
udlbook
0b41646bf3 Add files via upload 2025-03-27 12:57:57 -04:00
udlbook
16afbcdf83 Created using Colab 2025-03-24 15:35:15 -04:00
udlbook
b0add1f8e2 Merge pull request #277 from ullizen/patch-1
Update 4_2_Clipping_functions.ipynb
2025-03-24 15:31:02 -04:00
ullizen
03ebe5a039 Update 4_2_Clipping_functions.ipynb 2025-03-08 10:52:03 +01:00
udlbook
41e8262f20 Created using Colab 2025-03-04 16:39:17 -05:00
udlbook
2c6e1cb9f8 Created using Colab 2025-03-04 16:32:31 -05:00
udlbook
6c99c6b7eb Created using Colab 2025-03-04 14:31:39 -05:00
udlbook
0988ae8bd0 Merge pull request #273 from fredhsu/patch-1
Update 7_2_Backpropagation.ipynb to fix equation references
2025-03-04 14:00:59 -05:00
Fred Hsu
2cca6dec75 Update 7_2_Backpropagation.ipynb to fix equation references
Some off by one errors in the equation references.
2025-02-27 15:39:46 -08:00
udlbook
49d74b66a9 Created using Colab 2025-02-16 10:25:23 -05:00
udlbook
13c0ad30fe Merge pull request #270 from MarkGotham/main
"TO DO" > "TODO
2025-02-16 10:22:59 -05:00
udlbook
95549683c4 Created using Colab 2025-02-11 15:13:30 -05:00
Mark Gotham
9649ce382b "TO DO" > "TODO
In [commit 6072ad4](6072ad4), @KajvanRijn kindly changed all "TO DO" to "TODO" in the code blocks. That's useful. In addition, it should be changed (as here) in the instructions. Then there's no doubt or issue for anyone searching all instances.
2025-02-11 15:11:06 +00:00
udlbook
666cbb02d5 Created using Colab 2025-02-01 14:56:25 -05:00
udlbook
f0337130cb Created using Colab 2025-01-30 11:35:39 -05:00
udlbook
472571aef0 Created using Colab 2025-01-29 10:39:29 -05:00
udlbook
13b39c2f72 Created using Colab 2025-01-29 10:32:57 -05:00
udlbook
84a11d68ed Created using Colab 2025-01-29 10:29:54 -05:00
udlbook
653d2f7b84 Created using Colab 2025-01-29 10:28:29 -05:00
udlbook
a7ed3e2c34 Created using Colab 2025-01-29 10:24:36 -05:00
udlbook
40a2c3ca8b Created using Colab 2025-01-29 10:17:58 -05:00
udlbook
fb66cd682d Created using Colab 2025-01-28 11:43:39 -05:00
udlbook
88e8526fa7 Created using Colab 2025-01-28 10:59:00 -05:00
udlbook
667346fbdd Created using Colab 2025-01-28 10:57:32 -05:00
udlbook
4e564088a1 Created using Colab 2025-01-28 10:50:31 -05:00
udlbook
f1c07f53bf Created using Colab 2025-01-28 10:48:39 -05:00
udlbook
623b9782e7 Created using Colab 2025-01-28 10:36:43 -05:00
udlbook
60c5a48477 Delete Trees/LinearRegression_LeastSquares.ipynb 2025-01-27 17:40:21 -05:00
udlbook
b4688bda68 Created using Colab 2025-01-27 17:38:54 -05:00
Simon Prince
faf34e0887 fixed typo 2025-01-23 16:52:43 -05:00
Simon Prince
8f2ef53eab Merge branch 'main' of https://github.com/udlbook/udlbook
Trying to fix website problems
2025-01-23 16:25:08 -05:00
Simon Prince
2f0339341c bib file, eqns 2025-01-23 16:11:01 -05:00
udlbook
f8acbaab82 Add files via upload 2025-01-23 15:49:08 -05:00
udlbook
2aaaef0838 Delete UDL_Equations.pdf 2025-01-23 15:47:55 -05:00
udlbook
9a2039d392 Add files via upload 2025-01-23 15:40:43 -05:00
udlbook
6d76e47849 Created using Colab 2024-12-29 17:13:26 -05:00
udlbook
b5c65665b6 Update 10_4_Downsampling_and_Upsampling.ipynb 2024-12-18 09:06:15 -05:00
udlbook
dd9a56d96b Created using Colab 2024-12-16 16:06:30 -05:00
udlbook
9b71ac0487 Merge pull request #243 from aleksandrskoselevs/patch-2
Update 15_2_Wasserstein_Distance.ipynb
2024-12-02 15:52:24 -05:00
udlbook
eaff933ff7 Created using Colab 2024-12-02 15:43:55 -05:00
udlbook
c3dfe95700 Merge pull request #249 from ThePiep/fix-TODO
Change "TO DO" in comments to "TODO"
2024-12-02 15:19:54 -05:00
Kaj van Rijn
7082ae8620 Merge branch 'main' of github.com:ThePiep/udlbook-piep 2024-11-22 15:36:33 +01:00
Kaj van Rijn
6072ad4450 Change all TO DO to TODO 2024-11-22 15:34:52 +01:00
udlbook
33197fde36 Add files via upload 2024-11-21 16:45:29 -05:00
udlbook
6d425c04d4 Update 3_3_Shallow_Network_Regions.ipynb 2024-11-18 15:33:42 -05:00
udlbook
57c95132d3 Created using Colab 2024-11-12 17:11:44 -05:00
udlbook
2b0ac95740 Created using Colab 2024-11-08 12:31:21 -05:00
udlbook
d5f198f2d8 Add files via upload 2024-11-04 15:25:38 -05:00
udlbook
4edd8c923d Add files via upload 2024-10-30 16:51:41 -04:00
aleksandrskoselevs
1adb96e006 Update 15_2_Wasserstein_Distance.ipynb 2024-10-30 09:19:22 +01:00
udlbook
3801b8d52d Created using Colab 2024-10-24 16:45:43 -04:00
udlbook
dc6b346bda Created using Colab 2024-10-24 16:43:14 -04:00
udlbook
5eb264540d Created using Colab 2024-10-24 16:40:27 -04:00
udlbook
7ba844f2b5 Created using Colab 2024-10-24 16:04:27 -04:00
aleksandrskoselevs
be86733a93 Update 15_2_Wasserstein_Distance.ipynb
Scaling of the distance matrix was not mentioned in the book.
2024-10-22 12:11:15 +02:00
udlbook
d101aa428b Merge pull request #236 from aleksandrskoselevs/patch-1
Update 13_4_Graph_Attention_Networks.ipynb
2024-10-15 17:24:40 -04:00
aleksandrskoselevs
8c6e40daee Update 13_4_Graph_Attention_Networks.ipynb
`phi` is defined in the book as a column vector
2024-10-11 10:54:05 +02:00
udlbook
efafb942eb Add files via upload 2024-10-01 15:14:01 -04:00
udlbook
b10a2b6940 Delete UDL_Answer_Booklet.pdf 2024-10-01 15:13:35 -04:00
udlbook
ede7247a0c Add files via upload 2024-10-01 15:13:14 -04:00
udlbook
c3b97af456 Created using Colab 2024-09-16 09:21:22 -04:00
udlbook
e1df2156a3 Created using Colab 2024-09-16 09:19:49 -04:00
udlbook
f887835646 Created using Colab 2024-09-16 09:18:12 -04:00
udlbook
e9c8d846f2 Created using Colab 2024-09-16 07:36:27 -04:00
udlbook
b7869e8b41 Add files via upload 2024-08-28 13:01:31 -04:00
udlbook
747ec9efe1 Merge pull request #227 from aleksandrskoselevs/main
Notebook 9_5_Augmentation - Removed duplicate weight initialization
2024-08-23 18:17:17 -04:00
udlbook
58dfb0390c Merge pull request #224 from muddlebee/udlbook
fix(8.1) : error in Chap08\8_1_MNIST_1D_Performance.ipynb
2024-08-23 14:24:32 -04:00
aleksandrskoselevs
3aeb8db4cd cleaner diff 2024-08-23 10:29:52 +02:00
aleksandrskoselevs
305a055079 Revert "Remove duplicate weight initialization"
This reverts commit 87cf590af9.
2024-08-23 10:29:04 +02:00
aleksandrskoselevs
87cf590af9 Remove duplicate weight initialization 2024-08-23 09:57:38 +02:00
muddlebee
ccedbb72e7 fix(8.1) : error in Chap08\8_1_MNIST_1D_Performance.ipynb 2024-08-17 19:20:02 +05:30
muddlebee
b423a67855 fix(8.1) : error in Chap08\8_1_MNIST_1D_Performance.ipynb 2024-08-17 03:50:15 +05:30
muddlebee
3c8dab14e6 fix(8.1) : error in Chap08\8_1_MNIST_1D_Performance.ipynb 2024-08-17 03:48:56 +05:30
udlbook
ab73ae785b Add files via upload 2024-08-05 18:47:05 -04:00
udlbook
df86bbba04 Merge pull request #219 from jhrcek/jhrcek/fix-duplicate-words
Fix duplicate word occurrences in notebooks
2024-07-30 16:07:03 -04:00
udlbook
a9868e6da8 Rename README.md to src/README.md 2024-07-30 16:01:39 -04:00
Jan Hrček
fed3962bce Fix markdown headings 2024-07-30 11:25:47 +02:00
Jan Hrček
c5fafbca97 Fix duplicate word occurrences in notebooks 2024-07-30 11:16:30 +02:00
udlbook
5f16e0f9bc Fixed problem with example label. 2024-07-29 18:52:49 -04:00
udlbook
121c81a04e Update index.html 2024-07-22 18:42:22 -04:00
udlbook
e968741846 Add files via upload 2024-07-22 17:09:30 -04:00
udlbook
37011065d7 Add files via upload 2024-07-22 17:09:15 -04:00
udlbook
afd20d0364 Update 17_1_Latent_Variable_Models.ipynb 2024-07-22 15:03:17 -04:00
udlbook
0d135f1ee7 Fixed problems with MNIST1D 2024-07-19 15:55:44 -04:00
udlbook
54a020304e Merge pull request #211 from qualiaMachine/patch-1
Update 8_3_Double_Descent.ipynb
2024-07-10 15:53:00 -04:00
Chris Endemann
ccbbc4126e Update 8_3_Double_Descent.ipynb
Apologies, accidentally removed the "open in colab" button in the pull request you accepted earlier today. This corrects the mistake!
2024-07-10 14:15:21 -05:00
udlbook
d3273c99e2 Merge pull request #210 from qualiaMachine/main
Add vertical line to double descent plot indicating where count(weights) = count(train)
2024-07-10 14:33:31 -04:00
Chris Endemann
f9e45c976c Merge branch 'udlbook:main' into main 2024-07-10 09:43:18 -05:00
Chris Endemann
b005cec9c1 Update 8_3_Double_Descent.ipynb
I added a little code to include a vertical dashed line on the plot representing where total_weights = number of train observations.  I also moved n_epochs as an argument to fit_model() so learners can play around with the impact of n_epochs more easily.
2024-07-10 09:42:38 -05:00
udlbook
b8a91ad34d Merge pull request #208 from SwayStar123/patch-4
Update 12_2_Multihead_Self_Attention.ipynb
2024-07-09 17:53:31 -04:00
SwayStar123
a2a86c27bc Update 12_2_Multihead_Self_Attention.ipynb
title number is incorrect, its actually 12.2
2024-07-06 17:19:13 +05:30
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
147 changed files with 42332 additions and 1788 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 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

View File

@@ -0,0 +1,432 @@
{
"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/BorealisODENumerical.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JXsO7ce7oqeq"
},
"source": [
"# Numerical methods for ODEs\n",
"\n",
"This blog contains code that accompanies the RBC Borealis blog on numerical methods for ODEs. Contact udlbookmail@gmail.com if you find any problems."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "AnvAKtP_oqes"
},
"source": [
"Import relevant libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "UF-gJyZggyrl"
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "szWLVrSSoqet"
},
"source": [
"Define the ODE that we will be experimenting with."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NkrGZLL6iM3P"
},
"outputs": [],
"source": [
"# The ODE that we will experiment with\n",
"def ode_lin_homog(t,x):\n",
" return 0.5 * x ;\n",
"\n",
"# The derivative of the ODE function with respect to x (needed for Taylor's method)\n",
"def ode_lin_homog_deriv_x(t,x):\n",
" return 0.5 ;\n",
"\n",
"# The derivative of the ODE function with respect to t (needed for Taylor's method)\n",
"def ode_lin_homog_deriv_t(t,x):\n",
" return 0.0 ;\n",
"\n",
"# The closed form solution (so we can measure the error)\n",
"def ode_lin_homog_soln(t,C=0.5):\n",
" return C * np.exp(0.5 * t) ;"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "In1C9wZkoqet"
},
"source": [
"This is a generic method that runs the numerical methods. It takes the initial conditions ($t_0$, $x_0$), the final time $t_1$ and the step size $h$. It also takes the ODE function itself and its derivatives (only used for Taylor's method). Finally, the parameter \"step_function\" is the method used to update (e.g., Euler's methods, Runge-Kutte 4-step)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "VZfZDJAfmyrf"
},
"outputs": [],
"source": [
"def run_numerical(x_0, t_0, t_1, h, ode_func, ode_func_deriv_x, ode_func_deriv_t, ode_soln, step_function):\n",
" x = [x_0]\n",
" t = [t_0]\n",
" while (t[-1] <= t_1):\n",
" x = x+[step_function(x[-1],t[-1],h, ode_func, ode_func_deriv_x, ode_func_deriv_t)]\n",
" t = t + [t[-1]+h]\n",
"\n",
" # Returns x,y plot plus total numerical error at last point.\n",
" return t, x, np.abs(ode_soln(t[-1])-x[-1])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Vfkc3-_7oqet"
},
"source": [
"Run the numerical method with step sizes of 2.0, 1.0, 0.5, 0.25, 0.125, 0.0675 and plot the results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1tyGbMZhoqeu"
},
"outputs": [],
"source": [
"def run_and_plot(ode, ode_deriv_x, ode_deriv_t, ode_solution, step_function):\n",
" # Specify the grid of points to draw the ODE\n",
" t = np.arange(0.04, 4.0, 0.2)\n",
" x = np.arange(0.04, 4.0, 0.2)\n",
" T, X = np.meshgrid(t,x)\n",
"\n",
" # ODE equation at these grid points (used to draw quiver-plot)\n",
" dx = ode(T,X)\n",
" dt = np.ones(dx.shape)\n",
"\n",
" # The ground truth solution\n",
" t2= np.arange(0,10,0.1)\n",
" x2 = ode_solution(t2)\n",
"\n",
" #####################################x_0, t_0, t_1, h #################################################\n",
" t_sim1,x_sim1,error1 = run_numerical(0.5, 0.0, 4.0, 2.0000, ode, ode_deriv_x, ode_deriv_t, ode_solution, step_function)\n",
" t_sim2,x_sim2,error2 = run_numerical(0.5, 0.0, 4.0, 1.0000, ode, ode_deriv_x, ode_deriv_t, ode_solution, step_function)\n",
" t_sim3,x_sim3,error3 = run_numerical(0.5, 0.0, 4.0, 0.5000, ode, ode_deriv_x, ode_deriv_t, ode_solution, step_function)\n",
" t_sim4,x_sim4,error4 = run_numerical(0.5, 0.0, 4.0, 0.2500, ode, ode_deriv_x, ode_deriv_t, ode_solution, step_function)\n",
" t_sim5,x_sim5,error5 = run_numerical(0.5, 0.0, 4.0, 0.1250, ode, ode_deriv_x, ode_deriv_t, ode_solution, step_function)\n",
" t_sim6,x_sim6,error6 = run_numerical(0.5, 0.0, 4.0, 0.0675, ode, ode_deriv_x, ode_deriv_t, ode_solution, step_function)\n",
"\n",
" # Plot the ODE and ground truth solution\n",
" fig,ax = plt.subplots()\n",
" ax.quiver(T,X,dt,dx, scale=35.0)\n",
" ax.plot(t2,x2,'r-')\n",
"\n",
" # Plot the numerical approximations\n",
" ax.plot(t_sim1,x_sim1,'.-',markeredgecolor='#773c23ff',markerfacecolor='#d18362', color='#d18362', markersize=10)\n",
" ax.plot(t_sim2,x_sim2,'.-',markeredgecolor='#773c23ff',markerfacecolor='#d18362', color='#d18362', markersize=10)\n",
" ax.plot(t_sim3,x_sim3,'.-',markeredgecolor='#773c23ff',markerfacecolor='#d18362', color='#d18362', markersize=10)\n",
" ax.plot(t_sim4,x_sim4,'.-',markeredgecolor='#773c23ff',markerfacecolor='#d18362', color='#d18362', markersize=10)\n",
" ax.plot(t_sim5,x_sim5,'.-',markeredgecolor='#773c23ff',markerfacecolor='#d18362', color='#d18362', markersize=10)\n",
" ax.plot(t_sim6,x_sim6,'.-',markeredgecolor='#773c23ff',markerfacecolor='#d18362', color='#d18362', markersize=10)\n",
"\n",
" ax.set_aspect('equal')\n",
" ax.set_xlim(0,4)\n",
" ax.set_ylim(0,4)\n",
"\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JYrq8QIwvOIy"
},
"source": [
"# Euler Method\n",
"\n",
"Define the Euler method and set up functions for plotting."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "N73xMnCukVVX"
},
"outputs": [],
"source": [
"def euler_step(x_0, t_0, h, ode_func, ode_func_deriv_x=None, ode_func_deriv_t=None):\n",
" return x_0 + h * ode_func(t_0, x_0) ;"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4B1_PGEcsZ9H"
},
"outputs": [],
"source": [
"run_and_plot(ode_lin_homog, None, None, ode_lin_homog_soln, euler_step)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FfwNihtkvJeX"
},
"source": [
"# Heun's Method"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "srHfNDcDxI1o"
},
"outputs": [],
"source": [
"def heun_step(x_0, t_0, h, ode_func, ode_func_deriv_x=None, ode_func_deriv_t=None):\n",
" f_x0_t0 = ode_func(t_0, x_0)\n",
" return x_0 + h/2 * ( f_x0_t0 + ode_func(t_0+h, x_0+h*f_x0_t0)) ;"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "WOApHz9xoqev"
},
"outputs": [],
"source": [
"run_and_plot(ode_lin_homog, None, None, ode_lin_homog_soln, heun_step)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0XSzzFDIvRhm"
},
"source": [
"# Modified Euler method"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fSXprgVJ5Yep"
},
"outputs": [],
"source": [
"def modified_euler_step(x_0, t_0, h, ode_func, ode_func_deriv_x=None, ode_func_deriv_t=None):\n",
" f_x0_t0 = ode_func(t_0, x_0)\n",
" return x_0 + h * ode_func(t_0+h/2, x_0+ h * f_x0_t0/2) ;"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8LKSrCD2oqev"
},
"outputs": [],
"source": [
"run_and_plot(ode_lin_homog, None, None, ode_lin_homog_soln, modified_euler_step)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yp8ZBpwooqev"
},
"source": [
"# Second order Taylor's method"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NtBBgzWLoqev"
},
"outputs": [],
"source": [
"def taylor_2nd_order(x_0, t_0, h, ode_func, ode_func_deriv_x, ode_func_deriv_t):\n",
" f1 = ode_func(t_0, x_0)\n",
" return x_0 + h * ode_func(t_0, x_0) + (h*h/2) * (ode_func_deriv_x(t_0,x_0) * ode_func(t_0, x_0) + ode_func_deriv_t(t_0, x_0))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ioeeIohUoqev"
},
"outputs": [],
"source": [
"run_and_plot(ode_lin_homog, ode_lin_homog_deriv_x, ode_lin_homog_deriv_t, ode_lin_homog_soln, taylor_2nd_order)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WcuhV5lL1zAJ"
},
"source": [
"# Fourth Order Runge Kutta"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0NZN81Bpwu56"
},
"outputs": [],
"source": [
"def runge_kutta_4_step(x_0, t_0, h, ode_func, ode_func_deriv_x=None, ode_func_deriv_t=None):\n",
" f1 = ode_func(t_0, x_0)\n",
" f2 = ode_func(t_0+h/2,x_0+f1 * h/2)\n",
" f3 = ode_func(t_0+h/2,x_0+f2 * h/2)\n",
" f4 = ode_func(t_0+h, x_0+ f3*h)\n",
" return x_0 + (h/6) * (f1 + 2*f2 + 2*f3+f4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "K-OxE9E6oqew"
},
"outputs": [],
"source": [
"run_and_plot(ode_lin_homog, None, None, ode_lin_homog_soln, runge_kutta_4_step)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7JifxBhhoqew"
},
"source": [
"# Plot the error as a function of step size"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZoEpmlCfsi9P"
},
"outputs": [],
"source": [
"# Run systematically with a number of different step sizes and store errors for each\n",
"def get_errors(ode, ode_deriv_x, ode_deriv_t, ode_solution, step_function):\n",
" # Choose the step size h to divide the plotting interval into 1,2,4,8... segments.\n",
" # The plots in the article add a few more smaller step sizes, but this takes a while to compute.\n",
" # Add them back in if you want the full plot.\n",
" all_h = (1./np.array([1,2,4,8,16,32,64,128,256,512,1024,2048,4096])).tolist()\n",
" all_err = []\n",
"\n",
" for i in range(len(all_h)):\n",
" t_sim,x_sim,err = run_numerical(0.5, 0.0, 4.0, all_h[i], ode, ode_deriv_x, ode_deriv_t, ode_solution, step_function)\n",
" all_err = all_err + [err]\n",
"\n",
" return all_h, all_err"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "X0O0KK47xF28"
},
"outputs": [],
"source": [
"# Plot the errors\n",
"all_h, all_err_euler = get_errors(ode_lin_homog, ode_lin_homog_deriv_x, ode_lin_homog_deriv_t, ode_lin_homog_soln, euler_step)\n",
"all_h, all_err_heun = get_errors(ode_lin_homog, ode_lin_homog_deriv_x, ode_lin_homog_deriv_t, ode_lin_homog_soln, heun_step)\n",
"all_h, all_err_mod_euler = get_errors(ode_lin_homog, ode_lin_homog_deriv_x, ode_lin_homog_deriv_t, ode_lin_homog_soln, modified_euler_step)\n",
"all_h, all_err_taylor = get_errors(ode_lin_homog, ode_lin_homog_deriv_x, ode_lin_homog_deriv_t, ode_lin_homog_soln, taylor_2nd_order)\n",
"all_h, all_err_rk = get_errors(ode_lin_homog, ode_lin_homog_deriv_x, ode_lin_homog_deriv_t, ode_lin_homog_soln, runge_kutta_4_step)\n",
"\n",
"\n",
"fig, ax = plt.subplots()\n",
"ax.loglog(all_h, all_err_euler,'ro-')\n",
"ax.loglog(all_h, all_err_heun,'bo-')\n",
"ax.loglog(all_h, all_err_mod_euler,'go-')\n",
"ax.loglog(all_h, all_err_taylor,'co-')\n",
"ax.loglog(all_h, all_err_rk,'mo-')\n",
"ax.set_ylim(1e-13,1e1)\n",
"ax.set_xlim(1e-6,1e1)\n",
"ax.set_aspect(0.5)\n",
"ax.set_xlabel('Step size, $h$')\n",
"ax.set_ylabel('Error')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BttOqpeo9MsJ"
},
"source": [
"Note that for this ODE, the Heun, Modified Euler and Taylor methods provide EXACTLY the same updates, and so the error curves for all three are identical (subject to difference is numerical rounding errors). This is not in general the case, although the general trend would be the same for each."
]
}
],
"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.9.10"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

1127
Blogs/Borealis_NNGP.ipynb Normal file

File diff suppressed because one or more lines are too long

View File

@@ -128,7 +128,7 @@
"\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."
"Note that 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"

View File

@@ -199,7 +199,7 @@
{
"cell_type": "markdown",
"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": {
"id": "MvVX6tl9AEXF"

View File

@@ -218,7 +218,7 @@
{
"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 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 likelihood and the negative log likelihood."
],
"metadata": {
"id": "MvVX6tl9AEXF"

View File

@@ -128,7 +128,7 @@
"\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."
"Note that 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"

View File

@@ -214,7 +214,7 @@
{
"cell_type": "code",
"source": [
"# Compute the derivative of the the loss with respect to the function output f_val\n",
"# Compute the derivative of 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",

View File

@@ -1,18 +1,16 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap01/1_1_BackgroundMathematics.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": "s5zzKSOusPOB"
@@ -41,7 +39,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "WV2Dl6owme2d"
@@ -99,7 +96,7 @@
"ax.plot(x,y,'r-')\n",
"ax.set_ylim([0,10]);ax.set_xlim([0,10])\n",
"ax.set_xlabel('x'); ax.set_ylabel('y')\n",
"plt.show\n",
"plt.show()\n",
"\n",
"# TODO -- experiment with changing the values of beta and omega\n",
"# to understand what they do. Try to make a line\n",
@@ -107,7 +104,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "AedfvD9dxShZ"
@@ -192,7 +188,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "i8tLwpls476R"
@@ -236,7 +231,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "fGzVJQ6N-mHJ"
@@ -275,11 +269,10 @@
"# Compute with vector/matrix form\n",
"y_vec = beta_vec+np.matmul(omega_mat, x_vec)\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"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "3LGRoTMLU8ZU"
@@ -293,7 +286,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "7Y5zdKtKZAB2"
@@ -325,11 +317,10 @@
"ax.plot(x,y,'r-')\n",
"ax.set_ylim([0,100]);ax.set_xlim([-5,5])\n",
"ax.set_xlabel('x'); ax.set_ylabel('exp[x]')\n",
"plt.show"
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "XyrT8257IWCu"
@@ -341,11 +332,10 @@
"2. What is $\\exp[1]$?\n",
"3. What is $\\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"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "R6A4e5IxIWCu"
@@ -373,11 +363,10 @@
"ax.plot(x,y,'r-')\n",
"ax.set_ylim([-5,5]);ax.set_xlim([0,5])\n",
"ax.set_xlabel('x'); ax.set_ylabel('$\\log[x]$')\n",
"plt.show"
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "yYWrL5AXIWCv"
@@ -397,8 +386,8 @@
],
"metadata": {
"colab": {
"include_colab_link": true,
"provenance": []
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOmndC0N7dFV7W3Mh5ljOLl",
"include_colab_link": true
},
"kernelspec": {
@@ -197,7 +196,7 @@
"source": [
"# Visualizing the loss function\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",
"Now let's plot that function"
],
@@ -235,8 +234,8 @@
"levels = 40\n",
"ax.contour(phi0_mesh, phi1_mesh, all_losses ,levels, colors=['#80808080'])\n",
"ax.set_ylim([1,-1])\n",
"ax.set_xlabel('Intercept, $\\phi_0$')\n",
"ax.set_ylabel('Slope, $\\phi_1$')\n",
"ax.set_xlabel(r'Intercept, $\\phi_0$')\n",
"ax.set_ylabel(r'Slope, $\\phi_1$')\n",
"\n",
"# Plot the position of your best fitting line on the loss function\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": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNioITtfAcfxEfM3UOfQyb9",
"include_colab_link": true
},
"kernelspec": {
@@ -62,7 +61,7 @@
"source": [
"The number of regions $N$ created by a shallow neural network with $D_i$ inputs and $D$ hidden units is given by Zaslavsky's formula:\n",
"\n",
"\\begin{equation}N = \\sum_{j=0}^{D_{i}}\\binom{D}{j}=\\sum_{j=0}^{D_{i}} \\frac{D!}{(D-j)!j!} \\end{equation} <br>\n",
"\\begin{equation}N = \\sum_{j=0}^{D_{i}}\\binom{D}{j}=\\sum_{j=0}^{D_{i}} \\frac{D!}{(D-j)!j!} \\end{equation} \n",
"\n"
],
"metadata": {
@@ -221,7 +220,7 @@
{
"cell_type": "code",
"source": [
"# Now let's plot the graph from figure 3.9a (takes ~1min)\n",
"# Now let's plot the graph from figure 3.9b (takes ~1min)\n",
"dims = np.array([1,5,10,50,100])\n",
"regions = np.zeros((dims.shape[0], 200))\n",
"params = np.zeros((dims.shape[0], 200))\n",

View File

@@ -134,7 +134,7 @@
{
"cell_type": "markdown",
"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": {
"id": "LxBJCObC-NTY"

View File

@@ -4,7 +4,7 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyPkFrjmRAUf0fxN07RC4xMI",
"authorship_tag": "ABX9TyPZzptvvf7OPZai8erQ/0xT",
"include_colab_link": true
},
"kernelspec": {
@@ -127,26 +127,26 @@
" fig, ax = plt.subplots(3,3)\n",
" fig.set_size_inches(8.5, 8.5)\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,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,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[1,0].plot(x,h1_prime,'r-'); ax[1,0].set_ylabel(\"$h_{1}^{'}$\")\n",
" ax[1,1].plot(x,h2_prime,'b-'); ax[1,1].set_ylabel(\"$h_{2}^{'}$\")\n",
" ax[1,2].plot(x,h3_prime,'g-'); ax[1,2].set_ylabel(\"$h_{3}^{'}$\")\n",
" ax[2,0].plot(x,phi1_h1_prime,'r-'); ax[2,0].set_ylabel(\"$\\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,2].plot(x,phi3_h3_prime,'g-'); ax[2,2].set_ylabel(\"$\\phi_3 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(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(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(r\"$h_{1}^{'}$\")\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(r\"$h_{3}^{'}$\")\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(r\"$\\phi_2 h_{2}^{'}$\")\n",
" ax[2,2].plot(x,phi3_h3_prime,'g-'); ax[2,2].set_ylabel(r\"$\\phi_3 h_{3}^{'}$\")\n",
"\n",
" for plot_y 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_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",
"\n",
" fig, ax = plt.subplots()\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_aspect(0.5)\n",
" plt.show()"
@@ -169,7 +169,7 @@
{
"cell_type": "code",
"source": [
"# Define parameters (note first dimension of theta and phi is padded to make indices match\n",
"# Define parameters (note first dimension of theta and psi is padded to make indices match\n",
"# notation in book)\n",
"theta = np.zeros([4,2])\n",
"psi = np.zeros([4,4])\n",

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyO2DaD75p+LGi7WgvTzjrk1",
"include_colab_link": true
},
"kernelspec": {
@@ -31,7 +30,7 @@
"source": [
"# **Notebook 4.3 Deep neural networks**\n",
"\n",
"This network investigates converting neural networks to matrix form.\n",
"This notebook investigates converting neural networks to matrix form.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TODO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
@@ -118,7 +117,7 @@
{
"cell_type": "markdown",
"source": [
"Let's define a network. 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": {
"id": "LxBJCObC-NTY"
@@ -150,7 +149,7 @@
{
"cell_type": "markdown",
"source": [
"Now we'll define the same neural network, but this time, we will use matrix form. When you get this right, it will draw the same plot as above."
"Now we'll define the same neural network, but this time, we will use matrix form as in equation 4.15. When you get this right, it will draw the same plot as above."
],
"metadata": {
"id": "XCJqo_AjfAra"
@@ -176,8 +175,8 @@
"n1_in_mat = np.reshape(n1_in,(n_dim_in,n_data))\n",
"\n",
"# This runs the network for ALL of the inputs, x at once so we can draw graph\n",
"h1 = ReLU(np.matmul(beta_0,np.ones((1,n_data))) + np.matmul(Omega_0,n1_in_mat))\n",
"n1_out = np.matmul(beta_1,np.ones((1,n_data))) + np.matmul(Omega_1,h1)\n",
"h1 = ReLU(beta_0 + np.matmul(Omega_0,n1_in_mat))\n",
"n1_out = beta_1 + np.matmul(Omega_1,h1)\n",
"\n",
"# Draw the network and check that it looks the same as the non-matrix case\n",
"plot_neural(n1_in, n1_out)"
@@ -247,9 +246,9 @@
"n1_in_mat = np.reshape(n1_in,(n_dim_in,n_data))\n",
"\n",
"# This runs the network for ALL of the inputs, x at once so we can draw graph (hence extra np.ones term)\n",
"h1 = ReLU(np.matmul(beta_0,np.ones((1,n_data))) + np.matmul(Omega_0,n1_in_mat))\n",
"h2 = ReLU(np.matmul(beta_1,np.ones((1,n_data))) + np.matmul(Omega_1,h1))\n",
"n1_out = np.matmul(beta_2,np.ones((1,n_data))) + np.matmul(Omega_2,h2)\n",
"h1 = ReLU(beta_0 + np.matmul(Omega_0,n1_in_mat))\n",
"h2 = ReLU(beta_1 + np.matmul(Omega_1,h1))\n",
"n1_out = beta_2 + np.matmul(Omega_2,h2)\n",
"\n",
"# Draw the network and check that it looks the same as the non-matrix version\n",
"plot_neural(n1_in, n1_out)"
@@ -291,10 +290,10 @@
"\n",
"\n",
"# If you set the parameters to the correct sizes, the following code will run\n",
"h1 = ReLU(np.matmul(beta_0,np.ones((1,n_data))) + np.matmul(Omega_0,x));\n",
"h2 = ReLU(np.matmul(beta_1,np.ones((1,n_data))) + np.matmul(Omega_1,h1));\n",
"h3 = ReLU(np.matmul(beta_2,np.ones((1,n_data))) + np.matmul(Omega_2,h2));\n",
"y = np.matmul(beta_3,np.ones((1,n_data))) + np.matmul(Omega_3,h3)\n",
"h1 = ReLU(beta_0 + np.matmul(Omega_0,x));\n",
"h2 = ReLU(beta_1 + np.matmul(Omega_1,h1));\n",
"h3 = ReLU(beta_2 + np.matmul(Omega_2,h2));\n",
"y = beta_3 + np.matmul(Omega_3,h3)\n",
"\n",
"if h1.shape[0] is not D_1 or h1.shape[1] is not n_data:\n",
" print(\"h1 is wrong shape\")\n",

View File

@@ -118,7 +118,7 @@
" ax.plot(x_model,y_model)\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.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_aspect(0.5)\n",
" if title is not None:\n",
@@ -185,7 +185,7 @@
{
"cell_type": "code",
"source": [
"# Return probability under normal distribution for input x\n",
"# Return probability under normal distribution\n",
"def normal_distribution(y, mu, sigma):\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",
@@ -222,7 +222,7 @@
"gauss_prob = normal_distribution(y_gauss, mu, sigma)\n",
"fig, ax = plt.subplots()\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",
"plt.show()\n",
"\n",
@@ -329,7 +329,7 @@
"mu_pred = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
"# Set the standard deviation to something reasonable\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",
"# Let's double check we get the right answer before proceeding\n",
"print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(11.452419564,nll))"
@@ -388,7 +388,7 @@
{
"cell_type": "markdown",
"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": {
"id": "OgcRojvPWh4V"
@@ -431,7 +431,7 @@
{
"cell_type": "code",
"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,2)\n",
"fig.set_size_inches(10.5, 5.5)\n",
"fig.tight_layout(pad=10.0)\n",
@@ -530,7 +530,7 @@
{
"cell_type": "code",
"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,2)\n",
"fig.set_size_inches(10.5, 5.5)\n",
"fig.tight_layout(pad=10.0)\n",
@@ -581,7 +581,7 @@
{
"cell_type": "markdown",
"source": [
"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",
"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",
"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": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOSb+W2AOFVQm8FZcHAb2Jq",
"include_colab_link": true
},
"kernelspec": {
@@ -120,12 +119,12 @@
" fig.set_size_inches(7.0, 3.5)\n",
" fig.tight_layout(pad=3.0)\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",
" if title is not None:\n",
" ax[0].set_title(title)\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",
" if title is not None:\n",
" ax[1].set_title(title)\n",
@@ -199,7 +198,7 @@
{
"cell_type": "markdown",
"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": {
"id": "MvVX6tl9AEXF"
@@ -208,7 +207,7 @@
{
"cell_type": "code",
"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",
" # TODO-- write in the equation for the Bernoulli distribution\n",
" # Equation 5.17 from the notes (you will need np.power)\n",
@@ -269,7 +268,7 @@
"source": [
"# 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",
"# 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",
"lambda_train = sigmoid(model_out)\n",
"# Compute the likelihood\n",
@@ -336,7 +335,7 @@
{
"cell_type": "markdown",
"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": {
"id": "OgcRojvPWh4V"
@@ -359,7 +358,7 @@
" # Run the network with new parameters\n",
" model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\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",
" nlls[count] = compute_negative_log_likelihood(y_train, lambda_train)\n",
" # Draw the model for every 20th parameter setting\n",
@@ -378,7 +377,7 @@
{
"cell_type": "code",
"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 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",
@@ -430,7 +429,7 @@
"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",
"\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"
],
"metadata": {

View File

@@ -1,18 +1,16 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap05/5_3_Multiclass_Cross_entropy_Loss.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": "jSlFkICHwHQF"
@@ -142,7 +140,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "PsgLZwsPxauP"
@@ -209,13 +206,12 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"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."
"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 likelihood and the negative log likelihood."
]
},
{
@@ -226,7 +222,7 @@
},
"outputs": [],
"source": [
"# Return probability under Categorical distribution for input x\n",
"# 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)])"
@@ -240,15 +236,13 @@
},
"outputs": [],
"source": [
"# 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.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",
"\n"
"# Here are three examples\n",
"print(categorical_distribution(np.array([[0]]),np.array([[0.2],[0.5],[0.3]])))\n",
"print(categorical_distribution(np.array([[1]]),np.array([[0.2],[0.5],[0.3]])))\n",
"print(categorical_distribution(np.array([[2]]),np.array([[0.2],[0.5],[0.3]])))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "R5z_0dzQMF35"
@@ -286,7 +280,7 @@
"source": [
"# 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",
"# 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",
"lambda_train = softmax(model_out)\n",
"# Compute the likelihood\n",
@@ -296,7 +290,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "HzphKgPfOvlk"
@@ -318,7 +311,7 @@
"source": [
"# Return the negative log likelihood of the data under the model\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",
" # Replace the line below\n",
" nll = 0\n",
@@ -336,24 +329,23 @@
"source": [
"# 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",
"# 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 log likelihood\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))"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "OgcRojvPWh4V"
},
"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$)"
"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$)"
]
},
{
@@ -378,7 +370,7 @@
" # Run the network with new parameters\n",
" model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\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",
" nlls[count] = compute_negative_log_likelihood(y_train, lambda_train)\n",
" # Draw the model for every 20th parameter setting\n",
@@ -397,7 +389,7 @@
},
"outputs": [],
"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 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",
@@ -440,7 +432,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "771G8N1Vk5A2"
@@ -448,16 +439,15 @@
"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",
"\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"
]
}
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyOPv/l+ToaApJV7Nz+8AtpV",
"include_colab_link": true,
"provenance": []
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyN4E9Vtuk6t2BhZ0Ajv5SW3",
"include_colab_link": true
},
"kernelspec": {
@@ -67,7 +66,7 @@
" fig,ax = plt.subplots()\n",
" ax.plot(phi_plot,loss_function(phi_plot),'r-')\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",
" plt.axvspan(a, d, facecolor='k', alpha=0.2)\n",
" ax.plot([a,a],[0,1],'b-')\n",
@@ -113,7 +112,7 @@
" b = 0.33\n",
" c = 0.66\n",
" d = 1.0\n",
" n_iter =0;\n",
" n_iter = 0\n",
"\n",
" # While we haven't found the minimum closely enough\n",
" while np.abs(b-c) > thresh and n_iter < max_iter:\n",
@@ -131,8 +130,8 @@
"\n",
" print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n",
"\n",
" # Rule #1 If the HEIGHT at point A is less 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",
" # Rule #1 If the HEIGHT at point A is less than the HEIGHT at points B, C, and D then move them to they are half\n",
" # as far from A as they start\n",
" # i.e. bring them closer to the original point\n",
" # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n",
" if (0):\n",
@@ -140,7 +139,7 @@
"\n",
"\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 c becomes 2/3 between a and new d\n",
" # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n",
@@ -148,7 +147,7 @@
" continue;\n",
"\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 c becomes 2/3 between new a and d\n",
" # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n",

View File

@@ -1,18 +1,16 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
"id": "view-in-github",
"colab_type": "text"
},
"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>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "el8l05WQEO46"
@@ -111,13 +109,12 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "QU5mdGvpTtEG"
},
"source": [
"Now lets create compute the sum of squares loss for the training data"
"Now let's compute the sum of squares loss for the training data"
]
},
{
@@ -140,7 +137,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "eB5DQvU5hYNx"
@@ -162,7 +158,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "F3trnavPiHpH"
@@ -218,7 +213,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "s9Duf05WqqSC"
@@ -252,7 +246,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "RS1nEcYVuEAM"
@@ -265,7 +258,7 @@
"\\frac{\\partial L}{\\partial \\phi_{1}}&\\approx & \\frac{L[\\phi_0, \\phi_1+\\delta]-L[\\phi_0, \\phi_1]}{\\delta}\n",
"\\end{align}\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."
]
},
{
@@ -290,7 +283,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "5EIjMM9Fw2eT"
@@ -317,7 +309,7 @@
" b = 0.33 * max_dist\n",
" c = 0.66 * max_dist\n",
" d = 1.0 * max_dist\n",
" n_iter =0;\n",
" n_iter = 0\n",
"\n",
" # While we haven't found the minimum closely enough\n",
" while np.abs(b-c) > thresh and n_iter < max_iter:\n",
@@ -333,15 +325,15 @@
" print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n",
" print('a %f, b%f, c%f, d%f'%(lossa,lossb,lossc,lossd))\n",
"\n",
" # Rule #1 If point A is less than points B, C, and D then halve points B,C, and D\n",
" # Rule #1 If point A is less than points B, C, and D then halve distance from A to points B,C, and D\n",
" if np.argmin((lossa,lossb,lossc,lossd))==0:\n",
" b = b/2\n",
" c = c/2\n",
" d = d/2\n",
" b = a+ (b-a)/2\n",
" c = a+ (c-a)/2\n",
" d = a+ (d-a)/2\n",
" continue;\n",
"\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 c becomes 2/3 between a and new d\n",
" if lossb < lossc:\n",
@@ -351,7 +343,7 @@
" continue\n",
"\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 c becomes 2/3 between new a and d\n",
" a = b\n",
@@ -412,8 +404,8 @@
],
"metadata": {
"colab": {
"include_colab_link": true,
"provenance": []
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",

View File

@@ -1,18 +1,16 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
"id": "view-in-github",
"colab_type": "text"
},
"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>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "el8l05WQEO46"
@@ -53,7 +51,7 @@
},
"outputs": [],
"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",
"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",
@@ -122,13 +120,12 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "QU5mdGvpTtEG"
},
"source": [
"Now lets create compute the sum of squares loss for the training data"
"Now let's compute the sum of squares loss for the training data"
]
},
{
@@ -150,7 +147,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "eB5DQvU5hYNx"
@@ -172,7 +168,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "F3trnavPiHpH"
@@ -198,7 +193,7 @@
" 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",
" # 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",
" loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n",
@@ -228,7 +223,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "s9Duf05WqqSC"
@@ -279,7 +273,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "RS1nEcYVuEAM"
@@ -316,7 +309,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "5EIjMM9Fw2eT"
@@ -343,7 +335,7 @@
" b = 0.33 * max_dist\n",
" c = 0.66 * max_dist\n",
" d = 1.0 * max_dist\n",
" n_iter =0;\n",
" n_iter = 0\n",
"\n",
" # While we haven't found the minimum closely enough\n",
" while np.abs(b-c) > thresh and n_iter < max_iter:\n",
@@ -359,15 +351,15 @@
" print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n",
" print('a %f, b%f, c%f, d%f'%(lossa,lossb,lossc,lossd))\n",
"\n",
" # Rule #1 If point A is less than points B, C, and D then halve points B,C, and D\n",
" # Rule #1 If point A is less than points B, C, and D then change B,C,D so they are half their current distance from A\n",
" if np.argmin((lossa,lossb,lossc,lossd))==0:\n",
" b = b/2\n",
" c = c/2\n",
" d = d/2\n",
" b = a+ (b-a)/2\n",
" c = a+ (c-a)/2\n",
" d = a+ (d-a)/2\n",
" continue;\n",
"\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 c becomes 2/3 between a and new d\n",
" if lossb < lossc:\n",
@@ -377,7 +369,7 @@
" continue\n",
"\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 c becomes 2/3 between new a and d\n",
" a = b\n",
@@ -577,9 +569,8 @@
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyNk5FN4qlw3pk8BwDVWw1jN",
"include_colab_link": true,
"provenance": []
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",

View File

@@ -61,7 +61,7 @@
{
"cell_type": "code",
"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",
"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",
@@ -137,7 +137,7 @@
{
"cell_type": "markdown",
"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": {
"id": "QU5mdGvpTtEG"
@@ -160,7 +160,7 @@
" 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",
" # 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",
" loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n",
@@ -365,7 +365,6 @@
"\n",
" # Update the parameters\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",
"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",

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNFsCOnucz1nQt7PBEnKeTV",
"include_colab_link": true
},
"kernelspec": {
@@ -109,8 +108,8 @@
" 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',markersize=10)\n",
" ax.set_xlabel(\"$\\phi_{0}$\")\n",
" ax.set_ylabel(\"$\\phi_1}$\")\n",
" ax.set_xlabel(r\"$\\phi_{0}$\")\n",
" ax.set_ylabel(r\"$\\phi_{1}$\")\n",
" plt.show()"
],
"metadata": {
@@ -169,7 +168,7 @@
{
"cell_type": "markdown",
"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",
"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",
"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": {
"id": "_6KoKBJdGGI4"

View File

@@ -279,7 +279,7 @@
"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",
"like original = 0.139, like from forward pass = 0.000\n"
"l_i original = 0.139, l_i from forward pass = 0.000\n"
]
}
],
@@ -292,7 +292,7 @@
"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(\"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"
]
},
{

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyM2kkHLr00J4Jeypw41sTkQ",
"include_colab_link": true
},
"kernelspec": {
@@ -68,7 +67,7 @@
"# Set seed so we always get the same random numbers\n",
"np.random.seed(0)\n",
"\n",
"# Number of layers\n",
"# Number of hidden layers\n",
"K = 5\n",
"# Number of neurons per layer\n",
"D = 6\n",
@@ -115,9 +114,9 @@
{
"cell_type": "markdown",
"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_{0\\ldots K}$ are the entries of the list \"all_weights\" and the biases $\\boldsymbol\\beta_{0\\ldots K}$ are the entries of the list \"all_biases\"\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": {
"id": "5irtyxnLJSGX"
@@ -132,7 +131,7 @@
" K = len(all_weights) -1\n",
"\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_h = [None] * (K+1)\n",
"\n",
@@ -142,8 +141,8 @@
"\n",
" # Run through the layers, calculating all_f[0...K-1] and all_h[1...K]\n",
" for layer in range(K):\n",
" # Update preactivations and activations at this layer according to eqn 7.16\n",
" # Remmember to use np.matmul for matrrix multiplications\n",
" # Update preactivations and activations at this layer according to eqn 7.17\n",
" # Remember to use np.matmul for matrix multiplications\n",
" # TODO -- Replace the lines below\n",
" all_f[layer] = all_h[layer]\n",
" all_h[layer+1] = all_f[layer]\n",
@@ -166,7 +165,7 @@
{
"cell_type": "code",
"source": [
"# Define in input\n",
"# Define input\n",
"net_input = np.ones((D_i,1)) * 1.2\n",
"# Compute network output\n",
"net_output, all_f, all_h = compute_network_output(net_input,all_weights, all_biases)\n",
@@ -230,8 +229,8 @@
"# We'll need the indicator function\n",
"def indicator_function(x):\n",
" x_in = np.array(x)\n",
" x_in[x_in>=0] = 1\n",
" x_in[x_in<0] = 0\n",
" x_in[x_in>0] = 1\n",
" x_in[x_in<=0] = 0\n",
" return x_in\n",
"\n",
"# Main backward pass routine\n",
@@ -249,23 +248,23 @@
"\n",
" # Now work backwards through the network\n",
" for layer in range(K,-1,-1):\n",
" # TODO Calculate the derivatives of the loss with respect to the 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.22)\n",
" # NOTE! To take a copy of matrix X, use Z=np.array(X)\n",
" # REPLACE THIS LINE\n",
" all_dl_dbiases[layer] = np.zeros_like(all_biases[layer])\n",
"\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",
" # 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.23)\n",
" # Don't forget to use np.matmul\n",
" # REPLACE THIS LINE\n",
" all_dl_dweights[layer] = np.zeros_like(all_weights[layer])\n",
"\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",
" # 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.25)\n",
" # REPLACE THIS LINE\n",
" all_dl_dh[layer] = np.zeros_like(all_h[layer])\n",
"\n",
"\n",
" if layer > 0:\n",
" # TODO Calculate the derivatives of the loss with respect to the pre-activation f (use deriv of ReLu function, first part of last line of eq. 7.24)\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.25)\n",
" # REPLACE THIS LINE\n",
" all_dl_df[layer-1] = np.zeros_like(all_f[layer-1])\n",
"\n",
@@ -300,7 +299,7 @@
"delta_fd = 0.000001\n",
"\n",
"# Test the dervatives of the bias vectors\n",
"for layer in range(K):\n",
"for layer in range(K+1):\n",
" dl_dbias = np.zeros_like(all_dl_dbiases[layer])\n",
" # For every element in the bias\n",
" for row in range(all_biases[layer].shape[0]):\n",
@@ -324,7 +323,7 @@
"\n",
"\n",
"# Test the derivatives of the weights matrices\n",
"for layer in range(K):\n",
"for layer in range(K+1):\n",
" dl_dweight = np.zeros_like(all_dl_dweights[layer])\n",
" # For every element in the bias\n",
" for row in range(all_weights[layer].shape[0]):\n",

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNHLXFpiSnUzAbzhtOk+bxu",
"include_colab_link": true
},
"kernelspec": {
@@ -120,7 +119,7 @@
" K = len(all_weights)-1\n",
"\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_h = [None] * (K+1)\n",
"\n",
@@ -151,7 +150,7 @@
{
"cell_type": "markdown",
"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": {
"id": "bIUrcXnOqChl"
@@ -177,7 +176,7 @@
"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",
"\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])))"
],
"metadata": {
@@ -196,7 +195,7 @@
"# Change this to 50 layers with 80 hidden units per layer\n",
"\n",
"# TODO\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": {
"id": "VL_SO4tar3DC"
@@ -249,6 +248,9 @@
"\n",
"# Main backward pass routine\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",
" all_dl_dweights = [None] * (K+1)\n",
" all_dl_dbiases = [None] * (K+1)\n",
@@ -335,8 +337,8 @@
{
"cell_type": "code",
"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",
"# and the 1000 training examples\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 100 training examples\n",
"\n",
"# TODO\n",
"# Change this to 50 layers with 80 hidden units per layer\n",

View File

@@ -1,28 +1,10 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"gpuType": "T4",
"authorship_tag": "ABX9TyOuKMUcKfOIhIL2qTX9jJCy",
"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"
"colab_type": "text",
"id": "view-in-github"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap08/8_1_MNIST_1D_Performance.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
@@ -30,6 +12,9 @@
},
{
"cell_type": "markdown",
"metadata": {
"id": "L6chybAVFJW2"
},
"source": [
"# **Notebook 8.1: MNIST_1D_Performance**\n",
"\n",
@@ -38,25 +23,27 @@
"Work through the cells below, running each cell in turn. In various places you will see the words \"TODO\". 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": "L6chybAVFJW2"
}
]
},
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d"
],
"execution_count": null,
"metadata": {
"id": "ifVjS4cTOqKz"
},
"execution_count": null,
"outputs": []
"outputs": [],
"source": [
"# Run this if you're in a Colab to install MNIST 1D repository\n",
"%pip install git+https://github.com/greydanus/mnist1d"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qyE7G1StPIqO"
},
"outputs": [],
"source": [
"import torch, torch.nn as nn\n",
"from torch.utils.data import TensorDataset, DataLoader\n",
@@ -64,42 +51,42 @@
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import mnist1d"
],
"metadata": {
"id": "qyE7G1StPIqO"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "markdown",
"source": [
"Let's generate a training and test dataset using the MNIST1D code. The dataset gets saved as a .pkl file so it doesn't have to be regenerated each time."
],
"metadata": {
"id": "F7LNq72SP6jO"
}
},
"source": [
"Let's generate a training and test dataset using the MNIST1D code. The dataset gets saved as a .pkl file so it doesn't have to be regenerated each time."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YLxf7dJfPaqw"
},
"outputs": [],
"source": [
"args = mnist1d.data.get_dataset_args()\n",
"data = mnist1d.data.get_dataset(args, path='./sample_data/mnist1d_data.pkl', download=False, regenerate=False)\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": "YLxf7dJfPaqw"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FxaB5vc0uevl"
},
"outputs": [],
"source": [
"D_i = 40 # Input dimensions\n",
"D_k = 100 # Hidden dimensions\n",
@@ -120,15 +107,15 @@
"\n",
"# Call the function you just defined\n",
"model.apply(weights_init)\n"
],
"metadata": {
"id": "FxaB5vc0uevl"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_rX6N3VyyQTY"
},
"outputs": [],
"source": [
"# choose cross entropy loss function (equation 5.24)\n",
"loss_function = torch.nn.CrossEntropyLoss()\n",
@@ -136,11 +123,10 @@
"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(data['x'].astype('float32'))\n",
"y_train = torch.tensor(data['y'].transpose().astype('long'))\n",
"y_train = torch.tensor(data['y'].transpose().astype('int64'))\n",
"x_test= torch.tensor(data['x_test'].astype('float32'))\n",
"y_test = torch.tensor(data['y_test'].astype('long'))\n",
"y_test = torch.tensor(data['y_test'].astype('int64'))\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",
@@ -185,15 +171,15 @@
"\n",
" # tell scheduler to consider updating learning rate\n",
" scheduler.step()"
],
"metadata": {
"id": "_rX6N3VyyQTY"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "yI-l6kA_EH9G"
},
"outputs": [],
"source": [
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
@@ -214,25 +200,38 @@
"ax.set_title('Train loss %3.2f, Test loss %3.2f'%(losses_train[-1],losses_test[-1]))\n",
"ax.legend()\n",
"plt.show()"
],
"metadata": {
"id": "yI-l6kA_EH9G"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "q-yT6re6GZS4"
},
"source": [
"**TODO**\n",
"\n",
"Play with the model -- try changing the number of layers, hidden units, learning rate, batch size, momentum or anything else you like. See if you can improve the test results.\n",
"\n",
"Is it a good idea to optimize the hyperparameters in this way? Will the final result be a good estimate of the true test performance?"
],
"metadata": {
"id": "q-yT6re6GZS4"
}
}
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"authorship_tag": "ABX9TyOuKMUcKfOIhIL2qTX9jJCy",
"gpuType": "T4",
"include_colab_link": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@@ -92,7 +92,7 @@
{
"cell_type": "code",
"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",
"\n",
" fig,ax = plt.subplots()\n",
@@ -203,7 +203,7 @@
"# Closed form solution\n",
"beta, omega = fit_model_closed_form(x_data,y_data,n_hidden=3)\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",
"y_model = network(x_model, beta, omega)\n",
"\n",
@@ -268,7 +268,7 @@
"mean_model, std_model = get_model_mean_variance(n_data, n_datasets, n_hidden, sigma_func) ;\n",
"\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": {
"id": "Wxk64t2SoX9c"
@@ -302,7 +302,7 @@
"sigma_func = 0.3\n",
"n_hidden = 5\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",
"\n",
"for c_hidden in range(len(hidden_variables)):\n",

View File

@@ -5,7 +5,6 @@
"colab": {
"provenance": [],
"gpuType": "T4",
"authorship_tag": "ABX9TyN/KUpEObCKnHZ/4Onp5sHG",
"include_colab_link": true
},
"kernelspec": {
@@ -48,8 +47,8 @@
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d"
"# Run this if you're in a Colab to install MNIST 1D repository\n",
"!pip install git+https://github.com/greydanus/mnist1d"
],
"metadata": {
"id": "fn9BP5N5TguP"
@@ -100,7 +99,7 @@
"# 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]))"
"print(\"Dimensionality of each example: {}\".format(data['x'].shape[-1]))"
],
"metadata": {
"id": "PW2gyXL5UkLU"
@@ -124,7 +123,7 @@
" D_k = n_hidden # Hidden dimensions\n",
" D_o = 10 # Output dimensions\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",
" model = nn.Sequential(\n",
" nn.Linear(D_i, D_k),\n",
@@ -148,7 +147,7 @@
{
"cell_type": "code",
"source": [
"def fit_model(model, data):\n",
"def fit_model(model, data, n_epoch):\n",
"\n",
" # choose cross entropy loss function (equation 5.24)\n",
" loss_function = torch.nn.CrossEntropyLoss()\n",
@@ -157,7 +156,6 @@
" optimizer = torch.optim.SGD(model.parameters(), lr = 0.01, momentum=0.9)\n",
"\n",
"\n",
" # create 100 dummy data points and store in data loader class\n",
" x_train = torch.tensor(data['x'].astype('float32'))\n",
" y_train = torch.tensor(data['y'].transpose().astype('long'))\n",
" x_test= torch.tensor(data['x_test'].astype('float32'))\n",
@@ -166,9 +164,6 @@
" # 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",
" # loop over the dataset n_epoch times\n",
" n_epoch = 1000\n",
"\n",
" for epoch in range(n_epoch):\n",
" # loop over batches\n",
" for i, batch in enumerate(data_loader):\n",
@@ -205,6 +200,18 @@
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def count_parameters(model):\n",
" return sum(p.numel() for p in model.parameters() if p.requires_grad)"
],
"metadata": {
"id": "AQNCmFNV6JpV"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
@@ -228,19 +235,27 @@
"# This code will take a while (~30 mins on GPU) to run! Go and make a cup of coffee!\n",
"\n",
"hidden_variables = np.array([2,4,6,8,10,14,18,22,26,30,35,40,45,50,55,60,70,80,90,100,120,140,160,180,200,250,300,400]) ;\n",
"\n",
"errors_train_all = np.zeros_like(hidden_variables)\n",
"errors_test_all = np.zeros_like(hidden_variables)\n",
"total_weights_all = np.zeros_like(hidden_variables)\n",
"\n",
"# loop over the dataset n_epoch times\n",
"n_epoch = 1000\n",
"\n",
"# For each hidden variable size\n",
"for c_hidden in range(len(hidden_variables)):\n",
" print(f'Training model with {hidden_variables[c_hidden]:3d} hidden variables')\n",
" # Get a model\n",
" model = get_model(hidden_variables[c_hidden]) ;\n",
" # Count and store number of weights\n",
" total_weights_all[c_hidden] = count_parameters(model)\n",
" # Train the model\n",
" errors_train, errors_test = fit_model(model, data)\n",
" errors_train, errors_test = fit_model(model, data, n_epoch)\n",
" # Store the results\n",
" errors_train_all[c_hidden] = errors_train\n",
" errors_test_all[c_hidden]= errors_test"
" errors_test_all[c_hidden]= errors_test\n",
"\n"
],
"metadata": {
"id": "K4OmBZGHWXpk"
@@ -251,12 +266,29 @@
{
"cell_type": "code",
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"\n",
"# Assuming data['y'] is available and contains the training examples\n",
"num_training_examples = len(data['y'])\n",
"\n",
"# Find the index where total_weights_all is closest to num_training_examples\n",
"closest_index = np.argmin(np.abs(np.array(total_weights_all) - num_training_examples))\n",
"\n",
"# Get the corresponding value of hidden variables\n",
"hidden_variable_at_num_training_examples = hidden_variables[closest_index]\n",
"\n",
"# Plot the results\n",
"fig, ax = plt.subplots()\n",
"ax.plot(hidden_variables, errors_train_all, 'r-', label='train')\n",
"ax.plot(hidden_variables, errors_test_all, 'b-', label='test')\n",
"ax.set_ylim(0,100);\n",
"ax.set_xlabel('No hidden variables'); ax.set_ylabel('Error')\n",
"\n",
"# Add a vertical line at the point where total weights equal the number of training examples\n",
"ax.axvline(x=hidden_variable_at_num_training_examples, color='g', linestyle='--', label='N(weights) = N(train)')\n",
"\n",
"ax.set_ylim(0, 100)\n",
"ax.set_xlabel('No. hidden variables')\n",
"ax.set_ylabel('Error')\n",
"ax.legend()\n",
"plt.show()\n"
],
@@ -265,6 +297,24 @@
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "KT4X8_hE5NFb"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "iGKZSfVF2r4z"
},
"execution_count": null,
"outputs": []
}
]
}

View File

@@ -134,7 +134,7 @@
"source": [
"# Volume of a hypersphere\n",
"\n",
"In the second part of this notebook we calculate the volume of a hypersphere of radius 0.5 (i.e., of diameter 1) as a function of the radius. 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."
"In the second part of this notebook we calculate the volume of a hypersphere of radius 0.5 (i.e., of diameter 1) as a function of the radius. Note that 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"
@@ -224,7 +224,7 @@
{
"cell_type": "markdown",
"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",
"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

@@ -178,7 +178,7 @@
"\n",
"def draw_loss_function(compute_loss, data, model, my_colormap, phi_iters = None):\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",
" loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n",
@@ -304,7 +304,7 @@
"for c_step in range (n_steps):\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",
" # Measure loss and draw model every 4th step\n",
" # Measure loss and draw model every 8th step\n",
" if c_step % 8 == 0:\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",
@@ -369,7 +369,7 @@
"# Code to draw the regularization function\n",
"def draw_reg_function():\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",
" loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n",
@@ -399,7 +399,7 @@
"# Code to draw loss function with regularization\n",
"def draw_loss_function_reg(data, model, lambda_, my_colormap, phi_iters = None):\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",
" loss_mesh = np.zeros_like(freqs_mesh)\n",
" # Compute loss for every set of parameters\n",
@@ -512,7 +512,7 @@
"for c_step in range (n_steps):\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",
" # Measure loss and draw model every 4th step\n",
" # Measure loss and draw model every 8th step\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",
" 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",
"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": {
"id": "wrszSLrqZG4k"

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOR3WOJwfTlMD8eOLsPfPrz",
"include_colab_link": true
},
"kernelspec": {
@@ -140,7 +139,7 @@
" fig.set_size_inches(7,7)\n",
" ax.contourf(phi0mesh, phi1mesh, loss_function, 256, cmap=my_colormap);\n",
" ax.contour(phi0mesh, phi1mesh, loss_function, 20, colors=['#80808080'])\n",
" ax.set_xlabel('$\\phi_{0}$'); ax.set_ylabel('$\\phi_{1}$')\n",
" ax.set_xlabel(r'$\\phi_{0}$'); ax.set_ylabel(r'$\\phi_{1}$')\n",
"\n",
" if grad_path_typical_lr is not None:\n",
" ax.plot(grad_path_typical_lr[0,:], grad_path_typical_lr[1,:],'ro-')\n",
@@ -310,7 +309,7 @@
"grad_path_tiny_lr = None ;\n",
"\n",
"\n",
"# TODO: Run the gradient descent on the modified loss\n",
"# TODO: Run the gradient descent on the unmodified loss\n",
"# function with 100 steps and a very small learning rate alpha of 0.05\n",
"# Replace this line:\n",
"grad_path_typical_lr = None ;\n",

View File

@@ -52,7 +52,7 @@
"# import libraries\n",
"import numpy as np\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)"
]
},
@@ -80,7 +80,7 @@
" for i in range(n_data):\n",
" x[i] = np.random.uniform(i/n_data, (i+1)/n_data, 1)\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",
" for i in range(n_data):\n",
" y[i] = true_function(x[i])\n",
@@ -96,7 +96,7 @@
{
"cell_type": "code",
"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",
"\n",
" fig,ax = plt.subplots()\n",
@@ -137,7 +137,7 @@
"n_data = 15\n",
"x_data,y_data = generate_data(n_data, sigma_func)\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)"
],
"metadata": {
@@ -216,7 +216,7 @@
"# Closed form solution\n",
"beta, omega = fit_model_closed_form(x_data,y_data,n_hidden=14)\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",
"y_model = network(x_model, beta, omega)\n",
"\n",
@@ -297,7 +297,7 @@
{
"cell_type": "code",
"source": [
"# Plot the median of the results\n",
"# Plot the mean of the results\n",
"# TODO -- find the mean prediction\n",
"# Replace this line\n",
"y_model_mean = all_y_model[0,:]\n",

View File

@@ -1,18 +1,16 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap09/9_4_Bayesian_Approach.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": "el8l05WQEO46"
@@ -38,7 +36,7 @@
"# import libraries\n",
"import numpy as np\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)"
]
},
@@ -87,7 +85,7 @@
},
"outputs": [],
"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",
"\n",
" fig,ax = plt.subplots()\n",
@@ -159,7 +157,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "i8T_QduzeBmM"
@@ -195,7 +192,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "JojV6ueRk49G"
@@ -211,7 +207,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "YX0O_Ciwp4W1"
@@ -225,7 +220,7 @@
" &\\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{align}\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",
"\\begin{align}\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",
@@ -277,7 +272,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "GjPnlG4q0UFK"
@@ -334,7 +328,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "GiNg5EroUiUb"
@@ -343,17 +336,16 @@
"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",
"\\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",
"&=& \\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",
"&=& \\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",
"[\\mathbf{h}^*;1]\\biggr]\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 \\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",
"&= \\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",
"[\\mathbf{h}^*;1]\\biggr],\n",
"\\end{align}\n",
"\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",
"\n",
"\n",
"\n",
"To compute this, we reformulated the integrand using the relations from appendices\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 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",
"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",
"\n",
"If you feel so inclined you can work through the math of this yourself.\n",
@@ -404,7 +396,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "8Hcbe_16sK0F"
@@ -419,9 +410,8 @@
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyMB8B4269DVmrcLoCWrhzKF",
"include_colab_link": true,
"provenance": []
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyM38ZVBK4/xaHk5Ys5lF6dN",
"include_colab_link": true
},
"kernelspec": {
@@ -44,8 +43,8 @@
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d"
"# Run this if you're in a Colab to install MNIST 1D repository\n",
"!pip install git+https://github.com/greydanus/mnist1d"
],
"metadata": {
"id": "syvgxgRr3myY"
@@ -95,7 +94,7 @@
"D_k = 200 # Hidden dimensions\n",
"D_o = 10 # Output dimensions\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",
"model = nn.Sequential(\n",
"nn.Linear(D_i, D_k),\n",
@@ -108,10 +107,7 @@
" # Initialize the parameters with He initialization\n",
" if isinstance(layer_in, nn.Linear):\n",
" nn.init.kaiming_uniform_(layer_in.weight)\n",
" layer_in.bias.data.fill_(0.0)\n",
"\n",
"# Call the function you just defined\n",
"model.apply(weights_init)"
" layer_in.bias.data.fill_(0.0)\n"
],
"metadata": {
"id": "JfIFWFIL33eF"

View File

@@ -4,7 +4,7 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNJodaaCLMRWL9vTl8B/iLI",
"authorship_tag": "ABX9TyNb46PJB/CC1pcHGfjpUUZg",
"include_colab_link": true
},
"kernelspec": {
@@ -45,8 +45,8 @@
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d"
"# 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"

View File

@@ -31,7 +31,7 @@
"source": [
"# **Notebook 10.4: Downsampling and Upsampling**\n",
"\n",
"This notebook investigates the down sampling and downsampling methods discussed in section 10.4 of the book.\n",
"This notebook investigates the upsampling and downsampling methods discussed in section 10.4 of the book.\n",
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TODO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n",
@@ -301,7 +301,7 @@
"cell_type": "code",
"source": [
"# 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)"
],
"metadata": {

View File

@@ -4,7 +4,7 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNAcc98STMeyQgh9SbVHWG+",
"authorship_tag": "ABX9TyORZF8xy4X1yf4oRhRq8Rtm",
"include_colab_link": true
},
"kernelspec": {
@@ -65,10 +65,19 @@
"source": [
"# Run this once to load the train and test data straight into a dataloader class\n",
"# that will provide the batches\n",
"\n",
"# (It may complain that some files are missing because the files seem to have been\n",
"# reorganized on the underlying website, but it still seems to work). If everything is working\n",
"# properly, then the whole notebook should run to the end without further problems\n",
"# even before you make changes.\n",
"batch_size_train = 64\n",
"batch_size_test = 1000\n",
"\n",
"# TODO Change this directory to point towards an existing directory\n",
"myDir = '/files/'\n",
"\n",
"train_loader = torch.utils.data.DataLoader(\n",
" torchvision.datasets.MNIST('/files/', train=True, download=True,\n",
" torchvision.datasets.MNIST(myDir, train=True, download=True,\n",
" transform=torchvision.transforms.Compose([\n",
" torchvision.transforms.ToTensor(),\n",
" torchvision.transforms.Normalize(\n",
@@ -77,7 +86,7 @@
" batch_size=batch_size_train, shuffle=True)\n",
"\n",
"test_loader = torch.utils.data.DataLoader(\n",
" torchvision.datasets.MNIST('/files/', train=False, download=True,\n",
" torchvision.datasets.MNIST(myDir, train=False, download=True,\n",
" transform=torchvision.transforms.Compose([\n",
" torchvision.transforms.ToTensor(),\n",
" torchvision.transforms.Normalize(\n",

View File

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

View File

@@ -4,7 +4,7 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyMXS3SPB4cS/4qxix0lH/Hq",
"authorship_tag": "ABX9TyNIY8tswL9e48d5D53aSmHO",
"include_colab_link": true
},
"kernelspec": {
@@ -45,8 +45,8 @@
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d"
"# 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"

View File

@@ -4,7 +4,7 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyPVeAd3eDpEOCFh8CVyr1zz",
"authorship_tag": "ABX9TyPx2mM2zTHmDJeKeiE1RymT",
"include_colab_link": true
},
"kernelspec": {
@@ -45,8 +45,8 @@
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d"
"# 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"

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyMSk8qTqDYqFnRJVZKlsue0",
"include_colab_link": true
},
"kernelspec": {
@@ -29,7 +28,7 @@
{
"cell_type": "markdown",
"source": [
"# **Notebook 12.1: Multhead Self-Attention**\n",
"# **Notebook 12.2: Multihead Self-Attention**\n",
"\n",
"This notebook builds a multihead self-attention mechanism as in figure 12.6\n",
"\n",
@@ -147,9 +146,7 @@
" exp_values = np.exp(data_in) ;\n",
" # Sum over columns\n",
" denom = np.sum(exp_values, axis = 0);\n",
" # Replicate denominator to N rows\n",
" denom = np.matmul(np.ones((data_in.shape[0],1)), denom[np.newaxis,:])\n",
" # Compute softmax\n",
" # Compute softmax (numpy broadcasts denominator to all rows automatically)\n",
" softmax = exp_values / denom\n",
" # return the answer\n",
" return softmax"

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOMSGUFWT+YN0fwYHpMmHJM",
"include_colab_link": true
},
"kernelspec": {
@@ -99,7 +98,7 @@
"\n",
"# TODO -- Define node matrix\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",
"# chemical number of the element).\n",
"# Chemical numbers: Hydrogen-->1, Carbon-->6, Oxygen-->8\n",

View File

@@ -4,7 +4,7 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOdSkjfQnSZXnffGsZVM7r5",
"authorship_tag": "ABX9TyO/wJ4N9w01f04mmrs/ZSHY",
"include_colab_link": true
},
"kernelspec": {
@@ -109,7 +109,7 @@
"# Choose random values for the parameters\n",
"omega = np.random.normal(size=(D,D))\n",
"beta = np.random.normal(size=(D,1))\n",
"phi = np.random.normal(size=(1,2*D))"
"phi = np.random.normal(size=(2*D,1))"
],
"metadata": {
"id": "79TSK7oLMobe"
@@ -185,10 +185,10 @@
"np.set_printoptions(precision=3)\n",
"output = graph_attention(X, omega, beta, phi, A);\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.768 0.672 0. 0.529 3.841 4.749 5.376 4.761]\")\n",
"print(\" [0.305 0.129 0. 0.341 0.785 1.014 1.113 1.024]\")\n",
"print(\" [0. 0. 0. 0. 0.35 0.864 1.098 0.871]]]\")\n",
"print(\"[[0. 0.028 0.37 0. 0.97 0. 0. 0.698]\")\n",
"print(\" [0. 0. 0. 0. 1.184 0. 2.654 0. ]\")\n",
"print(\" [1.13 0.564 0. 1.298 0.268 0. 0. 0.779]\")\n",
"print(\" [0.825 0. 0. 1.175 0. 0. 0. 0. ]]]\")\n",
"\n",
"\n",
"print(\"Your answer is:\")\n",

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyM0StKV3FIZ3MZqfflqC0Rv",
"include_colab_link": true
},
"kernelspec": {
@@ -339,7 +338,7 @@
" print(\"Initial generator loss = \", compute_generator_loss(z, theta, phi0, phi1))\n",
" for iter in range(n_iter):\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",
" theta = theta + alpha * dl_dtheta ;\n",
"\n",

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNyLnpoXgKN+RGCuTUszCAZ",
"include_colab_link": true
},
"kernelspec": {
@@ -87,6 +86,7 @@
"cell_type": "code",
"source": [
"# TODO Define the distance matrix from figure 15.8d\n",
"# The index should be normalized before being used in the distance calculation.\n",
"# Replace this line\n",
"dist_mat = np.zeros((10,10))\n",
"\n",
@@ -129,7 +129,7 @@
{
"cell_type": "code",
"source": [
"draw_2D_heatmap(dist_mat,'Distance $|i-j|$', my_colormap)"
"draw_2D_heatmap(dist_mat,r'Distance $|i-j|$', my_colormap)"
],
"metadata": {
"id": "G0HFPBXyHT6V"
@@ -153,9 +153,9 @@
"cell_type": "code",
"source": [
"# 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",
"A = np.zeros((20,100))\n"
"A = np.zeros((20,100))"
],
"metadata": {
"id": "7KrybL96IuNW"
@@ -197,8 +197,8 @@
{
"cell_type": "code",
"source": [
"P = np.array(opt.x).reshape(10,10)\n",
"draw_2D_heatmap(P,'Transport plan $\\mathbf{P}$', my_colormap)"
"TP = np.array(opt.x).reshape(10,10)\n",
"draw_2D_heatmap(TP,r'Transport plan $\\mathbf{P}$', my_colormap)"
],
"metadata": {
"id": "nZGfkrbRV_D0"
@@ -218,8 +218,9 @@
{
"cell_type": "code",
"source": [
"was = np.sum(P * dist_mat)\n",
"print(\"Wasserstein distance = \", was)"
"was = np.sum(TP * dist_mat)\n",
"print(\"Your Wasserstein distance = \", was)\n",
"print(\"Correct answer = 0.15148578811369506\")"
],
"metadata": {
"id": "yiQ_8j-Raq3c"

View File

@@ -55,7 +55,7 @@
"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",
"As in figure 17.2, we'll assume that the output is two dimensional, 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",

View File

@@ -1,18 +1,16 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
"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>"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
@@ -40,7 +38,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "paLz5RukZP1J"
@@ -114,7 +111,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "r5Hl2QkimWx9"
@@ -139,13 +135,12 @@
"\n",
"fig,ax = plt.subplots()\n",
"ax.plot(phi_vals, expected_vals,'r-')\n",
"ax.set_xlabel('Parameter $\\phi$')\n",
"ax.set_ylabel('$\\mathbb{E}_{Pr(x|\\phi)}[f[x]]$')\n",
"ax.set_xlabel(r'Parameter $\\phi$')\n",
"ax.set_ylabel(r'$\\mathbb{E}_{Pr(x|\\phi)}[f[x]]$')\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "zTCykVeWqj_O"
@@ -253,13 +248,12 @@
"\n",
"fig,ax = plt.subplots()\n",
"ax.plot(phi_vals, deriv_vals,'r-')\n",
"ax.set_xlabel('Parameter $\\phi$')\n",
"ax.set_ylabel('$\\partial/\\partial\\phi\\mathbb{E}_{Pr(x|\\phi)}[f[x]]$')\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()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ASu4yKSwAEYI"
@@ -269,7 +263,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "xoFR1wifc8-b"
@@ -366,13 +359,12 @@
"\n",
"fig,ax = plt.subplots()\n",
"ax.plot(phi_vals, deriv_vals,'r-')\n",
"ax.set_xlabel('Parameter $\\phi$')\n",
"ax.set_ylabel('$\\partial/\\partial\\phi\\mathbb{E}_{Pr(x|\\phi)}[f[x]]$')\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()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "1TWBiUC7bQSw"
@@ -403,7 +395,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "d-0tntSYdKPR"
@@ -415,9 +406,8 @@
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyOxO2/0DTH4n4zhC97qbagY",
"include_colab_link": true,
"provenance": []
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",

View File

@@ -1,18 +1,16 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
"id": "view-in-github",
"colab_type": "text"
},
"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"
@@ -40,7 +38,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "f7a6xqKjkmvT"
@@ -61,7 +58,7 @@
"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-1)^4 \\bigr]\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}"
]
},
@@ -126,7 +123,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "Jr4UPcqmnXCS"
@@ -166,8 +162,8 @@
"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])"
" mean_all[i],variance_all[i] = compute_mean_variance(n_sample_all[i])\n",
" print(\"No samples: \", n_sample_all[i], \", Mean: \", mean_all[i], \", Variance: \", variance_all[i])"
]
},
{
@@ -189,7 +185,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "XTUpxFlSuOl7"
@@ -199,7 +194,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "6hxsl3Pxo1TT"
@@ -234,7 +228,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "G9Xxo0OJsIqD"
@@ -283,7 +276,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "2sVDqP0BvxqM"
@@ -313,8 +305,8 @@
"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])"
" mean_all2[i], variance_all2[i] = compute_mean_variance2(n_sample_all[i])\n",
" print(\"No samples: \", n_sample_all[i], \", Mean: \", mean_all2[i], \", Variance: \", variance_all2[i])"
]
},
{
@@ -348,7 +340,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "EtBP6NeLwZqz"
@@ -360,7 +351,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "_wuF-NoQu1--"
@@ -387,7 +377,7 @@
"def compute_expectation2b(n_samples):\n",
" # TODO -- complete this function\n",
" # 1. Draw n_samples from auxiliary distribution\n",
" # 2. Compute f[y] for those samples\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",
@@ -432,8 +422,8 @@
"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])"
" mean_all2b[i], variance_all2b[i] = compute_mean_variance2b(n_sample_all[i])\n",
" print(\"No samples: \", n_sample_all[i], \", Mean: \", mean_all2b[i], \", Variance: \", variance_all2b[i])"
]
},
{
@@ -478,7 +468,6 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "y8rgge9MNiOc"
@@ -490,9 +479,8 @@
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyNecz9/CDOggPSmy1LjT/Dv",
"include_colab_link": true,
"provenance": []
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",

View File

@@ -3,8 +3,8 @@
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
"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>"
@@ -409,7 +409,7 @@
" # 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",
" # 6. Multiply result by 0.01 to compensate for bin size\n",
"\n",
" # Replace this line:\n",
" marginal_at_time_t = marginal_at_time_t\n",
"\n",
@@ -454,9 +454,8 @@
],
"metadata": {
"colab": {
"authorship_tag": "ABX9TyMpC8kgLnXx0XQBtwNAQ4jJ",
"include_colab_link": true,
"provenance": []
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",

View File

@@ -4,7 +4,6 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOlD6kmCxX3SKKuh3oJikKA",
"include_colab_link": true
},
"kernelspec": {
@@ -393,7 +392,7 @@
{
"cell_type": "code",
"source": [
"# Update the state values for the current policy, by making the values at at adjacent\n",
"# Update the state values for the current policy, by making the values 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",
@@ -406,6 +405,10 @@
" state_values_new[state] = 3.0\n",
" break\n",
"\n",
" # TODO -- Write this function (from equation 19.11, but bear in mind policy is deterministic here)\n",
" # Replace this line\n",
" state_values_new[state] = 0\n",
"\n",
" return state_values_new\n",
"\n",
"# Greedily choose the action that maximizes the value for each state.\n",

View File

@@ -1,20 +1,4 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyMWjsdr5SDwyzcDftnehlNo",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
@@ -28,6 +12,9 @@
},
{
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 19.3: Monte-Carlo methods**\n",
"\n",
@@ -37,42 +24,49 @@
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TODO\". 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"
}
"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",
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image"
],
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"execution_count": null,
"outputs": []
"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"
],
"metadata": {
"id": "ZsvrUszPLyEG"
},
"execution_count": null,
"outputs": []
]
},
{
"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",
@@ -257,205 +251,281 @@
"\n",
"\n",
" plt.show()"
],
"metadata": {
"id": "Gq1HfJsHN3SB"
},
"execution_count": null,
"outputs": []
]
},
{
"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\n",
"layout[10] = 1; reward_structure[10] = -2\n",
"layout[14] = 1; reward_structure[14] = -2\n",
"layout[15] = 2; reward_structure[15] = 3\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)"
],
"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"
}
},
"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"
],
"metadata": {
"id": "Fhc6DzZNOjiC"
}
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "l7rT78BbOgTi"
},
"outputs": [],
"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",
"[[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.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",
"[[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.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",
"[[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.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",
"[[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)"
],
"metadata": {
"id": "l7rT78BbOgTi"
" 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])"
]
},
"execution_count": null,
"outputs": []
{
"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, stochastic_policy):\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"
],
"metadata": {
"id": "akjrncMF-FkU"
},
"execution_count": null,
"outputs": []
" return new_state, reward, action, is_terminal"
]
},
{
"cell_type": "code",
"source": [
"# Run one episode and return actions, rewards, returns\n",
"def get_one_episode(initial_state, transition_probabilities_given_action, reward_structure, stochastic_policy):\n",
"\n",
" max_steps = 1000\n",
" states = np.zeros(max_steps, dtype='uint8') ;\n",
" rewards = np.zeros(max_steps) ;\n",
" actions = np.zeros(max_steps, dtype='uint8') ;\n",
"\n",
" t = 0\n",
" states[t] = initial_state\n",
" # While haven't reached maximum number of steps\n",
" while t< max_steps:\n",
" # Keep stepping through MDP\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",
" # If we reach te:rminal state then quit\n",
" if states[t]==15:\n",
" break;\n",
" t+=1\n",
"\n",
" states = states[:t+1]\n",
" rewards = rewards[:t+1]\n",
" actions = actions[:t+1]\n",
"\n",
" return states, rewards, actions"
],
"execution_count": null,
"metadata": {
"id": "bFYvF9nAloIA"
},
"execution_count": null,
"outputs": []
"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.1):\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",
@@ -464,27 +534,27 @@
"\n",
"\n",
" return stochastic_policy"
],
"metadata": {
"id": "_AKwdtQQHzIK"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "markdown",
"source": [
"Let's try generating an episode"
],
"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(0)\n",
"np.random.seed(6)\n",
"# Print in compact form\n",
"np.set_printoptions(precision=3)\n",
"\n",
@@ -494,32 +564,55 @@
"# Convert deterministic policy to stochastic\n",
"stochastic_policy = deterministic_policy_to_epsilon_greedy(policy)\n",
"\n",
"print(\"Initial policy:\")\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",
"states, rewards, actions = get_one_episode(initial_state,transition_probabilities_given_action, reward_structure, stochastic_policy)"
],
"metadata": {
"id": "5zQ1Oh9Zvnwt"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"We'll need to calculate the returns (discounted cumulative reward) for each state action pair"
],
"metadata": {
"id": "nl6rtNffwhcU"
}
"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_like(rewards)\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",
@@ -529,26 +622,26 @@
" for i in range(len(rewards)):\n",
" return_val += rewards[i] * np.power(gamma, i)\n",
" return return_val"
],
"metadata": {
"id": "FxrItqGPLTq7"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "markdown",
"source": [
"This routine does the main work of the 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."
],
"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, stochastic_policy, gamma, n_rollouts=1):\n",
"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",
@@ -574,18 +667,18 @@
" 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"
],
"metadata": {
"id": "hCghcKlOJXSM"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8jWhDlkaKj7Q"
},
"outputs": [],
"source": [
"# Set seed so random numbers always the same\n",
"np.random.seed(3)\n",
"np.random.seed(0)\n",
"# Print in compact form\n",
"np.set_printoptions(precision=3)\n",
"\n",
@@ -597,32 +690,60 @@
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
"mdp_drawer.draw(layout, policy = policy, rewards = reward_structure)\n",
"\n",
"\n",
"n_policy_update = 5\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, stochastic_policy, gamma, n_rollouts=1000)\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"
],
"metadata": {
"id": "8jWhDlkaKj7Q"
},
"execution_count": null,
"outputs": []
" mdp_drawer.draw(layout, policy = policy, rewards = reward_structure, state_action_values=state_action_values)\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"source": [
"You can see that the results are quite noisy, but there is a definite improvement from the initial policy."
],
"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

@@ -1,20 +1,4 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyNEAhORON7DFN1dZMhDK/PO",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
@@ -28,6 +12,9 @@
},
{
"cell_type": "markdown",
"metadata": {
"id": "t9vk9Elugvmi"
},
"source": [
"# **Notebook 19.4: Temporal difference methods**\n",
"\n",
@@ -35,42 +22,49 @@
"\n",
"Work through the cells below, running each cell in turn. In various places you will see the words \"TODO\". 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"
}
"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",
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image"
],
"execution_count": null,
"metadata": {
"id": "OLComQyvCIJ7"
},
"execution_count": null,
"outputs": []
"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"
],
"metadata": {
"id": "ZsvrUszPLyEG"
},
"execution_count": null,
"outputs": []
]
},
{
"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",
@@ -253,269 +247,516 @@
" 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()"
],
"metadata": {
"id": "Gq1HfJsHN3SB"
]
},
"execution_count": null,
"outputs": []
{
"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\n",
"layout[10] = 1; reward_structure[10] = -2\n",
"layout[14] = 1; reward_structure[14] = -2\n",
"layout[15] = 2; reward_structure[15] = 3\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)"
],
"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"
}
},
"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"
],
"metadata": {
"id": "Fhc6DzZNOjiC"
}
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wROjgnqh76xN"
},
"outputs": [],
"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",
"[[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.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",
"[[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.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",
"[[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.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",
"[[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)"
],
"metadata": {
"id": "l7rT78BbOgTi"
" 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])"
]
},
"execution_count": null,
"outputs": []
{
"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 q_learning_step(state_action_values, reward, state, new_state, action, gamma, alpha = 0.1):\n",
"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"
],
"metadata": {
"id": "5pO6-9ACWhiV"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "code",
"cell_type": "markdown",
"metadata": {
"id": "u4OHTTk176xO"
},
"source": [
"# This takes a single step from an MDP which just has a completely random policy\n",
"def markov_decision_process_step(state, transition_probabilities_given_action, reward_structure):\n",
" # Pick action\n",
" action = np.random.randint(4)\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 -- here the reward is for leaving the state\n",
" reward = reward_structure[state]\n",
"\n",
" return new_state, reward, action"
],
"metadata": {
"id": "akjrncMF-FkU"
},
"execution_count": null,
"outputs": []
"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 = np.argmax(state_action_values, axis=0).astype(int)\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 = markov_decision_process_step(initial_state, transition_probabilities_given_action, reward_structure)\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, gamma)\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.27650262412468796\")\n",
"print(\"True value: 0.3024718977397814\")\n",
"\n",
"policy = np.argmax(state_action_values, axis=0).astype(int)\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"
],
"metadata": {
"id": "Fu5_VjvbSwfJ"
},
"execution_count": null,
"outputs": []
]
},
{
"cell_type": "markdown",
"source": [
"Now let's run this for a while and watch the policy improve"
],
"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",
"# Hard code termination state of finding fish\n",
"state_action_values[:,n_state-1] = 3.0\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",
"policy = np.argmax(state_action_values, axis=0).astype(int)\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",
"\n",
"state = np.random.randint(n_state-1)\n",
"\n",
"# Run for a number of iterations\n",
"for c_iter in range(10000):\n",
" new_state, reward, action = markov_decision_process_step(state, transition_probabilities_given_action, reward_structure)\n",
" state_action_values_after = q_learning_step(state_action_values, reward, state, new_state, action, gamma)\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 new_state==15:\n",
" if is_terminal:\n",
" state = np.random.randint(n_state-1)\n",
" else:\n",
" state = new_state\n",
" # Update the policy\n",
" state_action_values = np.copy(state_action_values_after)\n",
" policy = np.argmax(state_action_values, axis=0).astype(int)\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)"
],
"metadata": {
"id": "qQFhwVqPcCFH"
]
},
{
"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,
"outputs": []
}
"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

@@ -4,7 +4,7 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyPkSYbEjOcEmLt8tU6HxNuR",
"authorship_tag": "ABX9TyNgBRvfIlngVobKuLE6leM+",
"include_colab_link": true
},
"kernelspec": {
@@ -45,8 +45,8 @@
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d"
"# 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"

View File

@@ -4,7 +4,7 @@
"metadata": {
"colab": {
"provenance": [],
"authorship_tag": "ABX9TyOo4vm4MXcIvAzVlMCaLikH",
"authorship_tag": "ABX9TyO6xuszaG4nNAcWy/3juLkn",
"include_colab_link": true
},
"kernelspec": {
@@ -44,8 +44,8 @@
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d"
"# 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"

View File

@@ -5,7 +5,7 @@
"colab": {
"provenance": [],
"gpuType": "T4",
"authorship_tag": "ABX9TyMjPBfDONmjqTSyEQDP2gjY",
"authorship_tag": "ABX9TyOG/5A+P053/x1IfFg52z4V",
"include_colab_link": true
},
"kernelspec": {
@@ -47,8 +47,8 @@
{
"cell_type": "code",
"source": [
"# Run this if you're in a Colab to make a local copy of the MNIST 1D repository\n",
"!git clone https://github.com/greydanus/mnist1d"
"# 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"

View File

@@ -43,7 +43,8 @@
"id": "Sg2i1QmhKW5d"
},
"source": [
"# Run this if you're in a Colab\n",
"# Run this if you're in a Colab to install MNIST 1D repository\n",
"!pip install git+https://github.com/greydanus/mnist1d\n",
"!git clone https://github.com/greydanus/mnist1d"
],
"execution_count": null,
@@ -95,6 +96,12 @@
"id": "I-vm_gh5xTJs"
},
"source": [
"from mnist1d.data import get_dataset, get_dataset_args\n",
"from mnist1d.utils import set_seed, to_pickle, from_pickle\n",
"\n",
"import sys ; sys.path.append('./mnist1d/notebooks')\n",
"from train import get_model_args, train_model\n",
"\n",
"args = mnist1d.get_dataset_args()\n",
"data = mnist1d.get_dataset(args=args) # by default, this will download a pre-made dataset from the GitHub repo\n",
"\n",
@@ -210,7 +217,7 @@
" # we would return [1,1,0,0,1]\n",
" # Remember that these are torch tensors and not numpy arrays\n",
" # Replace this function:\n",
" mask = torch.ones_like(scores)\n",
" mask = torch.ones_like(absolute_weights)\n",
"\n",
"\n",
" return mask"
@@ -237,7 +244,6 @@
"def find_lottery_ticket(model, dataset, args, sparsity_schedule, criteria_fn=None, **kwargs):\n",
"\n",
" criteria_fn = lambda init_params, final_params: final_params.abs()\n",
"\n",
" init_params = model.get_layer_vecs()\n",
" stats = {'train_losses':[], 'test_losses':[], 'train_accs':[], 'test_accs':[]}\n",
" models = []\n",
@@ -253,7 +259,7 @@
" model.set_layer_masks(masks)\n",
"\n",
" # training process\n",
" results = mnist1d.train_model(dataset, model, args)\n",
" results = train_model(dataset, model, args)\n",
" model = results['checkpoints'][-1]\n",
"\n",
" # store stats\n",
@@ -291,7 +297,8 @@
},
"source": [
"# train settings\n",
"model_args = mnist1d.get_model_args()\n",
"from train import get_model_args, train_model\n",
"model_args = get_model_args()\n",
"model_args.total_steps = 1501\n",
"model_args.hidden_size = 500\n",
"model_args.print_every = 5000 # print never\n",

View File

@@ -137,7 +137,7 @@
"id": "CfZ-srQtmff2"
},
"source": [
"Why might the distributions for blue and yellow populations be different? It could be that the behaviour of the populations is identical, but the credit rating algorithm is biased; it may favor one population over another or simply be more noisy for one group. Alternatively, it could be that that the populations genuinely behave differently. In practice, the differences in blue and yellow distributions are probably attributable to a combination of these factors.\n",
"Why might the distributions for blue and yellow populations be different? It could be that the behaviour of the populations is identical, but the credit rating algorithm is biased; it may favor one population over another or simply be more noisy for one group. Alternatively, it could be that the populations genuinely behave differently. In practice, the differences in blue and yellow distributions are probably attributable to a combination of these factors.\n",
"\n",
"Lets assume that we cant retrain the credit score prediction algorithm; our job is to adjudicate whether each individual is refused the loan ($\\hat{y}=0$)\n",
" or granted it ($\\hat{y}=1$). Since we only have the credit score\n",
@@ -382,7 +382,7 @@
"source": [
"# Equal opportunity:\n",
"\n",
"The thresholds are chosen so that so that the true positive rate is is the same for both population. Of the people who pay back the loan, the same proportion are offered credit in each group. In terms of the two ROC curves, it means choosing thresholds so that the vertical position on each curve is the same without regard for the horizontal position."
"The thresholds are chosen so that so that the true positive rate is the same for both population. Of the people who pay back the loan, the same proportion are offered credit in each group. In terms of the two ROC curves, it means choosing thresholds so that the vertical position on each curve is the same without regard for the horizontal position."
]
},
{

7
Notebooks/LICENSE (MIT) Normal file
View File

@@ -0,0 +1,7 @@
Copyright 2023 Simon Prince
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1061
Trees/SAT_Crossword.ipynb Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

248
Trees/SAT_Exhaustive.ipynb Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

270
Trees/SAT_Sudoku.ipynb Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

251
Trees/SAT_Tseitin.ipynb Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

264
Trees/SAT_Z3.ipynb Normal file

File diff suppressed because one or more lines are too long

335
Trees/SAT_Z3_Answers.ipynb Normal file

File diff suppressed because one or more lines are too long

Binary file not shown.

Binary file not shown.

2229
UDL_Equations.tex Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -1,406 +1,20 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>udlbook</title>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Encode+Sans+Expanded:wght@400;700&display=swap"
rel="stylesheet"
/>
<title>Understanding Deep Learning</title>
</head>
<body>
<div id="head">
<div>
<h1 style="margin: 0; font-size: 36px">Understanding Deep Learning</h1>
by Simon J.D. Prince
<br>Published by MIT Press Dec 5th 2023.<br>
<ul>
<li>
<p style="font-size: larger; margin-bottom: 0">Download draft PDF Chapters 1-21 <a
href="https://github.com/udlbook/udlbook/releases/download/v.1.18/UnderstandingDeepLearning_24_12_23_C.pdf">here</a>
</p>2023-12-24. CC-BY-NC-ND license<br>
<img src="https://img.shields.io/github/downloads/udlbook/udlbook/total" alt="download stats shield">
</li>
<li> Order your copy from <a href="https://mitpress.mit.edu/9780262048644/understanding-deep-learning/">here </a></li>
<li> Known errata can be found here: <a
href="https://github.com/udlbook/udlbook/raw/main/UDL_Errata.pdf">PDF</a></li>
<li> Report new errata via <a href="https://github.com/udlbook/udlbook/issues">github</a>
or contact me directly at udlbookmail@gmail.com
<li> Follow me on <a href="https://twitter.com/SimonPrinceAI">Twitter</a> or <a
href="https://www.linkedin.com/in/simon-prince-615bb9165/">LinkedIn</a> for updates.
</ul>
<h2>Table of contents</h2>
<ul>
<li> Chapter 1 - Introduction
<li> Chapter 2 - Supervised learning
<li> Chapter 3 - Shallow neural networks
<li> Chapter 4 - Deep neural networks
<li> Chapter 5 - Loss functions
<li> Chapter 6 - Training models
<li> Chapter 7 - Gradients and initialization
<li> Chapter 8 - Measuring performance
<li> Chapter 9 - Regularization
<li> Chapter 10 - Convolutional networks
<li> Chapter 11 - Residual networks
<li> Chapter 12 - Transformers
<li> Chapter 13 - Graph neural networks
<li> Chapter 14 - Unsupervised learning
<li> Chapter 15 - Generative adversarial networks
<li> Chapter 16 - Normalizing flows
<li> Chapter 17 - Variational autoencoders
<li> Chapter 18 - Diffusion models
<li> Chapter 19 - Deep reinforcement learning
<li> Chapter 20 - Why does deep learning work?
<li> Chapter 21 - Deep learning and ethics
</ul>
</div>
<div id="cover">
<img src="https://raw.githubusercontent.com/udlbook/udlbook/main/UDLCoverSmall.jpg"
alt="front cover">
</div>
</div>
<div id="body">
<h2>Resources for instructors </h2>
<p>Instructor answer booklet available with proof of credentials via <a
href="https://mitpress.mit.edu/9780262048644/understanding-deep-learning"> MIT Press</a>.</p>
<p>Request an exam/desk copy via <a href="https://mitpress.ublish.com/request?cri=15055">MIT Press</a>.</p>
<p>Figures in PDF (vector) / SVG (vector) / Powerpoint (images):
<ul>
<li> Chapter 1 - Introduction: <a href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap1PDF.zip">PDF
Figures</a> / <a href="https://drive.google.com/uc?export=download&id=1udnl5pUOAc8DcAQ7HQwyzP9pwL95ynnv">
SVG
Figures</a> / <a
href="https://docs.google.com/presentation/d/1IjTqIUvWCJc71b5vEJYte-Dwujcp7rvG/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 2 - Supervised learning: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap2PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1VSxcU5y1qNFlmd3Lb3uOWyzILuOj1Dla"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1Br7R01ROtRWPlNhC_KOommeHAWMBpWtz/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 3 - Shallow neural networks: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap3PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=19kZFWlXhzN82Zx02ByMmSZOO4T41fmqI"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1e9M3jB5I9qZ4dCBY90Q3Hwft_i068QVQ/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 4 - Deep neural networks: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap4PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1ojr0ebsOhzvS04ItAflX2cVmYqHQHZUa"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1LTSsmY4mMrJbqXVvoTOCkQwHrRKoYnJj/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 5 - Loss functions: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap5PDF.zip">PDF
Figures</a> / <a href="https://drive.google.com/uc?export=download&id=17MJO7fiMpFZVqKeqXTbQ36AMpmR4GizZ">
SVG
Figures</a> / <a
href="https://docs.google.com/presentation/d/1gcpC_3z9oRp87eMkoco-kdLD-MM54Puk/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 6 - Training models: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap6PDF.zip">PDF
Figures</a> / <a href="https://drive.google.com/uc?export=download&id=1VPdhFRnCr9_idTrX0UdHKGAw2shUuwhK">
SVG
Figures</a> / <a
href="https://docs.google.com/presentation/d/1AKoeggAFBl9yLC7X5tushAGzCCxmB7EY/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 7 - Gradients and initialization: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap7PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1TTl4gvrTvNbegnml4CoGoKOOd6O8-PGs"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/11zhB6PI-Dp6Ogmr4IcI6fbvbqNqLyYcz/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 8 - Measuring performance: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap8PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=19eQOnygd_l0DzgtJxXuYnWa4z7QKJrJx"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1SHRmJscDLUuQrG7tmysnScb3ZUAqVMZo/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 9 - Regularization: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap9PDF.zip">PDF
Figures</a> / <a href="https://drive.google.com/uc?export=download&id=1LprgnUGL7xAM9-jlGZC9LhMPeefjY0r0">
SVG
Figures</a> / <a
href="https://docs.google.com/presentation/d/1VwIfvjpdfTny6sEfu4ZETwCnw6m8Eg-5/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 10 - Convolutional networks: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap10PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1-Wb3VzaSvVeRzoUzJbI2JjZE0uwqupM9"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1MtfKBC4Y9hWwGqeP6DVwUNbi1j5ncQCg/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 11 - Residual networks: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap11PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1Mr58jzEVseUAfNYbGWCQyDtEDwvfHRi1"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1saY8Faz0KTKAAifUrbkQdLA2qkyEjOPI/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 12 - Transformers: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap12PDF.zip">PDF
Figures</a> / <a href="https://drive.google.com/uc?export=download&id=1txzOVNf8-jH4UfJ6SLnrtOfPd1Q3ebzd">
SVG
Figures</a> / <a
href="https://docs.google.com/presentation/d/1GVNvYWa0WJA6oKg89qZre-UZEhABfm0l/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 13 - Graph neural networks: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap13PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1lQIV6nRp6LVfaMgpGFhuwEXG-lTEaAwe"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1YwF3U82c1mQ74c1WqHVTzLZ0j7GgKaWP/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 14 - Unsupervised learning: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap14PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1aMbI6iCuUvOywqk5pBOmppJu1L1anqsM"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1A-lBGv3NHl4L32NvfFgy1EKeSwY-0UeB/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">
PowerPoint Figures</a>
<li> Chapter 15 - Generative adversarial networks: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap15PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1EErnlZCOlXc3HK7m83T2Jh_0NzIUHvtL"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/10Ernk41ShOTf4IYkMD-l4dJfKATkXH4w/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 16 - Normalizing flows: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap16PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1B9bxtmdugwtg-b7Y4AdQKAIEVWxjx8l3"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1nLLzqb9pdfF_h6i1HUDSyp7kSMIkSUUA/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 17 - Variational autoencoders: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap17PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1SNtNIY7khlHQYMtaOH-FosSH3kWwL4b7"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1lQE4Bu7-LgvV2VlJOt_4dQT-kusYl7Vo/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Chapter 18 - Diffusion models: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap18PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1A-pIGl4PxjVMYOKAUG3aT4a8wD3G-q_r"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1x_ufIBtVPzWUvRieKMkpw5SdRjXWwdfR/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">
PowerPoint Figures</a>
<li> Chapter 19 - Deep reinforcement learning: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap19PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1a5WUoF7jeSgwC_PVdckJi1Gny46fCqh0"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1TnYmVbFNhmMFetbjyfXGmkxp1EHauMqr/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">
PowerPoint Figures </a>
<li> Chapter 20 - Why does deep learning work?: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap20PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1M2d0DHEgddAQoIedKSDTTt7m1ZdmBLQ3"> SVG Figures</a>
/
<a href="https://docs.google.com/presentation/d/1coxF4IsrCzDTLrNjRagHvqB_FBy10miA/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">
PowerPoint Figures</a>
<li> Chapter 21 - Deep learning and ethics: <a
href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap21PDF.zip">PDF Figures</a> / <a
href="https://drive.google.com/uc?export=download&id=1jixmFfwmZkW_UVYzcxmDcMsdFFtnZ0bU"> SVG Figures</a>/
<a
href="https://docs.google.com/presentation/d/1EtfzanZYILvi9_-Idm28zD94I_6OrN9R/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">PowerPoint
Figures</a>
<li> Appendices - <a href="https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLAppendixPDF.zip">PDF
Figures</a> / <a href="https://drive.google.com/uc?export=download&id=1k2j7hMN40ISPSg9skFYWFL3oZT7r8v-l">
SVG
Figures</a> / <a
href="https://docs.google.com/presentation/d/1_2cJHRnsoQQHst0rwZssv-XH4o5SEHks/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true">Powerpoint
Figures</a>
</ul>
Instructions for editing figures / equations can be found <a
href="https://drive.google.com/file/d/1T_MXXVR4AfyMnlEFI-UVDh--FXI5deAp/view?usp=sharing">here</a>.
<p> My slides for 20 lecture undergraduate deep learning course:</p>
<ul>
<li><a href="https://drive.google.com/uc?export=download&id=17RHb11BrydOvxSFNbRIomE1QKLVI087m">1. Introduction</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1491zkHULC7gDfqlV6cqUxyVYXZ-de-Ub">2. Supervised Learning</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1XkP1c9EhOBowla1rT1nnsDGMf2rZvrt7">3. Shallow Neural Networks</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1e2ejfZbbfMKLBv0v-tvBWBdI8gO3SSS1">4. Deep Neural Networks</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1fxQ_a1Q3eFPZ4kPqKbak6_emJK-JfnRH">5. Loss Functions</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=17QQ5ZzXBtR_uCNCUU1gPRWWRUeZN9exW">6. Fitting Models</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1hC8JUCOaFWiw3KGn0rm7nW6mEq242QDK">7. Computing Gradients</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1tSjCeAVg0JCeBcPgDJDbi7Gg43Qkh9_d">7b. Initialization</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1RVZW3KjEs0vNSGx3B2fdizddlr6I0wLl">8. Performance</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1LTicIKPRPbZRkkg6qOr1DSuOB72axood">9. Regularization</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1bGVuwAwrofzZdfvj267elIzkYMIvYFj0">10. Convolutional Networks</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=14w31QqWRDix1GdUE-na0_E0kGKBhtKzs">11. Image Generation</a></li>
<li><a href="https://drive.google.com/uc?export=download&id=1af6bTTjAbhDYfrDhboW7Fuv52Gk9ygKr">12. Transformers and LLMs</a></li>
</ul>
<h2>Resources for students</h2>
<p>Answers to selected questions: <a
href="https://github.com/udlbook/udlbook/raw/main/UDL_Answer_Booklet_Students.pdf">PDF</a>
</p>
<p>Python notebooks: (Early ones more thoroughly tested than later ones!)</p>
<ul>
<li> Notebook 1.1 - Background mathematics: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap01/1_1_BackgroundMathematics.ipynb">ipynb/colab</a>
</li>
<li> Notebook 2.1 - Supervised learning: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap02/2_1_Supervised_Learning.ipynb">ipynb/colab</a>
</li>
<li> Notebook 3.1 - Shallow networks I: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap03/3_1_Shallow_Networks_I.ipynb">ipynb/colab </a>
</li>
<li> Notebook 3.2 - Shallow networks II: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap03/3_2_Shallow_Networks_II.ipynb">ipynb/colab </a>
</li>
<li> Notebook 3.3 - Shallow network regions: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap03/3_3_Shallow_Network_Regions.ipynb">ipynb/colab </a>
</li>
<li> Notebook 3.4 - Activation functions: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap03/3_4_Activation_Functions.ipynb">ipynb/colab </a>
</li>
<li> Notebook 4.1 - Composing networks: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap04/4_1_Composing_Networks.ipynb">ipynb/colab </a>
</li>
<li> Notebook 4.2 - Clipping functions: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap04/4_2_Clipping_functions.ipynb">ipynb/colab </a>
</li>
<li> Notebook 4.3 - Deep networks: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap04/4_3_Deep_Networks.ipynb">ipynb/colab </a>
</li>
<li> Notebook 5.1 - Least squares loss: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap05/5_1_Least_Squares_Loss.ipynb">ipynb/colab </a>
</li>
<li> Notebook 5.2 - Binary cross-entropy loss: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap05/5_2_Binary_Cross_Entropy_Loss.ipynb">ipynb/colab </a>
</li>
<li> Notebook 5.3 - Multiclass cross-entropy loss: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap05/5_3_Multiclass_Cross_entropy_Loss.ipynb">ipynb/colab </a>
</li>
<li> Notebook 6.1 - Line search: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_1_Line_Search.ipynb">ipynb/colab </a>
</li>
<li> Notebook 6.2 - Gradient descent: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_2_Gradient_Descent.ipynb">ipynb/colab </a>
</li>
<li> Notebook 6.3 - Stochastic gradient descent: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_3_Stochastic_Gradient_Descent.ipynb">ipynb/colab </a>
</li>
<li> Notebook 6.4 - Momentum: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_4_Momentum.ipynb">ipynb/colab </a>
</li>
<li> Notebook 6.5 - Adam: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_5_Adam.ipynb">ipynb/colab </a>
</li>
<li> Notebook 7.1 - Backpropagation in toy model: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap07/7_1_Backpropagation_in_Toy_Model.ipynb">ipynb/colab </a>
</li>
<li> Notebook 7.2 - Backpropagation: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap07/7_2_Backpropagation.ipynb">ipynb/colab </a>
</li>
<li> Notebook 7.3 - Initialization: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap07/7_3_Initialization.ipynb">ipynb/colab </a>
</li>
<li> Notebook 8.1 - MNIST-1D performance: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap08/8_1_MNIST_1D_Performance.ipynb">ipynb/colab </a>
</li>
<li> Notebook 8.2 - Bias-variance trade-off: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap08/8_2_Bias_Variance_Trade_Off.ipynb">ipynb/colab </a>
</li>
<li> Notebook 8.3 - Double descent: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap08/8_3_Double_Descent.ipynb">ipynb/colab </a>
</li>
<li> Notebook 8.4 - High-dimensional spaces: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap08/8_4_High_Dimensional_Spaces.ipynb">ipynb/colab </a>
</li>
<li> Notebook 9.1 - L2 regularization: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_1_L2_Regularization.ipynb">ipynb/colab </a>
</li>
<li> Notebook 9.2 - Implicit regularization: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_2_Implicit_Regularization.ipynb">ipynb/colab </a>
</li>
<li> Notebook 9.3 - Ensembling: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_3_Ensembling.ipynb">ipynb/colab </a>
</li>
<li> Notebook 9.4 - Bayesian approach: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_4_Bayesian_Approach.ipynb">ipynb/colab </a>
</li>
<li> Notebook 9.5 - Augmentation <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_5_Augmentation.ipynb">ipynb/colab </a>
</li>
<li> Notebook 10.1 - 1D convolution: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_1_1D_Convolution.ipynb">ipynb/colab </a>
</li>
<li> Notebook 10.2 - Convolution for MNIST-1D: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_2_Convolution_for_MNIST_1D.ipynb">ipynb/colab </a>
</li>
<li> Notebook 10.3 - 2D convolution: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_3_2D_Convolution.ipynb">ipynb/colab </a>
</li>
<li> Notebook 10.4 - Downsampling & upsampling: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_4_Downsampling_and_Upsampling.ipynb">ipynb/colab </a>
</li>
<li> Notebook 10.5 - Convolution for MNIST: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_5_Convolution_For_MNIST.ipynb">ipynb/colab </a>
</li>
<li> Notebook 11.1 - Shattered gradients: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap11/11_1_Shattered_Gradients.ipynb">ipynb/colab </a>
</li>
<li> Notebook 11.2 - Residual networks: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap11/11_2_Residual_Networks.ipynb">ipynb/colab </a>
</li>
<li> Notebook 11.3 - Batch normalization: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap11/11_3_Batch_Normalization.ipynb">ipynb/colab </a>
</li>
<li> Notebook 12.1 - Self-attention: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap12/12_1_Self_Attention.ipynb">ipynb/colab </a>
</li>
<li> Notebook 12.2 - Multi-head self-attention: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap12/12_2_Multihead_Self_Attention.ipynb">ipynb/colab </a>
</li>
<li> Notebook 12.3 - Tokenization: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap12/12_3_Tokenization.ipynb">ipynb/colab </a>
</li>
<li> Notebook 12.4 - Decoding strategies: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap12/12_4_Decoding_Strategies.ipynb">ipynb/colab </a>
</li>
<li> Notebook 13.1 - Encoding graphs: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap13/13_1_Graph_Representation.ipynb">ipynb/colab </a>
</li>
<li> Notebook 13.2 - Graph classification : <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap13/13_2_Graph_Classification.ipynb">ipynb/colab </a>
</li>
<li> Notebook 13.3 - Neighborhood sampling: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap13/13_3_Neighborhood_Sampling.ipynb">ipynb/colab </a>
</li>
<li> Notebook 13.4 - Graph attention: <a
href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap13/13_4_Graph_Attention_Networks.ipynb">ipynb/colab </a>
</li>
<li> Notebook 15.1 - GAN toy example: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap15/15_1_GAN_Toy_Example.ipynb">ipynb/colab </a></li>
<li> Notebook 15.2 - Wasserstein distance: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap15/15_2_Wasserstein_Distance.ipynb">ipynb/colab </a></li>
<li> Notebook 16.1 - 1D normalizing flows: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap16/16_1_1D_Normalizing_Flows.ipynb">ipynb/colab </a></li>
<li> Notebook 16.2 - Autoregressive flows: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap16/16_2_Autoregressive_Flows.ipynb">ipynb/colab </a></li>
<li> Notebook 16.3 - Contraction mappings: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap16/16_3_Contraction_Mappings.ipynb">ipynb/colab </a></li>
<li> Notebook 17.1 - Latent variable models: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap17/17_1_Latent_Variable_Models.ipynb">ipynb/colab </a></li>
<li> Notebook 17.2 - Reparameterization trick: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap17/17_2_Reparameterization_Trick.ipynb">ipynb/colab </a></li>
<li> Notebook 17.3 - Importance sampling: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap17/17_3_Importance_Sampling.ipynb">ipynb/colab </a></li>
<li> Notebook 18.1 - Diffusion encoder: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap18/18_1_Diffusion_Encoder.ipynb">ipynb/colab </a></li>
<li> Notebook 18.2 - 1D diffusion model: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap18/18_2_1D_Diffusion_Model.ipynb">ipynb/colab </a></li>
<li> Notebook 18.3 - Reparameterized model: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap18/18_3_Reparameterized_Model.ipynb">ipynb/colab </a></li>
<li> Notebook 18.4 - Families of diffusion models: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap18/18_4_Families_of_Diffusion_Models.ipynb">ipynb/colab </a></li>
<li> Notebook 19.1 - Markov decision processes: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_1_Markov_Decision_Processes.ipynb">ipynb/colab </a></li>
<li> Notebook 19.2 - Dynamic programming: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_2_Dynamic_Programming.ipynb">ipynb/colab </a></li>
<li> Notebook 19.3 - Monte-Carlo methods: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_3_Monte_Carlo_Methods.ipynb">ipynb/colab </a></li>
<li> Notebook 19.4 - Temporal difference methods: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_4_Temporal_Difference_Methods.ipynb">ipynb/colab </a></li>
<li> Notebook 19.5 - Control variates: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_5_Control_Variates.ipynb">ipynb/colab </a></li>
<li> Notebook 20.1 - Random data: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap20/20_1_Random_Data.ipynb">ipynb/colab </a></li>
<li> Notebook 20.2 - Full-batch gradient descent: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap20/20_2_Full_Batch_Gradient_Descent.ipynb">ipynb/colab </a></li>
<li> Notebook 20.3 - Lottery tickets: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap20/20_3_Lottery_Tickets.ipynb">ipynb/colab </a></li>
<li> Notebook 20.4 - Adversarial attacks: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap20/20_4_Adversarial_Attacks.ipynb">ipynb/colab </a></li>
<li> Notebook 21.1 - Bias mitigation: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap21/21_1_Bias_Mitigation.ipynb">ipynb/colab </a></li>
<li> Notebook 21.2 - Explainability: <a href="https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap21/21_2_Explainability.ipynb">ipynb/colab </a></li>
</ul>
<br>
<h2>Citation</h2>
<pre><code>
@book{prince2023understanding,
author = "Simon J.D. Prince",
title = "Understanding Deep Learning",
publisher = "MIT Press",
year = 2023,
url = "http://udlbook.com"
}
</code></pre>
</div>
<div id="root"></div>
<script type="module" src="/src/index.jsx"></script>
</body>
</html>

8
jsconfig.json Normal file
View File

@@ -0,0 +1,8 @@
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
}
}

4457
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

36
package.json Executable file
View File

@@ -0,0 +1,36 @@
{
"name": "udlbook-website",
"version": "0.1.0",
"private": true,
"homepage": "https://udlbook.github.io/udlbook",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"predeploy": "npm run build",
"deploy": "gh-pages -d dist",
"clean": "rm -rf node_modules dist",
"format": "prettier --write ."
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.2.1",
"react-router-dom": "^6.23.1",
"react-scroll": "^1.8.4",
"styled-components": "^6.1.11"
},
"devDependencies": {
"@vitejs/plugin-react-swc": "^3.5.0",
"eslint": "^8.57.0",
"eslint-plugin-react": "^7.34.2",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.7",
"gh-pages": "^6.1.1",
"prettier": "^3.3.1",
"prettier-plugin-organize-imports": "^3.2.4",
"vite": "^5.2.12"
}
}

BIN
public/NMI_Review.pdf Normal file

Binary file not shown.

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

12
src/App.jsx Executable file
View File

@@ -0,0 +1,12 @@
import Index from "@/pages";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
export default function App() {
return (
<Router>
<Routes>
<Route exact path="/udlbook" element={<Index />} />
</Routes>
</Router>
);
}

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