Compare commits

..

36 Commits

Author SHA1 Message Date
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
29 changed files with 212 additions and 159 deletions

View File

@@ -31,7 +31,7 @@
"source": [ "source": [
"# Gradient flow\n", "# Gradient flow\n",
"\n", "\n",
"This notebook replicates some of the results in the the Borealis AI [blog](https://www.borealisai.com/research-blogs/gradient-flow/) on gradient flow. \n" "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": { "metadata": {
"id": "ucrRRJ4dq8_d" "id": "ucrRRJ4dq8_d"

View File

@@ -166,7 +166,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"Routines to calculate the empirical and analytical NTK (i.e. the NTK with infinite hidden units) for the the shallow network" "Routines to calculate the empirical and analytical NTK (i.e. the NTK with infinite hidden units) for the shallow network"
], ],
"metadata": { "metadata": {
"id": "mxW8E5kYIzlj" "id": "mxW8E5kYIzlj"

View File

@@ -128,7 +128,7 @@
"\n", "\n",
"In part (b) of the practical we calculate the volume of a hypersphere of radius 0.5 (i.e., of diameter 1) as a function of the radius. You will find that the volume decreases to almost nothing in high dimensions. All of the volume is in the corners of the unit hypercube (which always has volume 1). Double weird.\n", "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", "\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": { "metadata": {
"id": "b2FYKV1SL4Z7" "id": "b2FYKV1SL4Z7"

View File

@@ -199,7 +199,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"The left is model output and the right is the model output after the sigmoid has been applied, so it now lies in the range [0,1] and represents the probability, that y=1. The black dots show the training data. We'll compute the the likelihood and the negative log likelihood." "The left is model output and the right is the model output after the sigmoid has been applied, so it now lies in the range [0,1] and represents the probability, that y=1. The black dots show the training data. We'll compute the likelihood and the negative log likelihood."
], ],
"metadata": { "metadata": {
"id": "MvVX6tl9AEXF" "id": "MvVX6tl9AEXF"

View File

@@ -218,7 +218,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"The left is model output and the right is the model output after the softmax has been applied, so it now lies in the range [0,1] and represents the 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": { "metadata": {
"id": "MvVX6tl9AEXF" "id": "MvVX6tl9AEXF"

View File

@@ -128,7 +128,7 @@
"\n", "\n",
"In part (b) of the practical we calculate the volume of a hypersphere of radius 0.5 (i.e., of diameter 1) as a function of the radius. You will find that the volume decreases to almost nothing in high dimensions. All of the volume is in the corners of the unit hypercube (which always has volume 1). Double weird.\n", "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", "\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": { "metadata": {
"id": "b2FYKV1SL4Z7" "id": "b2FYKV1SL4Z7"

View File

@@ -214,7 +214,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "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", "def dl_df(f_val,y):\n",
" # Compute sigmoid of network output\n", " # Compute sigmoid of network output\n",
" sig_f_val = sig(f_val)\n", " sig_f_val = sig(f_val)\n",

File diff suppressed because one or more lines are too long

View File

@@ -211,7 +211,7 @@
"id": "MvVX6tl9AEXF" "id": "MvVX6tl9AEXF"
}, },
"source": [ "source": [
"The left is model output and the right is the model output after the softmax has been applied, so it now lies in the range [0,1] and represents the 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."
] ]
}, },
{ {

View File

@@ -130,7 +130,8 @@
"\n", "\n",
" print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n", " print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n",
"\n", "\n",
" # Rule #1 If the HEIGHT at point A is less than the HEIGHT at points B, C, and D then halve values of B, C, and D\n", " # 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", " # i.e. bring them closer to the original point\n",
" # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n", " # TODO REPLACE THE BLOCK OF CODE BELOW WITH THIS RULE\n",
" if (0):\n", " if (0):\n",

View File

@@ -1,18 +1,16 @@
{ {
"cells": [ "cells": [
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"colab_type": "text", "id": "view-in-github",
"id": "view-in-github" "colab_type": "text"
}, },
"source": [ "source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap06/6_2_Gradient_Descent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" "<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap06/6_2_Gradient_Descent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "el8l05WQEO46" "id": "el8l05WQEO46"
@@ -111,7 +109,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "QU5mdGvpTtEG" "id": "QU5mdGvpTtEG"
@@ -140,7 +137,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "eB5DQvU5hYNx" "id": "eB5DQvU5hYNx"
@@ -162,7 +158,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "F3trnavPiHpH" "id": "F3trnavPiHpH"
@@ -218,7 +213,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "s9Duf05WqqSC" "id": "s9Duf05WqqSC"
@@ -252,7 +246,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "RS1nEcYVuEAM" "id": "RS1nEcYVuEAM"
@@ -290,7 +283,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "5EIjMM9Fw2eT" "id": "5EIjMM9Fw2eT"
@@ -333,11 +325,11 @@
" print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n", " print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n",
" print('a %f, b%f, c%f, d%f'%(lossa,lossb,lossc,lossd))\n", " print('a %f, b%f, c%f, d%f'%(lossa,lossb,lossc,lossd))\n",
"\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", " if np.argmin((lossa,lossb,lossc,lossd))==0:\n",
" b = b/2\n", " b = a+ (b-a)/2\n",
" c = c/2\n", " c = a+ (c-a)/2\n",
" d = d/2\n", " d = a+ (d-a)/2\n",
" continue;\n", " continue;\n",
"\n", "\n",
" # Rule #2 If point b is less than point c then\n", " # Rule #2 If point b is less than point c then\n",
@@ -412,8 +404,8 @@
], ],
"metadata": { "metadata": {
"colab": { "colab": {
"include_colab_link": true, "provenance": [],
"provenance": [] "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
"display_name": "Python 3", "display_name": "Python 3",

View File

@@ -1,18 +1,16 @@
{ {
"cells": [ "cells": [
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"colab_type": "text", "id": "view-in-github",
"id": "view-in-github" "colab_type": "text"
}, },
"source": [ "source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap06/6_3_Stochastic_Gradient_Descent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" "<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/Chap06/6_3_Stochastic_Gradient_Descent.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "el8l05WQEO46" "id": "el8l05WQEO46"
@@ -122,7 +120,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "QU5mdGvpTtEG" "id": "QU5mdGvpTtEG"
@@ -150,7 +147,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "eB5DQvU5hYNx" "id": "eB5DQvU5hYNx"
@@ -172,7 +168,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "F3trnavPiHpH" "id": "F3trnavPiHpH"
@@ -228,7 +223,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "s9Duf05WqqSC" "id": "s9Duf05WqqSC"
@@ -279,7 +273,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "RS1nEcYVuEAM" "id": "RS1nEcYVuEAM"
@@ -316,7 +309,6 @@
] ]
}, },
{ {
"attachments": {},
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "5EIjMM9Fw2eT" "id": "5EIjMM9Fw2eT"
@@ -359,11 +351,11 @@
" print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n", " print('Iter %d, a=%3.3f, b=%3.3f, c=%3.3f, d=%3.3f'%(n_iter, a,b,c,d))\n",
" print('a %f, b%f, c%f, d%f'%(lossa,lossb,lossc,lossd))\n", " print('a %f, b%f, c%f, d%f'%(lossa,lossb,lossc,lossd))\n",
"\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", " if np.argmin((lossa,lossb,lossc,lossd))==0:\n",
" b = b/2\n", " b = a+ (b-a)/2\n",
" c = c/2\n", " c = a+ (c-a)/2\n",
" d = d/2\n", " d = a+ (d-a)/2\n",
" continue;\n", " continue;\n",
"\n", "\n",
" # Rule #2 If point b is less than point c then\n", " # Rule #2 If point b is less than point c then\n",
@@ -577,9 +569,8 @@
], ],
"metadata": { "metadata": {
"colab": { "colab": {
"authorship_tag": "ABX9TyNk5FN4qlw3pk8BwDVWw1jN", "provenance": [],
"include_colab_link": true, "include_colab_link": true
"provenance": []
}, },
"kernelspec": { "kernelspec": {
"display_name": "Python 3", "display_name": "Python 3",

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": [ "cells": [
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": { "metadata": {
"id": "view-in-github", "colab_type": "text",
"colab_type": "text" "id": "view-in-github"
}, },
"source": [ "source": [
"<a href=\"https://colab.research.google.com/github/udlbook/udlbook/blob/main/Notebooks/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>" "<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", "cell_type": "markdown",
"metadata": {
"id": "L6chybAVFJW2"
},
"source": [ "source": [
"# **Notebook 8.1: MNIST_1D_Performance**\n", "# **Notebook 8.1: MNIST_1D_Performance**\n",
"\n", "\n",
@@ -38,25 +23,27 @@
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n", "Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
"\n", "\n",
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions." "Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
], ]
"metadata": {
"id": "L6chybAVFJW2"
}
}, },
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "execution_count": null,
"# Run this if you're in a Colab to install MNIST 1D repository\n",
"%pip install git+https://github.com/greydanus/mnist1d"
],
"metadata": { "metadata": {
"id": "ifVjS4cTOqKz" "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", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qyE7G1StPIqO"
},
"outputs": [],
"source": [ "source": [
"import torch, torch.nn as nn\n", "import torch, torch.nn as nn\n",
"from torch.utils.data import TensorDataset, DataLoader\n", "from torch.utils.data import TensorDataset, DataLoader\n",
@@ -64,44 +51,42 @@
"import numpy as np\n", "import numpy as np\n",
"import matplotlib.pyplot as plt\n", "import matplotlib.pyplot as plt\n",
"import mnist1d" "import mnist1d"
], ]
"metadata": {
"id": "qyE7G1StPIqO"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "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": { "metadata": {
"id": "F7LNq72SP6jO" "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", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YLxf7dJfPaqw"
},
"outputs": [],
"source": [ "source": [
"!mkdir ./sample_data\n",
"\n",
"args = mnist1d.data.get_dataset_args()\n", "args = mnist1d.data.get_dataset_args()\n",
"data = mnist1d.data.get_dataset(args, path='./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", "\n",
"# The training and test input and outputs are in\n", "# The training and test input and outputs are in\n",
"# data['x'], data['y'], data['x_test'], and data['y_test']\n", "# data['x'], data['y'], data['x_test'], and data['y_test']\n",
"print(\"Examples in training set: {}\".format(len(data['y'])))\n", "print(\"Examples in training set: {}\".format(len(data['y'])))\n",
"print(\"Examples in test set: {}\".format(len(data['y_test'])))\n", "print(\"Examples in test set: {}\".format(len(data['y_test'])))\n",
"print(\"Length of each example: {}\".format(data['x'].shape[-1]))" "print(\"Length of each example: {}\".format(data['x'].shape[-1]))"
], ]
"metadata": {
"id": "YLxf7dJfPaqw"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FxaB5vc0uevl"
},
"outputs": [],
"source": [ "source": [
"D_i = 40 # Input dimensions\n", "D_i = 40 # Input dimensions\n",
"D_k = 100 # Hidden dimensions\n", "D_k = 100 # Hidden dimensions\n",
@@ -122,15 +107,15 @@
"\n", "\n",
"# Call the function you just defined\n", "# Call the function you just defined\n",
"model.apply(weights_init)\n" "model.apply(weights_init)\n"
], ]
"metadata": {
"id": "FxaB5vc0uevl"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_rX6N3VyyQTY"
},
"outputs": [],
"source": [ "source": [
"# choose cross entropy loss function (equation 5.24)\n", "# choose cross entropy loss function (equation 5.24)\n",
"loss_function = torch.nn.CrossEntropyLoss()\n", "loss_function = torch.nn.CrossEntropyLoss()\n",
@@ -139,9 +124,9 @@
"# object that decreases learning rate by half every 10 epochs\n", "# object that decreases learning rate by half every 10 epochs\n",
"scheduler = StepLR(optimizer, step_size=10, gamma=0.5)\n", "scheduler = StepLR(optimizer, step_size=10, gamma=0.5)\n",
"x_train = torch.tensor(data['x'].astype('float32'))\n", "x_train = torch.tensor(data['x'].astype('float32'))\n",
"y_train = torch.tensor(data['y'].transpose().astype('long'))\n", "y_train = torch.tensor(data['y'].transpose().astype('int64'))\n",
"x_test= torch.tensor(data['x_test'].astype('float32'))\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", "\n",
"# load the data into a class that creates the batches\n", "# load the data into a class that creates the batches\n",
"data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n", "data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n",
@@ -186,15 +171,15 @@
"\n", "\n",
" # tell scheduler to consider updating learning rate\n", " # tell scheduler to consider updating learning rate\n",
" scheduler.step()" " scheduler.step()"
], ]
"metadata": {
"id": "_rX6N3VyyQTY"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null,
"metadata": {
"id": "yI-l6kA_EH9G"
},
"outputs": [],
"source": [ "source": [
"# Plot the results\n", "# Plot the results\n",
"fig, ax = plt.subplots()\n", "fig, ax = plt.subplots()\n",
@@ -215,25 +200,38 @@
"ax.set_title('Train loss %3.2f, Test loss %3.2f'%(losses_train[-1],losses_test[-1]))\n", "ax.set_title('Train loss %3.2f, Test loss %3.2f'%(losses_train[-1],losses_test[-1]))\n",
"ax.legend()\n", "ax.legend()\n",
"plt.show()" "plt.show()"
], ]
"metadata": {
"id": "yI-l6kA_EH9G"
},
"execution_count": null,
"outputs": []
}, },
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {
"id": "q-yT6re6GZS4"
},
"source": [ "source": [
"**TO DO**\n", "**TO DO**\n",
"\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", "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", "\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?" "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

@@ -99,7 +99,7 @@
"# data['x'], data['y'], data['x_test'], and data['y_test']\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 training set: {}\".format(len(data['y'])))\n",
"print(\"Examples in test set: {}\".format(len(data['y_test'])))\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": { "metadata": {
"id": "PW2gyXL5UkLU" "id": "PW2gyXL5UkLU"
@@ -147,7 +147,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [
"def fit_model(model, data):\n", "def fit_model(model, data, n_epoch):\n",
"\n", "\n",
" # choose cross entropy loss function (equation 5.24)\n", " # choose cross entropy loss function (equation 5.24)\n",
" loss_function = torch.nn.CrossEntropyLoss()\n", " loss_function = torch.nn.CrossEntropyLoss()\n",
@@ -164,9 +164,6 @@
" # load the data into a class that creates the batches\n", " # load the data into a class that creates the batches\n",
" data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n", " data_loader = DataLoader(TensorDataset(x_train,y_train), batch_size=100, shuffle=True, worker_init_fn=np.random.seed(1))\n",
"\n", "\n",
" # loop over the dataset n_epoch times\n",
" n_epoch = 1000\n",
"\n",
" for epoch in range(n_epoch):\n", " for epoch in range(n_epoch):\n",
" # loop over batches\n", " # loop over batches\n",
" for i, batch in enumerate(data_loader):\n", " for i, batch in enumerate(data_loader):\n",
@@ -203,6 +200,18 @@
"execution_count": null, "execution_count": null,
"outputs": [] "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", "cell_type": "markdown",
"source": [ "source": [
@@ -226,19 +235,27 @@
"# This code will take a while (~30 mins on GPU) to run! Go and make a cup of coffee!\n", "# This code will take a while (~30 mins on GPU) to run! Go and make a cup of coffee!\n",
"\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", "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_train_all = np.zeros_like(hidden_variables)\n",
"errors_test_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", "\n",
"# For each hidden variable size\n", "# For each hidden variable size\n",
"for c_hidden in range(len(hidden_variables)):\n", "for c_hidden in range(len(hidden_variables)):\n",
" print(f'Training model with {hidden_variables[c_hidden]:3d} hidden variables')\n", " print(f'Training model with {hidden_variables[c_hidden]:3d} hidden variables')\n",
" # Get a model\n", " # Get a model\n",
" model = get_model(hidden_variables[c_hidden]) ;\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", " # 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", " # Store the results\n",
" errors_train_all[c_hidden] = errors_train\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": { "metadata": {
"id": "K4OmBZGHWXpk" "id": "K4OmBZGHWXpk"
@@ -249,12 +266,29 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "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", "# Plot the results\n",
"fig, ax = plt.subplots()\n", "fig, ax = plt.subplots()\n",
"ax.plot(hidden_variables, errors_train_all, 'r-', label='train')\n", "ax.plot(hidden_variables, errors_train_all, 'r-', label='train')\n",
"ax.plot(hidden_variables, errors_test_all, 'b-', label='test')\n", "ax.plot(hidden_variables, errors_test_all, 'b-', label='test')\n",
"ax.set_ylim(0,100);\n", "\n",
"ax.set_xlabel('No hidden variables'); ax.set_ylabel('Error')\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", "ax.legend()\n",
"plt.show()\n" "plt.show()\n"
], ],
@@ -263,6 +297,24 @@
}, },
"execution_count": null, "execution_count": null,
"outputs": [] "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": [ "source": [
"# Volume of a hypersphere\n", "# Volume of a hypersphere\n",
"\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": { "metadata": {
"id": "b2FYKV1SL4Z7" "id": "b2FYKV1SL4Z7"

View File

@@ -107,10 +107,7 @@
" # Initialize the parameters with He initialization\n", " # Initialize the parameters with He initialization\n",
" if isinstance(layer_in, nn.Linear):\n", " if isinstance(layer_in, nn.Linear):\n",
" nn.init.kaiming_uniform_(layer_in.weight)\n", " nn.init.kaiming_uniform_(layer_in.weight)\n",
" layer_in.bias.data.fill_(0.0)\n", " layer_in.bias.data.fill_(0.0)\n"
"\n",
"# Call the function you just defined\n",
"model.apply(weights_init)"
], ],
"metadata": { "metadata": {
"id": "JfIFWFIL33eF" "id": "JfIFWFIL33eF"

View File

@@ -4,7 +4,7 @@
"metadata": { "metadata": {
"colab": { "colab": {
"provenance": [], "provenance": [],
"authorship_tag": "ABX9TyNAcc98STMeyQgh9SbVHWG+", "authorship_tag": "ABX9TyNELb86uz5qbhEKH81UqFKT",
"include_colab_link": true "include_colab_link": true
}, },
"kernelspec": { "kernelspec": {
@@ -65,6 +65,11 @@
"source": [ "source": [
"# Run this once to load the train and test data straight into a dataloader class\n", "# Run this once to load the train and test data straight into a dataloader class\n",
"# that will provide the batches\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_train = 64\n",
"batch_size_test = 1000\n", "batch_size_test = 1000\n",
"train_loader = torch.utils.data.DataLoader(\n", "train_loader = torch.utils.data.DataLoader(\n",
@@ -91,6 +96,15 @@
"execution_count": null, "execution_count": null,
"outputs": [] "outputs": []
}, },
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "YGwbxJDEm88i"
},
"execution_count": null,
"outputs": []
},
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "source": [

View File

@@ -28,7 +28,7 @@
{ {
"cell_type": "markdown", "cell_type": "markdown",
"source": [ "source": [
"# **Notebook 12.1: Multihead Self-Attention**\n", "# **Notebook 12.2: Multihead Self-Attention**\n",
"\n", "\n",
"This notebook builds a multihead self-attention mechanism as in figure 12.6\n", "This notebook builds a multihead self-attention mechanism as in figure 12.6\n",
"\n", "\n",

View File

@@ -109,7 +109,7 @@
"# Choose random values for the parameters\n", "# Choose random values for the parameters\n",
"omega = np.random.normal(size=(D,D))\n", "omega = np.random.normal(size=(D,D))\n",
"beta = np.random.normal(size=(D,1))\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": { "metadata": {
"id": "79TSK7oLMobe" "id": "79TSK7oLMobe"

View File

@@ -55,7 +55,7 @@
"Pr(z) = \\text{Norm}_{z}[0,1]\n", "Pr(z) = \\text{Norm}_{z}[0,1]\n",
"\\end{equation}\n", "\\end{equation}\n",
"\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", "\n",
"\\begin{align}\n", "\\begin{align}\n",
"x_{1} &=& 0.5\\cdot\\exp\\Bigl[\\sin\\bigl[2+ 3.675 z \\bigr]\\Bigr]\\\\\n", "x_{1} &=& 0.5\\cdot\\exp\\Bigl[\\sin\\bigl[2+ 3.675 z \\bigr]\\Bigr]\\\\\n",

View File

@@ -393,7 +393,7 @@
{ {
"cell_type": "code", "cell_type": "code",
"source": [ "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", "# states compatible with the Bellman equation (equation 19.11)\n",
"def policy_evaluation(policy, state_values, rewards, transition_probabilities_given_action, gamma):\n", "def policy_evaluation(policy, state_values, rewards, transition_probabilities_given_action, gamma):\n",
"\n", "\n",

View File

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

View File

@@ -137,7 +137,7 @@
"id": "CfZ-srQtmff2" "id": "CfZ-srQtmff2"
}, },
"source": [ "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", "\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", "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", " or granted it ($\\hat{y}=1$). Since we only have the credit score\n",
@@ -382,7 +382,7 @@
"source": [ "source": [
"# Equal opportunity:\n", "# Equal opportunity:\n",
"\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."
] ]
}, },
{ {

Binary file not shown.

Binary file not shown.

View File

@@ -10,6 +10,7 @@
href="https://fonts.googleapis.com/css2?family=Encode+Sans+Expanded:wght@400;700&display=swap" href="https://fonts.googleapis.com/css2?family=Encode+Sans+Expanded:wght@400;700&display=swap"
rel="stylesheet" rel="stylesheet"
/> />
<title>Understanding Deep Learning</title> <title>Understanding Deep Learning</title>
</head> </head>
<body> <body>