Compare commits
222 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab73ae785b | ||
|
|
df86bbba04 | ||
|
|
a9868e6da8 | ||
|
|
fed3962bce | ||
|
|
c5fafbca97 | ||
|
|
5f16e0f9bc | ||
|
|
121c81a04e | ||
|
|
e968741846 | ||
|
|
37011065d7 | ||
|
|
afd20d0364 | ||
|
|
0d135f1ee7 | ||
|
|
54a020304e | ||
|
|
ccbbc4126e | ||
|
|
d3273c99e2 | ||
|
|
f9e45c976c | ||
|
|
b005cec9c1 | ||
|
|
b8a91ad34d | ||
|
|
a2a86c27bc | ||
|
|
d80d04c2d4 | ||
|
|
c1f0181653 | ||
|
|
6e18234d24 | ||
|
|
5730c05547 | ||
|
|
ccb80c16b8 | ||
|
|
87387b2b4c | ||
|
|
06eaec9749 | ||
|
|
9aeda14efa | ||
|
|
d1df6426b2 | ||
|
|
43b8fa3685 | ||
|
|
ca6e4b29ac | ||
|
|
267d6ccb7f | ||
|
|
735947b728 | ||
|
|
251aef1876 | ||
|
|
07ff6c06b1 | ||
|
|
29e4cec04e | ||
|
|
c3ce38410c | ||
|
|
646e60ed95 | ||
|
|
5e61bcf694 | ||
|
|
54399a3c68 | ||
|
|
3926ff41ea | ||
|
|
9c34bfed02 | ||
|
|
9176623331 | ||
|
|
5534df187e | ||
|
|
9b58b2862f | ||
|
|
2070ac4400 | ||
|
|
393e4907dc | ||
|
|
e850676722 | ||
|
|
796f17ed90 | ||
|
|
dc0301a86e | ||
|
|
813f628e4e | ||
|
|
3ae7d68f6e | ||
|
|
a96a14999f | ||
|
|
f91e878eef | ||
|
|
9b89499b75 | ||
|
|
7d6ac5e34f | ||
|
|
55dbe7e0c4 | ||
|
|
1cf21ea61a | ||
|
|
e4191beb79 | ||
|
|
10b9dea9a4 | ||
|
|
414eeb3557 | ||
|
|
f126809572 | ||
|
|
2a30c49d22 | ||
|
|
bb32fe0cdf | ||
|
|
1ee756cf9a | ||
|
|
742d922ce7 | ||
|
|
c02eea499c | ||
|
|
cb94b61abd | ||
|
|
447bb82e2f | ||
|
|
77da5694bb | ||
|
|
96c7e41c9d | ||
|
|
625d1e29bb | ||
|
|
3cf0c4c418 | ||
|
|
03c92541ad | ||
|
|
def3e5234b | ||
|
|
815adb9b21 | ||
|
|
5ba28e5b56 | ||
|
|
8566a7322f | ||
|
|
c867e67e8c | ||
|
|
cba27b3da4 | ||
|
|
1c706bd058 | ||
|
|
72514994bf | ||
|
|
872926c17e | ||
|
|
0dfeb169be | ||
|
|
89a0532283 | ||
|
|
af5a719496 | ||
|
|
56c31efc90 | ||
|
|
06fc37c243 | ||
|
|
45793f02f8 | ||
|
|
7c4cc1ddb4 | ||
|
|
35b6f67bbf | ||
|
|
194baf622a | ||
|
|
a547fee3f4 | ||
|
|
ea4858e78e | ||
|
|
444b06d5c2 | ||
|
|
98bce9edb5 | ||
|
|
37e9ae2311 | ||
|
|
ea1b6ad998 | ||
|
|
d17a5a3872 | ||
|
|
3e7e059bff | ||
|
|
445ad11c46 | ||
|
|
6928b50966 | ||
|
|
e1d34ed561 | ||
|
|
f3528f758b | ||
|
|
5c7a03172a | ||
|
|
0233131b07 | ||
|
|
8200299e64 | ||
|
|
2ac42e70d3 | ||
|
|
dd0eaeb781 | ||
|
|
2cdff544f3 | ||
|
|
384e122c5f | ||
|
|
1343b68c60 | ||
|
|
30420a2f92 | ||
|
|
89e8ebcbc5 | ||
|
|
14b751ff47 | ||
|
|
80e99ef2da | ||
|
|
46214f64bc | ||
|
|
c875fb0361 | ||
|
|
451ccc0832 | ||
|
|
4b939b7426 | ||
|
|
2d300a16a1 | ||
|
|
d057548be9 | ||
|
|
75976a32d0 | ||
|
|
48b204df2c | ||
|
|
9b68e6a8e6 | ||
|
|
862ac6e4d3 | ||
|
|
8fe07cf0fb | ||
|
|
c9679dee90 | ||
|
|
90d879494f | ||
|
|
19bdc23674 | ||
|
|
d7f9929a3c | ||
|
|
a7ac089fc0 | ||
|
|
8fd753d191 | ||
|
|
51424b57bd | ||
|
|
80732b29bc | ||
|
|
36e3a53764 | ||
|
|
569749963b | ||
|
|
d17e47421b | ||
|
|
e8fca0cb0a | ||
|
|
19c0c7ab3e | ||
|
|
418ea93e83 | ||
|
|
ea248af22f | ||
|
|
5492ed0ee5 | ||
|
|
d9138d6177 | ||
|
|
a5413d6a15 | ||
|
|
faf53a49a0 | ||
|
|
7e41097381 | ||
|
|
72b2d79ec7 | ||
|
|
d81bef8a6e | ||
|
|
911da8ca58 | ||
|
|
031401a3dd | ||
|
|
4652f90f09 | ||
|
|
5f524edd3b | ||
|
|
7a423507f5 | ||
|
|
4a5bd9c4d5 | ||
|
|
c0cd9c2aea | ||
|
|
924b6e220d | ||
|
|
b535a13d57 | ||
|
|
d0d413b9f6 | ||
|
|
1b53be1e08 | ||
|
|
bd12e774a4 | ||
|
|
e6c3938567 | ||
|
|
50c93469d5 | ||
|
|
666e2de7d8 | ||
|
|
e947b261f8 | ||
|
|
30801a1d2b | ||
|
|
22d5bc320f | ||
|
|
5c0fd0057f | ||
|
|
9b2b30d4cc | ||
|
|
46e119fcf2 | ||
|
|
f197be3554 | ||
|
|
0fa468cf2c | ||
|
|
e11989bd78 | ||
|
|
566120cc48 | ||
|
|
9f2449fcde | ||
|
|
025b677457 | ||
|
|
435971e3e2 | ||
|
|
6e76cb9b96 | ||
|
|
732fc6f0b7 | ||
|
|
f2a3fab832 | ||
|
|
8e3008673d | ||
|
|
07bcc98a85 | ||
|
|
f4fa3e8397 | ||
|
|
21cff37c72 | ||
|
|
187c6a7352 | ||
|
|
8e4a0d4daf | ||
|
|
23b5affab3 | ||
|
|
4fb8ffe622 | ||
|
|
2adc1da566 | ||
|
|
6e4551a69f | ||
|
|
65c685706a | ||
|
|
934f5f7748 | ||
|
|
365cb41bba | ||
|
|
4855761fb2 | ||
|
|
37b4a76130 | ||
|
|
ef791e5195 | ||
|
|
49945ff1c7 | ||
|
|
cd8f08b2f3 | ||
|
|
8e85e9111c | ||
|
|
be6a0a07fe | ||
|
|
762ac337ae | ||
|
|
e692fdd226 | ||
|
|
a7d363fcf1 | ||
|
|
69dffd8c79 | ||
|
|
c81296d080 | ||
|
|
7ca2790c65 | ||
|
|
73d1a4d28e | ||
|
|
3f268ab9b9 | ||
|
|
a371b98529 | ||
|
|
9a683c502f | ||
|
|
9a22703818 | ||
|
|
c19e2411c5 | ||
|
|
db836826f6 | ||
|
|
6f775910fe | ||
|
|
c11d57f313 | ||
|
|
67f102dd65 | ||
|
|
351199ec7e | ||
|
|
9409fbb447 | ||
|
|
707f93daae | ||
|
|
d2f885db37 | ||
|
|
8400d98b76 | ||
|
|
adbf4322b8 | ||
|
|
c87294176f | ||
|
|
b6b121cb1d |
10
.editorconfig
Normal file
10
.editorconfig
Normal 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
18
.eslintrc.cjs
Normal 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
30
.gitignore
vendored
Executable 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
7
.prettierignore
Normal file
@@ -0,0 +1,7 @@
|
||||
# ignore these directories when formatting the repo
|
||||
/Blogs
|
||||
/CM20315
|
||||
/CM20315_2023
|
||||
/Notebooks
|
||||
/PDFFigures
|
||||
/Slides
|
||||
14
.prettierrc.cjs
Normal file
14
.prettierrc.cjs
Normal 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;
|
||||
1097
Blogs/BorealisBayesianFunction.ipynb
Normal file
1097
Blogs/BorealisBayesianFunction.ipynb
Normal file
File diff suppressed because one or more lines are too long
519
Blogs/BorealisBayesianParameter.ipynb
Normal file
519
Blogs/BorealisBayesianParameter.ipynb
Normal file
File diff suppressed because one or more lines are too long
401
Blogs/BorealisGradientFlow.ipynb
Normal file
401
Blogs/BorealisGradientFlow.ipynb
Normal 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
1109
Blogs/BorealisNTK.ipynb
Normal file
File diff suppressed because one or more lines are too long
1127
Blogs/Borealis_NNGP.ipynb
Normal file
1127
Blogs/Borealis_NNGP.ipynb
Normal file
File diff suppressed because one or more lines are too long
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -46,11 +46,11 @@
|
||||
"source": [
|
||||
"**Linear functions**<br> We will be using the term *linear equation* to mean a weighted sum of inputs plus an offset. If there is just one input $x$, then this is a straight line:\n",
|
||||
"\n",
|
||||
"\\begin{equation}y=\\beta+\\omega x,\\end{equation} <br>\n",
|
||||
"\\begin{equation}y=\\beta+\\omega x,\\end{equation}\n",
|
||||
"\n",
|
||||
"where $\\beta$ is the y-intercept of the linear and $\\omega$ is the slope of the line. When there are two inputs $x_{1}$ and $x_{2}$, then this becomes:\n",
|
||||
"\n",
|
||||
"\\begin{equation}y=\\beta+\\omega_1 x_1 + \\omega_2 x_2.\\end{equation} <br><br>\n",
|
||||
"\\begin{equation}y=\\beta+\\omega_1 x_1 + \\omega_2 x_2.\\end{equation}\n",
|
||||
"\n",
|
||||
"Any other functions are by definition **non-linear**.\n",
|
||||
"\n",
|
||||
@@ -96,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",
|
||||
@@ -195,15 +195,15 @@
|
||||
"source": [
|
||||
"Often we will want to compute many linear functions at the same time. For example, we might have three inputs, $x_1$, $x_2$, and $x_3$ and want to compute two linear functions giving $y_1$ and $y_2$. Of course, we could do this by just running each equation separately,<br><br>\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}y_1 &=& \\beta_1 + \\omega_{11} x_1 + \\omega_{12} x_2 + \\omega_{13} x_3\\\\\n",
|
||||
"\\begin{align}y_1 &=& \\beta_1 + \\omega_{11} x_1 + \\omega_{12} x_2 + \\omega_{13} x_3\\\\\n",
|
||||
"y_2 &=& \\beta_2 + \\omega_{21} x_1 + \\omega_{22} x_2 + \\omega_{23} x_3.\n",
|
||||
"\\end{eqnarray}<br>\n",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"However, we can write it more compactly with vectors and matrices:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\begin{bmatrix} y_1\\\\ y_2 \\end{bmatrix} = \\begin{bmatrix}\\beta_{1}\\\\\\beta_{2}\\end{bmatrix}+ \\begin{bmatrix}\\omega_{11}&\\omega_{12}&\\omega_{13}\\\\\\omega_{21}&\\omega_{22}&\\omega_{23}\\end{bmatrix}\\begin{bmatrix}x_{1}\\\\x_{2}\\\\x_{3}\\end{bmatrix},\n",
|
||||
"\\end{equation}<br>\n",
|
||||
"\\end{equation}\n",
|
||||
"or\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
@@ -269,7 +269,7 @@
|
||||
"# 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"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -295,7 +295,7 @@
|
||||
"\n",
|
||||
"Throughout the book, we'll be using some special functions (see Appendix B.1.3). The most important of these are the logarithm and exponential functions. Let's investigate their properties.\n",
|
||||
"\n",
|
||||
"We'll start with the exponential function $y=\\mbox{exp}[x]=e^x$ which maps the real line $[-\\infty,+\\infty]$ to non-negative numbers $[0,+\\infty]$."
|
||||
"We'll start with the exponential function $y=\\exp[x]=e^x$ which maps the real line $[-\\infty,+\\infty]$ to non-negative numbers $[0,+\\infty]$."
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -317,7 +317,7 @@
|
||||
"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()"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -328,11 +328,11 @@
|
||||
"source": [
|
||||
"# Questions\n",
|
||||
"\n",
|
||||
"1. What is $\\mbox{exp}[0]$? \n",
|
||||
"2. What is $\\mbox{exp}[1]$?\n",
|
||||
"3. What is $\\mbox{exp}[-\\infty]$?\n",
|
||||
"4. What is $\\mbox{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"
|
||||
"1. What is $\\exp[0]$? \n",
|
||||
"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 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"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -363,7 +363,7 @@
|
||||
"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()"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -374,12 +374,12 @@
|
||||
"source": [
|
||||
"# Questions\n",
|
||||
"\n",
|
||||
"1. What is $\\mbox{log}[0]$? \n",
|
||||
"2. What is $\\mbox{log}[1]$?\n",
|
||||
"3. What is $\\mbox{log}[e]$?\n",
|
||||
"4. What is $\\mbox{log}[\\exp[3]]$?\n",
|
||||
"5. What is $\\mbox{exp}[\\log[4]]$?\n",
|
||||
"6. What is $\\mbox{log}[-1]$?\n",
|
||||
"1. What is $\\log[0]$? \n",
|
||||
"2. What is $\\log[1]$?\n",
|
||||
"3. What is $\\log[e]$?\n",
|
||||
"4. What is $\\log[\\exp[3]]$?\n",
|
||||
"5. What is $\\exp[\\log[4]]$?\n",
|
||||
"6. What is $\\log[-1]$?\n",
|
||||
"7. Is the logarithm function concave or convex?\n"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -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
@@ -4,7 +4,6 @@
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyNk2dAhwwRxGpfVSC3b2Owv",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
@@ -182,7 +181,7 @@
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now we'll extend this model to have two outputs $y_1$ and $y_2$, each of which can be visualized with a separate heatmap. You will now have sets of parameters $\\phi_{10}, \\phi_{11}, \\phi_{12}$, $\\phi_{13} and $\\phi_{20}, \\phi_{21}, \\phi_{22}$, \\phi_{23}$ that correspond to each of these outputs."
|
||||
"Now we'll extend this model to have two outputs $y_1$ and $y_2$, each of which can be visualized with a separate heatmap. You will now have sets of parameters $\\phi_{10}, \\phi_{11}, \\phi_{12}, \\phi_{13}$ and $\\phi_{20}, \\phi_{21}, \\phi_{22}, \\phi_{23}$ that correspond to each of these outputs."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Xl6LcrUyM7Lh"
|
||||
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyOmxhh3ymYWX+1HdZ91I6zU",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/Chap03/3_4_Activation_Functions.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Mn0F56yY8ohX"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 3.4 -- Activation functions**\n",
|
||||
"\n",
|
||||
@@ -36,10 +25,7 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and write code to complete the functions. There are also questions interspersed in the text.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Mn0F56yY8ohX"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
@@ -57,6 +43,11 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "AeHzflFt9Tgn"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Plot the shallow neural network. We'll assume input in is range [0,1] and output [-1,1]\n",
|
||||
"# If the plot_all flag is set to true, then we'll plot all the intermediate stages as in Figure 3.3\n",
|
||||
@@ -94,15 +85,15 @@
|
||||
" for i in range(len(x_data)):\n",
|
||||
" ax.plot(x_data[i], y_data[i],)\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "AeHzflFt9Tgn"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "7qeIUrh19AkH"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define a shallow neural network with, one input, one output, and three hidden units\n",
|
||||
"def shallow_1_1_3(x, activation_fn, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31):\n",
|
||||
@@ -123,38 +114,39 @@
|
||||
"\n",
|
||||
" # Return everything we have calculated\n",
|
||||
" return y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "7qeIUrh19AkH"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "cwTp__Fk9YUx"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define the Rectified Linear Unit (ReLU) function\n",
|
||||
"def ReLU(preactivation):\n",
|
||||
" activation = preactivation.clip(0.0)\n",
|
||||
" return activation"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "cwTp__Fk9YUx"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"First, let's run the network with a ReLU functions"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "INQkRzyn9kVC"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"First, let's run the network with a ReLU functions"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "jT9QuKou9i0_"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Now lets define some parameters and run the neural network\n",
|
||||
"theta_10 = 0.3 ; theta_11 = -1.0\n",
|
||||
@@ -170,15 +162,14 @@
|
||||
" shallow_1_1_3(x, ReLU, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n",
|
||||
"# And then plot it\n",
|
||||
"plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "jT9QuKou9i0_"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "-I8N7r1o9HYf"
|
||||
},
|
||||
"source": [
|
||||
"# Sigmoid activation function\n",
|
||||
"\n",
|
||||
@@ -189,13 +180,15 @@
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"(Note that the factor of 10 is not standard -- but it allow us to plot on the same axes as the ReLU examples)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "-I8N7r1o9HYf"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "hgkioNyr975Y"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define the sigmoid function\n",
|
||||
"def sigmoid(preactivation):\n",
|
||||
@@ -204,15 +197,15 @@
|
||||
" activation = np.zeros_like(preactivation);\n",
|
||||
"\n",
|
||||
" return activation"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "hgkioNyr975Y"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "94HIXKJH97ve"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Make an array of inputs\n",
|
||||
"z = np.arange(-1,1,0.01)\n",
|
||||
@@ -224,24 +217,25 @@
|
||||
"ax.set_xlim([-1,1]);ax.set_ylim([0,1])\n",
|
||||
"ax.set_xlabel('z'); ax.set_ylabel('sig[z]')\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "94HIXKJH97ve"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's see what happens when we use this activation function in a neural network"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "p3zQNXhj-J-o"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's see what happens when we use this activation function in a neural network"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "C1dASr9L-GNt"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"theta_10 = 0.3 ; theta_11 = -1.0\n",
|
||||
"theta_20 = -1.0 ; theta_21 = 2.0\n",
|
||||
@@ -256,39 +250,41 @@
|
||||
" shallow_1_1_3(x, sigmoid, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n",
|
||||
"# And then plot it\n",
|
||||
"plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "C1dASr9L-GNt"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"You probably notice that this gives nice smooth curves. So why don't we use this? Aha... it's not obvious right now, but we will get to it when we learn to fit models."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Uuam_DewA9fH"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"You probably notice that this gives nice smooth curves. So why don't we use this? Aha... it's not obvious right now, but we will get to it when we learn to fit models."
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "C9WKkcMUABze"
|
||||
},
|
||||
"source": [
|
||||
"# Heaviside activation function\n",
|
||||
"\n",
|
||||
"The Heaviside function is defined as:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\mbox{heaviside}[z] = \\begin{cases} 0 & \\quad z <0 \\\\ 1 & \\quad z\\geq 0\\end{cases}\n",
|
||||
"\\text{heaviside}[z] = \\begin{cases} 0 & \\quad z <0 \\\\ 1 & \\quad z\\geq 0\\end{cases}\n",
|
||||
"\\end{equation}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "C9WKkcMUABze"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "-1qFkdOL-NPc"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define the heaviside function\n",
|
||||
"def heaviside(preactivation):\n",
|
||||
@@ -299,15 +295,15 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return activation"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "-1qFkdOL-NPc"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "mSPyp7iA-44H"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Make an array of inputs\n",
|
||||
"z = np.arange(-1,1,0.01)\n",
|
||||
@@ -319,15 +315,15 @@
|
||||
"ax.set_xlim([-1,1]);ax.set_ylim([-2,2])\n",
|
||||
"ax.set_xlabel('z'); ax.set_ylabel('heaviside[z]')\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "mSPyp7iA-44H"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "t99K2lSl--Mq"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"theta_10 = 0.3 ; theta_11 = -1.0\n",
|
||||
"theta_20 = -1.0 ; theta_21 = 2.0\n",
|
||||
@@ -342,39 +338,41 @@
|
||||
" shallow_1_1_3(x, heaviside, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n",
|
||||
"# And then plot it\n",
|
||||
"plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t99K2lSl--Mq"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"This can approximate any function, but the output is discontinuous, and there are also reasons not to use it that we will discover when we learn more about model fitting."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "T65MRtM-BCQA"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"This can approximate any function, but the output is discontinuous, and there are also reasons not to use it that we will discover when we learn more about model fitting."
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "RkB-XZMLBTaR"
|
||||
},
|
||||
"source": [
|
||||
"# Linear activation functions\n",
|
||||
"\n",
|
||||
"Neural networks don't work if the activation function is linear. For example, consider what would happen if the activation function was:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\mbox{lin}[z] = a + bz\n",
|
||||
"\\text{lin}[z] = a + bz\n",
|
||||
"\\end{equation}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "RkB-XZMLBTaR"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Q59v3saj_jq1"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define the linear activation function\n",
|
||||
"def lin(preactivation):\n",
|
||||
@@ -384,15 +382,15 @@
|
||||
" activation = a+b * preactivation\n",
|
||||
" # Return\n",
|
||||
" return activation"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Q59v3saj_jq1"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "IwodsBr0BkDn"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO\n",
|
||||
"# 1. The linear activation function above just returns the input: (0+1*z) = z\n",
|
||||
@@ -415,12 +413,23 @@
|
||||
" shallow_1_1_3(x, lin, phi_0,phi_1,phi_2,phi_3, theta_10, theta_11, theta_20, theta_21, theta_30, theta_31)\n",
|
||||
"# And then plot it\n",
|
||||
"plot_neural(x, y, pre_1, pre_2, pre_3, act_1, act_2, act_3, w_act_1, w_act_2, w_act_3, plot_all=True)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"id": "IwodsBr0BkDn"
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyOmxhh3ymYWX+1HdZ91I6zU",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
]
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyPEQEGetZqWnLRNn99Q2aaT",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
@@ -29,7 +28,7 @@
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"#Notebook 4.1 -- Composing networks\n",
|
||||
"# Notebook 4.1 -- Composing networks\n",
|
||||
"\n",
|
||||
"The purpose of this notebook is to understand what happens when we feed one neural network into another. It works through an example similar to 4.1 and varies both networks\n",
|
||||
"\n",
|
||||
@@ -135,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"
|
||||
@@ -220,7 +219,7 @@
|
||||
"source": [
|
||||
"# TODO\n",
|
||||
"# Take a piece of paper and draw what you think will happen when we feed the\n",
|
||||
"# output of the first network into the second one now that we have changed it. Draw the relationship between\n",
|
||||
"# output of the first network into the modified second network. Draw the relationship between\n",
|
||||
"# the input of the first network and the output of the second one."
|
||||
],
|
||||
"metadata": {
|
||||
@@ -261,7 +260,7 @@
|
||||
"source": [
|
||||
"# TODO\n",
|
||||
"# Take a piece of paper and draw what you think will happen when we feed the\n",
|
||||
"# output of the first network now we have changed it into the original second network. Draw the relationship between\n",
|
||||
"# output of the modified first network into the original second network. Draw the relationship between\n",
|
||||
"# the input of the first network and the output of the second one."
|
||||
],
|
||||
"metadata": {
|
||||
@@ -302,7 +301,7 @@
|
||||
"source": [
|
||||
"# TODO\n",
|
||||
"# Take a piece of paper and draw what you think will happen when we feed the\n",
|
||||
"# output of the first network into the original second network. Draw the relationship between\n",
|
||||
"# output of the first network into the a copy of itself. Draw the relationship between\n",
|
||||
"# the input of the first network and the output of the second one."
|
||||
],
|
||||
"metadata": {
|
||||
@@ -350,7 +349,7 @@
|
||||
"# network (blue curve above)\n",
|
||||
"\n",
|
||||
"# Take away conclusion: with very few parameters, we can make A LOT of linear regions, but\n",
|
||||
"# they depend on one another in complex ways that quickly become to difficult to understand intuitively."
|
||||
"# they depend on one another in complex ways that quickly become too difficult to understand intuitively."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "HqzePCLOVQK7"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyPkFrjmRAUf0fxN07RC4xMI",
|
||||
"authorship_tag": "ABX9TyPZzptvvf7OPZai8erQ/0xT",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
@@ -29,7 +29,7 @@
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"#Notebook 4.2 -- Clipping functions\n",
|
||||
"# Notebook 4.2 -- Clipping functions\n",
|
||||
"\n",
|
||||
"The purpose of this notebook is to understand how a neural network with two hidden layers build more complicated functions by clipping and recombining the representations at the intermediate hidden variables.\n",
|
||||
"\n",
|
||||
@@ -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()"
|
||||
|
||||
@@ -118,7 +118,7 @@
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's define a networks. We'll just consider the inputs and outputs over the range [-1,1]. If you set the \"plot_all\" flat to True, you can see the details of how it was created."
|
||||
"Let's define a network. We'll just consider the inputs and outputs over the range [-1,1]."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "LxBJCObC-NTY"
|
||||
|
||||
@@ -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"
|
||||
],
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyOSb+W2AOFVQm8FZcHAb2Jq",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
@@ -66,7 +65,7 @@
|
||||
" return activation\n",
|
||||
"\n",
|
||||
"# Define a shallow neural network\n",
|
||||
"def shallow_nn(x, beta_0, omega_0, beta_1, omaga_1):\n",
|
||||
"def shallow_nn(x, beta_0, omega_0, beta_1, omega_1):\n",
|
||||
" # Make sure that input data is (1 x n_data) array\n",
|
||||
" n_data = x.size\n",
|
||||
" x = np.reshape(x,(1,n_data))\n",
|
||||
@@ -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": {
|
||||
|
||||
@@ -1,20 +1,4 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyOPv/l+ToaApJV7Nz+8AtpV",
|
||||
"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": "jSlFkICHwHQF"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 5.3 Multiclass Cross-Entropy Loss**\n",
|
||||
"\n",
|
||||
@@ -36,10 +23,7 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "jSlFkICHwHQF"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
@@ -61,6 +45,11 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Fv7SZR3tv7mV"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define the Rectified Linear Unit (ReLU) function\n",
|
||||
"def ReLU(preactivation):\n",
|
||||
@@ -77,15 +66,15 @@
|
||||
" h1 = ReLU(np.matmul(beta_0,np.ones((1,n_data))) + np.matmul(omega_0,x))\n",
|
||||
" model_out = np.matmul(beta_1,np.ones((1,n_data))) + np.matmul(omega_1,h1)\n",
|
||||
" return model_out"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Fv7SZR3tv7mV"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "pUT9Ain_HRim"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Get parameters for model -- we can call this function to easily reset them\n",
|
||||
"def get_parameters():\n",
|
||||
@@ -103,15 +92,15 @@
|
||||
" omega_1[2,0] = 16.0; omega_1[2,1] = -8.0; omega_1[2,2] =-8\n",
|
||||
"\n",
|
||||
" return beta_0, omega_0, beta_1, omega_1"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "pUT9Ain_HRim"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "NRR67ri_1TzN"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Utility function for plotting data\n",
|
||||
"def plot_multiclass_classification(x_model, out_model, lambda_model, x_data = None, y_data = None, title= None):\n",
|
||||
@@ -148,26 +137,26 @@
|
||||
" if y_data[i] ==2:\n",
|
||||
" ax[1].plot(x_data[i],-0.05, 'b.')\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "NRR67ri_1TzN"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "PsgLZwsPxauP"
|
||||
},
|
||||
"source": [
|
||||
"# Multiclass classification\n",
|
||||
"\n",
|
||||
"For multiclass classification, the network must predict the probability of $K$ classes, using $K$ outputs. However, these probability must be non-negative and sum to one, and the network outputs can take arbitrary values. Hence, we pass the outputs through a softmax function which maps $K$ arbitrary values to $K$ non-negative values that sum to one."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "PsgLZwsPxauP"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "uFb8h-9IXnIe"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Softmax function that maps a vector of arbitrary values to a vector of values that are positive and sum to one.\n",
|
||||
"def softmax(model_out):\n",
|
||||
@@ -184,15 +173,15 @@
|
||||
" softmax_model_out = np.ones_like(model_out)/ exp_model_out.shape[0]\n",
|
||||
"\n",
|
||||
" return softmax_model_out"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "uFb8h-9IXnIe"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "VWzNOt1swFVd"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"\n",
|
||||
"# Let's create some 1D training data\n",
|
||||
@@ -214,62 +203,62 @@
|
||||
"model_out= shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n",
|
||||
"lambda_model = softmax(model_out)\n",
|
||||
"plot_multiclass_classification(x_model, model_out, lambda_model, x_train, y_train)\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "VWzNOt1swFVd"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"The left is model output and the right is the model output after the softmax has been applied, so it now lies in the range [0,1] and represents the probability, that y=0 (red), 1 (green) and 2 (blue) The dots at the bottom show the training data with the same color scheme. So we want the red curve to be high where there are red dots, the green curve to be high where there are green dots, and the blue curve to be high where there are blue dots We'll compute the the likelihood and the negative log likelihood."
|
||||
],
|
||||
"metadata": {
|
||||
"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 likelihood and the negative log likelihood."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Return probability under Categorical distribution for input x\n",
|
||||
"# Just take value from row k of lambda param where y =k,\n",
|
||||
"def categorical_distribution(y, lambda_param):\n",
|
||||
" return np.array([lambda_param[row, i] for i, row in enumerate (y)])"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "YaLdRlEX0FkU"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Return probability under categorical distribution for observed class y\n",
|
||||
"# Just take value from row k of lambda param where y =k,\n",
|
||||
"def categorical_distribution(y, lambda_param):\n",
|
||||
" return np.array([lambda_param[row, i] for i, row in enumerate (y)])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4TSL14dqHHbV"
|
||||
},
|
||||
"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"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4TSL14dqHHbV"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's compute the likelihood using this function"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "R5z_0dzQMF35"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's compute the likelihood using this function"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "zpS7o6liCx7f"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Return the likelihood of all of the data under the model\n",
|
||||
"def compute_likelihood(y_train, lambda_param):\n",
|
||||
@@ -280,93 +269,93 @@
|
||||
" likelihood = 0\n",
|
||||
"\n",
|
||||
" return likelihood"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "zpS7o6liCx7f"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "1hQxBLoVNlr2"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Let's test this\n",
|
||||
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
|
||||
"# Use our neural network to predict the 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",
|
||||
"likelihood = compute_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\"%(0.000000041,likelihood))"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "1hQxBLoVNlr2"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "HzphKgPfOvlk"
|
||||
},
|
||||
"source": [
|
||||
"You can see that this gives a very small answer, even for this small 1D dataset, and with the model fitting quite well. This is because it is the product of several probabilities, which are all quite small themselves.\n",
|
||||
"This will get out of hand pretty quickly with real datasets -- the likelihood will get so small that we can't represent it with normal finite-precision math\n",
|
||||
"\n",
|
||||
"This is why we use negative log likelihood"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "HzphKgPfOvlk"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "dsT0CWiKBmTV"
|
||||
},
|
||||
"outputs": [],
|
||||
"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",
|
||||
"\n",
|
||||
" return nll"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "dsT0CWiKBmTV"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"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",
|
||||
"model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
|
||||
"# Pass the outputs through the softmax function\n",
|
||||
"lambda_train = softmax(model_out)\n",
|
||||
"# Compute the log likelihood\n",
|
||||
"nll = compute_negative_log_likelihood(y_train, lambda_train)\n",
|
||||
"# Let's double check we get the right answer before proceeding\n",
|
||||
"print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(17.015457867,nll))"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "nVxUXg9rQmwI"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Let's test this\n",
|
||||
"beta_0, omega_0, beta_1, omega_1 = get_parameters()\n",
|
||||
"# Use our neural network to predict the parameters of the categorical distribution\n",
|
||||
"model_out = shallow_nn(x_train, beta_0, omega_0, beta_1, omega_1)\n",
|
||||
"# Pass the outputs through the softmax function\n",
|
||||
"lambda_train = softmax(model_out)\n",
|
||||
"# Compute the negative log likelihood\n",
|
||||
"nll = compute_negative_log_likelihood(y_train, lambda_train)\n",
|
||||
"# Let's double check we get the right answer before proceeding\n",
|
||||
"print(\"Correct answer = %9.9f, Your answer = %9.9f\"%(17.015457867,nll))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's investigate finding the maximum likelihood / minimum log likelihood solution. For simplicity, we'll assume that all the parameters are fixed except one and look at how the likelihood and log likelihood change as we manipulate the last parameter. We'll start with overall y_offset, beta_1 (formerly phi_0)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "OgcRojvPWh4V"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's investigate finding the maximum likelihood / minimum negative log likelihood solution. For simplicity, we'll assume that all the parameters are fixed except one and look at how the likelihood and negative log likelihood change as we manipulate the last parameter. We'll start with overall y_offset, $\\beta_1$ (formerly $\\phi_0$)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "pFKtDaAeVU4U"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define a range of values for the parameter\n",
|
||||
"beta_1_vals = np.arange(-2,6.0,0.1)\n",
|
||||
@@ -382,7 +371,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",
|
||||
@@ -391,17 +380,17 @@
|
||||
" model_out = shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n",
|
||||
" lambda_model = softmax(model_out)\n",
|
||||
" plot_multiclass_classification(x_model, model_out, lambda_model, x_train, y_train, title=\"beta1[0,0]=%3.3f\"%(beta_1[0,0]))\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "pFKtDaAeVU4U"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "UHXeTa9MagO6"
|
||||
},
|
||||
"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",
|
||||
@@ -421,15 +410,15 @@
|
||||
"plt.axvline(x = beta_1_vals[np.argmax(likelihoods)], linestyle='dotted')\n",
|
||||
"\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "UHXeTa9MagO6"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "aDEPhddNdN4u"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Hopefully, you can see that the maximum of the likelihood fn is at the same position as the minimum negative log likelihood solution\n",
|
||||
"# Let's check that:\n",
|
||||
@@ -441,24 +430,34 @@
|
||||
"model_out = shallow_nn(x_model, beta_0, omega_0, beta_1, omega_1)\n",
|
||||
"lambda_model = softmax(model_out)\n",
|
||||
"plot_multiclass_classification(x_model, model_out, lambda_model, x_train, y_train, title=\"beta1[0,0]=%3.3f\"%(beta_1[0,0]))\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "aDEPhddNdN4u"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "771G8N1Vk5A2"
|
||||
},
|
||||
"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": {
|
||||
"id": "771G8N1Vk5A2"
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -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,7 @@
|
||||
"\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 halve values of B, C, and D\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 +138,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 +146,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",
|
||||
|
||||
@@ -1,32 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/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"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 6.2 Gradient descent**\n",
|
||||
"\n",
|
||||
@@ -36,10 +26,7 @@
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n",
|
||||
"\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "el8l05WQEO46"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
@@ -58,34 +45,39 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4cRkrh9MZ58Z"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Let's create our training data 12 pairs {x_i, y_i}\n",
|
||||
"# We'll try to fit the straight line model to these data\n",
|
||||
"data = np.array([[0.03,0.19,0.34,0.46,0.78,0.81,1.08,1.18,1.39,1.60,1.65,1.90],\n",
|
||||
" [0.67,0.85,1.05,1.00,1.40,1.50,1.30,1.54,1.55,1.68,1.73,1.60]])"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4cRkrh9MZ58Z"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "WQUERmb2erAe"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Let's define our model -- 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"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "WQUERmb2erAe"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "qFRe9POHF2le"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Draw model\n",
|
||||
"def draw_model(data,model,phi,title=None):\n",
|
||||
@@ -101,39 +93,40 @@
|
||||
" if title is not None:\n",
|
||||
" ax.set_title(title)\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "qFRe9POHF2le"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "TXx1Tpd1Tl-I"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize the parameters to some arbitrary values and draw the model\n",
|
||||
"phi = np.zeros((2,1))\n",
|
||||
"phi[0] = 0.6 # Intercept\n",
|
||||
"phi[1] = -0.2 # Slope\n",
|
||||
"draw_model(data,model,phi, \"Initial parameters\")\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "TXx1Tpd1Tl-I"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now lets create compute the sum of squares loss for the training data"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "QU5mdGvpTtEG"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's compute the sum of squares loss for the training data"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "I7dqTY2Gg7CR"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_loss(data_x, data_y, model, phi):\n",
|
||||
" # TODO -- Write this function -- replace the line below\n",
|
||||
@@ -144,45 +137,47 @@
|
||||
" loss = 0\n",
|
||||
"\n",
|
||||
" return loss"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "I7dqTY2Gg7CR"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's just test that we got that right"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "eB5DQvU5hYNx"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's just test that we got that right"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"loss = compute_loss(data[0,:],data[1,:],model,np.array([[0.6],[-0.2]]))\n",
|
||||
"print('Your loss = %3.3f, Correct loss = %3.3f'%(loss, 12.367))"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Ty05UtEEg9tc"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"loss = compute_loss(data[0,:],data[1,:],model,np.array([[0.6],[-0.2]]))\n",
|
||||
"print('Your loss = %3.3f, Correct loss = %3.3f'%(loss, 12.367))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's plot the whole loss function"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "F3trnavPiHpH"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's plot the whole loss function"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "K-NTHpAAHlCl"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def draw_loss_function(compute_loss, data, model, phi_iters = None):\n",
|
||||
" # Define pretty colormap\n",
|
||||
@@ -209,39 +204,40 @@
|
||||
" ax.set_ylim([1,-1])\n",
|
||||
" ax.set_xlabel('Intercept $\\phi_{0}$'); ax.set_ylabel('Slope, $\\phi_{1}$')\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "K-NTHpAAHlCl"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"draw_loss_function(compute_loss, data, model)"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "l8HbvIupnTME"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"draw_loss_function(compute_loss, data, model)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "s9Duf05WqqSC"
|
||||
},
|
||||
"source": [
|
||||
"Now let's compute the gradient vector for a given set of parameters:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\frac{\\partial L}{\\partial \\boldsymbol\\phi} = \\begin{bmatrix}\\frac{\\partial L}{\\partial \\phi_0} \\\\\\frac{\\partial L}{\\partial \\phi_1} \\end{bmatrix}.\n",
|
||||
"\\end{equation}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "s9Duf05WqqSC"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "UpswmkL2qwBT"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# These are in the lecture slides and notes, but worth trying to calculate them yourself to\n",
|
||||
"# check that you get them right. Write out the expression for the sum of squares loss and take the\n",
|
||||
@@ -253,31 +249,32 @@
|
||||
"\n",
|
||||
" # Return the gradient\n",
|
||||
" return np.array([[dl_dphi0],[dl_dphi1]])"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "UpswmkL2qwBT"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "RS1nEcYVuEAM"
|
||||
},
|
||||
"source": [
|
||||
"We can check we got this right using a trick known as **finite differences**. If we evaluate the function and then change one of the parameters by a very small amount and normalize by that amount, we get an approximation to the gradient, so:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"\\frac{\\partial L}{\\partial \\phi_{0}}&\\approx & \\frac{L[\\phi_0+\\delta, \\phi_1]-L[\\phi_0, \\phi_1]}{\\delta}\\\\\n",
|
||||
"\\frac{\\partial L}{\\partial \\phi_{1}}&\\approx & \\frac{L[\\phi_0, \\phi_1+\\delta]-L[\\phi_0, \\phi_1]}{\\delta}\n",
|
||||
"\\end{eqnarray}\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."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "RS1nEcYVuEAM"
|
||||
}
|
||||
"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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "QuwAHN7yt-gi"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Compute the gradient using your function\n",
|
||||
"gradient = compute_gradient(data[0,:],data[1,:], phi)\n",
|
||||
@@ -290,24 +287,25 @@
|
||||
" compute_loss(data[0,:],data[1,:],model,phi))/delta\n",
|
||||
"print(\"Approx gradients: (%3.3f,%3.3f)\"%(dl_dphi0_est,dl_dphi1_est))\n",
|
||||
"# There might be small differences in the last significant figure because finite gradients is an approximation\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "QuwAHN7yt-gi"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now we are ready to perform gradient descent. We'll need to use our line search routine from notebook 6.1, which I've reproduced here plus the helper function loss_function_1D that maps the search along the negative gradient direction in 2D space to a 1D problem (distance along this direction)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "5EIjMM9Fw2eT"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now we are ready to perform gradient descent. We'll need to use our line search routine from notebook 6.1, which I've reproduced here plus the helper function loss_function_1D that maps the search along the negative gradient direction in 2D space to a 1D problem (distance along this direction)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "XrJ2gQjfw1XP"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def loss_function_1D(dist_prop, data, model, phi_start, search_direction):\n",
|
||||
" # Return the loss after moving this far\n",
|
||||
@@ -319,7 +317,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",
|
||||
@@ -343,7 +341,7 @@
|
||||
" 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",
|
||||
@@ -353,7 +351,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",
|
||||
@@ -362,15 +360,15 @@
|
||||
"\n",
|
||||
" # Return average of two middle points\n",
|
||||
" return (b+c)/2.0"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "XrJ2gQjfw1XP"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "YVq6rmaWRD2M"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def gradient_descent_step(phi, data, model):\n",
|
||||
" # TODO -- update Phi with the gradient descent step (equation 6.3)\n",
|
||||
@@ -379,15 +377,15 @@
|
||||
" # 3. Update the parameters phi based on the gradient and the step size alpha.\n",
|
||||
"\n",
|
||||
" return phi"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "YVq6rmaWRD2M"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "tOLd0gtdRLLS"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize the parameters and draw the model\n",
|
||||
"n_steps = 10\n",
|
||||
@@ -409,12 +407,22 @@
|
||||
"\n",
|
||||
"# Draw the trajectory on the loss function\n",
|
||||
"draw_loss_function(compute_loss, data, model,phi_all)\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"id": "tOLd0gtdRLLS"
|
||||
"colab": {
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
]
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyNk5FN4qlw3pk8BwDVWw1jN",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/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"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 6.3: Stochastic gradient descent**\n",
|
||||
"\n",
|
||||
@@ -39,10 +28,7 @@
|
||||
"\n",
|
||||
"\n",
|
||||
"\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "el8l05WQEO46"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
@@ -61,8 +47,13 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4cRkrh9MZ58Z"
|
||||
},
|
||||
"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",
|
||||
@@ -74,15 +65,15 @@
|
||||
" -2.365e-02,5.098e-01,-2.777e-01,3.367e-01,1.927e-01,-2.222e-01,\n",
|
||||
" 6.352e-02,6.888e-03,3.224e-02,1.091e-02,-5.706e-01,-5.258e-02,\n",
|
||||
" -3.666e-02,1.709e-01,-4.805e-02,2.008e-01,-1.904e-01,5.952e-01]])"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4cRkrh9MZ58Z"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "WQUERmb2erAe"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Let's define our model\n",
|
||||
"def model(phi,x):\n",
|
||||
@@ -90,15 +81,15 @@
|
||||
" gauss_component = np.exp(-(phi[0] + 0.06 * phi[1] * x) * (phi[0] + 0.06 * phi[1] * x) / 32)\n",
|
||||
" y_pred= sin_component * gauss_component\n",
|
||||
" return y_pred"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "WQUERmb2erAe"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "qFRe9POHF2le"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Draw model\n",
|
||||
"def draw_model(data,model,phi,title=None):\n",
|
||||
@@ -113,39 +104,40 @@
|
||||
" if title is not None:\n",
|
||||
" ax.set_title(title)\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "qFRe9POHF2le"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "TXx1Tpd1Tl-I"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize the parameters and draw the model\n",
|
||||
"phi = np.zeros((2,1))\n",
|
||||
"phi[0] = -5 # Horizontal offset\n",
|
||||
"phi[1] = 25 # Frequency\n",
|
||||
"draw_model(data,model,phi, \"Initial parameters\")\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "TXx1Tpd1Tl-I"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now lets create compute the sum of squares loss for the training data"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "QU5mdGvpTtEG"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's compute the sum of squares loss for the training data"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "I7dqTY2Gg7CR"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_loss(data_x, data_y, model, phi):\n",
|
||||
" # TODO -- Write this function -- replace the line below\n",
|
||||
@@ -155,45 +147,47 @@
|
||||
" loss = 0\n",
|
||||
"\n",
|
||||
" return loss"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "I7dqTY2Gg7CR"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's just test that we got that right"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "eB5DQvU5hYNx"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's just test that we got that right"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"loss = compute_loss(data[0,:],data[1,:],model,np.array([[0.6],[-0.2]]))\n",
|
||||
"print('Your loss = %3.3f, Correct loss = %3.3f'%(loss, 16.419))"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Ty05UtEEg9tc"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"loss = compute_loss(data[0,:],data[1,:],model,np.array([[0.6],[-0.2]]))\n",
|
||||
"print('Your loss = %3.3f, Correct loss = %3.3f'%(loss, 16.419))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's plot the whole loss function"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "F3trnavPiHpH"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's plot the whole loss function"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "K-NTHpAAHlCl"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def draw_loss_function(compute_loss, data, model, phi_iters = None):\n",
|
||||
" # Define pretty colormap\n",
|
||||
@@ -204,7 +198,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",
|
||||
@@ -220,39 +214,40 @@
|
||||
" ax.set_ylim([2.5,22.5])\n",
|
||||
" ax.set_xlabel('Offset $\\phi_{0}$'); ax.set_ylabel('Frequency, $\\phi_{1}$')\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "K-NTHpAAHlCl"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"draw_loss_function(compute_loss, data, model)"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "l8HbvIupnTME"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"draw_loss_function(compute_loss, data, model)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "s9Duf05WqqSC"
|
||||
},
|
||||
"source": [
|
||||
"Now let's compute the gradient vector for a given set of parameters:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\frac{\\partial L}{\\partial \\boldsymbol\\phi} = \\begin{bmatrix}\\frac{\\partial L}{\\partial \\phi_0} \\\\\\frac{\\partial L}{\\partial \\phi_1} \\end{bmatrix}.\n",
|
||||
"\\end{equation}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "s9Duf05WqqSC"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "UpswmkL2qwBT"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# These came from writing out the expression for the sum of squares loss and taking the\n",
|
||||
"# derivative with respect to phi0 and phi1. It was a lot of hassle to get it right!\n",
|
||||
@@ -281,31 +276,32 @@
|
||||
" dl_dphi1 = gabor_deriv_phi1(data_x, data_y, phi[0],phi[1])\n",
|
||||
" # Return the gradient\n",
|
||||
" return np.array([[dl_dphi0],[dl_dphi1]])"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "UpswmkL2qwBT"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "RS1nEcYVuEAM"
|
||||
},
|
||||
"source": [
|
||||
"We can check we got this right using a trick known as **finite differences**. If we evaluate the function and then change one of the parameters by a very small amount and normalize by that amount, we get an approximation to the gradient, so:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"\\frac{\\partial L}{\\partial \\phi_{0}}&\\approx & \\frac{L[\\phi_0+\\delta, \\phi_1]-L[\\phi_0, \\phi_1]}{\\delta}\\\\\n",
|
||||
"\\frac{\\partial L}{\\partial \\phi_{1}}&\\approx & \\frac{L[\\phi_0, \\phi_1+\\delta]-L[\\phi_0, \\phi_1]}{\\delta}\n",
|
||||
"\\end{eqnarray}\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."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "RS1nEcYVuEAM"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "QuwAHN7yt-gi"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Compute the gradient using your function\n",
|
||||
"gradient = compute_gradient(data[0,:],data[1,:], phi)\n",
|
||||
@@ -317,24 +313,25 @@
|
||||
"dl_dphi1_est = (compute_loss(data[0,:],data[1,:],model,phi+np.array([[0],[delta]])) - \\\n",
|
||||
" compute_loss(data[0,:],data[1,:],model,phi))/delta\n",
|
||||
"print(\"Approx gradients: (%3.3f,%3.3f)\"%(dl_dphi0_est,dl_dphi1_est))\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "QuwAHN7yt-gi"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now we are ready to perform gradient descent. We'll need to use our line search routine from Notebook 6.1, which I've reproduced here plus the helper function loss_function_1D that converts from a 2D problem to a 1D problem"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "5EIjMM9Fw2eT"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now we are ready to perform gradient descent. We'll need to use our line search routine from Notebook 6.1, which I've reproduced here plus the helper function loss_function_1D that converts from a 2D problem to a 1D problem"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "XrJ2gQjfw1XP"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def loss_function_1D(dist_prop, data, model, phi_start, gradient):\n",
|
||||
" # Return the loss after moving this far\n",
|
||||
@@ -346,7 +343,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",
|
||||
@@ -370,7 +367,7 @@
|
||||
" 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",
|
||||
@@ -380,7 +377,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",
|
||||
@@ -389,15 +386,15 @@
|
||||
"\n",
|
||||
" # Return average of two middle points\n",
|
||||
" return (b+c)/2.0"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "XrJ2gQjfw1XP"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "YVq6rmaWRD2M"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def gradient_descent_step(phi, data, model):\n",
|
||||
" # Step 1: Compute the gradient\n",
|
||||
@@ -406,15 +403,15 @@
|
||||
" alpha = line_search(data, model, phi, gradient*-1, max_dist = 2.0)\n",
|
||||
" phi = phi - alpha * gradient\n",
|
||||
" return phi"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "YVq6rmaWRD2M"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "tOLd0gtdRLLS"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize the parameters\n",
|
||||
"n_steps = 21\n",
|
||||
@@ -435,41 +432,41 @@
|
||||
" draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n",
|
||||
"\n",
|
||||
"draw_loss_function(compute_loss, data, model,phi_all)\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "tOLd0gtdRLLS"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# TODO Experiment with starting the optimization in the previous cell in different places\n",
|
||||
"# and show that it heads to a local minimum if we don't start it in the right valley"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Oi8ZlH0ptLqA"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO Experiment with starting the optimization in the previous cell in different places\n",
|
||||
"# and show that it heads to a local minimum if we don't start it in the right valley"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4l-ueLk-oAxV"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def gradient_descent_step_fixed_learning_rate(phi, data, alpha):\n",
|
||||
" # TODO -- fill in this routine so that we take a fixed size step of size alpha without using line search\n",
|
||||
"\n",
|
||||
" return phi"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4l-ueLk-oAxV"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "oi9MX_GRpM41"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize the parameters\n",
|
||||
"n_steps = 21\n",
|
||||
@@ -490,28 +487,28 @@
|
||||
" draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n",
|
||||
"\n",
|
||||
"draw_loss_function(compute_loss, data, model,phi_all)\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "oi9MX_GRpM41"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "In6sQ5YCpMqn"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO Experiment with the learning rate, alpha.\n",
|
||||
"# What happens if you set it too large?\n",
|
||||
"# What happens if you set it too small?"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "In6sQ5YCpMqn"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "VKTC9-1Gpm3N"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def stochastic_gradient_descent_step(phi, data, alpha, batch_size):\n",
|
||||
" # TODO -- fill in this routine so that we take a fixed size step of size alpha but only using a subset (batch) of the data\n",
|
||||
@@ -522,15 +519,15 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return phi"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "VKTC9-1Gpm3N"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "469OP_UHskJ4"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the random number generator so you always get same numbers (disable if you don't want this)\n",
|
||||
"np.random.seed(1)\n",
|
||||
@@ -553,34 +550,45 @@
|
||||
" draw_model(data,model,phi_all[:,c_step+1], \"Iteration %d, loss = %f\"%(c_step+1,loss))\n",
|
||||
"\n",
|
||||
"draw_loss_function(compute_loss, data, model,phi_all)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "469OP_UHskJ4"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# TODO -- Experiment with different learning rates, starting points, batch sizes, number of steps. Get a feel for this."
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "LxE2kTa3s29p"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO -- Experiment with different learning rates, starting points, batch sizes, number of steps. Get a feel for this."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# TODO -- Add a learning rate schedule. Reduce the learning rate by a factor of beta every M iterations"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "lw4QPOaQTh5e"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
}
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO -- Add a learning rate schedule. Reduce the learning rate by a factor of beta every M iterations"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyNk5FN4qlw3pk8BwDVWw1jN",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyOjXmTmoff61y15VqEB5sDW",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/Chap07/7_1_Backpropagation_in_Toy_Model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "pOZ6Djz0dhoy"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 7.1: Backpropagation in Toy Model**\n",
|
||||
"\n",
|
||||
@@ -36,68 +25,67 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "pOZ6Djz0dhoy"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "1DmMo2w63CmT"
|
||||
},
|
||||
"source": [
|
||||
"We're going to investigate how to take the derivatives of functions where one operation is composed with another, which is composed with a third and so on. For example, consider the model:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
" \\mbox{f}[x,\\boldsymbol\\phi] = \\beta_3+\\omega_3\\cdot\\cos\\Bigl[\\beta_2+\\omega_2\\cdot\\exp\\bigl[\\beta_1+\\omega_1\\cdot\\sin[\\beta_0+\\omega_0x]\\bigr]\\Bigr],\n",
|
||||
" \\text{f}[x,\\boldsymbol\\phi] = \\beta_3+\\omega_3\\cdot\\cos\\Bigl[\\beta_2+\\omega_2\\cdot\\exp\\bigl[\\beta_1+\\omega_1\\cdot\\sin[\\beta_0+\\omega_0x]\\bigr]\\Bigr],\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"with parameters $\\boldsymbol\\phi=\\{\\beta_0,\\omega_0,\\beta_1,\\omega_1,\\beta_2,\\omega_2,\\beta_3,\\omega_3\\}$.<br>\n",
|
||||
"\n",
|
||||
"This is a composition of the functions $\\cos[\\bullet],\\exp[\\bullet],\\sin[\\bullet]$. I chose these just because you probably already know the derivatives of these functions:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray*}\n",
|
||||
"\\begin{align}\n",
|
||||
" \\frac{\\partial \\cos[z]}{\\partial z} = -\\sin[z] \\quad\\quad \\frac{\\partial \\exp[z]}{\\partial z} = \\exp[z] \\quad\\quad \\frac{\\partial \\sin[z]}{\\partial z} = \\cos[z].\n",
|
||||
"\\end{eqnarray*}\n",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"Suppose that we have a least squares loss function:\n",
|
||||
"\n",
|
||||
"\\begin{equation*}\n",
|
||||
"\\ell_i = (\\mbox{f}[x_i,\\boldsymbol\\phi]-y_i)^2,\n",
|
||||
"\\ell_i = (\\text{f}[x_i,\\boldsymbol\\phi]-y_i)^2,\n",
|
||||
"\\end{equation*}\n",
|
||||
"\n",
|
||||
"Assume that we know the current values of $\\beta_{0},\\beta_{1},\\beta_{2},\\beta_{3},\\omega_{0},\\omega_{1},\\omega_{2},\\omega_{3}$, $x_i$ and $y_i$. We could obviously calculate $\\ell_i$. But we also want to know how $\\ell_i$ changes when we make a small change to $\\beta_{0},\\beta_{1},\\beta_{2},\\beta_{3},\\omega_{0},\\omega_{1},\\omega_{2}$, or $\\omega_{3}$. In other words, we want to compute the eight derivatives:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray*}\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial \\beta_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{2}}, \\quad \\frac{\\partial \\ell_i }{\\partial \\beta_{3}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{2}}, \\quad\\mbox{and} \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{3}}.\n",
|
||||
"\\end{eqnarray*}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "1DmMo2w63CmT"
|
||||
}
|
||||
"\\begin{align}\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial \\beta_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\beta_{2}}, \\quad \\frac{\\partial \\ell_i }{\\partial \\beta_{3}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{0}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{1}}, \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{2}}, \\quad\\text{and} \\quad \\frac{\\partial \\ell_i}{\\partial \\omega_{3}}.\n",
|
||||
"\\end{align}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# import library\n",
|
||||
"import numpy as np"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "RIPaoVN834Lj"
|
||||
},
|
||||
"execution_count": 1,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# import library\n",
|
||||
"import numpy as np"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's first define the original function for $y$ and the loss term:"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "32-ufWhc3v2c"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's first define the original function for $y$ and the loss term:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "AakK_qen3BpU"
|
||||
},
|
||||
@@ -112,121 +100,129 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now we'll choose some values for the betas and the omegas and x and compute the output of the function:"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "y7tf0ZMt5OXt"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now we'll choose some values for the betas and the omegas and x and compute the output of the function:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"beta0 = 1.0; beta1 = 2.0; beta2 = -3.0; beta3 = 0.4\n",
|
||||
"omega0 = 0.1; omega1 = -0.4; omega2 = 2.0; omega3 = 3.0\n",
|
||||
"x = 2.3; y =2.0\n",
|
||||
"l_i_func = loss(x,y,beta0,beta1,beta2,beta3,omega0,omega1,omega2,omega3)\n",
|
||||
"print('l_i=%3.3f'%l_i_func)"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "pwvOcCxr41X_",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "pwvOcCxr41X_",
|
||||
"outputId": "9541922c-dfc4-4b2e-dfa3-3298812155ce"
|
||||
},
|
||||
"execution_count": 3,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"l_i=0.139\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"beta0 = 1.0; beta1 = 2.0; beta2 = -3.0; beta3 = 0.4\n",
|
||||
"omega0 = 0.1; omega1 = -0.4; omega2 = 2.0; omega3 = 3.0\n",
|
||||
"x = 2.3; y = 2.0\n",
|
||||
"l_i_func = loss(x,y,beta0,beta1,beta2,beta3,omega0,omega1,omega2,omega3)\n",
|
||||
"print('l_i=%3.3f'%l_i_func)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "u5w69NeT64yV"
|
||||
},
|
||||
"source": [
|
||||
"# Computing derivatives by hand\n",
|
||||
"\n",
|
||||
"We could compute expressions for the derivatives by hand and write code to compute them directly but some have very complex expressions, even for this relatively simple original equation. For example:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray*}\n",
|
||||
"\\begin{align}\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial \\omega_{0}} &=& -2 \\left( \\beta_3+\\omega_3\\cdot\\cos\\Bigl[\\beta_2+\\omega_2\\cdot\\exp\\bigl[\\beta_1+\\omega_1\\cdot\\sin[\\beta_0+\\omega_0\\cdot x_i]\\bigr]\\Bigr]-y_i\\right)\\nonumber \\\\\n",
|
||||
"&&\\hspace{0.5cm}\\cdot \\omega_1\\omega_2\\omega_3\\cdot x_i\\cdot\\cos[\\beta_0+\\omega_0 \\cdot x_i]\\cdot\\exp\\Bigl[\\beta_1 + \\omega_1 \\cdot \\sin[\\beta_0+\\omega_0\\cdot x_i]\\Bigr]\\nonumber\\\\\n",
|
||||
"&& \\hspace{1cm}\\cdot \\sin\\biggl[\\beta_2+\\omega_2\\cdot \\exp\\Bigl[\\beta_1 + \\omega_1 \\cdot \\sin[\\beta_0+\\omega_0\\cdot x_i]\\Bigr]\\biggr].\n",
|
||||
"\\end{eqnarray*}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "u5w69NeT64yV"
|
||||
}
|
||||
"\\end{align}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "7t22hALp5zkq"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"dldbeta3_func = 2 * (beta3 +omega3 * np.cos(beta2 + omega2 * np.exp(beta1+omega1 * np.sin(beta0+omega0 * x)))-y)\n",
|
||||
"dldomega0_func = -2 *(beta3 +omega3 * np.cos(beta2 + omega2 * np.exp(beta1+omega1 * np.sin(beta0+omega0 * x)))-y) * \\\n",
|
||||
" omega1 * omega2 * omega3 * x * np.cos(beta0 + omega0 * x) * np.exp(beta1 +omega1 * np.sin(beta0 + omega0 * x)) *\\\n",
|
||||
" np.sin(beta2 + omega2 * np.exp(beta1+ omega1* np.sin(beta0+omega0 * x)))"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "7t22hALp5zkq"
|
||||
},
|
||||
"execution_count": 4,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's make sure this is correct using finite differences:"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "iRh4hnu3-H3n"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's make sure this is correct using finite differences:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"dldomega0_fd = (loss(x,y,beta0,beta1,beta2,beta3,omega0+0.00001,omega1,omega2,omega3)-loss(x,y,beta0,beta1,beta2,beta3,omega0,omega1,omega2,omega3))/0.00001\n",
|
||||
"\n",
|
||||
"print('dydomega0: Function value = %3.3f, Finite difference value = %3.3f'%(dldomega0_func,dldomega0_fd))"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "1O3XmXMx-HlZ",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "1O3XmXMx-HlZ",
|
||||
"outputId": "389ed78e-9d8d-4e8b-9e6b-5f20c21407e8"
|
||||
},
|
||||
"execution_count": 5,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"dydomega0: Function value = 5.246, Finite difference value = 5.246\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"dldomega0_fd = (loss(x,y,beta0,beta1,beta2,beta3,omega0+0.00001,omega1,omega2,omega3)-loss(x,y,beta0,beta1,beta2,beta3,omega0,omega1,omega2,omega3))/0.00001\n",
|
||||
"\n",
|
||||
"print('dydomega0: Function value = %3.3f, Finite difference value = %3.3f'%(dldomega0_func,dldomega0_fd))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"The code to calculate $\\partial l_i/ \\partial \\omega_0$ is a bit of a nightmare. It's easy to make mistakes, and you can see that some parts of it are repeated (for example, the $\\sin[\\bullet]$ term), which suggests some kind of redundancy in the calculations. The goal of this practical is to compute the derivatives in a much simpler way. There will be three steps:"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "wS4IPjZAKWTN"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"The code to calculate $\\partial l_i/ \\partial \\omega_0$ is a bit of a nightmare. It's easy to make mistakes, and you can see that some parts of it are repeated (for example, the $\\sin[\\bullet]$ term), which suggests some kind of redundancy in the calculations. The goal of this practical is to compute the derivatives in a much simpler way. There will be three steps:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "8UWhvDeNDudz"
|
||||
},
|
||||
"source": [
|
||||
"**Step 1:** Write the original equations as a series of intermediate calculations.\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"f_{0} &=& \\beta_{0} + \\omega_{0} x_i\\nonumber\\\\\n",
|
||||
"h_{1} &=& \\sin[f_{0}]\\nonumber\\\\\n",
|
||||
"f_{1} &=& \\beta_{1} + \\omega_{1}h_{1}\\nonumber\\\\\n",
|
||||
@@ -235,16 +231,18 @@
|
||||
"h_{3} &=& \\cos[f_{2}]\\nonumber\\\\\n",
|
||||
"f_{3} &=& \\beta_{3} + \\omega_{3}h_{3}\\nonumber\\\\\n",
|
||||
"l_i &=& (f_3-y_i)^2\n",
|
||||
"\\end{eqnarray}\n",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"and compute and store the values of all of these intermediate values. We'll need them to compute the derivatives.<br> This is called the **forward pass**."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "8UWhvDeNDudz"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ZWKAq6HC90qV"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO compute all the f_k and h_k terms\n",
|
||||
"# Replace the code below\n",
|
||||
@@ -257,15 +255,34 @@
|
||||
"h3 = 0\n",
|
||||
"f3 = 0\n",
|
||||
"l_i = 0\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ZWKAq6HC90qV"
|
||||
},
|
||||
"execution_count": 6,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "ibxXw7TUW4Sx",
|
||||
"outputId": "4575e3eb-2b16-4e0b-c84e-9c22b443c3ce"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"f0: true value = 1.230, your value = 0.000\n",
|
||||
"h1: true value = 0.942, your value = 0.000\n",
|
||||
"f1: true value = 1.623, your value = 0.000\n",
|
||||
"h2: true value = 5.068, your value = 0.000\n",
|
||||
"f2: true value = 7.137, your value = 0.000\n",
|
||||
"h3: true value = 0.657, your value = 0.000\n",
|
||||
"f3: true value = 2.372, your value = 0.000\n",
|
||||
"l_i original = 0.139, l_i from forward pass = 0.000\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Let's check we got that right:\n",
|
||||
"print(\"f0: true value = %3.3f, your value = %3.3f\"%(1.230, f0))\n",
|
||||
@@ -275,42 +292,22 @@
|
||||
"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"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ibxXw7TUW4Sx",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"outputId": "4575e3eb-2b16-4e0b-c84e-9c22b443c3ce"
|
||||
},
|
||||
"execution_count": 7,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"text": [
|
||||
"f0: true value = 1.230, your value = 0.000\n",
|
||||
"h1: true value = 0.942, your value = 0.000\n",
|
||||
"f1: true value = 1.623, your value = 0.000\n",
|
||||
"h2: true value = 5.068, your value = 0.000\n",
|
||||
"f2: true value = 7.137, your value = 0.000\n",
|
||||
"h3: true value = 0.657, your value = 0.000\n",
|
||||
"f3: true value = 2.372, your value = 0.000\n",
|
||||
"like original = 0.139, like from forward pass = 0.000\n"
|
||||
]
|
||||
}
|
||||
"print(\"l_i original = %3.3f, l_i from forward pass = %3.3f\"%(l_i_func, l_i))\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "jay8NYWdFHuZ"
|
||||
},
|
||||
"source": [
|
||||
"**Step 2:** Compute the derivatives of $\\ell_i$ with respect to the intermediate quantities that we just calculated, but in reverse order:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"\\quad \\frac{\\partial \\ell_i}{\\partial f_3}, \\quad \\frac{\\partial \\ell_i}{\\partial h_3}, \\quad \\frac{\\partial \\ell_i}{\\partial f_2}, \\quad\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial h_2}, \\quad \\frac{\\partial \\ell_i}{\\partial f_1}, \\quad \\frac{\\partial \\ell_i}{\\partial h_1}, \\quad\\mbox{and} \\quad \\frac{\\partial \\ell_i}{\\partial f_0}.\n",
|
||||
"\\end{eqnarray}\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial h_2}, \\quad \\frac{\\partial \\ell_i}{\\partial f_1}, \\quad \\frac{\\partial \\ell_i}{\\partial h_1}, \\quad\\text{and} \\quad \\frac{\\partial \\ell_i}{\\partial f_0}.\n",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"The first of these derivatives is straightforward:\n",
|
||||
"\n",
|
||||
@@ -328,7 +325,7 @@
|
||||
"\n",
|
||||
"We can continue in this way, computing the derivatives of the output with respect to these intermediate quantities:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial f_{2}} &=& \\frac{\\partial h_{3}}{\\partial f_{2}}\\left(\n",
|
||||
"\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\n",
|
||||
"\\nonumber \\\\\n",
|
||||
@@ -336,16 +333,18 @@
|
||||
"\\frac{\\partial \\ell_i}{\\partial f_{1}} &=& \\frac{\\partial h_{2}}{\\partial f_{1}}\\left( \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\\nonumber \\\\\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial h_{1}} &=& \\frac{\\partial f_{1}}{\\partial h_{1}}\\left(\\frac{\\partial h_{2}}{\\partial f_{1}} \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right)\\nonumber \\\\\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial f_{0}} &=& \\frac{\\partial h_{1}}{\\partial f_{0}}\\left(\\frac{\\partial f_{1}}{\\partial h_{1}}\\frac{\\partial h_{2}}{\\partial f_{1}} \\frac{\\partial f_{2}}{\\partial h_{2}}\\frac{\\partial h_{3}}{\\partial f_{2}}\\frac{\\partial f_{3}}{\\partial h_{3}}\\frac{\\partial \\ell_i}{\\partial f_{3}} \\right).\n",
|
||||
"\\end{eqnarray}\n",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"In each case, we have already computed all of the terms except the last one in the previous step, and the last term is simple to evaluate. This is called the **backward pass**."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "jay8NYWdFHuZ"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "gCQJeI--Egdl"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO -- Compute the derivatives of the output with respect\n",
|
||||
"# to the intermediate computations h_k and f_k (i.e, run the backward pass)\n",
|
||||
@@ -358,37 +357,22 @@
|
||||
"dldf1 = 1\n",
|
||||
"dldh1 = 1\n",
|
||||
"dldf0 = 1\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "gCQJeI--Egdl"
|
||||
},
|
||||
"execution_count": 8,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Let's check we got that right\n",
|
||||
"print(\"dldf3: true value = %3.3f, your value = %3.3f\"%(0.745, dldf3))\n",
|
||||
"print(\"dldh3: true value = %3.3f, your value = %3.3f\"%(2.234, dldh3))\n",
|
||||
"print(\"dldf2: true value = %3.3f, your value = %3.3f\"%(-1.683, dldf2))\n",
|
||||
"print(\"dldh2: true value = %3.3f, your value = %3.3f\"%(-3.366, dldh2))\n",
|
||||
"print(\"dldf1: true value = %3.3f, your value = %3.3f\"%(-17.060, dldf1))\n",
|
||||
"print(\"dldh1: true value = %3.3f, your value = %3.3f\"%(6.824, dldh1))\n",
|
||||
"print(\"dldf0: true value = %3.3f, your value = %3.3f\"%(2.281, dldf0))"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "dS1OrLtlaFr7",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "dS1OrLtlaFr7",
|
||||
"outputId": "414f0862-ae36-4a0e-b68f-4758835b0e23"
|
||||
},
|
||||
"execution_count": 9,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"dldf3: true value = 0.745, your value = -4.000\n",
|
||||
"dldh3: true value = 2.234, your value = -12.000\n",
|
||||
@@ -399,33 +383,25 @@
|
||||
"dldf0: true value = 2.281, your value = 1.000\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Let's check we got that right\n",
|
||||
"print(\"dldf3: true value = %3.3f, your value = %3.3f\"%(0.745, dldf3))\n",
|
||||
"print(\"dldh3: true value = %3.3f, your value = %3.3f\"%(2.234, dldh3))\n",
|
||||
"print(\"dldf2: true value = %3.3f, your value = %3.3f\"%(-1.683, dldf2))\n",
|
||||
"print(\"dldh2: true value = %3.3f, your value = %3.3f\"%(-3.366, dldh2))\n",
|
||||
"print(\"dldf1: true value = %3.3f, your value = %3.3f\"%(-17.060, dldf1))\n",
|
||||
"print(\"dldh1: true value = %3.3f, your value = %3.3f\"%(6.824, dldh1))\n",
|
||||
"print(\"dldf0: true value = %3.3f, your value = %3.3f\"%(2.281, dldf0))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"**Step 3:** Finally, we consider how the loss~$\\ell_{i}$ changes when we change the parameters $\\beta_{\\bullet}$ and $\\omega_{\\bullet}$. Once more, we apply the chain rule:\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial \\beta_{k}} &=& \\frac{\\partial f_{k}}{\\partial \\beta_{k}}\\frac{\\partial \\ell_i}{\\partial f_{k}}\\nonumber \\\\\n",
|
||||
"\\frac{\\partial \\ell_i}{\\partial \\omega_{k}} &=& \\frac{\\partial f_{k}}{\\partial \\omega_{k}}\\frac{\\partial \\ell_i}{\\partial f_{k}}.\n",
|
||||
"\\end{eqnarray}\n",
|
||||
"\n",
|
||||
"\\noindent In each case, the second term on the right-hand side was computed in step 2. When $k>0$, we have~$f_{k}=\\beta_{k}+\\omega_k \\cdot h_{k}$, so:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\frac{\\partial f_{k}}{\\partial \\beta_{k}} = 1 \\quad\\quad\\mbox{and}\\quad \\quad \\frac{\\partial f_{k}}{\\partial \\omega_{k}} &=& h_{k}.\n",
|
||||
"\\end{eqnarray}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "FlzlThQPGpkU"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "1I2BhqZhGMK6"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO -- Calculate the final derivatives with respect to the beta and omega terms\n",
|
||||
"\n",
|
||||
@@ -437,38 +413,22 @@
|
||||
"dldomega1 = 1\n",
|
||||
"dldbeta0 = 1\n",
|
||||
"dldomega0 = 1\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "1I2BhqZhGMK6"
|
||||
},
|
||||
"execution_count": 10,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Let's check we got them right\n",
|
||||
"print('dldbeta3: Your value = %3.3f, True value = %3.3f'%(dldbeta3, 0.745))\n",
|
||||
"print('dldomega3: Your value = %3.3f, True value = %3.3f'%(dldomega3, 0.489))\n",
|
||||
"print('dldbeta2: Your value = %3.3f, True value = %3.3f'%(dldbeta2, -1.683))\n",
|
||||
"print('dldomega2: Your value = %3.3f, True value = %3.3f'%(dldomega2, -8.530))\n",
|
||||
"print('dldbeta1: Your value = %3.3f, True value = %3.3f'%(dldbeta1, -17.060))\n",
|
||||
"print('dldomega1: Your value = %3.3f, True value = %3.3f'%(dldomega1, -16.079))\n",
|
||||
"print('dldbeta0: Your value = %3.3f, True value = %3.3f'%(dldbeta0, 2.281))\n",
|
||||
"print('dldomega0: Your value = %3.3f, Function value = %3.3f, Finite difference value = %3.3f'%(dldomega0, dldomega0_func, dldomega0_fd))"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "38eiOn2aHgHI",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "38eiOn2aHgHI",
|
||||
"outputId": "1a67a636-e832-471e-e771-54824363158a"
|
||||
},
|
||||
"execution_count": 11,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"dldbeta3: Your value = 1.000, True value = 0.745\n",
|
||||
"dldomega3: Your value = 1.000, True value = 0.489\n",
|
||||
@@ -480,16 +440,44 @@
|
||||
"dldomega0: Your value = 1.000, Function value = 5.246, Finite difference value = 5.246\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Let's check we got them right\n",
|
||||
"print('dldbeta3: Your value = %3.3f, True value = %3.3f'%(dldbeta3, 0.745))\n",
|
||||
"print('dldomega3: Your value = %3.3f, True value = %3.3f'%(dldomega3, 0.489))\n",
|
||||
"print('dldbeta2: Your value = %3.3f, True value = %3.3f'%(dldbeta2, -1.683))\n",
|
||||
"print('dldomega2: Your value = %3.3f, True value = %3.3f'%(dldomega2, -8.530))\n",
|
||||
"print('dldbeta1: Your value = %3.3f, True value = %3.3f'%(dldbeta1, -17.060))\n",
|
||||
"print('dldomega1: Your value = %3.3f, True value = %3.3f'%(dldomega1, -16.079))\n",
|
||||
"print('dldbeta0: Your value = %3.3f, True value = %3.3f'%(dldbeta0, 2.281))\n",
|
||||
"print('dldomega0: Your value = %3.3f, Function value = %3.3f, Finite difference value = %3.3f'%(dldomega0, dldomega0_func, dldomega0_fd))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Using this method, we can compute the derivatives quite easily without needing to compute very complicated expressions. In the next practical, we'll apply this same method to a deep neural network."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "N2ZhrR-2fNa1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Using this method, we can compute the derivatives quite easily without needing to compute very complicated expressions. In the next practical, we'll apply this same method to a deep neural network."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyN7JeDgslwtZcwRCOuGuPFt",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyOlKB4TrCJnt91TnHOrfRSJ",
|
||||
"authorship_tag": "ABX9TyM2kkHLr00J4Jeypw41sTkQ",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
@@ -115,9 +115,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_{1\\ldots K}$ are the entries of the list \"all_weights\" and the biases $\\boldsymbol\\beta_{1\\ldots K}$ are the entries of the list \"all_biases\"\n",
|
||||
"\n",
|
||||
"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 +132,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",
|
||||
@@ -143,7 +143,7 @@
|
||||
" # 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",
|
||||
" # 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 +166,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",
|
||||
@@ -249,7 +249,7 @@
|
||||
"\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.21)\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",
|
||||
@@ -265,7 +265,7 @@
|
||||
"\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.24)\n",
|
||||
" # REPLACE THIS LINE\n",
|
||||
" all_dl_df[layer-1] = np.zeros_like(all_f[layer-1])\n",
|
||||
"\n",
|
||||
@@ -311,10 +311,16 @@
|
||||
" network_output_2, *_ = compute_network_output(net_input, all_weights, all_biases)\n",
|
||||
" dl_dbias[row] = (least_squares_loss(network_output_1, y) - least_squares_loss(network_output_2,y))/delta_fd\n",
|
||||
" all_dl_dbiases_fd[layer] = np.array(dl_dbias)\n",
|
||||
" print(\"-----------------------------------------------\")\n",
|
||||
" print(\"Bias %d, derivatives from backprop:\"%(layer))\n",
|
||||
" print(all_dl_dbiases[layer])\n",
|
||||
" print(\"Bias %d, derivatives from finite differences\"%(layer))\n",
|
||||
" print(all_dl_dbiases_fd[layer])\n",
|
||||
" if np.allclose(all_dl_dbiases_fd[layer],all_dl_dbiases[layer],rtol=1e-05, atol=1e-08, equal_nan=False):\n",
|
||||
" print(\"Success! Derivatives match.\")\n",
|
||||
" else:\n",
|
||||
" print(\"Failure! Derivatives different.\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Test the derivatives of the weights matrices\n",
|
||||
@@ -330,10 +336,15 @@
|
||||
" network_output_2, *_ = compute_network_output(net_input, all_weights, all_biases)\n",
|
||||
" dl_dweight[row][col] = (least_squares_loss(network_output_1, y) - least_squares_loss(network_output_2,y))/delta_fd\n",
|
||||
" all_dl_dweights_fd[layer] = np.array(dl_dweight)\n",
|
||||
" print(\"-----------------------------------------------\")\n",
|
||||
" print(\"Weight %d, derivatives from backprop:\"%(layer))\n",
|
||||
" print(all_dl_dweights[layer])\n",
|
||||
" print(\"Weight %d, derivatives from finite differences\"%(layer))\n",
|
||||
" print(all_dl_dweights_fd[layer])"
|
||||
" print(all_dl_dweights_fd[layer])\n",
|
||||
" if np.allclose(all_dl_dweights_fd[layer],all_dl_dweights[layer],rtol=1e-05, atol=1e-08, equal_nan=False):\n",
|
||||
" print(\"Success! Derivatives match.\")\n",
|
||||
" else:\n",
|
||||
" print(\"Failure! Derivatives different.\")"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "PK-UtE3hreAK"
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyNHLXFpiSnUzAbzhtOk+bxu",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
@@ -117,10 +116,10 @@
|
||||
"def compute_network_output(net_input, all_weights, all_biases):\n",
|
||||
"\n",
|
||||
" # Retrieve number of layers\n",
|
||||
" K = len(all_weights) -1\n",
|
||||
" 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"
|
||||
@@ -164,7 +163,7 @@
|
||||
"K = 5\n",
|
||||
"# Number of neurons per layer\n",
|
||||
"D = 8\n",
|
||||
" # Input layer\n",
|
||||
"# Input layer\n",
|
||||
"D_i = 1\n",
|
||||
"# Output layer\n",
|
||||
"D_o = 1\n",
|
||||
@@ -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",
|
||||
"# TO DO\n",
|
||||
"# Now experiment with sigma_sq_omega to try to stop the variance of the forward computation explode"
|
||||
"# Now experiment with sigma_sq_omega to try to stop the variance of the forward computation exploding"
|
||||
],
|
||||
"metadata": {
|
||||
"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",
|
||||
@@ -297,7 +299,7 @@
|
||||
"K = 5\n",
|
||||
"# Number of neurons per layer\n",
|
||||
"D = 8\n",
|
||||
" # Input layer\n",
|
||||
"# Input layer\n",
|
||||
"D_i = 1\n",
|
||||
"# Output layer\n",
|
||||
"D_o = 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",
|
||||
"# TO DO\n",
|
||||
"# Change this to 50 layers with 80 hidden units per layer\n",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"gpuType": "T4",
|
||||
"authorship_tag": "ABX9TyNLj3HOpVB87nRu7oSLuBaU",
|
||||
"authorship_tag": "ABX9TyOuKMUcKfOIhIL2qTX9jJCy",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
@@ -46,8 +46,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": "ifVjS4cTOqKz"
|
||||
@@ -83,8 +83,10 @@
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"!mkdir ./sample_data\n",
|
||||
"\n",
|
||||
"args = mnist1d.data.get_dataset_args()\n",
|
||||
"data = mnist1d.data.get_dataset(args, path='./mnist1d_data.pkl', download=False, regenerate=False)\n",
|
||||
"data = mnist1d.data.get_dataset(args, path='./sample_data/mnist1d_data.pkl', download=False, regenerate=False)\n",
|
||||
"\n",
|
||||
"# The training and test input and outputs are in\n",
|
||||
"# data['x'], data['y'], data['x_test'], and data['y_test']\n",
|
||||
@@ -136,7 +138,6 @@
|
||||
"optimizer = torch.optim.SGD(model.parameters(), lr = 0.05, momentum=0.9)\n",
|
||||
"# 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",
|
||||
"x_test= torch.tensor(data['x_test'].astype('float32'))\n",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
"ax.plot(hidden_variables, errors_train_all, 'r-', label='train')\n",
|
||||
"ax.plot(hidden_variables, errors_test_all, 'b-', label='test')\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": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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!"
|
||||
],
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,20 +1,4 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyMB8B4269DVmrcLoCWrhzKF",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
@@ -28,6 +12,9 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "el8l05WQEO46"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 9.4: Bayesian approach**\n",
|
||||
"\n",
|
||||
@@ -36,10 +23,7 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "el8l05WQEO46"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
@@ -52,26 +36,31 @@
|
||||
"# 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)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "3hpqmFyQNrbt"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# The true function that we are trying to estimate, defined on [0,1]\n",
|
||||
"def true_function(x):\n",
|
||||
" y = np.exp(np.sin(x*(2*3.1413)))\n",
|
||||
" return y"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "3hpqmFyQNrbt"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "skZMM5TbNwq4"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Generate some data points with or without noise\n",
|
||||
"def generate_data(n_data, sigma_y=0.3):\n",
|
||||
@@ -86,17 +75,17 @@
|
||||
" y[i] = true_function(x[i])\n",
|
||||
" y[i] += np.random.normal(0, sigma_y, 1)\n",
|
||||
" return x,y"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "skZMM5TbNwq4"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ziwD_R7lN0DY"
|
||||
},
|
||||
"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",
|
||||
@@ -117,15 +106,15 @@
|
||||
" ax.set_xlabel('Input, $x$')\n",
|
||||
" ax.set_ylabel('Output, $y$')\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ziwD_R7lN0DY"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "2CgKanwaN3NM"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Generate true function\n",
|
||||
"x_func = np.linspace(0, 1.0, 100)\n",
|
||||
@@ -139,15 +128,15 @@
|
||||
"\n",
|
||||
"# Plot the function, data and uncertainty\n",
|
||||
"plot_function(x_func, y_func, x_data, y_data, sigma_func=sigma_func)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "2CgKanwaN3NM"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "gorZ6i97N7AR"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define model -- beta is a scalar and omega has size n_hidden,1\n",
|
||||
"def network(x, beta, omega):\n",
|
||||
@@ -165,15 +154,13 @@
|
||||
" y = y + beta\n",
|
||||
"\n",
|
||||
" return y"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "gorZ6i97N7AR"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "i8T_QduzeBmM"
|
||||
},
|
||||
"source": [
|
||||
"Now let's compute a probability distribution over the model parameters using Bayes's rule:\n",
|
||||
"\n",
|
||||
@@ -184,69 +171,71 @@
|
||||
"We'll define the prior $Pr(\\boldsymbol\\phi)$ as:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"Pr(\\boldsymbol\\phi) = \\mbox{Norm}_{\\boldsymbol\\phi}\\bigl[\\mathbf{0},\\sigma^2_p\\mathbf{I}\\bigr]\n",
|
||||
"Pr(\\boldsymbol\\phi) = \\text{Norm}_{\\boldsymbol\\phi}\\bigl[\\mathbf{0},\\sigma^2_p\\mathbf{I}\\bigr]\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"where $\\phi=[\\omega_1,\\omega_2\\ldots \\omega_n, \\beta]^T$ and $\\sigma^2_{p}$ is the prior variance.\n",
|
||||
"\n",
|
||||
"The likelihood term $\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi)$ is given by:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi) &=& \\prod_{i=1}^{I} \\mbox{Norm}_{y_i}\\bigl[\\mbox{f}[\\mathbf{x}_{i},\\boldsymbol\\phi],\\sigma_d^2\\bigr]\\\\\n",
|
||||
"&=& \\prod_{i=1}^{I} \\mbox{Norm}_{y_i}\\bigl[\\boldsymbol\\omega\\mathbf{h}_i+\\beta,\\sigma_d^2\\bigr]\\\\\n",
|
||||
"&=& \\mbox{Norm}_{\\mathbf{y}}\\bigl[\\mathbf{H}^T\\boldsymbol\\phi,\\sigma^2\\mathbf{I}\\bigr].\n",
|
||||
"\\end{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi) &=& \\prod_{i=1}^{I} \\text{Norm}_{y_i}\\bigl[\\text{f}[\\mathbf{x}_{i},\\boldsymbol\\phi],\\sigma_d^2\\bigr]\\\\\n",
|
||||
"&=& \\prod_{i=1}^{I} \\text{Norm}_{y_i}\\bigl[\\boldsymbol\\omega\\mathbf{h}_i+\\beta,\\sigma_d^2\\bigr]\\\\\n",
|
||||
"&=& \\text{Norm}_{\\mathbf{y}}\\bigl[\\mathbf{H}^T\\boldsymbol\\phi,\\sigma^2\\mathbf{I}\\bigr].\n",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"where $\\sigma^2$ is the measurement noise and $\\mathbf{h}_{i}$ is the column vector of hidden variables for the $i^{th}$ input. Here the vector $\\mathbf{y}$ and matrix $\\mathbf{H}$ are defined as:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\mathbf{y} = \\begin{bmatrix}y_1\\\\y_2\\\\\\vdots\\\\y_{I}\\end{bmatrix}\\quad\\mbox{and}\\quad \\mathbf{H} = \\begin{bmatrix}\\mathbf{h}_{1}&\\mathbf{h}_{2}&\\cdots&\\mathbf{h}_{I}\\\\1&1&\\cdots &1\\end{bmatrix}.\n",
|
||||
"\\mathbf{y} = \\begin{bmatrix}y_1\\\\y_2\\\\\\vdots\\\\y_{I}\\end{bmatrix}\\quad\\text{and}\\quad \\mathbf{H} = \\begin{bmatrix}\\mathbf{h}_{1}&\\mathbf{h}_{2}&\\cdots&\\mathbf{h}_{I}\\\\1&1&\\cdots &1\\end{bmatrix}.\n",
|
||||
"\\end{equation}\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "i8T_QduzeBmM"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "JojV6ueRk49G"
|
||||
},
|
||||
"source": [
|
||||
"To make progress we use the change of variable relation (Appendix C.3.4 of the book) to rewrite the likelihood term as a normal distribution in the parameters $\\boldsymbol\\phi$:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"\\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi+\\beta)\n",
|
||||
"&=& \\mbox{Norm}_{\\mathbf{y}}\\bigl[\\mathbf{H}^T\\boldsymbol\\phi,\\sigma^2\\bigr]\\\\\n",
|
||||
"&\\propto& \\mbox{Norm}_{\\boldsymbol\\phi}\\bigl[(\\mathbf{H}\\mathbf{H}^T)^{-1}\\mathbf{H}\\mathbf{y},\\sigma^2(\\mathbf{H}\\mathbf{H}^t)^{-1}\\bigr]\n",
|
||||
"\\end{eqnarray}\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "JojV6ueRk49G"
|
||||
}
|
||||
"&=& \\text{Norm}_{\\mathbf{y}}\\bigl[\\mathbf{H}^T\\boldsymbol\\phi,\\sigma^2\\bigr]\\\\\n",
|
||||
"&\\propto& \\text{Norm}_{\\boldsymbol\\phi}\\bigl[(\\mathbf{H}\\mathbf{H}^T)^{-1}\\mathbf{H}\\mathbf{y},\\sigma^2(\\mathbf{H}\\mathbf{H}^t)^{-1}\\bigr]\n",
|
||||
"\\end{align}\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "YX0O_Ciwp4W1"
|
||||
},
|
||||
"source": [
|
||||
"Finally, we can combine the likelihood and prior terms using the product of two normal distributions relation (Appendix C.3.3).\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
" Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) &\\propto& \\prod_{i=1}^{I} Pr(\\mathbf{y}_{i}|\\mathbf{x}_{i},\\boldsymbol\\phi) Pr(\\boldsymbol\\phi)\\\\\n",
|
||||
" &\\propto&\\mbox{Norm}_{\\boldsymbol\\phi}\\bigl[(\\mathbf{H}\\mathbf{H}^T)^{-1}\\mathbf{H}\\mathbf{y},\\sigma^2(\\mathbf{H}\\mathbf{H}^T)^{-1}\\bigr] \\mbox{Norm}_{\\boldsymbol\\phi}\\bigl[\\mathbf{0},\\sigma^2_p\\mathbf{I}\\bigr]\\\\\n",
|
||||
" &\\propto&\\mbox{Norm}_{\\boldsymbol\\phi}\\biggl[\\frac{1}{\\sigma^2}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y},\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\biggr].\n",
|
||||
"\\end{eqnarray}\n",
|
||||
" &\\propto&\\text{Norm}_{\\boldsymbol\\phi}\\bigl[(\\mathbf{H}\\mathbf{H}^T)^{-1}\\mathbf{H}\\mathbf{y},\\sigma^2(\\mathbf{H}\\mathbf{H}^T)^{-1}\\bigr] \\text{Norm}_{\\boldsymbol\\phi}\\bigl[\\mathbf{0},\\sigma^2_p\\mathbf{I}\\bigr]\\\\\n",
|
||||
" &\\propto&\\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{eqnarray}\n",
|
||||
" Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) &=& \\mbox{Norm}_{\\boldsymbol\\phi}\\biggl[\\frac{1}{\\sigma^2}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y},\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\biggr].\n",
|
||||
"\\end{eqnarray}\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",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"TODO -- On a piece of paper, use the relations in Appendix C.3.3 and C.3.4 to fill in the missing steps and establish that this is the correct formula for the posterior."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "YX0O_Ciwp4W1"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "nF1AcgNDwm4t"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_H(x_data, n_hidden):\n",
|
||||
" psi1 = np.ones((n_hidden+1,1));\n",
|
||||
@@ -280,24 +269,24 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return phi_mean, phi_covar"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "nF1AcgNDwm4t"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now we can draw samples from this distribution"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "GjPnlG4q0UFK"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now we can draw samples from this distribution"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "K4vYc82D0BMq"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define parameters\n",
|
||||
"n_hidden = 5\n",
|
||||
@@ -313,15 +302,15 @@
|
||||
"x_model = x_func\n",
|
||||
"y_model_mean = network(x_model, phi_mean[-1], phi_mean[0:n_hidden])\n",
|
||||
"plot_function(x_func, y_func, x_data, y_data, x_model, y_model_mean)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "K4vYc82D0BMq"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "TVIjhubkSw-R"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO Draw two samples from the normal distribution over the parameters\n",
|
||||
"# Replace these lines\n",
|
||||
@@ -336,37 +325,40 @@
|
||||
"# Draw the two models\n",
|
||||
"plot_function(x_func, y_func, x_data, y_data, x_model, y_model_sample1)\n",
|
||||
"plot_function(x_func, y_func, x_data, y_data, x_model, y_model_sample2)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "TVIjhubkSw-R"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "GiNg5EroUiUb"
|
||||
},
|
||||
"source": [
|
||||
"Now we need to perform inference for a new data points $\\mathbf{x}^*$ with corresponding hidden values $\\mathbf{h}^*$. Instead of having a single estimate of the parameters, we have a distribution over the possible parameters. So we marginalize (integrate) over this distribution to account for all possible values:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"Pr(y^*|\\mathbf{x}^*) &=& \\int Pr(y^{*}|\\mathbf{x}^*,\\boldsymbol\\phi)Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) d\\boldsymbol\\phi\\\\\n",
|
||||
"&=& \\int \\mbox{Norm}_{y^*}\\bigl[\\begin{bmatrix}\\mathbf{h}^{*T}&1\\end{bmatrix}\\boldsymbol\\phi,\\sigma^2]\\cdot\\mbox{Norm}_{\\boldsymbol\\phi}\\biggl[\\frac{1}{\\sigma^2}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y},\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\biggr]d\\boldsymbol\\phi\\\\\n",
|
||||
"&=& \\mbox{Norm}_{y^*}\\biggl[\\frac{1}{\\sigma^2} \\begin{bmatrix}\\mathbf{h}^{*T}&1\\end{bmatrix}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\\mathbf{H}\\mathbf{y}, \\begin{bmatrix}\\mathbf{h}^{*T}&1\\end{bmatrix}\\left(\\frac{1}{\\sigma^2}\\mathbf{H}\\mathbf{H}^T+\\frac{1}{\\sigma_p^2}\\mathbf{I}\\right)^{-1}\n",
|
||||
"\\begin{bmatrix}\\mathbf{h}^*\\\\1\\end{bmatrix}\\biggr]\n",
|
||||
"\\end{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"Pr(y^*|\\mathbf{x}^*) &= \\int Pr(y^{*}|\\mathbf{x}^*,\\boldsymbol\\phi)Pr(\\boldsymbol\\phi|\\{\\mathbf{x}_{i},\\mathbf{y}_{i}\\}) d\\boldsymbol\\phi\\\\\n",
|
||||
"&= \\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",
|
||||
"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",
|
||||
"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",
|
||||
"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."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "GiNg5EroUiUb"
|
||||
}
|
||||
"If you feel so inclined you can work through the math of this yourself.\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ILxT4EfW2lUm"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Predict mean and variance of y_star from x_star\n",
|
||||
"def inference(x_star, x_data, y_data, sigma_sq, sigma_p_sq, n_hidden):\n",
|
||||
@@ -381,15 +373,15 @@
|
||||
" y_star_var = 1\n",
|
||||
"\n",
|
||||
" return y_star_mean, y_star_var"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ILxT4EfW2lUm"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "87cjUjMaixHZ"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"x_model = x_func\n",
|
||||
"y_model = np.zeros_like(x_model)\n",
|
||||
@@ -401,24 +393,34 @@
|
||||
"\n",
|
||||
"# Draw the model\n",
|
||||
"plot_function(x_func, y_func, x_data, y_data, x_model, y_model, sigma_model=y_model_std)\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "87cjUjMaixHZ"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "8Hcbe_16sK0F"
|
||||
},
|
||||
"source": [
|
||||
"TODO:\n",
|
||||
"\n",
|
||||
"1. Experiment running this again with different numbers of hidden units. Make a prediction for what will happen when you increase / decrease them.\n",
|
||||
"2. Experiment with what happens if you make the prior variance $\\sigma^2_p$ to a smaller value like 1. How do you explain the results?"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"id": "8Hcbe_16sK0F"
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -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",
|
||||
@@ -186,7 +185,7 @@
|
||||
"ax.plot(errors_test,'b-',label='test')\n",
|
||||
"ax.set_ylim(0,100); ax.set_xlim(0,n_epoch)\n",
|
||||
"ax.set_xlabel('Epoch'); ax.set_ylabel('Error')\n",
|
||||
"ax.set_title('TrainError %3.2f, Test Error %3.2f'%(errors_train[-1],errors_test[-1]))\n",
|
||||
"ax.set_title('Train Error %3.2f, Test Error %3.2f'%(errors_train[-1],errors_test[-1]))\n",
|
||||
"ax.legend()\n",
|
||||
"plt.show()"
|
||||
],
|
||||
@@ -233,7 +232,7 @@
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"n_data_orig = data['x'].shape[0]\n",
|
||||
"# We'll double the amount o fdata\n",
|
||||
"# We'll double the amount of data\n",
|
||||
"n_data_augment = n_data_orig+4000\n",
|
||||
"augmented_x = np.zeros((n_data_augment, D_i))\n",
|
||||
"augmented_y = np.zeros(n_data_augment)\n",
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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()"
|
||||
],
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyOdSkjfQnSZXnffGsZVM7r5",
|
||||
"authorship_tag": "ABX9TyO/wJ4N9w01f04mmrs/ZSHY",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyNyLnpoXgKN+RGCuTUszCAZ",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
@@ -129,7 +128,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 +152,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 +196,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 +217,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"
|
||||
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyNeCWINUqqUGKMcxsqPFTAh",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/Chap16/16_3_Contraction_Mappings.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 16.3: Contraction mappings**\n",
|
||||
"\n",
|
||||
@@ -36,38 +25,40 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4Pfz2KSghdVI"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define a function that is a contraction mapping\n",
|
||||
"def f(z):\n",
|
||||
" return 0.3 + 0.5 *z + 0.02 * np.sin(z*15)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4Pfz2KSghdVI"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "zEwCbIx0hpAI"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def draw_function(f, fixed_point=None):\n",
|
||||
" z = np.arange(0,1,0.01)\n",
|
||||
@@ -84,35 +75,36 @@
|
||||
" ax.set_xlabel('Input, $z$')\n",
|
||||
" ax.set_ylabel('Output, f$[z]$')\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "zEwCbIx0hpAI"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"draw_function(f)"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "k4e5Yu0fl8bz"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"draw_function(f)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's find where $\\mbox{f}[z]=z$ using fixed point iteration"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "DfgKrpCAjnol"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's find where $\\text{f}[z]=z$ using fixed point iteration"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "bAOBvZT-j3lv"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Takes a function f and a starting point z\n",
|
||||
"def fixed_point_iteration(f, z0):\n",
|
||||
@@ -125,115 +117,117 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return z_out"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "bAOBvZT-j3lv"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's test that and plot the solution"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "CAS0lgIomAa0"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's test that and plot the solution"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "EYQZJdNPk8Lg"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Now let's test that\n",
|
||||
"z = fixed_point_iteration(f, 0.2)\n",
|
||||
"draw_function(f, z)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "EYQZJdNPk8Lg"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4DipPiqVlnwJ"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Let's define another function\n",
|
||||
"def f2(z):\n",
|
||||
" return 0.7 + -0.6 *z + 0.03 * np.sin(z*15)\n",
|
||||
"draw_function(f2)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4DipPiqVlnwJ"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "tYOdbWcomdEE"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Now let's test that\n",
|
||||
"# TODO Before running this code, predict what you think will happen\n",
|
||||
"z = fixed_point_iteration(f2, 0.9)\n",
|
||||
"draw_function(f2, z)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "tYOdbWcomdEE"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Mni37RUpmrIu"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Let's define another function\n",
|
||||
"# Define a function that is a contraction mapping\n",
|
||||
"def f3(z):\n",
|
||||
" return -0.2 + 1.5 *z + 0.1 * np.sin(z*15)\n",
|
||||
"draw_function(f3)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Mni37RUpmrIu"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "agt5mfJrnM1O"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Now let's test that\n",
|
||||
"# TODO Before running this code, predict what you think will happen\n",
|
||||
"z = fixed_point_iteration(f3, 0.7)\n",
|
||||
"draw_function(f3, z)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "agt5mfJrnM1O"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Finally, let's invert a problem of the form $y = z+ f[z]$ for a given value of $y$. What is the $z$ that maps to it?"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "n6GI46-ZoQz6"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Finally, let's invert a problem of the form $y = z+ f[z]$ for a given value of $y$. What is the $z$ that maps to it?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"def f4(z):\n",
|
||||
" return -0.3 + 0.5 *z + 0.02 * np.sin(z*15)"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "dy6r3jr9rjPf"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def f4(z):\n",
|
||||
" return -0.3 + 0.5 *z + 0.02 * np.sin(z*15)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "GMX64Iz0nl-B"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def fixed_point_iteration_z_plus_f(f, y, z0):\n",
|
||||
" # TODO -- write this function\n",
|
||||
@@ -241,15 +235,15 @@
|
||||
" z_out = 1\n",
|
||||
"\n",
|
||||
" return z_out"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "GMX64Iz0nl-B"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "uXxKHad5qT8Y"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def draw_function2(f, y, fixed_point=None):\n",
|
||||
" z = np.arange(0,1,0.01)\n",
|
||||
@@ -267,15 +261,15 @@
|
||||
" ax.set_xlabel('Input, $z$')\n",
|
||||
" ax.set_ylabel('Output, z+f$[z]$')\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "uXxKHad5qT8Y"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "mNEBXC3Aqd_1"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test this out and draw\n",
|
||||
"y = 0.8\n",
|
||||
@@ -283,12 +277,23 @@
|
||||
"draw_function2(f4,y,z)\n",
|
||||
"# If you have done this correctly, the red dot should be\n",
|
||||
"# where the cyan curve has a y value of 0.8"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"id": "mNEBXC3Aqd_1"
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyNeCWINUqqUGKMcxsqPFTAh",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
]
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyOSEQVqxE5KrXmsZVh9M3gq",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/Chap17/17_1_Latent_Variable_Models.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 17.1: Latent variable models**\n",
|
||||
"\n",
|
||||
@@ -36,72 +25,76 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"import scipy\n",
|
||||
"from matplotlib.colors import ListedColormap\n",
|
||||
"from matplotlib import cm"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "IyVn-Gi-p7wf"
|
||||
},
|
||||
"source": [
|
||||
"We'll assume that our base distribution over the latent variables is a 1D standard normal so that\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"Pr(z) = \\mbox{Norm}_{z}[0,1]\n",
|
||||
"Pr(z) = \\text{Norm}_{z}[0,1]\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"As in figure 17.2, we'll assume that the output is two dimensional, we we need to define a function that maps from the 1D latent variable to two dimensions. Usually, we would use a neural network, but in this case, we'll just define an arbitrary relationship.\n",
|
||||
"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{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"x_{1} &=& 0.5\\cdot\\exp\\Bigl[\\sin\\bigl[2+ 3.675 z \\bigr]\\Bigr]\\\\\n",
|
||||
"x_{2} &=& \\sin\\bigl[2+ 2.85 z \\bigr]\n",
|
||||
"\\end{eqnarray}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "IyVn-Gi-p7wf"
|
||||
}
|
||||
"\\end{align}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ZIfQwhd-AV6L"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# The function that maps z to x1 and x2\n",
|
||||
"def f(z):\n",
|
||||
" x_1 = np.exp(np.sin(2+z*3.675)) * 0.5\n",
|
||||
" x_2 = np.cos(2+z*2.85)\n",
|
||||
" return x_1, x_2"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ZIfQwhd-AV6L"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's plot the 3D relation between the two observed variables $x_{1}$ and $x_{2}$ and the latent variables $z$ as in figure 17.2 of the book. We'll use the opacity to represent the prior probability $Pr(z)$."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "KB9FU34onW1j"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's plot the 3D relation between the two observed variables $x_{1}$ and $x_{2}$ and the latent variables $z$ as in figure 17.2 of the book. We'll use the opacity to represent the prior probability $Pr(z)$."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "lW08xqAgnP4q"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def draw_3d_projection(z,pr_z, x1,x2):\n",
|
||||
" alpha = pr_z / np.max(pr_z)\n",
|
||||
@@ -118,28 +111,28 @@
|
||||
" ax.set_zlim(-1,1)\n",
|
||||
" ax.set_box_aspect((3,1,1))\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "lW08xqAgnP4q"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "9DUTauMi6tPk"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Compute the prior\n",
|
||||
"def get_prior(z):\n",
|
||||
" return scipy.stats.multivariate_normal.pdf(z)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "9DUTauMi6tPk"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "PAzHq461VqvF"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define the latent variable values\n",
|
||||
"z = np.arange(-3.0,3.0,0.01)\n",
|
||||
@@ -149,40 +142,41 @@
|
||||
"x1,x2 = f(z)\n",
|
||||
"# Plot the function\n",
|
||||
"draw_3d_projection(z,pr_z, x1,x2)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "PAzHq461VqvF"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"The likelihood is defined as:\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
" Pr(x_1,x_2|z) &=& \\mbox{Norm}_{[x_1,x_2]}\\Bigl[\\mathbf{f}[z],\\sigma^{2}\\mathbf{I}\\Bigr]\n",
|
||||
"\\end{eqnarray}\n",
|
||||
"\n",
|
||||
"so we will also need to define the noise level $\\sigma^2$"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "sQg2gKR5zMrF"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"The likelihood is defined as:\n",
|
||||
"\\begin{align}\n",
|
||||
" Pr(x_1,x_2|z) &=& \\text{Norm}_{[x_1,x_2]}\\Bigl[\\mathbf{f}[z],\\sigma^{2}\\mathbf{I}\\Bigr]\n",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"so we will also need to define the noise level $\\sigma^2$"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"sigma_sq = 0.04"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "In_Vg4_0nva3"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"sigma_sq = 0.04"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "6P6d-AgAqxXZ"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Draws a heatmap to represent a probability distribution, possibly with samples overlaed\n",
|
||||
"def plot_heatmap(x1_mesh,x2_mesh,y_mesh, x1_samples=None, x2_samples=None, title=None):\n",
|
||||
@@ -207,15 +201,15 @@
|
||||
" ax.set_xlabel('$x_1$'); ax.set_ylabel('$x_2$')\n",
|
||||
" plt.show()\n",
|
||||
"\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "6P6d-AgAqxXZ"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "diYKb7_ZgjlJ"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Returns the likelihood\n",
|
||||
"def get_likelihood(x1_mesh, x2_mesh, z_val):\n",
|
||||
@@ -226,24 +220,25 @@
|
||||
" mn = scipy.stats.multivariate_normal([x1, x2], [[sigma_sq, 0], [0, sigma_sq]])\n",
|
||||
" pr_x1_x2_given_z_val = mn.pdf(np.dstack((x1_mesh, x2_mesh)))\n",
|
||||
" return pr_x1_x2_given_z_val"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "diYKb7_ZgjlJ"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's plot the likelihood $Pr(x_1,x_2|z)$ as in fig 17.3b in the book."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "0X4NwixzqxtZ"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's plot the likelihood $Pr(x_1,x_2|z)$ as in fig 17.3b in the book."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "hWfqK-Oz5_DT"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Choose some z value\n",
|
||||
"z_val = 1.8\n",
|
||||
@@ -256,30 +251,31 @@
|
||||
"plot_heatmap(x1_mesh, x2_mesh, pr_x1_x2_given_z_val, title=\"Conditional distribution $Pr(x_1,x_2|z)$\")\n",
|
||||
"\n",
|
||||
"# TODO -- Experiment with different values of z and make sure that you understand the what is happening."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "hWfqK-Oz5_DT"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "25xqXnmFo-PH"
|
||||
},
|
||||
"source": [
|
||||
"The data density is found by marginalizing over the latent variables $z$:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
" Pr(x_1,x_2) &=& \\int Pr(x_1,x_2, z) dz \\nonumber \\\\\n",
|
||||
" &=& \\int Pr(x_1,x_2 | z) \\cdot Pr(z)dz\\nonumber \\\\\n",
|
||||
" &=& \\int \\mbox{Norm}_{[x_1,x_2]}\\Bigl[\\mathbf{f}[z],\\sigma^{2}\\mathbf{I}\\Bigr]\\cdot \\mbox{Norm}_{z}\\left[\\mathbf{0},\\mathbf{I}\\right]dz.\n",
|
||||
"\\end{eqnarray}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "25xqXnmFo-PH"
|
||||
}
|
||||
" &=& \\int \\text{Norm}_{[x_1,x_2]}\\Bigl[\\mathbf{f}[z],\\sigma^{2}\\mathbf{I}\\Bigr]\\cdot \\text{Norm}_{z}\\left[\\mathbf{0},\\mathbf{I}\\right]dz.\n",
|
||||
"\\end{align}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "H0Ijce9VzeCO"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TODO Compute the data density\n",
|
||||
"# We can't integrate this function in closed form\n",
|
||||
@@ -293,24 +289,25 @@
|
||||
"\n",
|
||||
"# Plot the result\n",
|
||||
"plot_heatmap(x1_mesh, x2_mesh, pr_x1_x2, title=\"Data density $Pr(x_1,x_2)$\")\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "H0Ijce9VzeCO"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's draw some samples from the model"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "W264N7By_h9y"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's draw some samples from the model"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Li3mK_I48k0k"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def draw_samples(n_sample):\n",
|
||||
" # TODO Write this routine to draw n_sample samples from the model\n",
|
||||
@@ -320,37 +317,38 @@
|
||||
" x1_samples=0; x2_samples = 0;\n",
|
||||
"\n",
|
||||
" return x1_samples, x2_samples"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Li3mK_I48k0k"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's plot those samples on top of the heat map."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "D7N7oqLe-eJO"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's plot those samples on top of the heat map."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "XRmWv99B-BWO"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"x1_samples, x2_samples = draw_samples(500)\n",
|
||||
"# Plot the result\n",
|
||||
"plot_heatmap(x1_mesh, x2_mesh, pr_x1_x2, x1_samples, x2_samples, title=\"Data density $Pr(x_1,x_2)$\")\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "XRmWv99B-BWO"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "PwOjzPD5_1OF"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Return the posterior distribution\n",
|
||||
"def get_posterior(x1,x2):\n",
|
||||
@@ -364,15 +362,15 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return z, pr_z_given_x1_x2"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "PwOjzPD5_1OF"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "PKFUY42K-Tp7"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"x1 = 0.9; x2 = -0.9\n",
|
||||
"z, pr_z_given_x1_x2 = get_posterior(x1,x2)\n",
|
||||
@@ -385,12 +383,23 @@
|
||||
"ax.set_xlim([-3,3])\n",
|
||||
"ax.set_ylim([0,1.5 * np.max(pr_z_given_x1_x2)])\n",
|
||||
"plt.show()"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"id": "PKFUY42K-Tp7"
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyOSEQVqxE5KrXmsZVh9M3gq",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
]
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -1,20 +1,4 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyOxO2/0DTH4n4zhC97qbagY",
|
||||
"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 17.2: Reparameterization trick**\n",
|
||||
"\n",
|
||||
@@ -36,30 +23,30 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "paLz5RukZP1J"
|
||||
},
|
||||
"source": [
|
||||
"The reparameterization trick computes the derivative of an expectation of a function $\\mbox{f}[x]$:\n",
|
||||
"The reparameterization trick computes the derivative of an expectation of a function $\\text{f}[x]$:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\bigl[\\mbox{f}[x]\\bigr],\n",
|
||||
"\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\bigl[\\text{f}[x]\\bigr],\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"with respect to the parameters $\\boldsymbol\\phi$ of the distribution $Pr(x|\\boldsymbol\\phi)$ that the expectation is over.\n",
|
||||
@@ -67,21 +54,23 @@
|
||||
"Let's consider a simple concrete example, where:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"Pr(x|\\phi) = \\mbox{Norm}_{x}\\Bigl[\\mu, \\sigma^2\\Bigr]=\\mbox{Norm}_{x}\\Bigl[\\phi^3,(\\exp[\\phi])^2\\Bigr]\n",
|
||||
"Pr(x|\\phi) = \\text{Norm}_{x}\\Bigl[\\mu, \\sigma^2\\Bigr]=\\text{Norm}_{x}\\Bigl[\\phi^3,(\\exp[\\phi])^2\\Bigr]\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"and\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\mbox{f}[x] = x^2+\\sin[x]\n",
|
||||
"\\text{f}[x] = x^2+\\sin[x]\n",
|
||||
"\\end{equation}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "paLz5RukZP1J"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "FdEbMnDBY0i9"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Let's approximate this expectation for a particular value of phi\n",
|
||||
"def compute_expectation(phi, n_samples):\n",
|
||||
@@ -96,15 +85,15 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return expected_f_given_phi"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "FdEbMnDBY0i9"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "FTh7LJ0llNJZ"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the seed so the random numbers are all the same\n",
|
||||
"np.random.seed(0)\n",
|
||||
@@ -119,24 +108,24 @@
|
||||
"n_samples = 10000000\n",
|
||||
"expected_f_given_phi2 = compute_expectation(phi2, n_samples)\n",
|
||||
"print(\"Your value: \", expected_f_given_phi2, \", True value: 0.8176793102849222\")"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "FTh7LJ0llNJZ"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Le't plot this expectation as a function of phi"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "r5Hl2QkimWx9"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Le't plot this expectation as a function of phi"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "05XxVLJxmkER"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"phi_vals = np.arange(-1.5,1.5, 0.05)\n",
|
||||
"expected_vals = np.zeros_like(phi_vals)\n",
|
||||
@@ -146,18 +135,16 @@
|
||||
"\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()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "05XxVLJxmkER"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "zTCykVeWqj_O"
|
||||
},
|
||||
"source": [
|
||||
"It's this curve that we want to find the derivative of (so for example, we could run gradient descent and find the minimum.\n",
|
||||
"\n",
|
||||
@@ -166,28 +153,30 @@
|
||||
"The answer is the reparameterization trick. We note that:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\mbox{Norm}_{x}\\Bigl[\\mu, \\sigma^2\\Bigr]=\\mbox{Norm}_{x}\\Bigl[0, 1\\Bigr] \\times \\sigma + \\mu\n",
|
||||
"\\text{Norm}_{x}\\Bigl[\\mu, \\sigma^2\\Bigr]=\\text{Norm}_{x}\\Bigl[0, 1\\Bigr] \\times \\sigma + \\mu\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"and so:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\mbox{Norm}_{x}\\Bigl[\\phi^3,(\\exp[\\phi])^2\\Bigr] = \\mbox{Norm}_{x}\\Bigl[0, 1\\Bigr] \\times \\exp[\\phi]+ \\phi^3\n",
|
||||
"\\text{Norm}_{x}\\Bigl[\\phi^3,(\\exp[\\phi])^2\\Bigr] = \\text{Norm}_{x}\\Bigl[0, 1\\Bigr] \\times \\exp[\\phi]+ \\phi^3\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"So, if we draw a sample $\\epsilon^*$ from $\\mbox{Norm}_{\\epsilon}[0, 1]$, then we can compute a sample $x^*$ as:\n",
|
||||
"So, if we draw a sample $\\epsilon^*$ from $\\text{Norm}_{\\epsilon}[0, 1]$, then we can compute a sample $x^*$ as:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray*}\n",
|
||||
"\\begin{align}\n",
|
||||
"x^* &=& \\epsilon^* \\times \\sigma + \\mu \\\\\n",
|
||||
"&=& \\epsilon^* \\times \\exp[\\phi]+ \\phi^3\n",
|
||||
"\\end{eqnarray*}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "zTCykVeWqj_O"
|
||||
}
|
||||
"\\end{align}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "w13HVpi9q8nF"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_df_dx_star(x_star):\n",
|
||||
" # TODO Compute this derivative (function defined at the top)\n",
|
||||
@@ -222,15 +211,15 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return df_dphi"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "w13HVpi9q8nF"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ntQT4An79kAl"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the seed so the random numbers are all the same\n",
|
||||
"np.random.seed(0)\n",
|
||||
@@ -241,15 +230,15 @@
|
||||
"\n",
|
||||
"deriv = compute_derivative_of_expectation(phi1, n_samples)\n",
|
||||
"print(\"Your value: \", deriv, \", True value: 5.726338035051403\")"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ntQT4An79kAl"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "t0Jqd_IN_lMU"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"phi_vals = np.arange(-1.5,1.5, 0.05)\n",
|
||||
"deriv_vals = np.zeros_like(phi_vals)\n",
|
||||
@@ -259,40 +248,38 @@
|
||||
"\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()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t0Jqd_IN_lMU"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"This should look plausibly like the derivative of the function we plotted above!"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ASu4yKSwAEYI"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"This should look plausibly like the derivative of the function we plotted above!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "xoFR1wifc8-b"
|
||||
},
|
||||
"source": [
|
||||
"The reparameterization trick computes the derivative of an expectation of a function $\\mbox{f}[x]$:\n",
|
||||
"The reparameterization trick computes the derivative of an expectation of a function $\\text{f}[x]$:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\bigl[\\mbox{f}[x]\\bigr],\n",
|
||||
"\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\bigl[\\text{f}[x]\\bigr],\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"with respect to the parameters $\\boldsymbol\\phi$ of the distribution $Pr(x|\\boldsymbol\\phi)$ that the expectation is over. This derivative can also be computed as:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\bigl[\\mbox{f}[x]\\bigr] &=& \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\left[\\mbox{f}[x]\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\log\\bigl[ Pr(x|\\boldsymbol\\phi)\\bigr]\\right]\\nonumber \\\\\n",
|
||||
"&\\approx & \\frac{1}{I}\\sum_{i=1}^{I}\\mbox{f}[x_i]\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\log\\bigl[ Pr(x_i|\\boldsymbol\\phi)\\bigr].\n",
|
||||
"\\end{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\bigl[\\text{f}[x]\\bigr] &=& \\mathbb{E}_{Pr(x|\\boldsymbol\\phi)}\\left[\\text{f}[x]\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\log\\bigl[ Pr(x|\\boldsymbol\\phi)\\bigr]\\right]\\nonumber \\\\\n",
|
||||
"&\\approx & \\frac{1}{I}\\sum_{i=1}^{I}\\text{f}[x_i]\\frac{\\partial}{\\partial \\boldsymbol\\phi} \\log\\bigl[ Pr(x_i|\\boldsymbol\\phi)\\bigr].\n",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"This method is known as the REINFORCE algorithm or score function estimator. Problem 17.5 asks you to prove this relation. Let's use this method to compute the gradient and compare.\n",
|
||||
"\n",
|
||||
@@ -301,13 +288,15 @@
|
||||
"\\begin{equation}\n",
|
||||
" Pr(x|\\mu,\\sigma^2) = \\frac{1}{\\sqrt{2\\pi\\sigma^{2}}}\\exp\\left[-\\frac{(x-\\mu)^{2}}{2\\sigma^{2}}\\right].\n",
|
||||
"\\end{equation}\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "xoFR1wifc8-b"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4TUaxiWvASla"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def d_log_pr_x_given_phi(x,phi):\n",
|
||||
" # TODO -- fill in this function\n",
|
||||
@@ -333,15 +322,15 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return deriv"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4TUaxiWvASla"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "0RSN32Rna_C_"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the seed so the random numbers are all the same\n",
|
||||
"np.random.seed(0)\n",
|
||||
@@ -352,15 +341,15 @@
|
||||
"\n",
|
||||
"deriv = compute_derivative_of_expectation_score_function(phi1, n_samples)\n",
|
||||
"print(\"Your value: \", deriv, \", True value: 5.724609927313369\")"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "0RSN32Rna_C_"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "EM_i5zoyElHR"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"phi_vals = np.arange(-1.5,1.5, 0.05)\n",
|
||||
"deriv_vals = np.zeros_like(phi_vals)\n",
|
||||
@@ -370,27 +359,27 @@
|
||||
"\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()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "EM_i5zoyElHR"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"This should look the same as the derivative that we computed with the reparameterization trick. So, is there any advantage to one way or the other? Let's compare the variances of the estimates\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "1TWBiUC7bQSw"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"This should look the same as the derivative that we computed with the reparameterization trick. So, is there any advantage to one way or the other? Let's compare the variances of the estimates\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "vV_Jx5bCbQGs"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"n_estimate = 100\n",
|
||||
"n_sample = 1000\n",
|
||||
@@ -403,21 +392,31 @@
|
||||
"\n",
|
||||
"print(\"Variance of reparameterization estimator\", np.var(reparam_estimates))\n",
|
||||
"print(\"Variance of score function estimator\", np.var(score_function_estimates))"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "vV_Jx5bCbQGs"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"The variance of the reparameterization estimator should be quite a bit lower than the score function estimator which is why it is preferred in this situation."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "d-0tntSYdKPR"
|
||||
}
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"The variance of the reparameterization estimator should be quite a bit lower than the score function estimator which is why it is preferred in this situation."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyNecz9/CDOggPSmy1LjT/Dv",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/Chap17/17_3_Importance_Sampling.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 17.3: Importance sampling**\n",
|
||||
"\n",
|
||||
@@ -36,25 +25,26 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "f7a6xqKjkmvT"
|
||||
},
|
||||
"source": [
|
||||
"Let's approximate the expectation\n",
|
||||
"\n",
|
||||
@@ -65,21 +55,23 @@
|
||||
"where\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"Pr(y)=\\mbox{Norm}_y[0,1]\n",
|
||||
"Pr(y)=\\text{Norm}_y[0,1]\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"by drawing $I$ samples $y_i$ and using the formula:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\mathbb{E}_{y}\\Bigl[\\exp\\bigl[- (y-1)^4\\bigr]\\Bigr] \\approx \\frac{1}{I} \\sum_{i=1}^I \\exp\\bigl[-(y-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}"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "f7a6xqKjkmvT"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "VjkzRr8o2ksg"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def f(y):\n",
|
||||
" return np.exp(-(y-1) *(y-1) *(y-1) * (y-1))\n",
|
||||
@@ -95,15 +87,15 @@
|
||||
"ax.set_xlabel(\"$y$\")\n",
|
||||
"ax.legend()\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "VjkzRr8o2ksg"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "LGAKHjUJnWmy"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_expectation(n_samples):\n",
|
||||
" # TODO -- compute this expectation\n",
|
||||
@@ -114,15 +106,15 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return expectation"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "LGAKHjUJnWmy"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "nmvixMqgodIP"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the seed so the random numbers are all the same\n",
|
||||
"np.random.seed(0)\n",
|
||||
@@ -131,26 +123,27 @@
|
||||
"n_samples = 100000000\n",
|
||||
"expected_f= compute_expectation(n_samples)\n",
|
||||
"print(\"Your value: \", expected_f, \", True value: 0.43160702267383166\")"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "nmvixMqgodIP"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Jr4UPcqmnXCS"
|
||||
},
|
||||
"source": [
|
||||
"Let's investigate how the variance of this approximation decreases as we increase the number of samples $N$.\n",
|
||||
"\n",
|
||||
"\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Jr4UPcqmnXCS"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "yrDp1ILUo08j"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_mean_variance(n_sample):\n",
|
||||
" n_estimate = 10000\n",
|
||||
@@ -158,15 +151,15 @@
|
||||
" for i in range(n_estimate):\n",
|
||||
" estimates[i] = compute_expectation(n_sample.astype(int))\n",
|
||||
" return np.mean(estimates), np.var(estimates)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "yrDp1ILUo08j"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "BcUVsodtqdey"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Compute the mean and variance for 1,2,... 20 samples\n",
|
||||
"n_sample_all = np.array([1.,2,3,4,5,6,7,8,9,10,15,20,25,30,45,50,60,70,80,90,100,150,200,250,300,350,400,450,500])\n",
|
||||
@@ -175,15 +168,15 @@
|
||||
"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])"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "BcUVsodtqdey"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "feXmyk0krpUi"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"fig,ax = plt.subplots()\n",
|
||||
"ax.semilogx(n_sample_all, mean_all,'r-',label='mean estimate')\n",
|
||||
@@ -193,24 +186,24 @@
|
||||
"ax.plot([0,500],[0.43160702267383166,0.43160702267383166],'k--',label='true value')\n",
|
||||
"ax.legend()\n",
|
||||
"plt.show()\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "feXmyk0krpUi"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"As you might expect, the more samples that we use to compute the approximate estimate, the lower the variance of the estimate."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "XTUpxFlSuOl7"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"As you might expect, the more samples that we use to compute the approximate estimate, the lower the variance of the estimate."
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "6hxsl3Pxo1TT"
|
||||
},
|
||||
"source": [
|
||||
" Now consider the function\n",
|
||||
" \\begin{equation}\n",
|
||||
@@ -218,13 +211,15 @@
|
||||
" \\end{equation}\n",
|
||||
"\n",
|
||||
"which decreases rapidly as we move away from the position $y=3$."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "6hxsl3Pxo1TT"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "znydVPW7sL4P"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def f2(y):\n",
|
||||
" return 20.446*np.exp(- (y-3) *(y-3) *(y-3) * (y-3))\n",
|
||||
@@ -236,46 +231,47 @@
|
||||
"ax.set_xlabel(\"$y$\")\n",
|
||||
"ax.legend()\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "znydVPW7sL4P"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "G9Xxo0OJsIqD"
|
||||
},
|
||||
"source": [
|
||||
"Let's again, compute the expectation:\n",
|
||||
"\n",
|
||||
"\\begin{eqnarray}\n",
|
||||
"\\mathbb{E}_{y}\\left[\\mbox{f}[y]\\right] &=& \\int \\mbox{f}[y] Pr(y) dy\\\\\n",
|
||||
"&\\approx& \\frac{1}{I} \\mbox{f}[y]\n",
|
||||
"\\end{eqnarray}\n",
|
||||
"\\begin{align}\n",
|
||||
"\\mathbb{E}_{y}\\left[\\text{f}[y]\\right] &=& \\int \\text{f}[y] Pr(y) dy\\\\\n",
|
||||
"&\\approx& \\frac{1}{I} \\text{f}[y]\n",
|
||||
"\\end{align}\n",
|
||||
"\n",
|
||||
"where $Pr(y)=\\mbox{Norm}_y[0,1]$ by approximating with samples $y_{i}$.\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "G9Xxo0OJsIqD"
|
||||
}
|
||||
"where $Pr(y)=\\text{Norm}_y[0,1]$ by approximating with samples $y_{i}$.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "l8ZtmkA2vH4y"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_expectation2(n_samples):\n",
|
||||
" y = np.random.normal(size=(n_samples,1))\n",
|
||||
" expectation = np.mean(f2(y))\n",
|
||||
"\n",
|
||||
" return expectation"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "l8ZtmkA2vH4y"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "dfUQyJ-svZ6F"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the seed so the random numbers are all the same\n",
|
||||
"np.random.seed(0)\n",
|
||||
@@ -284,26 +280,27 @@
|
||||
"n_samples = 100000000\n",
|
||||
"expected_f2= compute_expectation2(n_samples)\n",
|
||||
"print(\"Expected value: \", expected_f2)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "dfUQyJ-svZ6F"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "2sVDqP0BvxqM"
|
||||
},
|
||||
"source": [
|
||||
"I deliberately chose this function, because it's expectation is roughly the same as for the previous function.\n",
|
||||
"\n",
|
||||
"Again, let's look at the mean and the variance of the estimates"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "2sVDqP0BvxqM"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "mHnILRkOv0Ir"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_mean_variance2(n_sample):\n",
|
||||
" n_estimate = 10000\n",
|
||||
@@ -318,15 +315,15 @@
|
||||
"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])"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "mHnILRkOv0Ir"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "FkCX-hxxAnsw"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"fig,ax1 = plt.subplots()\n",
|
||||
"ax1.semilogx(n_sample_all, mean_all,'r-',label='mean estimate')\n",
|
||||
@@ -348,39 +345,41 @@
|
||||
"ax2.set_title(\"Second function\")\n",
|
||||
"ax2.legend()\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "FkCX-hxxAnsw"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "EtBP6NeLwZqz"
|
||||
},
|
||||
"source": [
|
||||
"You can see that the variance of the estimate of the second function is considerably worse than the estimate of the variance of estimate of the first function\n",
|
||||
"\n",
|
||||
"TODO: Think about why this is."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "EtBP6NeLwZqz"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "_wuF-NoQu1--"
|
||||
},
|
||||
"source": [
|
||||
" Now let's repeat this experiment with the second function, but this time use importance sampling with auxiliary distribution:\n",
|
||||
"\n",
|
||||
" \\begin{equation}\n",
|
||||
" q(y)=\\mbox{Norm}_{y}[3,1]\n",
|
||||
" q(y)=\\text{Norm}_{y}[3,1]\n",
|
||||
" \\end{equation}\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "_wuF-NoQu1--"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "jPm0AVYVIDnn"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def q_y(y):\n",
|
||||
" return (1/np.sqrt(2*np.pi)) * np.exp(-0.5 * (y-3) * (y-3))\n",
|
||||
@@ -388,22 +387,22 @@
|
||||
"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",
|
||||
" expectation = 0\n",
|
||||
"\n",
|
||||
" return expectation"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "jPm0AVYVIDnn"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "No2ByVvOM2yQ"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the seed so the random numbers are all the same\n",
|
||||
"np.random.seed(0)\n",
|
||||
@@ -412,15 +411,15 @@
|
||||
"n_samples = 100000000\n",
|
||||
"expected_f2= compute_expectation2b(n_samples)\n",
|
||||
"print(\"Your value: \", expected_f2,\", True value: 0.43163734204459125 \")"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "No2ByVvOM2yQ"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "6v8Jc7z4M3Mk"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_mean_variance2b(n_sample):\n",
|
||||
" n_estimate = 10000\n",
|
||||
@@ -435,15 +434,15 @@
|
||||
"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])"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "6v8Jc7z4M3Mk"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "C0beD4sNNM3L"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"fig,ax1 = plt.subplots()\n",
|
||||
"ax1.semilogx(n_sample_all, mean_all,'r-',label='mean estimate')\n",
|
||||
@@ -476,21 +475,33 @@
|
||||
"ax2.set_title(\"Second function with importance sampling\")\n",
|
||||
"ax2.legend()\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "C0beD4sNNM3L"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"You can see that the importance sampling technique has reduced the amount of variance for any given number of samples."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "y8rgge9MNiOc"
|
||||
}
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"You can see that the importance sampling technique has reduced the amount of variance for any given number of samples."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyNecz9/CDOggPSmy1LjT/Dv",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyM4DdZDGoP1xGst+Nn+rwvt",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/Chap18/18_2_1D_Diffusion_Model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 18.2: 1D Diffusion Model**\n",
|
||||
"\n",
|
||||
@@ -36,13 +25,15 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
@@ -50,15 +41,15 @@
|
||||
"from operator import itemgetter\n",
|
||||
"from scipy import stats\n",
|
||||
"from IPython.display import display, clear_output"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4PM8bf6lO0VE"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#Create pretty colormap as in book\n",
|
||||
"my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
|
||||
@@ -68,28 +59,28 @@
|
||||
"b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
|
||||
"my_colormap_vals = np.vstack((r,g,b)).transpose()/255.0\n",
|
||||
"my_colormap = ListedColormap(my_colormap_vals)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4PM8bf6lO0VE"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ONGRaQscfIOo"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Probability distribution for normal\n",
|
||||
"def norm_pdf(x, mu, sigma):\n",
|
||||
" return np.exp(-0.5 * (x-mu) * (x-mu) / (sigma * sigma)) / np.sqrt(2*np.pi*sigma*sigma)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ONGRaQscfIOo"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "gZvG0MKhfY8Y"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# True distribution is a mixture of four Gaussians\n",
|
||||
"class TrueDataDistribution:\n",
|
||||
@@ -110,15 +101,15 @@
|
||||
" mu_list = list(itemgetter(*hidden)(self.mu))\n",
|
||||
" sigma_list = list(itemgetter(*hidden)(self.sigma))\n",
|
||||
" return mu_list + sigma_list * epsilon"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "gZvG0MKhfY8Y"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "iJu_uBiaeUVv"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define ground truth probability distribution that we will model\n",
|
||||
"true_dist = TrueDataDistribution()\n",
|
||||
@@ -133,25 +124,26 @@
|
||||
"ax.set_ylim(0,1.0)\n",
|
||||
"ax.set_xlim(-3,3)\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "iJu_uBiaeUVv"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "DRHUG_41i4t_"
|
||||
},
|
||||
"source": [
|
||||
"To train the model to describe this distribution, we'll need to generate pairs of samples drawn from $Pr(z_t|x)$ (diffusion kernel) and $q(z_{t-1}|z_{t},x)$ (equation 18.15).\n",
|
||||
"\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "DRHUG_41i4t_"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "x6B8t72Ukscd"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# The diffusion kernel returns the parameters of Pr(z_{t}|x)\n",
|
||||
"def diffusion_kernel(x, t, beta):\n",
|
||||
@@ -180,24 +172,25 @@
|
||||
" z_tminus1 = np.random.normal(size=x_train.shape) * cd_std + cd_mean\n",
|
||||
"\n",
|
||||
" return z_t, z_tminus1"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "x6B8t72Ukscd"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"We also need models $\\mbox{f}_t[z_{t},\\phi_{t}]$ that map from $z_{t}$ to the mean of the distribution at time $z_{t-1}$. We're just going to use a very hacky non-parametric model (basically a lookup table) that tells you the result based on the (quantized) input."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "aSG_4uA8_zZ-"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"We also need models $\\text{f}_t[z_{t},\\phi_{t}]$ that map from $z_{t}$ to the mean of the distribution at time $z_{t-1}$. We're just going to use a very hacky non-parametric model (basically a lookup table) that tells you the result based on the (quantized) input."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ZHViC0pL_yy5"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# This code is really ugly! Don't look too closely at it!\n",
|
||||
"# All you need to know is that it is a model that trains from pairs zt, zt_minus1\n",
|
||||
@@ -223,15 +216,15 @@
|
||||
" bin_index = np.floor((zt+self.max_val)/self.inc)\n",
|
||||
" bin_index = np.clip(bin_index,0, len(self.model)-1).astype('uint32')\n",
|
||||
" return zt + self.model[bin_index]"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ZHViC0pL_yy5"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "CzVFybWoBygu"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Sample data from distribution (this would usually be our collected training set)\n",
|
||||
"n_sample = 100000\n",
|
||||
@@ -249,24 +242,25 @@
|
||||
" all_models.append(NonParametricModel())\n",
|
||||
" # The model at index t maps data from z_{t+1} to z_{t}\n",
|
||||
" all_models[t].train(zt,zt_minus1)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "CzVFybWoBygu"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now that we've learned the model, let's draw some samples from it. We start at $z_{100}$ and use the model to predict $z_{99}$, then $z_{98}$ and so on until finally we get to $z_{1}$ and then $x$ (represented as $z_{0}$ here). We'll store all of the intermediate stages as well, so we can plot the trajectories. See equations 18.16."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ZPc9SEvtl14U"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now that we've learned the model, let's draw some samples from it. We start at $z_{100}$ and use the model to predict $z_{99}$, then $z_{98}$ and so on until finally we get to $z_{1}$ and then $x$ (represented as $z_{0}$ here). We'll store all of the intermediate stages as well, so we can plot the trajectories. See equations 18.16."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "A-ZMFOvACIOw"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def sample(model, T, sigma_t, n_samples):\n",
|
||||
" # Create the output array\n",
|
||||
@@ -295,24 +289,25 @@
|
||||
" samples[t-1,:] = samples[t-1,:]\n",
|
||||
"\n",
|
||||
" return samples"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "A-ZMFOvACIOw"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's run the diffusion process for a whole bunch of samples"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ECAUfHNi9NVW"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's run the diffusion process for a whole bunch of samples"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "M-TY5w9Q8LYW"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"sigma_t=0.12288\n",
|
||||
"n_samples = 100000\n",
|
||||
@@ -329,24 +324,25 @@
|
||||
"plt.hist(sampled_data, bins=bins, density =True)\n",
|
||||
"ax.set_ylim(0, 0.8)\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "M-TY5w9Q8LYW"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's, plot the evolution of a few of the paths as in figure 18.7 (paths are from bottom to top now)."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "jYrAW6tN-gJ4"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's, plot the evolution of a few of the paths as in figure 18.7 (paths are from bottom to top now)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4XU6CDZC_kFo"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"fig, ax = plt.subplots()\n",
|
||||
"t_vals = np.arange(0,101,1)\n",
|
||||
@@ -360,21 +356,33 @@
|
||||
"ax.set_xlabel('value')\n",
|
||||
"ax.set_ylabel('z_{t}')\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4XU6CDZC_kFo"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Notice that the samples have a tendency to move from positions that are near the center at time 100 to positions that are high in the true probability distribution at time 0"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "SGTYGGevAktz"
|
||||
}
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Notice that the samples have a tendency to move from positions that are near the center at time 100 to positions that are high in the true probability distribution at time 0"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyM4DdZDGoP1xGst+Nn+rwvt",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyNd+D0/IVWXtU2GKsofyk2d",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/Chap18/18_3_Reparameterized_Model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 18.3: 1D Reparameterized model**\n",
|
||||
"\n",
|
||||
@@ -36,13 +25,15 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
@@ -50,15 +41,15 @@
|
||||
"from operator import itemgetter\n",
|
||||
"from scipy import stats\n",
|
||||
"from IPython.display import display, clear_output"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4PM8bf6lO0VE"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#Create pretty colormap as in book\n",
|
||||
"my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
|
||||
@@ -68,28 +59,28 @@
|
||||
"b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
|
||||
"my_colormap_vals = np.vstack((r,g,b)).transpose()/255.0\n",
|
||||
"my_colormap = ListedColormap(my_colormap_vals)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4PM8bf6lO0VE"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ONGRaQscfIOo"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Probability distribution for normal\n",
|
||||
"def norm_pdf(x, mu, sigma):\n",
|
||||
" return np.exp(-0.5 * (x-mu) * (x-mu) / (sigma * sigma)) / np.sqrt(2*np.pi*sigma*sigma)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ONGRaQscfIOo"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "gZvG0MKhfY8Y"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# True distribution is a mixture of four Gaussians\n",
|
||||
"class TrueDataDistribution:\n",
|
||||
@@ -110,15 +101,15 @@
|
||||
" mu_list = list(itemgetter(*hidden)(self.mu))\n",
|
||||
" sigma_list = list(itemgetter(*hidden)(self.sigma))\n",
|
||||
" return mu_list + sigma_list * epsilon"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "gZvG0MKhfY8Y"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "iJu_uBiaeUVv"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define ground truth probability distribution that we will model\n",
|
||||
"true_dist = TrueDataDistribution()\n",
|
||||
@@ -133,25 +124,26 @@
|
||||
"ax.set_ylim(0,1.0)\n",
|
||||
"ax.set_xlim(-3,3)\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "iJu_uBiaeUVv"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "DRHUG_41i4t_"
|
||||
},
|
||||
"source": [
|
||||
"To train the model to describe this distribution, we'll need to generate pairs of samples drawn from $Pr(z_t|x)$ (diffusion kernel) and $q(z_{t-1}|z_{t},x)$ (equation 18.15).\n",
|
||||
"\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "DRHUG_41i4t_"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "x6B8t72Ukscd"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Return z_t (the argument of g_{t}[] in the loss function in algorithm 18.1) and epsilon\n",
|
||||
"def get_data_pairs(x_train,t,beta):\n",
|
||||
@@ -161,24 +153,25 @@
|
||||
" z_t = np.ones_like(x_train)\n",
|
||||
"\n",
|
||||
" return z_t, epsilon"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "x6B8t72Ukscd"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"We also need models $\\mbox{g}_t[z_{t},\\phi_{t}]$ that map from $z_{t}$ to the noise $\\epsilon$ that was added. We're just going to use a very hacky non-parametric model (basically a lookup table) that tells you the result based on the (quantized) input."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "aSG_4uA8_zZ-"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"We also need models $\\text{g}_t[z_{t},\\phi_{t}]$ that map from $z_{t}$ to the noise $\\epsilon$ that was added. We're just going to use a very hacky non-parametric model (basically a lookup table) that tells you the result based on the (quantized) input."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ZHViC0pL_yy5"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# This code is really ugly! Don't look too closely at it!\n",
|
||||
"# All you need to know is that it is a model that trains from pairs zt, zt_minus1\n",
|
||||
@@ -204,15 +197,15 @@
|
||||
" bin_index = np.floor((zt+self.max_val)/self.inc)\n",
|
||||
" bin_index = np.clip(bin_index,0, len(self.model)-1).astype('uint32')\n",
|
||||
" return self.model[bin_index]"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ZHViC0pL_yy5"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "CzVFybWoBygu"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Sample data from distribution (this would usually be our collected training set)\n",
|
||||
"n_sample = 100000\n",
|
||||
@@ -230,24 +223,25 @@
|
||||
" all_models.append(NonParametricModel())\n",
|
||||
" # The model at index t maps data from z_{t+1} to epsilon\n",
|
||||
" all_models[t].train(zt,epsilon)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "CzVFybWoBygu"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now that we've learned the model, let's draw some samples from it. We start at $z_{100}$ and use the model to predict $z_{99}$, then $z_{98}$ and so on until finally we get to $z_{1}$ and then $x$ (represented as $z_{0}$ here). We'll store all of the intermediate stages as well, so we can plot the trajectories. See algorithm 18.2"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ZPc9SEvtl14U"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now that we've learned the model, let's draw some samples from it. We start at $z_{100}$ and use the model to predict $z_{99}$, then $z_{98}$ and so on until finally we get to $z_{1}$ and then $x$ (represented as $z_{0}$ here). We'll store all of the intermediate stages as well, so we can plot the trajectories. See algorithm 18.2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "A-ZMFOvACIOw"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def sample(model, T, sigma_t, n_samples):\n",
|
||||
" # Create the output array\n",
|
||||
@@ -277,24 +271,25 @@
|
||||
" samples[t-1,:] = samples[t-1,:]\n",
|
||||
"\n",
|
||||
" return samples"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "A-ZMFOvACIOw"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's run the diffusion process for a whole bunch of samples"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ECAUfHNi9NVW"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's run the diffusion process for a whole bunch of samples"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "M-TY5w9Q8LYW"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"sigma_t=0.12288\n",
|
||||
"n_samples = 100000\n",
|
||||
@@ -311,24 +306,25 @@
|
||||
"plt.hist(sampled_data, bins=bins, density =True)\n",
|
||||
"ax.set_ylim(0, 0.8)\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "M-TY5w9Q8LYW"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's, plot the evolution of a few of the paths as in figure 18.7 (paths are from bottom to top now)."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "jYrAW6tN-gJ4"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's, plot the evolution of a few of the paths as in figure 18.7 (paths are from bottom to top now)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4XU6CDZC_kFo"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"fig, ax = plt.subplots()\n",
|
||||
"t_vals = np.arange(0,101,1)\n",
|
||||
@@ -342,21 +338,33 @@
|
||||
"ax.set_xlabel('value')\n",
|
||||
"ax.set_ylabel('z_{t}')\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4XU6CDZC_kFo"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Notice that the samples have a tendency to move from positions that are near the center at time 100 to positions that are high in the true probability distribution at time 0"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "SGTYGGevAktz"
|
||||
}
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Notice that the samples have a tendency to move from positions that are near the center at time 100 to positions that are high in the true probability distribution at time 0"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyNd+D0/IVWXtU2GKsofyk2d",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyNFSvISBXo/Z1l+onknF2Gw",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/Chap18/18_4_Families_of_Diffusion_Models.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 18.4: Families of diffusion models**\n",
|
||||
"\n",
|
||||
@@ -36,13 +25,15 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
@@ -50,15 +41,15 @@
|
||||
"from operator import itemgetter\n",
|
||||
"from scipy import stats\n",
|
||||
"from IPython.display import display, clear_output"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "OLComQyvCIJ7"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4PM8bf6lO0VE"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"#Create pretty colormap as in book\n",
|
||||
"my_colormap_vals_hex =('2a0902', '2b0a03', '2c0b04', '2d0c05', '2e0c06', '2f0d07', '300d08', '310e09', '320f0a', '330f0b', '34100b', '35110c', '36110d', '37120e', '38120f', '39130f', '3a1410', '3b1411', '3c1511', '3d1612', '3e1613', '3f1713', '401714', '411814', '421915', '431915', '451a16', '461b16', '471b17', '481c17', '491d18', '4a1d18', '4b1e19', '4c1f19', '4d1f1a', '4e201b', '50211b', '51211c', '52221c', '53231d', '54231d', '55241e', '56251e', '57261f', '58261f', '592720', '5b2821', '5c2821', '5d2922', '5e2a22', '5f2b23', '602b23', '612c24', '622d25', '632e25', '652e26', '662f26', '673027', '683027', '693128', '6a3229', '6b3329', '6c342a', '6d342a', '6f352b', '70362c', '71372c', '72372d', '73382e', '74392e', '753a2f', '763a2f', '773b30', '783c31', '7a3d31', '7b3e32', '7c3e33', '7d3f33', '7e4034', '7f4134', '804235', '814236', '824336', '834437', '854538', '864638', '874739', '88473a', '89483a', '8a493b', '8b4a3c', '8c4b3c', '8d4c3d', '8e4c3e', '8f4d3f', '904e3f', '924f40', '935041', '945141', '955242', '965343', '975343', '985444', '995545', '9a5646', '9b5746', '9c5847', '9d5948', '9e5a49', '9f5a49', 'a05b4a', 'a15c4b', 'a35d4b', 'a45e4c', 'a55f4d', 'a6604e', 'a7614e', 'a8624f', 'a96350', 'aa6451', 'ab6552', 'ac6552', 'ad6653', 'ae6754', 'af6855', 'b06955', 'b16a56', 'b26b57', 'b36c58', 'b46d59', 'b56e59', 'b66f5a', 'b7705b', 'b8715c', 'b9725d', 'ba735d', 'bb745e', 'bc755f', 'bd7660', 'be7761', 'bf7862', 'c07962', 'c17a63', 'c27b64', 'c27c65', 'c37d66', 'c47e67', 'c57f68', 'c68068', 'c78169', 'c8826a', 'c9836b', 'ca846c', 'cb856d', 'cc866e', 'cd876f', 'ce886f', 'ce8970', 'cf8a71', 'd08b72', 'd18c73', 'd28d74', 'd38e75', 'd48f76', 'd59077', 'd59178', 'd69279', 'd7937a', 'd8957b', 'd9967b', 'da977c', 'da987d', 'db997e', 'dc9a7f', 'dd9b80', 'de9c81', 'de9d82', 'df9e83', 'e09f84', 'e1a185', 'e2a286', 'e2a387', 'e3a488', 'e4a589', 'e5a68a', 'e5a78b', 'e6a88c', 'e7aa8d', 'e7ab8e', 'e8ac8f', 'e9ad90', 'eaae91', 'eaaf92', 'ebb093', 'ecb295', 'ecb396', 'edb497', 'eeb598', 'eeb699', 'efb79a', 'efb99b', 'f0ba9c', 'f1bb9d', 'f1bc9e', 'f2bd9f', 'f2bfa1', 'f3c0a2', 'f3c1a3', 'f4c2a4', 'f5c3a5', 'f5c5a6', 'f6c6a7', 'f6c7a8', 'f7c8aa', 'f7c9ab', 'f8cbac', 'f8ccad', 'f8cdae', 'f9ceb0', 'f9d0b1', 'fad1b2', 'fad2b3', 'fbd3b4', 'fbd5b6', 'fbd6b7', 'fcd7b8', 'fcd8b9', 'fcdaba', 'fddbbc', 'fddcbd', 'fddebe', 'fddfbf', 'fee0c1', 'fee1c2', 'fee3c3', 'fee4c5', 'ffe5c6', 'ffe7c7', 'ffe8c9', 'ffe9ca', 'ffebcb', 'ffeccd', 'ffedce', 'ffefcf', 'fff0d1', 'fff2d2', 'fff3d3', 'fff4d5', 'fff6d6', 'fff7d8', 'fff8d9', 'fffada', 'fffbdc', 'fffcdd', 'fffedf', 'ffffe0')\n",
|
||||
@@ -68,28 +59,28 @@
|
||||
"b = np.floor(my_colormap_vals_dec - r * 256 *256 - g * 256)\n",
|
||||
"my_colormap_vals = np.vstack((r,g,b)).transpose()/255.0\n",
|
||||
"my_colormap = ListedColormap(my_colormap_vals)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4PM8bf6lO0VE"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ONGRaQscfIOo"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Probability distribution for normal\n",
|
||||
"def norm_pdf(x, mu, sigma):\n",
|
||||
" return np.exp(-0.5 * (x-mu) * (x-mu) / (sigma * sigma)) / np.sqrt(2*np.pi*sigma*sigma)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ONGRaQscfIOo"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "gZvG0MKhfY8Y"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# True distribution is a mixture of four Gaussians\n",
|
||||
"class TrueDataDistribution:\n",
|
||||
@@ -110,15 +101,15 @@
|
||||
" mu_list = list(itemgetter(*hidden)(self.mu))\n",
|
||||
" sigma_list = list(itemgetter(*hidden)(self.sigma))\n",
|
||||
" return mu_list + sigma_list * epsilon"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "gZvG0MKhfY8Y"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "iJu_uBiaeUVv"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define ground truth probability distribution that we will model\n",
|
||||
"true_dist = TrueDataDistribution()\n",
|
||||
@@ -133,25 +124,26 @@
|
||||
"ax.set_ylim(0,1.0)\n",
|
||||
"ax.set_xlim(-3,3)\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "iJu_uBiaeUVv"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "DRHUG_41i4t_"
|
||||
},
|
||||
"source": [
|
||||
"To train the model to describe this distribution, we'll need to generate pairs of samples drawn from $Pr(z_t|x)$ (diffusion kernel) and $q(z_{t-1}|z_{t},x)$ (equation 18.15).\n",
|
||||
"\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "DRHUG_41i4t_"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "x6B8t72Ukscd"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Return z_t (the argument of g_{t}[] in the loss function in algorithm 18.1) and epsilon\n",
|
||||
"def get_data_pairs(x_train,t,beta):\n",
|
||||
@@ -161,24 +153,25 @@
|
||||
" z_t = x_train * np.sqrt(alpha_t) + np.sqrt(1-alpha_t) * epsilon\n",
|
||||
"\n",
|
||||
" return z_t, epsilon"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "x6B8t72Ukscd"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"We also need models $\\mbox{g}_t[z_{t},\\phi_{t}]$ that map from $z_{t}$ to the noise $\\epsilon$ that was added. We're just going to use a very hacky non-parametric model (basically a lookup table) that tells you the result based on the (quantized) input."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "aSG_4uA8_zZ-"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"We also need models $\\text{g}_t[z_{t},\\phi_{t}]$ that map from $z_{t}$ to the noise $\\epsilon$ that was added. We're just going to use a very hacky non-parametric model (basically a lookup table) that tells you the result based on the (quantized) input."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "ZHViC0pL_yy5"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# This code is really ugly! Don't look too closely at it!\n",
|
||||
"# All you need to know is that it is a model that trains from pairs zt, zt_minus1\n",
|
||||
@@ -204,15 +197,15 @@
|
||||
" bin_index = np.floor((zt+self.max_val)/self.inc)\n",
|
||||
" bin_index = np.clip(bin_index,0, len(self.model)-1).astype('uint32')\n",
|
||||
" return self.model[bin_index]"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ZHViC0pL_yy5"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "CzVFybWoBygu"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Sample data from distribution (this would usually be our collected training set)\n",
|
||||
"n_sample = 100000\n",
|
||||
@@ -230,15 +223,14 @@
|
||||
" all_models.append(NonParametricModel())\n",
|
||||
" # The model at index t maps data from z_{t+1} to epsilon\n",
|
||||
" all_models[t].train(zt,epsilon)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "CzVFybWoBygu"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "ZPc9SEvtl14U"
|
||||
},
|
||||
"source": [
|
||||
"Now that we've learned the model, let's draw some samples from it. We start at $z_{100}$ and use the model to predict $z_{99}$, then $z_{98}$ and so on until finally we get to $z_{1}$ and then $x$ (represented as $z_{0}$ here). We'll store all of the intermediate stages as well, so we can plot the trajectories.\n",
|
||||
"\n",
|
||||
@@ -247,17 +239,19 @@
|
||||
"One such model is the denoising diffusion implicit model, which has a sampling step:\n",
|
||||
"\n",
|
||||
"\\begin{equation}\n",
|
||||
"\\mathbf{z}_{t-1} = \\sqrt{\\alpha_{t-1}}\\left(\\frac{\\mathbf{z}_{t}-\\sqrt{1-\\alpha_{t}}\\mbox{g}_t[\\mathbf{z}_{t},\\boldsymbol\\phi]}{\\sqrt{\\alpha_{t}}}\\right) + \\sqrt{1-\\alpha_{t-1}-\\sigma^2}\\mbox{g}_t[\\mathbf{z}_{t},\\boldsymbol\\phi]+\\sigma\\epsilon\n",
|
||||
"\\mathbf{z}_{t-1} = \\sqrt{\\alpha_{t-1}}\\left(\\frac{\\mathbf{z}_{t}-\\sqrt{1-\\alpha_{t}}\\text{g}_t[\\mathbf{z}_{t},\\boldsymbol\\phi]}{\\sqrt{\\alpha_{t}}}\\right) + \\sqrt{1-\\alpha_{t-1}-\\sigma^2}\\text{g}_t[\\mathbf{z}_{t},\\boldsymbol\\phi]+\\sigma\\epsilon\n",
|
||||
"\\end{equation}\n",
|
||||
"\n",
|
||||
"(see equation 12 of the denoising [diffusion implicit models paper ](https://arxiv.org/pdf/2010.02502.pdf).\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ZPc9SEvtl14U"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "A-ZMFOvACIOw"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def sample_ddim(model, T, sigma_t, n_samples):\n",
|
||||
" # Create the output array\n",
|
||||
@@ -283,24 +277,25 @@
|
||||
" if t>0:\n",
|
||||
" samples[t-1,:] = samples[t-1,:]+ np.random.standard_normal(n_samples) * sigma_t\n",
|
||||
" return samples"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "A-ZMFOvACIOw"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's run the diffusion process for a whole bunch of samples"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ECAUfHNi9NVW"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's run the diffusion process for a whole bunch of samples"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "M-TY5w9Q8LYW"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Now we'll set the noise to a MUCH smaller level\n",
|
||||
"sigma_t=0.001\n",
|
||||
@@ -318,24 +313,25 @@
|
||||
"plt.hist(sampled_data, bins=bins, density =True)\n",
|
||||
"ax.set_ylim(0, 0.8)\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "M-TY5w9Q8LYW"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Let's, plot the evolution of a few of the paths as in figure 18.7 (paths are from bottom to top now)."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "jYrAW6tN-gJ4"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Let's, plot the evolution of a few of the paths as in figure 18.7 (paths are from bottom to top now)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4XU6CDZC_kFo"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"fig, ax = plt.subplots()\n",
|
||||
"t_vals = np.arange(0,101,1)\n",
|
||||
@@ -349,35 +345,37 @@
|
||||
"ax.set_xlabel('value')\n",
|
||||
"ax.set_ylabel('z_{t}')\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4XU6CDZC_kFo"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"The samples have a tendency to move from positions that are near the center at time 100 to positions that are high in the true probability distribution at time 0"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "SGTYGGevAktz"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"The samples have a tendency to move from positions that are near the center at time 100 to positions that are high in the true probability distribution at time 0"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Z-LZp_fMXxRt"
|
||||
},
|
||||
"source": [
|
||||
"Let's now sample from the accelerated model, that requires fewer models. Again, we don't need to learn anything new -- this is just the reverse process that corresponds to a different forward process that is compatible with the same diffusion kernel.\n",
|
||||
"\n",
|
||||
"There's nothing to do here except read the code. It uses the same DDIM model as you just implemented in the previous step, but it jumps timesteps five at a time."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Z-LZp_fMXxRt"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "3Z0erjGbYj1u"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def sample_accelerated(model, T, sigma_t, n_steps, n_samples):\n",
|
||||
" # Create the output array\n",
|
||||
@@ -403,24 +401,25 @@
|
||||
" if t>0:\n",
|
||||
" samples[c_step-1,:] = samples[c_step-1,:]+ np.random.standard_normal(n_samples) * sigma_t\n",
|
||||
" return samples"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "3Z0erjGbYj1u"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's draw a bunch of samples from the model"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "D3Sm_WYrcuED"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's draw a bunch of samples from the model"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "UB45c7VMcGy-"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"sigma_t=0.11\n",
|
||||
"n_samples = 100000\n",
|
||||
@@ -438,15 +437,15 @@
|
||||
"plt.hist(sampled_data, bins=bins, density =True)\n",
|
||||
"ax.set_ylim(0, 0.9)\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "UB45c7VMcGy-"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Luv-6w84c_qO"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"fig, ax = plt.subplots()\n",
|
||||
"step_increment = 100/ n_steps\n",
|
||||
@@ -464,21 +463,32 @@
|
||||
"ax.set_xlabel('value')\n",
|
||||
"ax.set_ylabel('z_{t}')\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Luv-6w84c_qO"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "LSJi72f0kw_e"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
]
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyNFSvISBXo/Z1l+onknF2Gw",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -393,7 +393,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",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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 \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
}
|
||||
"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",
|
||||
"print(\"Action = \", action)\n",
|
||||
"print(\"New state = \", new_state)\n",
|
||||
"print(\"Reward = \", reward)\n",
|
||||
"print(\"Initial state =\",initial_state)\n",
|
||||
"new_state, reward, action, is_terminal = markov_decision_process_step(initial_state, transition_probabilities_given_action, reward_structure, terminal_states)\n",
|
||||
"print(\"Action =\",action)\n",
|
||||
"print(\"New state =\",new_state)\n",
|
||||
"print(\"Reward =\", reward)\n",
|
||||
"\n",
|
||||
"state_action_values_after = q_learning_step(state_action_values, reward, initial_state, new_state, action, 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",
|
||||
"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",
|
||||
" state= np.random.randint(n_state-1)\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)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "djPTKuDk76xO"
|
||||
},
|
||||
"source": [
|
||||
"Finally, lets run this for a **single** episode and visualize the penguin's actions"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "pWObQf2h76xO"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def get_one_episode(n_state, state_action_values, terminal_states, gamma):\n",
|
||||
"\n",
|
||||
" state = np.random.randint(n_state-1)\n",
|
||||
"\n",
|
||||
" # Create lists to store all the states seen and actions taken throughout the single episode\n",
|
||||
" all_states = []\n",
|
||||
" all_actions = []\n",
|
||||
"\n",
|
||||
" # Initalize episode termination flag\n",
|
||||
" done = False\n",
|
||||
" # Initialize counter for steps in the episode\n",
|
||||
" steps = 0\n",
|
||||
"\n",
|
||||
" all_states.append(state)\n",
|
||||
"\n",
|
||||
" while not done:\n",
|
||||
" steps += 1\n",
|
||||
"\n",
|
||||
" new_state, reward, action, is_terminal = markov_decision_process_step(state, transition_probabilities_given_action, reward_structure, terminal_states)\n",
|
||||
" all_states.append(new_state)\n",
|
||||
" all_actions.append(action)\n",
|
||||
"\n",
|
||||
" state_action_values_after = q_learning_step(state_action_values, reward, state, new_state, action, is_terminal, gamma)\n",
|
||||
"\n",
|
||||
" # If in termination state, reset state randomly\n",
|
||||
" if is_terminal:\n",
|
||||
" state = np.random.randint(n_state-1)\n",
|
||||
" print(f'Episode Terminated at {steps} Steps')\n",
|
||||
" # Set episode termination flag\n",
|
||||
" done = True\n",
|
||||
" else:\n",
|
||||
" state = new_state\n",
|
||||
"\n",
|
||||
" # Update the policy\n",
|
||||
" state_action_values = deepcopy(state_action_values_after)\n",
|
||||
" policy = get_policy(state_action_values_after)\n",
|
||||
"\n",
|
||||
" return all_states, all_actions, policy, state_action_values\n",
|
||||
""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "P7cbCGT176xO"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def visualize_one_episode(states, actions):\n",
|
||||
" # Define actions for visualization\n",
|
||||
" acts = ['up', 'right', 'down', 'left']\n",
|
||||
"\n",
|
||||
" # Iterate over the states and actions\n",
|
||||
" for i in range(len(states)):\n",
|
||||
"\n",
|
||||
" if i == 0:\n",
|
||||
" print('Starting State:', states[i])\n",
|
||||
"\n",
|
||||
" elif i == len(states)-1:\n",
|
||||
" print('Episode Done:', states[i])\n",
|
||||
"\n",
|
||||
" else:\n",
|
||||
" print('State', states[i-1])\n",
|
||||
" a = actions[i]\n",
|
||||
" print('Action:', acts[a])\n",
|
||||
" print('Next State:', states[i])\n",
|
||||
"\n",
|
||||
" # Visualize the current state using the MDP drawer\n",
|
||||
" mdp_drawer.draw(layout, state=states[i], rewards=reward_structure, draw_state_index=True)\n",
|
||||
" clear_output(True)\n",
|
||||
"\n",
|
||||
" # Pause for a short duration to allow observation\n",
|
||||
" sleep(1.5)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "cr98F8PT76xP"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize the state-action values to random numbers\n",
|
||||
"np.random.seed(2)\n",
|
||||
"n_state = transition_probabilities_given_action.shape[0]\n",
|
||||
"n_action = transition_probabilities_given_action.shape[2]\n",
|
||||
"state_action_values = np.random.normal(size=(n_action, n_state))\n",
|
||||
"\n",
|
||||
"# Hard code value of termination state of finding fish to 0\n",
|
||||
"terminal_states = [15]\n",
|
||||
"state_action_values[:, terminal_states] = 0\n",
|
||||
"gamma = 0.9\n",
|
||||
"\n",
|
||||
"# Draw the initial setup\n",
|
||||
"print('Initial Policy:')\n",
|
||||
"policy = get_policy(state_action_values)\n",
|
||||
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
|
||||
"mdp_drawer.draw(layout, policy = policy, state_action_values = state_action_values, rewards = reward_structure)\n",
|
||||
"\n",
|
||||
"states, actions, policy, state_action_values = get_one_episode(n_state, state_action_values, terminal_states, gamma)\n",
|
||||
"\n",
|
||||
"print()\n",
|
||||
"print('Final Optimal Policy:')\n",
|
||||
"mdp_drawer = DrawMDP(n_rows, n_cols)\n",
|
||||
"mdp_drawer.draw(layout, policy = policy, state_action_values = state_action_values, rewards = reward_structure)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "5zBu1g3776xP"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"visualize_one_episode(states, actions)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"id": "qQFhwVqPcCFH"
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"include_colab_link": true
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"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
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,33 +1,22 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"provenance": [],
|
||||
"authorship_tag": "ABX9TyNQPfTDV6PFG7Ctcl+XVNlz",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"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/Chap21/21_1_Bias_Mitigation.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
},
|
||||
"source": [
|
||||
"# **Notebook 21.1: Bias mitigation**\n",
|
||||
"\n",
|
||||
@@ -36,39 +25,42 @@
|
||||
"Work through the cells below, running each cell in turn. In various places you will see the words \"TO DO\". Follow the instructions at these places and make predictions about what is going to happen or write code to complete the functions.\n",
|
||||
"\n",
|
||||
"Contact me at udlbookmail@gmail.com if you find any mistakes or have any suggestions.\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "t9vk9Elugvmi"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "yC_LpiJqZXEL"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "2FYo1dWGZXgg"
|
||||
},
|
||||
"source": [
|
||||
"# Worked example: loans\n",
|
||||
"\n",
|
||||
"Consider the example of an algorithm $c=\\mbox{f}[\\mathbf{x},\\boldsymbol\\phi]$ that predicts credit rating scores $c$ for loan decisions. There are two pools of loan applicants identified by the variable $p\\in\\{0,1\\}$ that we’ll describe as the blue and yellow populations. We assume that we are given historical data, so we know both the credit rating and whether the applicant actually defaulted on the loan ($y=0$) or\n",
|
||||
"Consider the example of an algorithm $c=\\text{f}[\\mathbf{x},\\boldsymbol\\phi]$ that predicts credit rating scores $c$ for loan decisions. There are two pools of loan applicants identified by the variable $p\\in\\{0,1\\}$ that we’ll describe as the blue and yellow populations. We assume that we are given historical data, so we know both the credit rating and whether the applicant actually defaulted on the loan ($y=0$) or\n",
|
||||
" repaid it ($y=1$).\n",
|
||||
"\n",
|
||||
"We can now think of four groups of data corresponding to (i) the blue and yellow populations and (ii) whether they did or did not repay the loan. For each of these four groups we have a distribution of credit ratings (figure 1). In an ideal world, the two distributions for the yellow population would be exactly the same as those for the blue population. However, as figure 1 shows, this is clearly not the case here."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "2FYo1dWGZXgg"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "O_0gGH9hZcjo"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Class that can describe interesting curve shapes based on the input parameters\n",
|
||||
"# Details don't matter\n",
|
||||
@@ -86,30 +78,30 @@
|
||||
" * 1.0 / np.sqrt(2*np.pi*self.sigma1*self.sigma1) \\\n",
|
||||
" + self.weight * (1-self.prop) * np.exp(-0.5 * (x-self.mean2) * (x-self.mean2) / (self.sigma2 * self.sigma2)) \\\n",
|
||||
" * 1.0 / np.sqrt(2*np.pi*self.sigma2*self.sigma2)\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "O_0gGH9hZcjo"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Bkp7vffBbrNW"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"credit_scores = np.arange(-4,4,0.01)\n",
|
||||
"freq_y0_p0 = FreqCurve(800, -1.5, -2.5, 0.8, 0.6, 0.6).freq(credit_scores)\n",
|
||||
"freq_y1_p0 = FreqCurve(500, 0.1, 0.7, 1.5, 0.8, 0.4 ).freq(credit_scores)\n",
|
||||
"freq_y0_p1 = FreqCurve(400, 0.2, -0.1, 0.8, 0.6, 0.3).freq(credit_scores)\n",
|
||||
"freq_y1_p1 = FreqCurve(650, 0.6, 1.6, 1.2, 0.7, 0.6 ).freq(credit_scores)\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Bkp7vffBbrNW"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Jf7uqyRyhVdS"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"\n",
|
||||
"fig = plt.figure\n",
|
||||
@@ -136,62 +128,65 @@
|
||||
"ax.legend()\n",
|
||||
"\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Jf7uqyRyhVdS"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"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",
|
||||
"Let’s assume that we can’t 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",
|
||||
" to go on, the best we can do is to assign different thresholds $\\tau_{1}$\n",
|
||||
" and $\\tau_{2}$\n",
|
||||
" for the blue and yellow populations so that the loan is granted if the credit score $c$ generated by the model exceeds $\\tau_0$ for the blue population and $\\tau_1$ for the yellow population."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "CfZ-srQtmff2"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's investiate how to set these thresholds to fulfil different criteria."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "569oU1OtoFz8"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's investiate how to set these thresholds to fulfil different criteria."
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "bE7yPyuWoSUy"
|
||||
},
|
||||
"source": [
|
||||
"# Blindness to protected attribute\n",
|
||||
"\n",
|
||||
"We'll first do the simplest possible thing. We'll choose the same threshold for both blue and yellow populations so that $\\tau_0$ = $\\tau_1$. Basically, we'll ignore what we know about the group membership. Let's see what the ramifications of that."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "bE7yPyuWoSUy"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Set the thresholds\n",
|
||||
"tau0 = tau1 = 0.0"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "WIG8I-LvoFBY"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the thresholds\n",
|
||||
"tau0 = tau1 = 0.0"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "2EvkCvVBiCBn"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def compute_probability_get_loan(credit_scores, frequencies, threshold):\n",
|
||||
" # TODO - Write this function\n",
|
||||
@@ -202,47 +197,49 @@
|
||||
"\n",
|
||||
"\n",
|
||||
" return prob"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "2EvkCvVBiCBn"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"First let's see what the overall probability of getting the loan is for the yellow and blue populations."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "AGT40q6_qfpv"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"First let's see what the overall probability of getting the loan is for the yellow and blue populations."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "4nI-PR_wqWj6"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"pr_get_loan_p0 = compute_probability_get_loan(credit_scores, freq_y0_p0+freq_y1_p0, tau0)\n",
|
||||
"pr_get_loan_p1 = compute_probability_get_loan(credit_scores, freq_y0_p1+freq_y1_p1, tau1)\n",
|
||||
"print(\"Probability blue group gets loan = %3.3f\"%(pr_get_loan_p0))\n",
|
||||
"print(\"Probability yellow group gets loan = %3.3f\"%(pr_get_loan_p1))"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "4nI-PR_wqWj6"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"Now let's plot a receiver operating characteristic (ROC) curve. This shows the rate of true positives $Pr(\\hat{y}=1|y=1)$ (people who got loan and paid it back) and false alarms $Pr(\\hat{y}=1|y=0)$ (people who got the loan but didn't pay it back) for all possible thresholds."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "G2pEa6h6sIyu"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"Now let's plot a receiver operating characteristic (ROC) curve. This shows the rate of true positives $Pr(\\hat{y}=1|y=1)$ (people who got loan and paid it back) and false alarms $Pr(\\hat{y}=1|y=0)$ (people who got the loan but didn't pay it back) for all possible thresholds."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "2C7kNt3hqwiu"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def plot_roc(credit_scores, freq_y0_p0, freq_y1_p0, freq_y0_p1, freq_y1_p1, tau0, tau1):\n",
|
||||
" true_positives_p0 = np.zeros_like(credit_scores)\n",
|
||||
@@ -272,61 +269,64 @@
|
||||
" ax.set_aspect('equal')\n",
|
||||
"\n",
|
||||
" plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "2C7kNt3hqwiu"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"plot_roc(credit_scores, freq_y0_p0, freq_y1_p0, freq_y0_p1, freq_y1_p1, tau0, tau1)"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "h3OOQeTsv8uS"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"plot_roc(credit_scores, freq_y0_p0, freq_y1_p0, freq_y0_p1, freq_y1_p1, tau0, tau1)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "UCObTsa57uuC"
|
||||
},
|
||||
"source": [
|
||||
"On this plot, the true positive and false alarm rate for the particular thresholds ($\\tau_0=\\tau_{1}=0$) that we chose are indicated by the circles.\n",
|
||||
"\n",
|
||||
"This criterion is clearly not great. The blue and yellow groups get given loans at different rates overall, and (for this threshold), the false alarms and true positives are also different, so it's not even fair when we consider whether the loans really were paid back. \n",
|
||||
"\n",
|
||||
"TODO -- investigate setting a different threshold $\\tau_{0}=\\tau_{1}$. Is it possible to make the overall rates that loans are given the same? Is it possible to make the false alarm rates the same? Is it possible to make the true positive rates the same?"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "UCObTsa57uuC"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Yhrxv5AQ-PWA"
|
||||
},
|
||||
"source": [
|
||||
"# Equality of odds\n",
|
||||
"\n",
|
||||
"This definition of fairness proposes that the false positive and true positive rates should be the same for both populations. This also sounds reasonable, but the ROC curve shows that it is not possible for this example. There is no combination of thresholds that can achieve this because the ROC curves do not intersect. Even if they did, we would be stuck giving loans based on the particular false positive and true positive rates at the intersection which might not be desirable."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Yhrxv5AQ-PWA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "l6yb8vjX-gdi"
|
||||
},
|
||||
"source": [
|
||||
"Demographic parity\n",
|
||||
"\n",
|
||||
"The thresholds can be chosen so that the same proportion of each group are classified as $\\hat{y}=1$ and given loans. We make an equal number of loans to each group despite the different tendencies of each to repay. This has the disadvantage that the true positive and false positive rates might be completely different in different populations. From the perspective of the lender, it is desirable to give loans in proportion to people’s ability to pay them back. From the perspective of an individual in a more reliable group, it may seem unfair that the other group gets offered the same number of loans despite the fact they are less reliable."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "l6yb8vjX-gdi"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "syjZ2fn5wC9-"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TO DO -- try to change the two thresholds so the overall probability of getting the loan is 0.6 for each group\n",
|
||||
"# Change the values in these lines\n",
|
||||
@@ -340,55 +340,58 @@
|
||||
"pr_get_loan_p1 = compute_probability_get_loan(credit_scores, freq_y0_p1+freq_y1_p1, tau1)\n",
|
||||
"print(\"Probability blue group gets loan = %3.3f\"%(pr_get_loan_p0))\n",
|
||||
"print(\"Probability yellow group gets loan = %3.3f\"%(pr_get_loan_p1))"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "syjZ2fn5wC9-"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"This is good, because now both groups get roughly the same amount of loans. But hold on... let's look at the ROC curve:"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "5QrtvZZlHCJy"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"This is good, because now both groups get roughly the same amount of loans. But hold on... let's look at the ROC curve:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"plot_roc(credit_scores, freq_y0_p0, freq_y1_p0, freq_y0_p1, freq_y1_p1, tau0, tau1)"
|
||||
],
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "VApyl_58GUQb"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"plot_roc(credit_scores, freq_y0_p0, freq_y1_p0, freq_y0_p1, freq_y1_p1, tau0, tau1)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"The blue dot is waaay above the yellow dot. The proportion of people who are given a load and do pay it back from the blue population is much higher than that from the yellow population. From another perspective, that's unfair... it seems like the yellow population are 'allowed' to default more often than the blue. This leads to another possibility."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "_GgX_b6yIE4W"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"The blue dot is waaay above the yellow dot. The proportion of people who are given a load and do pay it back from the blue population is much higher than that from the yellow population. From another perspective, that's unfair... it seems like the yellow population are 'allowed' to default more often than the blue. This leads to another possibility."
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "WDnaqetXHhlv"
|
||||
},
|
||||
"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."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "WDnaqetXHhlv"
|
||||
}
|
||||
"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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "zEN6HGJ7HJAZ"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# TO DO -- try to change the two thresholds so the true positive are 0.8 for each group\n",
|
||||
"# Change the values in these lines so that both points on the curves have a height of 0.8\n",
|
||||
@@ -397,45 +400,58 @@
|
||||
"\n",
|
||||
"\n",
|
||||
"plot_roc(credit_scores, freq_y0_p0, freq_y1_p0, freq_y0_p1, freq_y1_p1, tau0, tau1)"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "zEN6HGJ7HJAZ"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"This seems fair -- people who are given loans default at the same rate (20%) for both groups. But hold on... let's look at the overall loan rate between the two populations:"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "JsyW0pBGJ24b"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"This seems fair -- people who are given loans default at the same rate (20%) for both groups. But hold on... let's look at the overall loan rate between the two populations:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "2a5PXHeNJDjg"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Compute overall probability of getting loan\n",
|
||||
"pr_get_loan_p0 = compute_probability_get_loan(credit_scores, freq_y0_p0+freq_y1_p0, tau0)\n",
|
||||
"pr_get_loan_p1 = compute_probability_get_loan(credit_scores, freq_y0_p1+freq_y1_p1, tau1)\n",
|
||||
"print(\"Probability blue group gets loan = %3.3f\"%(pr_get_loan_p0))\n",
|
||||
"print(\"Probability yellow group gets loan = %3.3f\"%(pr_get_loan_p1))"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "2a5PXHeNJDjg"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"The conclusion from all this is that (i) definitions of fairness are quite subtle and (ii) it's not possible to satisfy them all simultaneously."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "tZTM7N6jKC7q"
|
||||
}
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"The conclusion from all this is that (i) definitions of fairness are quite subtle and (ii) it's not possible to satisfy them all simultaneously."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"authorship_tag": "ABX9TyNQPfTDV6PFG7Ctcl+XVNlz",
|
||||
"include_colab_link": true,
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
|
||||
7
Notebooks/LICENSE (MIT)
Normal file
7
Notebooks/LICENSE (MIT)
Normal 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.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
UDL_Errata.pdf
BIN
UDL_Errata.pdf
Binary file not shown.
422
index.html
422
index.html
@@ -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">
|
||||
</head>
|
||||
<head>
|
||||
<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"
|
||||
/>
|
||||
|
||||
<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/v1.17/UnderstandingDeepLearning_17_12_23_C.pdf">here</a>
|
||||
</p>2023-12-17. 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=1Kllhj0HdS_I3qE2XDU6ifgGGj3tmSRcl">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>
|
||||
</body>
|
||||
<title>Understanding Deep Learning</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/index.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
8
jsconfig.json
Normal file
8
jsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": "./",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
4457
package-lock.json
generated
Normal file
4457
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
36
package.json
Executable file
36
package.json
Executable 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
BIN
public/NMI_Review.pdf
Normal file
Binary file not shown.
BIN
public/favicon.ico
Normal file
BIN
public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
12
src/App.jsx
Executable file
12
src/App.jsx
Executable 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>
|
||||
);
|
||||
}
|
||||
34
src/README.md
Normal file
34
src/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Understanding Deep Learning
|
||||
|
||||
Understanding Deep Learning - Simon J.D. Prince
|
||||
|
||||
## Website
|
||||
|
||||
```shell
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Run the website in development mode
|
||||
npm dev
|
||||
|
||||
# Build the website
|
||||
npm build
|
||||
|
||||
# Preview the built website
|
||||
npm preview
|
||||
|
||||
# Format the code
|
||||
npm run format
|
||||
|
||||
# Lint the code
|
||||
npm run lint
|
||||
|
||||
# Clean the repository
|
||||
npm run clean
|
||||
|
||||
# Prepare to deploy the website
|
||||
npm run predeploy
|
||||
|
||||
# Deploy the website
|
||||
npm run deploy
|
||||
```
|
||||
145
src/components/Footer/FooterElements.jsx
Executable file
145
src/components/Footer/FooterElements.jsx
Executable file
@@ -0,0 +1,145 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
|
||||
export const FooterContainer = styled.footer`
|
||||
background-color: #101522;
|
||||
`;
|
||||
|
||||
export const FooterWrap = styled.div`
|
||||
padding: 48x 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
`;
|
||||
|
||||
export const FooterLinksContainer = styled.div`
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
|
||||
@media screen and (max-width: 820px) {
|
||||
padding-top: 32px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const FooterLinksWrapper = styled.div`
|
||||
display: flex;
|
||||
|
||||
@media screen and (max-width: 820px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
`;
|
||||
|
||||
export const FooterLinkItems = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
margin: 16px;
|
||||
text-align: left;
|
||||
width: 160px;
|
||||
box-sizing: border-box;
|
||||
color: #fff;
|
||||
|
||||
@media screen and (max-width: 420px) {
|
||||
margin: 0;
|
||||
padding: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
`;
|
||||
|
||||
export const FooterLinkTitle = styled.h1`
|
||||
font-size: 14px;
|
||||
margin-bottom: 16px;
|
||||
`;
|
||||
|
||||
export const FooterLink = styled(Link)`
|
||||
color: #ffffff;
|
||||
text-decoration: none;
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: 14px;
|
||||
|
||||
&:hover {
|
||||
color: #01bf71;
|
||||
transition: 0.3s ease-in-out;
|
||||
}
|
||||
`;
|
||||
|
||||
export const SocialMedia = styled.section`
|
||||
max-width: 1000px;
|
||||
width: 100%;
|
||||
`;
|
||||
|
||||
export const SocialMediaWrap = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
max-width: 1100px;
|
||||
margin: 20px auto 0 auto;
|
||||
|
||||
@media screen and (max-width: 820px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
`;
|
||||
|
||||
export const SocialAttrWrap = styled.div`
|
||||
color: #fff;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
max-width: 1100px;
|
||||
margin: 10px auto 0 auto;
|
||||
|
||||
@media screen and (max-width: 820px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
`;
|
||||
|
||||
export const SocialLogo = styled(Link)`
|
||||
color: #fff;
|
||||
justify-self: start;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
font-size: 1.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
font-weight: bold;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 20px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const WebsiteRights = styled.small`
|
||||
color: #fff;
|
||||
margin-bottom: 8px;
|
||||
`;
|
||||
|
||||
export const SocialIcons = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
width: 60px;
|
||||
margin-bottom: 8px;
|
||||
`;
|
||||
|
||||
export const SocialIconLink = styled.a`
|
||||
color: #fff;
|
||||
font-size: 24px;
|
||||
margin-right: 8px;
|
||||
`;
|
||||
|
||||
export const FooterImgWrap = styled.div`
|
||||
max-width: 555px;
|
||||
height: 100%;
|
||||
`;
|
||||
|
||||
export const FooterImg = styled.img`
|
||||
width: 100%;
|
||||
margin-top: 0;
|
||||
margin-right: 0;
|
||||
margin-left: 10px;
|
||||
padding-right: 0;
|
||||
`;
|
||||
84
src/components/Footer/index.jsx
Executable file
84
src/components/Footer/index.jsx
Executable file
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
FooterContainer,
|
||||
FooterWrap,
|
||||
SocialIconLink,
|
||||
SocialIcons,
|
||||
SocialLogo,
|
||||
SocialMedia,
|
||||
SocialMediaWrap,
|
||||
WebsiteRights,
|
||||
} from "@/components/Footer/FooterElements";
|
||||
import { FaGithub, FaLinkedin } from "react-icons/fa";
|
||||
import { FaSquareXTwitter } from "react-icons/fa6";
|
||||
import { animateScroll as scroll } from "react-scroll";
|
||||
|
||||
const images = [
|
||||
"https://freepik.com/free-vector/hand-coding-concept-illustration_21864184.htm#query=coding&position=17&from_view=search&track=sph&uuid=5896d847-38e4-4cb9-8fe1-103041c7c933",
|
||||
"https://freepik.com/free-vector/mathematics-concept-illustration_10733824.htm#query=professor&position=13&from_view=search&track=sph&uuid=5b1a188a-64c5-45af-aae2-8573bc1bed3c",
|
||||
"https://freepik.com/free-vector/content-concept-illustration_7171429.htm#query=media&position=3&from_view=search&track=sph&uuid=c7e35cf2-d85d-4bba-91a6-1cd883dcf153",
|
||||
"https://freepik.com/free-vector/library-concept-illustration_9148008.htm#query=library&position=40&from_view=search&track=sph&uuid=abecc792-b6b2-4ec0-b318-5e6cc73ba649",
|
||||
];
|
||||
|
||||
const socials = [
|
||||
{
|
||||
href: "https://twitter.com/SimonPrinceAI",
|
||||
icon: FaSquareXTwitter,
|
||||
alt: "Twitter",
|
||||
},
|
||||
{
|
||||
href: "https://linkedin.com/in/simon-prince-615bb9165/",
|
||||
icon: FaLinkedin,
|
||||
alt: "LinkedIn",
|
||||
},
|
||||
{
|
||||
href: "https://github.com/udlbook/udlbook",
|
||||
icon: FaGithub,
|
||||
alt: "GitHub",
|
||||
},
|
||||
];
|
||||
|
||||
export default function Footer() {
|
||||
const scrollToHome = () => {
|
||||
scroll.scrollToTop();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<FooterContainer>
|
||||
<FooterWrap>
|
||||
<SocialMedia>
|
||||
<SocialMediaWrap>
|
||||
<SocialLogo to="/udlbook" onClick={scrollToHome}>
|
||||
Understanding Deep Learning
|
||||
</SocialLogo>
|
||||
<WebsiteRights>
|
||||
© {new Date().getFullYear()} Simon J.D. Prince
|
||||
</WebsiteRights>
|
||||
<WebsiteRights>
|
||||
Images by StorySet on FreePik:{" "}
|
||||
{images.map((image, index) => (
|
||||
<a key={index} href={image}>
|
||||
[{index + 1}]
|
||||
</a>
|
||||
))}
|
||||
</WebsiteRights>
|
||||
<SocialIcons>
|
||||
{socials.map((social, index) => (
|
||||
<SocialIconLink
|
||||
key={index}
|
||||
href={social.href}
|
||||
target="_blank"
|
||||
aria-label={social.alt}
|
||||
alt={social.alt}
|
||||
>
|
||||
<social.icon />
|
||||
</SocialIconLink>
|
||||
))}
|
||||
</SocialIcons>
|
||||
</SocialMediaWrap>
|
||||
</SocialMedia>
|
||||
</FooterWrap>
|
||||
</FooterContainer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
294
src/components/HeroSection/HeroElements.jsx
Executable file
294
src/components/HeroSection/HeroElements.jsx
Executable file
@@ -0,0 +1,294 @@
|
||||
import styled from "styled-components";
|
||||
|
||||
export const HeroContainer = styled.div`
|
||||
background: #57c6d1;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 0 0px;
|
||||
position: static;
|
||||
z-index: 1;
|
||||
`;
|
||||
|
||||
export const HeroContent = styled.div`
|
||||
z-index: 3;
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
position: static;
|
||||
padding: 8px 24px;
|
||||
margin: 80px 0px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
`;
|
||||
|
||||
export const HeroH1 = styled.h1`
|
||||
color: #fff;
|
||||
font-size: 48px;
|
||||
text-align: center;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 40px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 32px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroP = styled.p`
|
||||
margin-top: 24px;
|
||||
color: #fff;
|
||||
font-size: 24px;
|
||||
text-align: center;
|
||||
max-width: 600px;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 18px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroBtnWrapper = styled.div`
|
||||
margin-top: 32px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
`;
|
||||
|
||||
export const HeroRow = styled.div`
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 20px;
|
||||
align-items: top;
|
||||
grid-template-areas: "col1 col2";
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-areas:
|
||||
"col2"
|
||||
"col1";
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroNewsItem = styled.div`
|
||||
margin-left: 4px;
|
||||
color: #000000;
|
||||
font-size: 16px;
|
||||
margin-bottom: 16px;
|
||||
display: flex;
|
||||
justify-content: start;
|
||||
`;
|
||||
|
||||
export const HeroNewsItemDate = styled.div`
|
||||
width: 20%;
|
||||
margin-right: 20px;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroNewsItemContent = styled.div`
|
||||
width: 80%;
|
||||
color: #000000;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroColumn1 = styled.div`
|
||||
margin-bottom: 15px;
|
||||
margin-left: 12px;
|
||||
margin-top: 60px;
|
||||
padding: 10px 15px;
|
||||
grid-area: col1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
margin-left: 0;
|
||||
margin-top: 20px;
|
||||
padding: 0;
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroColumn2 = styled.div`
|
||||
margin-bottom: 15px;
|
||||
padding: 0 15px;
|
||||
grid-area: col2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
padding: 0;
|
||||
}
|
||||
`;
|
||||
|
||||
export const TextWrapper = styled.div`
|
||||
max-width: 540px;
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
`;
|
||||
|
||||
export const HeroImgWrap = styled.div`
|
||||
max-width: 555px;
|
||||
height: 100%;
|
||||
`;
|
||||
|
||||
export const Img = styled.img`
|
||||
width: 100%;
|
||||
margin-top: 0;
|
||||
margin-right: 0;
|
||||
margin-left: 10px;
|
||||
padding-right: 0;
|
||||
`;
|
||||
|
||||
export const HeroDownloadsImg = styled.img`
|
||||
margin-top: 5px;
|
||||
margin-right: 0;
|
||||
margin-left: 0;
|
||||
padding-right: 0;
|
||||
margin-bottom: 10px;
|
||||
`;
|
||||
|
||||
export const HeroLink = styled.a`
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
padding: 0.6rem 0rem 0rem 0rem;
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
|
||||
&:before {
|
||||
position: absolute;
|
||||
margin: 0 auto;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background-color: #fff;
|
||||
content: "";
|
||||
opacity: 0.3;
|
||||
-webkit-transform: scaleX(1);
|
||||
transition-property:
|
||||
opacity,
|
||||
-webkit-transform;
|
||||
transition-duration: 0.3s;
|
||||
}
|
||||
|
||||
&:hover:before {
|
||||
opacity: 1;
|
||||
-webkit-transform: scaleX(1.05);
|
||||
}
|
||||
`;
|
||||
|
||||
export const UDLLink = styled.a`
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
font-weight: 300;
|
||||
margin: 0 2px;
|
||||
position: relative;
|
||||
|
||||
&:before {
|
||||
position: absolute;
|
||||
margin: 0 auto;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background-color: #000;
|
||||
content: "";
|
||||
opacity: 0.3;
|
||||
-webkit-transform: scaleX(1);
|
||||
transition-property:
|
||||
opacity,
|
||||
-webkit-transform;
|
||||
transition-duration: 0.3s;
|
||||
}
|
||||
|
||||
&:hover:before {
|
||||
opacity: 1;
|
||||
-webkit-transform: scaleX(1.05);
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroNewsTitle = styled.div`
|
||||
margin-left: 0px;
|
||||
color: #000000;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
line-height: 16px;
|
||||
margin-bottom: 36px;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 18px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroCitationTitle = styled.div`
|
||||
margin-left: 0px;
|
||||
color: #000000;
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
line-height: 16px;
|
||||
margin-bottom: 10px;
|
||||
margin-top: 36px;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 18px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroNewsBlock = styled.div``;
|
||||
|
||||
export const HeroCitationBlock = styled.div`
|
||||
font-size: 14px;
|
||||
margin-bottom: 0px;
|
||||
margin-top: 0px;
|
||||
`;
|
||||
|
||||
export const HeroFollowBlock = styled.div`
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 14px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const HeroNewsMoreButton = styled.button`
|
||||
background: #fff;
|
||||
color: #000;
|
||||
font-size: 16px;
|
||||
padding: 10px 24px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
margin-top: 20px;
|
||||
margin-bottom: 20px;
|
||||
align-self: center;
|
||||
|
||||
&:hover {
|
||||
background: #000;
|
||||
color: #fff;
|
||||
}
|
||||
`;
|
||||
209
src/components/HeroSection/index.jsx
Executable file
209
src/components/HeroSection/index.jsx
Executable file
@@ -0,0 +1,209 @@
|
||||
import {
|
||||
HeroCitationBlock,
|
||||
HeroCitationTitle,
|
||||
HeroColumn1,
|
||||
HeroColumn2,
|
||||
HeroContainer,
|
||||
HeroContent,
|
||||
HeroDownloadsImg,
|
||||
HeroFollowBlock,
|
||||
HeroImgWrap,
|
||||
HeroLink,
|
||||
HeroNewsBlock,
|
||||
HeroNewsItem,
|
||||
HeroNewsItemContent,
|
||||
HeroNewsItemDate,
|
||||
HeroNewsMoreButton,
|
||||
HeroNewsTitle,
|
||||
HeroRow,
|
||||
Img,
|
||||
UDLLink,
|
||||
} from "@/components/HeroSection/HeroElements";
|
||||
import img from "@/images/book_cover.jpg";
|
||||
import { useState } from "react";
|
||||
|
||||
const citation = `
|
||||
@book{prince2023understanding,
|
||||
author = "Simon J.D. Prince",
|
||||
title = "Understanding Deep Learning",
|
||||
publisher = "The MIT Press",
|
||||
year = 2023,
|
||||
url = "http://udlbook.com"
|
||||
}
|
||||
`;
|
||||
|
||||
const news = [
|
||||
{
|
||||
date: "05/22/24",
|
||||
content: (
|
||||
<HeroNewsItemContent>
|
||||
New{" "}
|
||||
<UDLLink href="https://borealisai.com/research-blogs/neural-tangent-kernel-applications/">
|
||||
blog
|
||||
</UDLLink>{" "}
|
||||
about the applications of the neural tangent kernel.
|
||||
</HeroNewsItemContent>
|
||||
),
|
||||
},
|
||||
{
|
||||
date: "05/10/24",
|
||||
content: (
|
||||
<HeroNewsItemContent>
|
||||
Positive{" "}
|
||||
<UDLLink href="https://github.com/udlbook/udlbook/blob/main/public/NMI_Review.pdf">
|
||||
review
|
||||
</UDLLink>{" "}
|
||||
in Nature Machine Intelligence.
|
||||
</HeroNewsItemContent>
|
||||
),
|
||||
},
|
||||
// {
|
||||
// date: "03/12/24",
|
||||
// content: <HeroNewsItemContent>Book now available again.</HeroNewsItemContent>,
|
||||
// },
|
||||
{
|
||||
date: "02/21/24",
|
||||
content: (
|
||||
<HeroNewsItemContent>
|
||||
New blog about the{" "}
|
||||
<UDLLink href="https://borealisai.com/research-blogs/the-neural-tangent-kernel/">
|
||||
Neural Tangent Kernel
|
||||
</UDLLink>
|
||||
.
|
||||
</HeroNewsItemContent>
|
||||
),
|
||||
},
|
||||
// {
|
||||
// date: "02/15/24",
|
||||
// content: (
|
||||
// <HeroNewsItemContent>
|
||||
// First printing of book has sold out in most places. Second printing available
|
||||
// mid-March.
|
||||
// </HeroNewsItemContent>
|
||||
// ),
|
||||
// },
|
||||
{
|
||||
date: "01/29/24",
|
||||
content: (
|
||||
<HeroNewsItemContent>
|
||||
New blog about{" "}
|
||||
<UDLLink href="https://borealisai.com/research-blogs/gradient-flow/">
|
||||
gradient flow
|
||||
</UDLLink>{" "}
|
||||
published.
|
||||
</HeroNewsItemContent>
|
||||
),
|
||||
},
|
||||
{
|
||||
date: "12/26/23",
|
||||
content: (
|
||||
<HeroNewsItemContent>
|
||||
Machine Learning Street Talk{" "}
|
||||
<UDLLink href="https://youtube.com/watch?v=sJXn4Cl4oww">podcast</UDLLink> discussing
|
||||
book.
|
||||
</HeroNewsItemContent>
|
||||
),
|
||||
},
|
||||
{
|
||||
date: "12/19/23",
|
||||
content: (
|
||||
<HeroNewsItemContent>
|
||||
Deeper Insights{" "}
|
||||
<UDLLink href="https://podcasts.apple.com/us/podcast/understanding-deep-learning-with-simon-prince/id1669436318?i=1000638269385">
|
||||
podcast
|
||||
</UDLLink>{" "}
|
||||
discussing book.
|
||||
</HeroNewsItemContent>
|
||||
),
|
||||
},
|
||||
{
|
||||
date: "12/06/23",
|
||||
content: (
|
||||
<HeroNewsItemContent>
|
||||
<UDLLink href="https://borealisai.com/news/understanding-deep-learning/">
|
||||
Interview
|
||||
</UDLLink>{" "}
|
||||
with Borealis AI.
|
||||
</HeroNewsItemContent>
|
||||
),
|
||||
},
|
||||
{
|
||||
date: "12/05/23",
|
||||
content: (
|
||||
<HeroNewsItemContent>
|
||||
Book released by{" "}
|
||||
<UDLLink href="https://mitpress.mit.edu/9780262048644/understanding-deep-learning/">
|
||||
The MIT Press
|
||||
</UDLLink>
|
||||
.
|
||||
</HeroNewsItemContent>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
export default function HeroSection() {
|
||||
const [showMoreNews, setShowMoreNews] = useState(false);
|
||||
|
||||
const toggleShowMore = () => {
|
||||
setShowMoreNews((p) => !p);
|
||||
};
|
||||
|
||||
return (
|
||||
<HeroContainer id="home">
|
||||
<HeroContent>
|
||||
<HeroRow>
|
||||
<HeroColumn1>
|
||||
<HeroNewsBlock>
|
||||
<HeroNewsTitle>RECENT NEWS:</HeroNewsTitle>
|
||||
{(showMoreNews ? news : news.slice(0, 7)).map((item, index) => (
|
||||
<HeroNewsItem key={index}>
|
||||
<HeroNewsItemDate>{item.date}</HeroNewsItemDate>
|
||||
{item.content}
|
||||
</HeroNewsItem>
|
||||
))}
|
||||
<HeroNewsMoreButton onClick={toggleShowMore}>
|
||||
{showMoreNews ? "Show less" : "Show more"}
|
||||
</HeroNewsMoreButton>
|
||||
</HeroNewsBlock>
|
||||
<HeroCitationTitle>CITATION:</HeroCitationTitle>
|
||||
<HeroCitationBlock>
|
||||
<pre>
|
||||
<code>{citation}</code>
|
||||
</pre>
|
||||
</HeroCitationBlock>
|
||||
<HeroFollowBlock>
|
||||
Follow me on{" "}
|
||||
<UDLLink href="https://twitter.com/SimonPrinceAI">Twitter</UDLLink> or{" "}
|
||||
<UDLLink href="https://linkedin.com/in/simon-prince-615bb9165/">
|
||||
LinkedIn
|
||||
</UDLLink>{" "}
|
||||
for updates.
|
||||
</HeroFollowBlock>
|
||||
</HeroColumn1>
|
||||
<HeroColumn2>
|
||||
<HeroImgWrap>
|
||||
<Img src={img} alt="Book Cover" />
|
||||
</HeroImgWrap>
|
||||
<HeroLink href="https://github.com/udlbook/udlbook/releases/download/v4.0.1/UnderstandingDeepLearning_05_27_24_C.pdf">
|
||||
Download full PDF (27 May 2024)
|
||||
</HeroLink>
|
||||
<br />
|
||||
<HeroDownloadsImg
|
||||
src="https://img.shields.io/github/downloads/udlbook/udlbook/total"
|
||||
alt="download stats shield"
|
||||
/>
|
||||
<HeroLink href="https://mitpress.mit.edu/9780262048644/understanding-deep-learning/">
|
||||
Buy the book
|
||||
</HeroLink>
|
||||
<HeroLink href="https://github.com/udlbook/udlbook/raw/main/UDL_Answer_Booklet_Students.pdf">
|
||||
Answers to selected questions
|
||||
</HeroLink>
|
||||
<HeroLink href="https://github.com/udlbook/udlbook/raw/main/UDL_Errata.pdf">
|
||||
Errata
|
||||
</HeroLink>
|
||||
</HeroColumn2>
|
||||
</HeroRow>
|
||||
</HeroContent>
|
||||
</HeroContainer>
|
||||
);
|
||||
}
|
||||
163
src/components/Instructors/InstructorsElements.jsx
Normal file
163
src/components/Instructors/InstructorsElements.jsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import styled from "styled-components";
|
||||
|
||||
export const InstructorsContainer = styled.div`
|
||||
color: #fff;
|
||||
/* background: #f9f9f9; */
|
||||
background: ${({ lightBg }) => (lightBg ? "#57c6d1" : "#010606")};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
padding: 100px 0;
|
||||
}
|
||||
`;
|
||||
|
||||
export const InstructorsWrapper = styled.div`
|
||||
display: grid;
|
||||
z-index: 1;
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
margin-right: auto;
|
||||
margin-left: auto;
|
||||
padding: 0 24px;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
export const InstructorsRow = styled.div`
|
||||
display: grid;
|
||||
grid-auto-columns: minmax(auto, 1fr);
|
||||
align-items: center;
|
||||
grid-template-areas: ${({ imgStart }) => (imgStart ? `'col2 col1'` : `'col1 col2'`)};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
grid-template-areas: ${({ imgStart }) =>
|
||||
imgStart ? `'col1' 'col2'` : `'col1 col1' 'col2 col2'`};
|
||||
}
|
||||
`;
|
||||
|
||||
export const InstructorsRow2 = styled.div`
|
||||
display: grid;
|
||||
grid-auto-columns: minmax(auto, 1fr);
|
||||
align-items: top;
|
||||
grid-template-areas: ${({ imgStart }) => (imgStart ? `'col2 col1'` : `'col1 col2'`)};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
grid-template-areas: ${({ imgStart }) =>
|
||||
imgStart ? `'col1' 'col2'` : `'col1 col1' 'col2 col2'`};
|
||||
}
|
||||
`;
|
||||
|
||||
export const Column1 = styled.div`
|
||||
margin-bottom: 15px;
|
||||
padding: 0 15px;
|
||||
grid-area: col1;
|
||||
`;
|
||||
|
||||
export const Column2 = styled.div`
|
||||
margin-bottom: 15px;
|
||||
padding: 0 15px;
|
||||
grid-area: col2;
|
||||
`;
|
||||
|
||||
export const TextWrapper = styled.div`
|
||||
max-width: 540px;
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
`;
|
||||
|
||||
export const TopLine = styled.p`
|
||||
color: #773c23;
|
||||
font-size: 16px;
|
||||
line-height: 16px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 1.4px;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 16px;
|
||||
`;
|
||||
|
||||
export const Heading = styled.h1`
|
||||
margin-bottom: 24px;
|
||||
font-size: 48px;
|
||||
line-height: 1.1;
|
||||
font-weight: 600;
|
||||
color: ${({ lightText }) => (lightText ? "#f7f8fa" : "#010606")};
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 32px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const Subtitle = styled.p`
|
||||
max-width: 440px;
|
||||
margin-bottom: 35px;
|
||||
font-size: 18px;
|
||||
line-height: 24px;
|
||||
color: ${({ darkText }) => (darkText ? "#010606" : "#fff")};
|
||||
`;
|
||||
|
||||
export const BtnWrap = styled.div`
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
`;
|
||||
|
||||
export const ImgWrap = styled.div`
|
||||
max-width: 555px;
|
||||
height: 100%;
|
||||
`;
|
||||
|
||||
export const Img = styled.img`
|
||||
width: 100%;
|
||||
margin-top: 0;
|
||||
margin-right: 0;
|
||||
margin-left: 10px;
|
||||
padding-right: 0;
|
||||
`;
|
||||
|
||||
export const InstructorsContent = styled.div`
|
||||
z-index: 3;
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
position: static;
|
||||
padding: 8px 0px;
|
||||
margin: 10px 0px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: left;
|
||||
list-style-position: inside;
|
||||
|
||||
@media screen and (max-width: 1050px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const InstructorsLink = styled.a`
|
||||
text-decoration: none;
|
||||
color: #555;
|
||||
font-weight: 300;
|
||||
margin: 0 2px;
|
||||
position: relative;
|
||||
|
||||
&:before {
|
||||
position: absolute;
|
||||
margin: 0 auto;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background-color: #555;
|
||||
content: "";
|
||||
opacity: 0.3;
|
||||
-webkit-transform: scaleX(1);
|
||||
transition-property:
|
||||
opacity,
|
||||
-webkit-transform;
|
||||
transition-duration: 0.3s;
|
||||
}
|
||||
|
||||
&:hover:before {
|
||||
opacity: 1;
|
||||
-webkit-transform: scaleX(1.05);
|
||||
}
|
||||
`;
|
||||
334
src/components/Instructors/index.jsx
Normal file
334
src/components/Instructors/index.jsx
Normal file
@@ -0,0 +1,334 @@
|
||||
import {
|
||||
Column1,
|
||||
Column2,
|
||||
Heading,
|
||||
Img,
|
||||
ImgWrap,
|
||||
InstructorsContainer,
|
||||
InstructorsContent,
|
||||
InstructorsLink,
|
||||
InstructorsRow,
|
||||
InstructorsRow2,
|
||||
InstructorsWrapper,
|
||||
Subtitle,
|
||||
TextWrapper,
|
||||
TopLine,
|
||||
} from "@/components/Instructors/InstructorsElements";
|
||||
import img from "@/images/instructor.svg";
|
||||
|
||||
const fullSlides = [
|
||||
{
|
||||
text: "Introduction",
|
||||
link: "https://drive.google.com/uc?export=download&id=17RHb11BrydOvxSFNbRIomE1QKLVI087m",
|
||||
},
|
||||
{
|
||||
text: "Supervised Learning",
|
||||
link: "https://drive.google.com/uc?export=download&id=1491zkHULC7gDfqlV6cqUxyVYXZ-de-Ub",
|
||||
},
|
||||
{
|
||||
text: "Shallow Neural Networks",
|
||||
link: "https://drive.google.com/uc?export=download&id=1XkP1c9EhOBowla1rT1nnsDGMf2rZvrt7",
|
||||
},
|
||||
{
|
||||
text: "Deep Neural Networks",
|
||||
link: "https://drive.google.com/uc?export=download&id=1e2ejfZbbfMKLBv0v-tvBWBdI8gO3SSS1",
|
||||
},
|
||||
{
|
||||
text: "Loss Functions",
|
||||
link: "https://drive.google.com/uc?export=download&id=1fxQ_a1Q3eFPZ4kPqKbak6_emJK-JfnRH",
|
||||
},
|
||||
{
|
||||
text: "Fitting Models",
|
||||
link: "https://drive.google.com/uc?export=download&id=17QQ5ZzXBtR_uCNCUU1gPRWWRUeZN9exW",
|
||||
},
|
||||
{
|
||||
text: "Computing Gradients",
|
||||
link: "https://drive.google.com/uc?export=download&id=1hC8JUCOaFWiw3KGn0rm7nW6mEq242QDK",
|
||||
},
|
||||
{
|
||||
text: "Initialization",
|
||||
link: "https://drive.google.com/uc?export=download&id=1tSjCeAVg0JCeBcPgDJDbi7Gg43Qkh9_d",
|
||||
},
|
||||
{
|
||||
text: "Performance",
|
||||
link: "https://drive.google.com/uc?export=download&id=1RVZW3KjEs0vNSGx3B2fdizddlr6I0wLl",
|
||||
},
|
||||
{
|
||||
text: "Regularization",
|
||||
link: "https://drive.google.com/uc?export=download&id=1LTicIKPRPbZRkkg6qOr1DSuOB72axood",
|
||||
},
|
||||
{
|
||||
text: "Convolutional Networks",
|
||||
link: "https://drive.google.com/uc?export=download&id=1bGVuwAwrofzZdfvj267elIzkYMIvYFj0",
|
||||
},
|
||||
{
|
||||
text: "Image Generation",
|
||||
link: "https://drive.google.com/uc?export=download&id=14w31QqWRDix1GdUE-na0_E0kGKBhtKzs",
|
||||
},
|
||||
{
|
||||
text: "Transformers and LLMs",
|
||||
link: "https://drive.google.com/uc?export=download&id=1af6bTTjAbhDYfrDhboW7Fuv52Gk9ygKr",
|
||||
},
|
||||
];
|
||||
|
||||
const figures = [
|
||||
{
|
||||
text: "Introduction",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap1PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1udnl5pUOAc8DcAQ7HQwyzP9pwL95ynnv",
|
||||
pptx: "https://docs.google.com/presentation/d/1IjTqIUvWCJc71b5vEJYte-Dwujcp7rvG/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Supervised learning",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap2PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1VSxcU5y1qNFlmd3Lb3uOWyzILuOj1Dla",
|
||||
pptx: "https://docs.google.com/presentation/d/1Br7R01ROtRWPlNhC_KOommeHAWMBpWtz/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Shallow neural networks",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap3PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=19kZFWlXhzN82Zx02ByMmSZOO4T41fmqI",
|
||||
pptx: "https://docs.google.com/presentation/d/1e9M3jB5I9qZ4dCBY90Q3Hwft_i068QVQ/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Deep neural networks",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap4PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1ojr0ebsOhzvS04ItAflX2cVmYqHQHZUa",
|
||||
pptx: "https://docs.google.com/presentation/d/1LTSsmY4mMrJbqXVvoTOCkQwHrRKoYnJj/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Loss functions",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap5PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=17MJO7fiMpFZVqKeqXTbQ36AMpmR4GizZ",
|
||||
pptx: "https://docs.google.com/presentation/d/1gcpC_3z9oRp87eMkoco-kdLD-MM54Puk/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Training models",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap6PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1VPdhFRnCr9_idTrX0UdHKGAw2shUuwhK",
|
||||
pptx: "https://docs.google.com/presentation/d/1AKoeggAFBl9yLC7X5tushAGzCCxmB7EY/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Gradients and initialization",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap7PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1TTl4gvrTvNbegnml4CoGoKOOd6O8-PGs",
|
||||
pptx: "https://docs.google.com/presentation/d/11zhB6PI-Dp6Ogmr4IcI6fbvbqNqLyYcz/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Measuring performance",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap8PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=19eQOnygd_l0DzgtJxXuYnWa4z7QKJrJx",
|
||||
pptx: "https://docs.google.com/presentation/d/1SHRmJscDLUuQrG7tmysnScb3ZUAqVMZo/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Regularization",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap9PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1LprgnUGL7xAM9-jlGZC9LhMPeefjY0r0",
|
||||
pptx: "https://docs.google.com/presentation/d/1VwIfvjpdfTny6sEfu4ZETwCnw6m8Eg-5/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Convolutional networks",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap10PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1-Wb3VzaSvVeRzoUzJbI2JjZE0uwqupM9",
|
||||
pptx: "https://docs.google.com/presentation/d/1MtfKBC4Y9hWwGqeP6DVwUNbi1j5ncQCg/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Residual networks",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap11PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1Mr58jzEVseUAfNYbGWCQyDtEDwvfHRi1",
|
||||
pptx: "https://docs.google.com/presentation/d/1saY8Faz0KTKAAifUrbkQdLA2qkyEjOPI/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Transformers",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap12PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1txzOVNf8-jH4UfJ6SLnrtOfPd1Q3ebzd",
|
||||
pptx: "https://docs.google.com/presentation/d/1GVNvYWa0WJA6oKg89qZre-UZEhABfm0l/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Graph neural networks",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap13PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1lQIV6nRp6LVfaMgpGFhuwEXG-lTEaAwe",
|
||||
pptx: "https://docs.google.com/presentation/d/1YwF3U82c1mQ74c1WqHVTzLZ0j7GgKaWP/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Unsupervised learning",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap14PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1aMbI6iCuUvOywqk5pBOmppJu1L1anqsM",
|
||||
pptx: "https://docs.google.com/presentation/d/1A-lBGv3NHl4L32NvfFgy1EKeSwY-0UeB/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "GANs",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap15PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1EErnlZCOlXc3HK7m83T2Jh_0NzIUHvtL",
|
||||
pptx: "https://docs.google.com/presentation/d/10Ernk41ShOTf4IYkMD-l4dJfKATkXH4w/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Normalizing flows",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap16PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1SNtNIY7khlHQYMtaOH-FosSH3kWwL4b7",
|
||||
pptx: "https://docs.google.com/presentation/d/1nLLzqb9pdfF_h6i1HUDSyp7kSMIkSUUA/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Variational autoencoders",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap17PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1B9bxtmdugwtg-b7Y4AdQKAIEVWxjx8l3",
|
||||
pptx: "https://docs.google.com/presentation/d/1lQE4Bu7-LgvV2VlJOt_4dQT-kusYl7Vo/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Diffusion models",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap18PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1A-pIGl4PxjVMYOKAUG3aT4a8wD3G-q_r",
|
||||
pptx: "https://docs.google.com/presentation/d/1x_ufIBtVPzWUvRieKMkpw5SdRjXWwdfR/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Deep reinforcement learning",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap19PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1a5WUoF7jeSgwC_PVdckJi1Gny46fCqh0",
|
||||
pptx: "https://docs.google.com/presentation/d/1TnYmVbFNhmMFetbjyfXGmkxp1EHauMqr/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Why does deep learning work?",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap20PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1M2d0DHEgddAQoIedKSDTTt7m1ZdmBLQ3",
|
||||
pptx: "https://docs.google.com/presentation/d/1coxF4IsrCzDTLrNjRagHvqB_FBy10miA/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Deep learning and ethics",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLChap21PDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1jixmFfwmZkW_UVYzcxmDcMsdFFtnZ0bU",
|
||||
pptx: "https://docs.google.com/presentation/d/1EtfzanZYILvi9_-Idm28zD94I_6OrN9R/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Appendices",
|
||||
links: {
|
||||
pdf: "https://github.com/udlbook/udlbook/raw/main/PDFFigures/UDLAppendixPDF.zip",
|
||||
svg: "https://drive.google.com/uc?export=download&id=1k2j7hMN40ISPSg9skFYWFL3oZT7r8v-l",
|
||||
pptx: "https://docs.google.com/presentation/d/1_2cJHRnsoQQHst0rwZssv-XH4o5SEHks/edit?usp=drive_link&ouid=110441678248547154185&rtpof=true&sd=true",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export default function InstructorsSection() {
|
||||
return (
|
||||
<>
|
||||
<InstructorsContainer lightBg={true} id="Instructors">
|
||||
<InstructorsWrapper>
|
||||
<InstructorsRow imgStart={false}>
|
||||
<Column1>
|
||||
<TextWrapper>
|
||||
<TopLine>Instructors</TopLine>
|
||||
<Heading lightText={false}>Resources for instructors</Heading>
|
||||
<Subtitle darkText={true}>
|
||||
All the figures in vector and image formats, full slides for
|
||||
first twelve chapters, instructor answer booklet
|
||||
</Subtitle>
|
||||
</TextWrapper>
|
||||
</Column1>
|
||||
<Column2>
|
||||
<ImgWrap>
|
||||
<Img src={img} alt="Instructor" />
|
||||
</ImgWrap>
|
||||
</Column2>
|
||||
</InstructorsRow>
|
||||
<InstructorsRow2>
|
||||
<Column1>
|
||||
<TopLine>Register</TopLine>
|
||||
<InstructorsLink href="https://mitpress.ublish.com/request?cri=15055">
|
||||
Register
|
||||
</InstructorsLink>{" "}
|
||||
with MIT Press for answer booklet.
|
||||
<InstructorsContent></InstructorsContent>
|
||||
<TopLine>Full slides</TopLine>
|
||||
<InstructorsContent>
|
||||
Slides for 20 lecture undergraduate deep learning course:
|
||||
</InstructorsContent>
|
||||
<InstructorsContent>
|
||||
<ol>
|
||||
{fullSlides.map((slide, index) => (
|
||||
<li key={index}>
|
||||
{slide.text}{" "}
|
||||
<InstructorsLink href={slide.link}>
|
||||
PPTX
|
||||
</InstructorsLink>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</InstructorsContent>
|
||||
</Column1>
|
||||
<Column2>
|
||||
<TopLine>Figures</TopLine>
|
||||
<InstructorsContent>
|
||||
<ol>
|
||||
{figures.map((figure, index) => (
|
||||
<li key={index}>
|
||||
{figure.text}:{" "}
|
||||
<InstructorsLink href={figure.links.pdf}>
|
||||
PDF
|
||||
</InstructorsLink>{" "}
|
||||
/{" "}
|
||||
<InstructorsLink href={figure.links.svg}>
|
||||
{" "}
|
||||
SVG
|
||||
</InstructorsLink>{" "}
|
||||
/{" "}
|
||||
<InstructorsLink href={figure.links.pptx}>
|
||||
PPTX{" "}
|
||||
</InstructorsLink>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</InstructorsContent>
|
||||
<InstructorsLink href="https://drive.google.com/file/d/1T_MXXVR4AfyMnlEFI-UVDh--FXI5deAp/view?usp=sharing">
|
||||
Instructions
|
||||
</InstructorsLink>{" "}
|
||||
for editing equations in figures.
|
||||
<InstructorsContent></InstructorsContent>
|
||||
</Column2>
|
||||
</InstructorsRow2>
|
||||
</InstructorsWrapper>
|
||||
</InstructorsContainer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
179
src/components/Media/MediaElements.jsx
Normal file
179
src/components/Media/MediaElements.jsx
Normal file
@@ -0,0 +1,179 @@
|
||||
import styled from "styled-components";
|
||||
|
||||
export const MediaContainer = styled.div`
|
||||
color: #fff;
|
||||
/* background: #f9f9f9; */
|
||||
background: ${({ lightBg }) => (lightBg ? "#f9f9f9" : "#010606")};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
padding: 100px 0;
|
||||
}
|
||||
`;
|
||||
|
||||
export const MediaWrapper = styled.div`
|
||||
display: grid;
|
||||
z-index: 1;
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
margin-right: auto;
|
||||
margin-left: auto;
|
||||
padding: 0 24px;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
export const MediaRow = styled.div`
|
||||
display: grid;
|
||||
grid-auto-columns: minmax(auto, 1fr);
|
||||
align-items: center;
|
||||
grid-template-areas: ${({ imgStart }) => (imgStart ? `'col2 col1'` : `'col1 col2'`)};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
grid-template-areas: ${({ imgStart }) =>
|
||||
imgStart ? `'col1' 'col2'` : `'col1 col1' 'col2 col2'`};
|
||||
}
|
||||
`;
|
||||
|
||||
export const Column1 = styled.div`
|
||||
margin-bottom: 15px;
|
||||
padding: 0 15px;
|
||||
grid-area: col1;
|
||||
`;
|
||||
|
||||
export const Column2 = styled.div`
|
||||
margin-bottom: 15px;
|
||||
padding: 0 15px;
|
||||
grid-area: col2;
|
||||
`;
|
||||
|
||||
export const TextWrapper = styled.div`
|
||||
max-width: 540px;
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
`;
|
||||
|
||||
export const TopLine = styled.p`
|
||||
color: #57c6d1;
|
||||
font-size: 16px;
|
||||
line-height: 16px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 1.4px;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 16px;
|
||||
`;
|
||||
|
||||
export const Heading = styled.h1`
|
||||
margin-bottom: 24px;
|
||||
font-size: 48px;
|
||||
line-height: 1.1;
|
||||
font-weight: 600;
|
||||
color: ${({ lightText }) => (lightText ? "#f7f8fa" : "#010606")};
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 32px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const Subtitle = styled.p`
|
||||
max-width: 440px;
|
||||
margin-bottom: 35px;
|
||||
font-size: 18px;
|
||||
line-height: 24px;
|
||||
color: ${({ darkText }) => (darkText ? "#010606" : "#fff")};
|
||||
`;
|
||||
|
||||
export const BtnWrap = styled.div`
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
`;
|
||||
|
||||
export const ImgWrap = styled.div`
|
||||
max-width: 555px;
|
||||
height: 100%;
|
||||
`;
|
||||
|
||||
export const Img = styled.img`
|
||||
width: 100%;
|
||||
margin-top: 0;
|
||||
margin-right: 0;
|
||||
margin-left: 10px;
|
||||
padding-right: 0;
|
||||
`;
|
||||
|
||||
export const MediaTextBlock = styled.div`
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 18px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const MediaContent = styled.div`
|
||||
z-index: 3;
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
position: static;
|
||||
padding: 8px 0px;
|
||||
margin: 10px 0px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: left;
|
||||
list-style-position: inside;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 14px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const MediaRow2 = styled.div`
|
||||
display: grid;
|
||||
grid-auto-columns: minmax(auto, 1fr);
|
||||
align-items: top;
|
||||
grid-template-areas: ${({ imgStart }) => (imgStart ? `'col2 col1'` : `'col1 col2'`)};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
grid-template-areas: ${({ imgStart }) =>
|
||||
imgStart ? `'col1' 'col2'` : `'col1 col1' 'col2 col2'`};
|
||||
}
|
||||
`;
|
||||
|
||||
export const VideoFrame = styled.div`
|
||||
width: 560px;
|
||||
height: 315px;
|
||||
|
||||
@media screen and (max-width: 1050px) {
|
||||
width: 280px;
|
||||
height: 157px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const MediaLink = styled.a`
|
||||
text-decoration: none;
|
||||
color: #57c6d1;
|
||||
font-weight: 300;
|
||||
margin: 0 2px;
|
||||
position: relative;
|
||||
|
||||
&:before {
|
||||
position: absolute;
|
||||
margin: 0 auto;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background-color: #57c6d1;
|
||||
content: "";
|
||||
opacity: 0.3;
|
||||
-webkit-transform: scaleX(1);
|
||||
transition-property:
|
||||
opacity,
|
||||
-webkit-transform;
|
||||
transition-duration: 0.3s;
|
||||
}
|
||||
|
||||
&:hover:before {
|
||||
opacity: 1;
|
||||
-webkit-transform: scaleX(1.05);
|
||||
}
|
||||
`;
|
||||
164
src/components/Media/index.jsx
Normal file
164
src/components/Media/index.jsx
Normal file
@@ -0,0 +1,164 @@
|
||||
import {
|
||||
Column1,
|
||||
Column2,
|
||||
Heading,
|
||||
Img,
|
||||
ImgWrap,
|
||||
MediaContainer,
|
||||
MediaContent,
|
||||
MediaLink,
|
||||
MediaRow,
|
||||
MediaRow2,
|
||||
MediaWrapper,
|
||||
Subtitle,
|
||||
TextWrapper,
|
||||
TopLine,
|
||||
VideoFrame,
|
||||
} from "@/components/Media/MediaElements";
|
||||
import img from "@/images/media.svg";
|
||||
|
||||
const interviews = [
|
||||
{
|
||||
href: "https://www.borealisai.com/news/understanding-deep-learning/",
|
||||
text: "Borealis AI",
|
||||
linkText: "interview",
|
||||
},
|
||||
{
|
||||
href: "https://shepherd.com/best-books/machine-learning-and-deep-neural-networks",
|
||||
text: "Shepherd ML book",
|
||||
linkText: "recommendations",
|
||||
},
|
||||
];
|
||||
|
||||
export default function MediaSection() {
|
||||
return (
|
||||
<>
|
||||
<MediaContainer lightBg={false} id="Media">
|
||||
<MediaWrapper>
|
||||
<MediaRow imgStart={true}>
|
||||
<Column1>
|
||||
<TextWrapper>
|
||||
<TopLine>Media</TopLine>
|
||||
<Heading lightText={true}>
|
||||
Reviews, videos, podcasts, interviews
|
||||
</Heading>
|
||||
<Subtitle darkText={false}>
|
||||
Various resources connected to the book
|
||||
</Subtitle>
|
||||
</TextWrapper>
|
||||
</Column1>
|
||||
<Column2>
|
||||
<ImgWrap>
|
||||
<Img src={img} alt="Media" />
|
||||
</ImgWrap>
|
||||
</Column2>
|
||||
</MediaRow>
|
||||
<MediaRow>
|
||||
<Column1>
|
||||
Machine learning street talk podcast
|
||||
<VideoFrame>
|
||||
<iframe
|
||||
width="100%"
|
||||
height="100%"
|
||||
src="https://www.youtube.com/embed/sJXn4Cl4oww?si=Lm_hQPqj0RXy-75H&controls=0"
|
||||
title="YouTube video player"
|
||||
frameBorder="2"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
allowfullscreen
|
||||
></iframe>
|
||||
</VideoFrame>
|
||||
</Column1>
|
||||
<Column2>
|
||||
Deeper insights podcast
|
||||
<VideoFrame>
|
||||
<iframe
|
||||
width="100%"
|
||||
height="100%"
|
||||
src="https://www.youtube.com/embed/nQf4o9TDSHI?si=uMk66zLD7uhuSnQ1&controls=0"
|
||||
title="YouTube video player"
|
||||
frameBorder="2"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
||||
allowfullscreen
|
||||
></iframe>
|
||||
</VideoFrame>
|
||||
</Column2>
|
||||
</MediaRow>
|
||||
<MediaRow2>
|
||||
<Column1>
|
||||
<TopLine>Reviews</TopLine>
|
||||
<MediaContent>
|
||||
{/* TODO: add dynamic rendering for reviews */}
|
||||
<ul>
|
||||
<li>
|
||||
Nature Machine Intelligence{" "}
|
||||
<MediaLink href="https://github.com/udlbook/udlbook/blob/main/public/NMI_Review.pdf">
|
||||
{" "}
|
||||
review{" "}
|
||||
</MediaLink>{" "}
|
||||
by{" "}
|
||||
<MediaLink href="https://wang-axis.github.io/">
|
||||
Ge Wang
|
||||
</MediaLink>
|
||||
</li>
|
||||
<li>
|
||||
Amazon{" "}
|
||||
<MediaLink href="https://www.amazon.com/Understanding-Deep-Learning-Simon-Prince-ebook/product-reviews/B0BXKH8XY6/">
|
||||
reviews
|
||||
</MediaLink>
|
||||
</li>
|
||||
<li>
|
||||
Goodreads{" "}
|
||||
<MediaLink href="https://www.goodreads.com/book/show/123239819-understanding-deep-learning?">
|
||||
reviews{" "}
|
||||
</MediaLink>
|
||||
</li>
|
||||
<li>
|
||||
Book{" "}
|
||||
<MediaLink href="https://medium.com/@vishalvignesh/udl-book-review-the-new-deep-learning-textbook-youll-want-to-finish-69e1557b018d">
|
||||
review
|
||||
</MediaLink>{" "}
|
||||
by Vishal V.
|
||||
</li>
|
||||
<li>
|
||||
Amazon{" "}
|
||||
<MediaLink href="https://www.amazon.com/Understanding-Deep-Learning-Simon-Prince-ebook/product-reviews/B0BXKH8XY6/">
|
||||
reviews
|
||||
</MediaLink>
|
||||
</li>
|
||||
<li>
|
||||
Goodreads{" "}
|
||||
<MediaLink href="https://www.goodreads.com/book/show/123239819-understanding-deep-learning?">
|
||||
reviews{" "}
|
||||
</MediaLink>
|
||||
</li>
|
||||
<li>
|
||||
Book{" "}
|
||||
<MediaLink href="https://medium.com/@vishalvignesh/udl-book-review-the-new-deep-learning-textbook-youll-want-to-finish-69e1557b018d">
|
||||
review
|
||||
</MediaLink>{" "}
|
||||
by Vishal V.
|
||||
</li>
|
||||
</ul>
|
||||
</MediaContent>
|
||||
</Column1>
|
||||
<Column2>
|
||||
<TopLine>Interviews</TopLine>
|
||||
<MediaContent>
|
||||
<ul>
|
||||
{interviews.map((interview, index) => (
|
||||
<li key={index}>
|
||||
{interview.text}{" "}
|
||||
<MediaLink href={interview.href}>
|
||||
{interview.linkText}
|
||||
</MediaLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</MediaContent>
|
||||
</Column2>
|
||||
</MediaRow2>
|
||||
</MediaWrapper>
|
||||
</MediaContainer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
183
src/components/More/MoreElements.jsx
Normal file
183
src/components/More/MoreElements.jsx
Normal file
@@ -0,0 +1,183 @@
|
||||
import styled from "styled-components";
|
||||
|
||||
export const MoreContainer = styled.div`
|
||||
color: #fff;
|
||||
/* background: #f9f9f9; */
|
||||
background: ${({ lightBg }) => (lightBg ? "#57c6d1" : "#010606")};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
padding: 100px 0;
|
||||
}
|
||||
`;
|
||||
|
||||
export const MoreWrapper = styled.div`
|
||||
display: grid;
|
||||
z-index: 1;
|
||||
/* height: 1050px; */
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
margin-right: auto;
|
||||
margin-left: auto;
|
||||
padding: 0 24px;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
export const MoreRow = styled.div`
|
||||
display: grid;
|
||||
grid-auto-columns: minmax(auto, 1fr);
|
||||
align-items: center;
|
||||
grid-template-areas: ${({ imgStart }) => (imgStart ? `'col2 col1'` : `'col1 col2'`)};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
grid-template-areas: ${({ imgStart }) =>
|
||||
imgStart ? `'col1' 'col2'` : `'col1 col1' 'col2 col2'`};
|
||||
}
|
||||
`;
|
||||
|
||||
export const MoreRow2 = styled.div`
|
||||
display: grid;
|
||||
grid-auto-columns: minmax(auto, 1fr);
|
||||
align-items: top;
|
||||
grid-template-areas: ${({ imgStart }) => (imgStart ? `'col2 col1'` : `'col1 col2'`)};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
grid-template-areas: ${({ imgStart }) =>
|
||||
imgStart ? `'col1' 'col2'` : `'col1 col1' 'col2 col2'`};
|
||||
}
|
||||
`;
|
||||
|
||||
export const Column1 = styled.div`
|
||||
margin-bottom: 15px;
|
||||
padding: 0 15px;
|
||||
grid-area: col1;
|
||||
`;
|
||||
|
||||
export const Column2 = styled.div`
|
||||
margin-bottom: 15px;
|
||||
padding: 0 15px;
|
||||
grid-area: col2;
|
||||
`;
|
||||
|
||||
export const TextWrapper = styled.div`
|
||||
max-width: 540px;
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
`;
|
||||
|
||||
export const TopLine = styled.p`
|
||||
color: #773c23;
|
||||
font-size: 16px;
|
||||
line-height: 16px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 1.4px;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 12px;
|
||||
margin-top: 16px;
|
||||
`;
|
||||
|
||||
export const Heading = styled.h1`
|
||||
margin-bottom: 24px;
|
||||
font-size: 48px;
|
||||
line-height: 1.1;
|
||||
font-weight: 600;
|
||||
color: ${({ lightText }) => (lightText ? "#f7f8fa" : "#010606")};
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 32px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const Subtitle = styled.p`
|
||||
max-width: 440px;
|
||||
margin-bottom: 35px;
|
||||
font-size: 18px;
|
||||
line-height: 24px;
|
||||
color: ${({ darkText }) => (darkText ? "#010606" : "#fff")};
|
||||
`;
|
||||
|
||||
export const BtnWrap = styled.div`
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
`;
|
||||
|
||||
export const ImgWrap = styled.div`
|
||||
max-width: 555px;
|
||||
height: 100%;
|
||||
`;
|
||||
|
||||
export const Img = styled.img`
|
||||
width: 100%;
|
||||
margin-top: 0;
|
||||
margin-right: 0;
|
||||
margin-left: 10px;
|
||||
padding-right: 0;
|
||||
`;
|
||||
|
||||
export const MoreContent = styled.div`
|
||||
z-index: 3;
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
position: static;
|
||||
padding: 8px 0px;
|
||||
margin: 10px 0px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: left;
|
||||
list-style-position: inside;
|
||||
`;
|
||||
|
||||
export const MoreOuterList = styled.ul`
|
||||
/* list-style:none; */
|
||||
list-style-position: inside;
|
||||
margin: 0;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 14px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const MoreInnerList = styled.ul`
|
||||
list-style-position: inside;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const MoreInnerP = styled.p`
|
||||
padding-left: 18px;
|
||||
padding-bottom: 10px;
|
||||
padding-top: 3px;
|
||||
font-size: 14px;
|
||||
color: #fff;
|
||||
`;
|
||||
|
||||
export const MoreLink = styled.a`
|
||||
text-decoration: none;
|
||||
color: #555;
|
||||
font-weight: 300;
|
||||
margin: 0 2px;
|
||||
position: relative;
|
||||
|
||||
&:before {
|
||||
position: absolute;
|
||||
margin: 0 auto;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background-color: #555;
|
||||
content: "";
|
||||
opacity: 0.3;
|
||||
-webkit-transform: scaleX(1);
|
||||
transition-property:
|
||||
opacity,
|
||||
-webkit-transform;
|
||||
transition-duration: 0.3s;
|
||||
}
|
||||
|
||||
&:hover:before {
|
||||
opacity: 1;
|
||||
-webkit-transform: scaleX(1.05);
|
||||
}
|
||||
`;
|
||||
933
src/components/More/index.jsx
Normal file
933
src/components/More/index.jsx
Normal file
@@ -0,0 +1,933 @@
|
||||
import {
|
||||
Column1,
|
||||
Column2,
|
||||
Heading,
|
||||
Img,
|
||||
ImgWrap,
|
||||
MoreContainer,
|
||||
MoreInnerList,
|
||||
MoreInnerP,
|
||||
MoreLink,
|
||||
MoreOuterList,
|
||||
MoreRow,
|
||||
MoreRow2,
|
||||
MoreWrapper,
|
||||
Subtitle,
|
||||
TextWrapper,
|
||||
TopLine,
|
||||
} from "@/components/More/MoreElements";
|
||||
import img from "@/images/more.svg";
|
||||
|
||||
const book = [
|
||||
{
|
||||
text: "Computer vision: models, learning, and inference",
|
||||
link: "http://computervisionmodels.com",
|
||||
details: [
|
||||
"2012 book published with CUP",
|
||||
"Focused on probabilistic models",
|
||||
'Pre-"deep learning"',
|
||||
"Lots of ML content",
|
||||
"Individual chapters available below",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const transformersAndLLMs = [
|
||||
{
|
||||
text: "Intro to LLMs",
|
||||
link: "https://www.borealisai.com/research-blogs/a-high-level-overview-of-large-language-models/",
|
||||
details: [
|
||||
"What is an LLM?",
|
||||
"Pretraining",
|
||||
"Instruction fine-tuning",
|
||||
"Reinforcement learning from human feedback",
|
||||
"Notable LLMs",
|
||||
"LLMs without training from scratch",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Transformers I",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-14-transformers-i-introduction/",
|
||||
details: [
|
||||
"Dot-Product self-attention",
|
||||
"Scaled dot-product self-attention",
|
||||
"Position encoding",
|
||||
"Multiple heads",
|
||||
"Transformer block",
|
||||
"Encoders",
|
||||
"Decoders",
|
||||
"Encoder-Decoders",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Transformers II",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-16-transformers-ii-extensions/",
|
||||
details: [
|
||||
"Sinusoidal position embeddings",
|
||||
"Learned position embeddings",
|
||||
"Relatives vs. absolute position embeddings",
|
||||
"Extending transformers to longer sequences",
|
||||
"Reducing attention matrix size",
|
||||
"Making attention matrix sparse",
|
||||
"Kernelizing attention computation",
|
||||
"Attention as an RNN",
|
||||
"Attention as a hypernetwork",
|
||||
"Attention as a routing network",
|
||||
"Attention and graphs",
|
||||
"Attention and convolutions",
|
||||
"Attention and gating",
|
||||
"Attention and memory retrieval",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Transformers III",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-17-transformers-iii-training/",
|
||||
details: [
|
||||
"Tricks for training transformers",
|
||||
"Why are these tricks required?",
|
||||
"Removing layer normalization",
|
||||
"Balancing residual dependencies",
|
||||
"Reducing optimizer variance",
|
||||
"How to train deeper transformers on small datasets",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Training and fine-tuning LLMs",
|
||||
link: "https://www.borealisai.com/research-blogs/training-and-fine-tuning-large-language-models/",
|
||||
details: [
|
||||
"Large language models",
|
||||
"Pretraining",
|
||||
"Supervised fine tuning",
|
||||
"Reinforcement learning from human feedback",
|
||||
"Direct preference optimization",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Speeding up inference in LLMs",
|
||||
link: "https://www.borealisai.com/research-blogs/speeding-up-inference-in-transformers/",
|
||||
details: [
|
||||
"Problems with transformers",
|
||||
"Attention-free transformers",
|
||||
"Complexity",
|
||||
"RWKV",
|
||||
"Linear transformers and performers",
|
||||
"Retentive network",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const mathForMachineLearning = [
|
||||
{
|
||||
text: "Linear algebra",
|
||||
link: "https://drive.google.com/file/d/1j2v2n6STPnblOCZ1_GBcVAZrsYkjPYwR/view?usp=sharing",
|
||||
details: [
|
||||
"Vectors and matrices",
|
||||
"Determinant and trace",
|
||||
"Orthogonal matrices",
|
||||
"Null space",
|
||||
"Linear transformations",
|
||||
"Singular value decomposition",
|
||||
"Least squares problems",
|
||||
"Principal direction problems",
|
||||
"Inversion of block matrices",
|
||||
"Schur complement identity",
|
||||
"Sherman-Morrison-Woodbury",
|
||||
"Matrix determinant lemma",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Introduction to probability",
|
||||
link: "https://drive.google.com/file/d/1cmxXneW122-hcfmMRjEE-n5C9T2YvuQX/view?usp=sharing",
|
||||
details: [
|
||||
"Random variables",
|
||||
"Joint probability",
|
||||
"Marginal probability",
|
||||
"Conditional probability",
|
||||
"Bayes' rule",
|
||||
"Independence",
|
||||
"Expectation",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Probability distributions",
|
||||
link: "https://drive.google.com/file/d/1GI3eZNB1CjTqYHLyuRhCV215rwqANVOx/view?usp=sharing",
|
||||
details: [
|
||||
"Bernouilli distribution",
|
||||
"Beta distribution",
|
||||
"Categorical distribution",
|
||||
"Dirichlet distribution",
|
||||
"Univariate normal distribution",
|
||||
"Normal inverse-scaled gamma distribution",
|
||||
"Multivariate normal distribution",
|
||||
"Normal inverse Wishart distribution",
|
||||
"Conjugacy",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Fitting probability distributions",
|
||||
link: "https://drive.google.com/file/d/1DZ4rCmC7AZ8PFc51PiMUIkBO-xqKT_CG/view?usp=sharing",
|
||||
details: [
|
||||
"Maximum likelihood",
|
||||
"Maximum a posteriori",
|
||||
"Bayesian approach",
|
||||
"Example: fitting normal",
|
||||
"Example: fitting categorical",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "The normal distribution",
|
||||
link: "https://drive.google.com/file/d/1CTfmsN-HJWZBRj8lY0ZhgHEbPCmYXWnA/view?usp=sharing",
|
||||
details: [
|
||||
"Types of covariance matrix",
|
||||
"Decomposition of covariance",
|
||||
"Linear transformations",
|
||||
"Marginal distributions",
|
||||
"Conditional distributions",
|
||||
"Product of two normals",
|
||||
"Change of variable formula",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const optimization = [
|
||||
{
|
||||
text: "Gradient-based optimization",
|
||||
link: "https://drive.google.com/file/d/1IoOSfJ0ku89aVyM9qygPl4MVnAhMEbAZ/view?usp=sharing",
|
||||
details: [
|
||||
"Convexity",
|
||||
"Steepest descent",
|
||||
"Newton's method",
|
||||
"Gauss-Newton method",
|
||||
"Line search",
|
||||
"Reparameterization",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Bayesian optimization",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-8-bayesian-optimization/",
|
||||
details: [
|
||||
"Gaussian processes",
|
||||
"Acquisition functions",
|
||||
"Incorporating noise",
|
||||
"Kernel choice",
|
||||
"Learning GP parameters",
|
||||
"Tips, tricks, and limitations",
|
||||
"Beta-Bernoulli bandit",
|
||||
"Random forests for BO",
|
||||
"Tree-Parzen estimators",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "SAT Solvers I",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-9-sat-solvers-i-introduction-and-applications/",
|
||||
details: [
|
||||
"Boolean logic and satisfiability",
|
||||
"Conjunctive normal form",
|
||||
"The Tseitin transformation",
|
||||
"SAT and related problems",
|
||||
"SAT constructions",
|
||||
"Graph coloring and scheduling",
|
||||
"Fitting binary neural networks",
|
||||
"Fitting decision trees",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "SAT Solvers II",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-10-sat-solvers-ii-algorithms/",
|
||||
details: [
|
||||
"Conditioning",
|
||||
"Resolution",
|
||||
"Solving 2-SAT by unit propagation",
|
||||
"Directional resolution",
|
||||
"SAT as binary search",
|
||||
"DPLL",
|
||||
"Conflict driven clause learning",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "SAT Solvers III",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-11-sat-solvers-iii-factor-graphs-and-smt-solvers/",
|
||||
details: [
|
||||
"Satisfiability vs. problem size",
|
||||
"Factor graph representation",
|
||||
"Max product / sum product for SAT",
|
||||
"Survey propagation",
|
||||
"SAT with non-binary variables",
|
||||
"SMT solvers",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const temporalModels = [
|
||||
{
|
||||
text: "Temporal models",
|
||||
link: "https://drive.google.com/file/d/1rrzGNyZDjXQ3_9ZqCGDmRMM3GYtHSBvj/view?usp=sharing",
|
||||
details: [
|
||||
"Kalman filter",
|
||||
"Smoothing",
|
||||
"Extended Kalman filter",
|
||||
"Unscented Kalman filter",
|
||||
"Particle filtering",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const computerVision = [
|
||||
{
|
||||
text: "Image Processing",
|
||||
link: "https://drive.google.com/file/d/1r3V1GC5grhPF2pD91izuE0hTrTUEpQ9I/view?usp=sharing",
|
||||
details: [
|
||||
"Whitening",
|
||||
"Histogram equalization",
|
||||
"Filtering",
|
||||
"Edges and corners",
|
||||
"Dimensionality reduction",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Pinhole camera",
|
||||
link: "https://drive.google.com/file/d/1dbMBE13MWcd84dEGjYeWsC6eXouoC0xn/view?usp=sharing",
|
||||
details: [
|
||||
"Pinhole camera model",
|
||||
"Radial distortion",
|
||||
"Homogeneous coordinates",
|
||||
"Learning extrinsic parameters",
|
||||
"Learning intrinsic parameters",
|
||||
"Inferring three-dimensional world points",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Geometric transformations",
|
||||
link: "https://drive.google.com/file/d/1UArrb1ovqvZHbv90MufkW372r__ZZACQ/view?usp=sharing",
|
||||
details: [
|
||||
"Euclidean, similarity, affine, projective transformations",
|
||||
"Fitting transformation models",
|
||||
"Inference in transformation models",
|
||||
"Three geometric problems for planes",
|
||||
"Transformations between images",
|
||||
"Robust learning of transformations",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Multiple cameras",
|
||||
link: "https://drive.google.com/file/d/1RqUoc7kvK8vqZF1NVuw7bIex9v4_QlSx/view?usp=sharing",
|
||||
details: [
|
||||
"Two view geometry",
|
||||
"The essential matrix",
|
||||
"The fundamental matrix",
|
||||
"Two-view reconstruction pipeline",
|
||||
"Rectification",
|
||||
"Multiview reconstruction",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const reinforcementLearning = [
|
||||
{
|
||||
text: "Transformers in RL",
|
||||
link: "https://arxiv.org/abs/2307.05979",
|
||||
details: [
|
||||
"Challenges in RL",
|
||||
"Advantages of transformers for RL",
|
||||
"Representation learning",
|
||||
"Transition function learning",
|
||||
"Reward learning",
|
||||
"Policy learning",
|
||||
"Training strategy",
|
||||
"Interpretability",
|
||||
"Applications",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const aiTheory = [
|
||||
{
|
||||
text: "Gradient flow",
|
||||
link: "https://www.borealisai.com/research-blogs/gradient-flow/",
|
||||
details: [
|
||||
"Gradient flow",
|
||||
"Evolution of residual",
|
||||
"Evolution of parameters",
|
||||
"Evolution of model predictions",
|
||||
"Evolution of prediction covariance",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Neural tangent kernel",
|
||||
link: "https://www.borealisai.com/research-blogs/the-neural-tangent-kernel/",
|
||||
details: [
|
||||
"Infinite width neural networks",
|
||||
"Training dynamics",
|
||||
"Empirical NTK for shallow network",
|
||||
"Analytical NTK for shallow network",
|
||||
"Empirical NTK for deep network",
|
||||
"Analytical NTK for deep network",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "NTK applications",
|
||||
link: "https://www.borealisai.com/research-blogs/neural-tangent-kernel-applications/",
|
||||
details: [
|
||||
"Trainability",
|
||||
"Convergence bounds",
|
||||
"Evolution of parameters",
|
||||
"Evolution of predictions",
|
||||
"NTK Gaussian processes",
|
||||
"NTK and generalizability",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const unsupervisedLearning = [
|
||||
{
|
||||
text: "Modeling complex data densities",
|
||||
link: "https://drive.google.com/file/d/1BrPHxAuyz28hhz_FtbO0A1cWYdMs2_h8/view?usp=sharing",
|
||||
details: [
|
||||
"Hidden variables",
|
||||
"Expectation maximization",
|
||||
"Mixture of Gaussians",
|
||||
"The t-distribution",
|
||||
"Factor analysis",
|
||||
"The EM algorithm in detail",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Variational autoencoders",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-5-variational-auto-encoders/",
|
||||
details: [
|
||||
"Non-linear latent variable models",
|
||||
"Evidence lower bound (ELBO)",
|
||||
"ELBO properties",
|
||||
"Variational approximation",
|
||||
"The variational autoencoder",
|
||||
"Reparameterization trick",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Normalizing flows: introduction and review",
|
||||
link: "https://arxiv.org/abs/1908.09257",
|
||||
details: [
|
||||
"Normalizing flows",
|
||||
"Elementwise and linear flows",
|
||||
"Planar and radial flows",
|
||||
"Coupling and auto-regressive flows",
|
||||
"Coupling functions",
|
||||
"Residual flows",
|
||||
"Infinitesimal (continuous) flows",
|
||||
"Datasets and performance",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const graphicalModels = [
|
||||
{
|
||||
text: "Graphical models",
|
||||
link: "https://drive.google.com/file/d/1ghgeRmeZMyzNHcuzVwS4vRP6BXi3npVO/view?usp=sharing",
|
||||
details: [
|
||||
"Conditional independence",
|
||||
"Directed graphical models",
|
||||
"Undirected graphical models",
|
||||
"Inference in graphical models",
|
||||
"Sampling in graphical models",
|
||||
"Learning in graphical models",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Models for chains and trees",
|
||||
link: "https://drive.google.com/file/d/1WAMc3wtZoPv5wRkdF-D0SShVYF6Net84/view?usp=sharing",
|
||||
details: [
|
||||
"Hidden Markov models",
|
||||
"Viterbi algorithm",
|
||||
"Forward-backward algorithm",
|
||||
"Belief propagation",
|
||||
"Sum product algorithm",
|
||||
"Extension to trees",
|
||||
"Graphs with loops",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Models for grids",
|
||||
link: "https://drive.google.com/file/d/1qqS9OfA1z7t12M45UaBr4CSCj1jwzcwz/view?usp=sharing",
|
||||
details: [
|
||||
"Markov random fields",
|
||||
"MAP inference in binary pairwise MRFs",
|
||||
"Graph cuts",
|
||||
"Multi-label pairwise MRFs",
|
||||
"Alpha-expansion algorithm",
|
||||
"Conditional random fields",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const machineLearning = [
|
||||
{
|
||||
text: "Learning and inference",
|
||||
link: "https://drive.google.com/file/d/1ArWWi-qbzK2ih6KpOeIF8wX5g3S4J5DY/view?usp=sharing",
|
||||
details: [
|
||||
"Discriminative models",
|
||||
"Generative models",
|
||||
"Example: regression",
|
||||
"Example: classification",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Regression models",
|
||||
link: "https://drive.google.com/file/d/1QZX5jm4xN8rhpvdjRsFP5Ybw1EXSNGaL/view?usp=sharing",
|
||||
details: [
|
||||
"Linear regression",
|
||||
"Bayesian linear regression",
|
||||
"Non-linear regression",
|
||||
"Bayesian non-linear regression",
|
||||
"The kernel trick",
|
||||
"Gaussian process regression",
|
||||
"Sparse linear regression",
|
||||
"Relevance vector regression",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Classification models",
|
||||
link: "https://drive.google.com/file/d/1-_f4Yfm8iBWcaZ2Gyjw6O0eZiODipmSV/view?usp=sharing",
|
||||
details: [
|
||||
"Logistic regression",
|
||||
"Bayesian logistic regression",
|
||||
"Non-linear logistic regression",
|
||||
"Gaussian process classification",
|
||||
"Relevance vector classification",
|
||||
"Incremental fitting: boosting and trees",
|
||||
"Multi-class logistic regression",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Few-shot learning and meta-learning I",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-2-few-shot-learning-and-meta-learning-i/",
|
||||
details: [
|
||||
"Meta-learning framework",
|
||||
"Approaches to meta-learning",
|
||||
"Matching networks",
|
||||
"Prototypical networks",
|
||||
"Relation networks",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Few-shot learning and meta-learning II",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-3-few-shot-learning-and-meta-learning-ii/",
|
||||
details: [
|
||||
"MAML & Reptile",
|
||||
"LSTM based meta-learning",
|
||||
"Reinforcement learning based approaches",
|
||||
"Memory augmented neural networks",
|
||||
"SNAIL",
|
||||
"Generative models",
|
||||
"Data augmentation approaches",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const nlp = [
|
||||
{
|
||||
text: "Neural natural language generation I",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-6-neural-natural-language-generation-decoding-algorithms/",
|
||||
details: [
|
||||
"Encoder-decoder architecture",
|
||||
"Maximum-likelihood training",
|
||||
"Greedy search",
|
||||
"Beam search",
|
||||
"Diverse beam search",
|
||||
"Top-k sampling",
|
||||
"Nucleus sampling",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Neural natural language generation II",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-7-neural-natural-language-generation-sequence-level-training/",
|
||||
details: [
|
||||
"Fine-tuning with reinforcement learning",
|
||||
"Training from scratch with RL",
|
||||
"RL vs. structured prediction",
|
||||
"Minimum risk training",
|
||||
"Scheduled sampling",
|
||||
"Beam search optimization",
|
||||
"SeaRNN",
|
||||
"Reward-augmented maximum likelihood",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Parsing I",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-15-parsing-i-context-free-grammars-and-cyk-algorithm/",
|
||||
details: [
|
||||
"Parse trees",
|
||||
"Context-free grammars",
|
||||
"Chomsky normal form",
|
||||
"CYK recognition algorithm",
|
||||
"Worked example",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Parsing II",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-18-parsing-ii-wcfgs-inside-algorithm-and-weighted-parsing/",
|
||||
details: [
|
||||
"Weighted context-free grammars",
|
||||
"Semirings",
|
||||
"Inside algorithm",
|
||||
"Inside weights",
|
||||
"Weighted parsing",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Parsing III",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-19-parsing-iii-pcfgs-and-inside-outside-algorithm/",
|
||||
details: [
|
||||
"Probabilistic context-free grammars",
|
||||
"Parameter estimation (supervised)",
|
||||
"Parameter estimation (unsupervised)",
|
||||
"Viterbi training",
|
||||
"Expectation maximization",
|
||||
"Outside from inside",
|
||||
"Interpretation of outside weights",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "XLNet",
|
||||
link: "https://www.borealisai.com/en/blog/understanding-xlnet/",
|
||||
details: [
|
||||
"Language modeling",
|
||||
"XLNet training objective",
|
||||
"Permutations",
|
||||
"Attention mask",
|
||||
"Two stream self-attention",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const responsibleAI = [
|
||||
{
|
||||
text: "Bias and fairness",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial1-bias-and-fairness-ai/",
|
||||
details: [
|
||||
"Sources of bias",
|
||||
"Demographic Parity",
|
||||
"Equality of odds",
|
||||
"Equality of opportunity",
|
||||
"Individual fairness",
|
||||
"Bias mitigation",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Explainability I",
|
||||
link: "https://www.borealisai.com/research-blogs/explainability-i-local-post-hoc-explanations/",
|
||||
details: [
|
||||
"Taxonomy of XAI approaches",
|
||||
"Local post-hoc explanations",
|
||||
"Individual conditional explanation",
|
||||
"Counterfactual explanations",
|
||||
"LIME & Anchors",
|
||||
"Shapley additive explanations & SHAP",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Explainability II",
|
||||
link: "https://www.borealisai.com/research-blogs/explainability-ii-global-explanations-proxy-models-and-interpretable-models/",
|
||||
details: [
|
||||
"Global feature importance",
|
||||
"Partial dependence & ICE plots",
|
||||
"Accumulated local effects",
|
||||
"Aggregate SHAP values",
|
||||
"Prototypes & criticisms",
|
||||
"Surrogate / proxy models",
|
||||
"Inherently interpretable models",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Differential privacy I",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-12-differential-privacy-i-introduction/",
|
||||
details: [
|
||||
"Early approaches to privacy",
|
||||
"Fundamental law of information recovery",
|
||||
"Differential privacy",
|
||||
"Properties of differential privacy",
|
||||
"The Laplace mechanism",
|
||||
"Examples",
|
||||
"Other mechanisms and definitions",
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "Differential privacy II",
|
||||
link: "https://www.borealisai.com/en/blog/tutorial-13-differential-privacy-ii-machine-learning-and-data-generation/",
|
||||
details: [
|
||||
"Differential privacy and matchine learning",
|
||||
"DPSGD",
|
||||
"PATE",
|
||||
"Differentially private data generation",
|
||||
"DPGAN",
|
||||
"PateGAN",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export default function MoreSection() {
|
||||
return (
|
||||
<>
|
||||
<MoreContainer lightBg={true} id="More">
|
||||
<MoreWrapper>
|
||||
<MoreRow imgStart={false}>
|
||||
<Column1>
|
||||
<TextWrapper>
|
||||
<TopLine>More</TopLine>
|
||||
<Heading lightText={false}>Further reading</Heading>
|
||||
<Subtitle darkText={true}>
|
||||
Other articles, blogs, and books that I have written. Most in a
|
||||
similar style and using the same notation as Understanding Deep
|
||||
Learning.
|
||||
</Subtitle>
|
||||
</TextWrapper>
|
||||
</Column1>
|
||||
<Column2>
|
||||
<ImgWrap>
|
||||
<Img src={img} alt="More" />
|
||||
</ImgWrap>
|
||||
</Column2>
|
||||
</MoreRow>
|
||||
<MoreRow2>
|
||||
<Column1>
|
||||
<TopLine>Book</TopLine>
|
||||
<MoreOuterList>
|
||||
{book.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Transformers & LLMs</TopLine>
|
||||
<MoreOuterList>
|
||||
{transformersAndLLMs.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Math for machine learning</TopLine>
|
||||
<MoreOuterList>
|
||||
{mathForMachineLearning.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Optimization</TopLine>
|
||||
<MoreOuterList>
|
||||
{optimization.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Temporal models</TopLine>
|
||||
<MoreOuterList>
|
||||
{temporalModels.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Computer vision</TopLine>
|
||||
<MoreOuterList>
|
||||
{computerVision.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Reinforcement learning</TopLine>
|
||||
<MoreOuterList>
|
||||
{reinforcementLearning.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
</Column1>
|
||||
|
||||
<Column2>
|
||||
<TopLine>AI Theory</TopLine>
|
||||
<MoreOuterList>
|
||||
{aiTheory.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Unsupervised learning</TopLine>
|
||||
<MoreOuterList>
|
||||
{unsupervisedLearning.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Graphical Models</TopLine>
|
||||
<MoreOuterList>
|
||||
{graphicalModels.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Machine learning</TopLine>
|
||||
<MoreOuterList>
|
||||
{machineLearning.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Natural language processing</TopLine>
|
||||
<MoreOuterList>
|
||||
{nlp.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
|
||||
<TopLine>Responsible AI</TopLine>
|
||||
<MoreOuterList>
|
||||
{responsibleAI.map((item, index) => (
|
||||
<li key={index}>
|
||||
<MoreLink href={item.link} target="_blank" rel="noreferrer">
|
||||
{item.text}
|
||||
</MoreLink>
|
||||
<MoreInnerP>
|
||||
<MoreInnerList>
|
||||
{item.details.map((detail, index) => (
|
||||
<li key={index}>{detail}</li>
|
||||
))}
|
||||
</MoreInnerList>
|
||||
</MoreInnerP>
|
||||
</li>
|
||||
))}
|
||||
</MoreOuterList>
|
||||
</Column2>
|
||||
</MoreRow2>
|
||||
</MoreWrapper>
|
||||
</MoreContainer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
119
src/components/Navbar/NavbarElements.jsx
Executable file
119
src/components/Navbar/NavbarElements.jsx
Executable file
@@ -0,0 +1,119 @@
|
||||
import { Link as LinkR } from "react-router-dom";
|
||||
import { Link as LinkS } from "react-scroll";
|
||||
import styled from "styled-components";
|
||||
|
||||
export const Nav = styled.nav`
|
||||
background: ${({ scrollNav }) => (scrollNav ? "#000" : "transparent")};
|
||||
height: 100px;
|
||||
margin-top: -100px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-size: 1rem;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
|
||||
@media screen and (max-width: 960px) {
|
||||
transition: 0.8s all ease;
|
||||
}
|
||||
`;
|
||||
|
||||
export const NavbarContainer = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
height: 100px;
|
||||
z-index: 1;
|
||||
width: 100%;
|
||||
padding: 0 24px;
|
||||
max-width: 1100px;
|
||||
`;
|
||||
|
||||
export const NavLogo = styled(LinkR)`
|
||||
color: #fff;
|
||||
justify-self: flex-start;
|
||||
cursor: pointer;
|
||||
font-size: 1.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-left: 24px;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 1rem;
|
||||
}
|
||||
`;
|
||||
|
||||
export const MobileIcon = styled.div`
|
||||
display: none;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
display: block;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
transform: translate(-100%, 60%);
|
||||
font-size: 1.8rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
`;
|
||||
|
||||
export const NavMenu = styled.ul`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
list-style: none;
|
||||
text-align: center;
|
||||
margin-right: -22px;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
|
||||
export const NavItem = styled.li`
|
||||
height: 80px;
|
||||
`;
|
||||
|
||||
export const NavBtn = styled.nav`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
|
||||
export const NavLinks = styled(LinkS)`
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
text-decoration: none;
|
||||
padding: 0 1rem;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
|
||||
&.active {
|
||||
border-bottom: 3px solid #57c6d1;
|
||||
}
|
||||
`;
|
||||
|
||||
export const NavBtnLink = styled(LinkR)`
|
||||
border-radius: 50px;
|
||||
background: #01bf71;
|
||||
white-space: nowrap;
|
||||
padding: 10px 22px;
|
||||
color: #010606;
|
||||
font-size: 16px;
|
||||
outline: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease-in-out;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
transition: all 0.2s ease-in-out;
|
||||
background: #fff;
|
||||
color: #010606;
|
||||
}
|
||||
`;
|
||||
104
src/components/Navbar/index.jsx
Executable file
104
src/components/Navbar/index.jsx
Executable file
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
MobileIcon,
|
||||
Nav,
|
||||
NavbarContainer,
|
||||
NavItem,
|
||||
NavLinks,
|
||||
NavLogo,
|
||||
NavMenu,
|
||||
} from "@/components/Navbar/NavbarElements";
|
||||
import { useEffect, useState } from "react";
|
||||
import { FaBars } from "react-icons/fa";
|
||||
import { IconContext } from "react-icons/lib";
|
||||
import { animateScroll as scroll } from "react-scroll";
|
||||
|
||||
export default function Navbar({ toggle }) {
|
||||
const [scrollNav, setScrollNav] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const changeNav = () => {
|
||||
setScrollNav(window.scrollY >= 80);
|
||||
};
|
||||
|
||||
window.addEventListener("scroll", changeNav);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("scroll", changeNav);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const scrollToHome = () => {
|
||||
scroll.scrollToTop();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<IconContext.Provider value={{ color: "#fff" }}>
|
||||
<Nav scrollNav={scrollNav}>
|
||||
<NavbarContainer>
|
||||
<NavLogo to="/udlbook/" onClick={scrollToHome}>
|
||||
<h1> Understanding Deep Learning </h1>
|
||||
</NavLogo>
|
||||
<MobileIcon onClick={toggle}>
|
||||
<FaBars />
|
||||
</MobileIcon>
|
||||
<NavMenu>
|
||||
<NavItem>
|
||||
<NavLinks
|
||||
to="Notebooks"
|
||||
smooth={true}
|
||||
duration={500}
|
||||
spy={true}
|
||||
exact="true"
|
||||
offset={-80}
|
||||
activeClass="active"
|
||||
>
|
||||
Notebooks
|
||||
</NavLinks>
|
||||
</NavItem>
|
||||
<NavItem>
|
||||
<NavLinks
|
||||
to="Instructors"
|
||||
smooth={true}
|
||||
duration={500}
|
||||
spy={true}
|
||||
exact="true"
|
||||
offset={-80}
|
||||
activeClass="active"
|
||||
>
|
||||
Instructors
|
||||
</NavLinks>
|
||||
</NavItem>
|
||||
<NavItem>
|
||||
<NavLinks
|
||||
to="Media"
|
||||
smooth={true}
|
||||
duration={500}
|
||||
spy={true}
|
||||
exact="true"
|
||||
offset={-80}
|
||||
activeClass="active"
|
||||
>
|
||||
Media
|
||||
</NavLinks>
|
||||
</NavItem>
|
||||
<NavItem>
|
||||
<NavLinks
|
||||
to="More"
|
||||
smooth={true}
|
||||
duration={500}
|
||||
spy={true}
|
||||
exact="true"
|
||||
offset={-80}
|
||||
activeClass="active"
|
||||
>
|
||||
More
|
||||
</NavLinks>
|
||||
</NavItem>
|
||||
</NavMenu>
|
||||
</NavbarContainer>
|
||||
</Nav>
|
||||
</IconContext.Provider>
|
||||
</>
|
||||
);
|
||||
}
|
||||
147
src/components/Notebooks/NotebookElements.jsx
Normal file
147
src/components/Notebooks/NotebookElements.jsx
Normal file
@@ -0,0 +1,147 @@
|
||||
import styled from "styled-components";
|
||||
|
||||
export const NotebookContainer = styled.div`
|
||||
color: #fff;
|
||||
/* background: #f9f9f9; */
|
||||
background: ${({ lightBg }) => (lightBg ? "#f9f9f9" : "#010606")};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
padding: 100px 0;
|
||||
}
|
||||
`;
|
||||
|
||||
export const NotebookWrapper = styled.div`
|
||||
display: grid;
|
||||
z-index: 1;
|
||||
/* height: 1250px; */
|
||||
width: 100%;
|
||||
max-width: 1100px;
|
||||
margin-right: auto;
|
||||
margin-left: auto;
|
||||
padding: 0 24px;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
export const NotebookRow = styled.div`
|
||||
display: grid;
|
||||
grid-auto-columns: minmax(auto, 1fr);
|
||||
align-items: center;
|
||||
grid-template-areas: ${({ imgStart }) => (imgStart ? `'col2 col1'` : `'col1 col2'`)};
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
grid-template-areas: ${({ imgStart }) =>
|
||||
imgStart ? `'col1' 'col2'` : `'col1 col1' 'col2 col2'`};
|
||||
}
|
||||
`;
|
||||
|
||||
export const Column1 = styled.p`
|
||||
margin-bottom: 15px;
|
||||
padding: 0 15px;
|
||||
grid-area: col1;
|
||||
|
||||
@media screen and (max-width: 1050px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const Column2 = styled.p`
|
||||
margin-bottom: 15px;
|
||||
padding: 0 15px;
|
||||
grid-area: col2;
|
||||
|
||||
@media screen and (max-width: 1050px) {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
font-size: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const TextWrapper = styled.div`
|
||||
max-width: 540px;
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
`;
|
||||
|
||||
export const TopLine = styled.p`
|
||||
color: #57c6d1;
|
||||
font-size: 16px;
|
||||
line-height: 16px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 1.4px;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 16px;
|
||||
`;
|
||||
|
||||
export const Heading = styled.h1`
|
||||
margin-bottom: 24px;
|
||||
font-size: 48px;
|
||||
line-height: 1.1;
|
||||
font-weight: 600;
|
||||
color: ${({ lightText }) => (lightText ? "#f7f8fa" : "#010606")};
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
font-size: 32px;
|
||||
}
|
||||
`;
|
||||
|
||||
export const Subtitle = styled.p`
|
||||
max-width: 440px;
|
||||
margin-bottom: 35px;
|
||||
font-size: 18px;
|
||||
line-height: 24px;
|
||||
color: ${({ darkText }) => (darkText ? "#010606" : "#fff")};
|
||||
`;
|
||||
|
||||
export const BtnWrap = styled.div`
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
`;
|
||||
|
||||
export const ImgWrap = styled.div`
|
||||
max-width: 555px;
|
||||
height: 100%;
|
||||
`;
|
||||
|
||||
export const Img = styled.img`
|
||||
width: 100%;
|
||||
margin-top: 0;
|
||||
margin-right: 0;
|
||||
margin-left: 10px;
|
||||
padding-right: 0;
|
||||
`;
|
||||
|
||||
export const NBLink = styled.a`
|
||||
text-decoration: none;
|
||||
color: #57c6d1;
|
||||
font-weight: 300;
|
||||
margin: 0 2px;
|
||||
position: relative;
|
||||
|
||||
&:before {
|
||||
position: absolute;
|
||||
margin: 0 auto;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background-color: #57c6d1;
|
||||
content: "";
|
||||
opacity: 0.3;
|
||||
-webkit-transform: scaleX(1);
|
||||
transition-property:
|
||||
opacity,
|
||||
-webkit-transform;
|
||||
transition-duration: 0.3s;
|
||||
}
|
||||
|
||||
&:hover:before {
|
||||
opacity: 1;
|
||||
-webkit-transform: scaleX(1.05);
|
||||
}
|
||||
`;
|
||||
344
src/components/Notebooks/index.jsx
Normal file
344
src/components/Notebooks/index.jsx
Normal file
@@ -0,0 +1,344 @@
|
||||
import {
|
||||
Column1,
|
||||
Column2,
|
||||
Heading,
|
||||
Img,
|
||||
ImgWrap,
|
||||
NBLink,
|
||||
NotebookContainer,
|
||||
NotebookRow,
|
||||
NotebookWrapper,
|
||||
Subtitle,
|
||||
TextWrapper,
|
||||
TopLine,
|
||||
} from "@/components/Notebooks/NotebookElements";
|
||||
import img from "@/images/coding.svg";
|
||||
|
||||
const notebooks = [
|
||||
{
|
||||
text: "Notebook 1.1 - Background mathematics",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap01/1_1_BackgroundMathematics.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 2.1 - Supervised learning",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap02/2_1_Supervised_Learning.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 3.1 - Shallow networks I",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap03/3_1_Shallow_Networks_I.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 3.2 - Shallow networks II",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap03/3_2_Shallow_Networks_II.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 3.3 - Shallow network regions",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap03/3_3_Shallow_Network_Regions.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 3.4 - Activation functions",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap03/3_4_Activation_Functions.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 4.1 - Composing networks",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap04/4_1_Composing_Networks.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 4.2 - Clipping functions",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap04/4_2_Clipping_functions.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 4.3 - Deep networks",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap04/4_3_Deep_Networks.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 5.1 - Least squares loss",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap05/5_1_Least_Squares_Loss.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 5.2 - Binary cross-entropy loss",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap05/5_2_Binary_Cross_Entropy_Loss.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 5.3 - Multiclass cross-entropy loss",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap05/5_3_Multiclass_Cross_entropy_Loss.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 6.1 - Line search",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_1_Line_Search.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 6.2 - Gradient descent",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_2_Gradient_Descent.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 6.3 - Stochastic gradient descent",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_3_Stochastic_Gradient_Descent.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 6.4 - Momentum",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_4_Momentum.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 6.5 - Adam",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap06/6_5_Adam.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 7.1 - Backpropagation in toy model",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap07/7_1_Backpropagation_in_Toy_Model.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 7.2 - Backpropagation",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap07/7_2_Backpropagation.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 7.3 - Initialization",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap07/7_3_Initialization.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 8.1 - MNIST-1D performance",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap08/8_1_MNIST_1D_Performance.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 8.2 - Bias-variance trade-off",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap08/8_2_Bias_Variance_Trade_Off.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 8.3 - Double descent",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap08/8_3_Double_Descent.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 8.4 - High-dimensional spaces",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap08/8_4_High_Dimensional_Spaces.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 9.1 - L2 regularization",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_1_L2_Regularization.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 9.2 - Implicit regularization",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_2_Implicit_Regularization.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 9.3 - Ensembling",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_3_Ensembling.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 9.4 - Bayesian approach",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_4_Bayesian_Approach.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 9.5 - Augmentation",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap09/9_5_Augmentation.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 10.1 - 1D convolution",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_1_1D_Convolution.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 10.2 - Convolution for MNIST-1D",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_2_Convolution_for_MNIST_1D.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 10.3 - 2D convolution",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_3_2D_Convolution.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 10.4 - Downsampling & upsampling",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_4_Downsampling_and_Upsampling.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 10.5 - Convolution for MNIST",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap10/10_5_Convolution_For_MNIST.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 11.1 - Shattered gradients",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap11/11_1_Shattered_Gradients.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 11.2 - Residual networks",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap11/11_2_Residual_Networks.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 11.3 - Batch normalization",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap11/11_3_Batch_Normalization.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 12.1 - Self-attention",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap12/12_1_Self_Attention.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 12.2 - Multi-head self-attention",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap12/12_2_Multihead_Self_Attention.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 12.3 - Tokenization",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap12/12_3_Tokenization.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 12.4 - Decoding strategies",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap12/12_4_Decoding_Strategies.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 13.1 - Encoding graphs",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap13/13_1_Graph_Representation.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 13.2 - Graph classification",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap13/13_2_Graph_Classification.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 13.3 - Neighborhood sampling",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap13/13_3_Neighborhood_Sampling.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 13.4 - Graph attention",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap13/13_4_Graph_Attention_Networks.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 15.1 - GAN toy example",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap15/15_1_GAN_Toy_Example.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 15.2 - Wasserstein distance",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap15/15_2_Wasserstein_Distance.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 16.1 - 1D normalizing flows",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap16/16_1_1D_Normalizing_Flows.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 16.2 - Autoregressive flows",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap16/16_2_Autoregressive_Flows.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 16.3 - Contraction mappings",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap16/16_3_Contraction_Mappings.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 17.1 - Latent variable models",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap17/17_1_Latent_Variable_Models.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 17.2 - Reparameterization trick",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap17/17_2_Reparameterization_Trick.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 17.3 - Importance sampling",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap17/17_3_Importance_Sampling.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 18.1 - Diffusion encoder",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap18/18_1_Diffusion_Encoder.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 18.2 - 1D diffusion model",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap18/18_2_1D_Diffusion_Model.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 18.3 - Reparameterized model",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap18/18_3_Reparameterized_Model.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 18.4 - Families of diffusion models",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap18/18_4_Families_of_Diffusion_Models.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 19.1 - Markov decision processes",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_1_Markov_Decision_Processes.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 19.2 - Dynamic programming",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_2_Dynamic_Programming.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 19.3 - Monte-Carlo methods",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_3_Monte_Carlo_Methods.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 19.4 - Temporal difference methods",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_4_Temporal_Difference_Methods.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 19.5 - Control variates",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap19/19_5_Control_Variates.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 20.1 - Random data",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap20/20_1_Random_Data.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 20.2 - Full-batch gradient descent",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap20/20_2_Full_Batch_Gradient_Descent.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 20.3 - Lottery tickets",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap20/20_3_Lottery_Tickets.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 20.4 - Adversarial attacks",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap20/20_4_Adversarial_Attacks.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 21.1 - Bias mitigation",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap21/21_1_Bias_Mitigation.ipynb",
|
||||
},
|
||||
{
|
||||
text: "Notebook 21.2 - Explainability",
|
||||
link: "https://github.com/udlbook/udlbook/blob/main/Notebooks/Chap21/21_2_Explainability.ipynb",
|
||||
},
|
||||
];
|
||||
|
||||
export default function NotebookSection() {
|
||||
return (
|
||||
<>
|
||||
<NotebookContainer lightBg={false} id="Notebooks">
|
||||
<NotebookWrapper>
|
||||
<NotebookRow imgStart={true}>
|
||||
<Column1>
|
||||
<TextWrapper>
|
||||
<TopLine>Coding exercises</TopLine>
|
||||
<Heading lightText={true}>
|
||||
Python notebooks covering the whole text
|
||||
</Heading>
|
||||
<Subtitle darkText={false}>
|
||||
Sixty eight python notebook exercises with missing code to fill
|
||||
in based on the text
|
||||
</Subtitle>
|
||||
</TextWrapper>
|
||||
</Column1>
|
||||
<Column2>
|
||||
<ImgWrap>
|
||||
<Img src={img} alt="Coding" />
|
||||
</ImgWrap>
|
||||
</Column2>
|
||||
</NotebookRow>
|
||||
<NotebookRow>
|
||||
<Column1>
|
||||
<ul>
|
||||
{/* render first half of notebooks*/}
|
||||
{notebooks.slice(0, notebooks.length / 2).map((notebook, index) => (
|
||||
<li key={index}>
|
||||
{notebook.text}:{" "}
|
||||
<NBLink href={notebook.link}>ipynb/colab</NBLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Column1>
|
||||
<Column2>
|
||||
<ul>
|
||||
{/* render second half of notebooks*/}
|
||||
{notebooks.slice(notebooks.length / 2).map((notebook, index) => (
|
||||
<li key={index}>
|
||||
{notebook.text}:{" "}
|
||||
<NBLink href={notebook.link}>ipynb/colab</NBLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Column2>
|
||||
</NotebookRow>
|
||||
</NotebookWrapper>
|
||||
</NotebookContainer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
96
src/components/Sidebar/SidebarElements.jsx
Executable file
96
src/components/Sidebar/SidebarElements.jsx
Executable file
@@ -0,0 +1,96 @@
|
||||
import { FaTimes } from "react-icons/fa";
|
||||
import { Link as LinkR } from "react-router-dom";
|
||||
import { Link as LinkS } from "react-scroll";
|
||||
import styled from "styled-components";
|
||||
|
||||
export const SidebarContainer = styled.aside`
|
||||
position: fixed;
|
||||
z-index: 999;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: #0d0d0d;
|
||||
display: grid;
|
||||
align-items: center;
|
||||
top: 0;
|
||||
left: 0;
|
||||
transition: 0.3s ease-in-out;
|
||||
opacity: ${({ isOpen }) => (isOpen ? "100%" : "0")};
|
||||
top: ${({ isOpen }) => (isOpen ? "0" : "-100%")};
|
||||
`;
|
||||
|
||||
export const CloseIcon = styled(FaTimes)`
|
||||
color: #fff;
|
||||
|
||||
&:hover {
|
||||
color: #01bf71;
|
||||
transition: 0.2s ease-in-out;
|
||||
}
|
||||
`;
|
||||
|
||||
export const Icon = styled.div`
|
||||
position: absolute;
|
||||
top: 1.2rem;
|
||||
right: 1.5rem;
|
||||
background: transparent;
|
||||
font-size: 2rem;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
`;
|
||||
|
||||
export const SidebarWrapper = styled.div`
|
||||
color: #ffffff;
|
||||
`;
|
||||
|
||||
export const SidebarMenu = styled.ul`
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-rows: repeat(6, 80px);
|
||||
text-align: center;
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
grid-template-rows: repeat(6, 60px);
|
||||
}
|
||||
`;
|
||||
|
||||
export const SidebarLink = styled(LinkS)`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1.5rem;
|
||||
text-decoration: none;
|
||||
list-style: none;
|
||||
transition: 0.2s ease-in-out;
|
||||
text-decoration: none;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
color: #01bf71;
|
||||
transition: 0.2s ease-in-out;
|
||||
}
|
||||
`;
|
||||
|
||||
export const SideBtnWrap = styled.div`
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
export const SidebarRoute = styled(LinkR)`
|
||||
border-radius: 50px;
|
||||
background: #01bf71;
|
||||
white-space: nowrap;
|
||||
padding: 16px 46px;
|
||||
color: #010606;
|
||||
font-size: 16px;
|
||||
outline: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease-in-out;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
transition: all 0.2s ease-in-out;
|
||||
background: #fff;
|
||||
color: #010606;
|
||||
}
|
||||
`;
|
||||
36
src/components/Sidebar/index.jsx
Executable file
36
src/components/Sidebar/index.jsx
Executable file
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
CloseIcon,
|
||||
Icon,
|
||||
SidebarContainer,
|
||||
SidebarLink,
|
||||
SidebarMenu,
|
||||
SidebarWrapper,
|
||||
} from "@/components/Sidebar/SidebarElements";
|
||||
|
||||
export default function Sidebar({ isOpen, toggle }) {
|
||||
return (
|
||||
<>
|
||||
<SidebarContainer isOpen={isOpen} onClick={toggle}>
|
||||
<Icon onClick={toggle}>
|
||||
<CloseIcon />
|
||||
</Icon>
|
||||
<SidebarWrapper>
|
||||
<SidebarMenu>
|
||||
<SidebarLink to="Notebooks" onClick={toggle}>
|
||||
Notebooks
|
||||
</SidebarLink>
|
||||
<SidebarLink to="Instructors" onClick={toggle}>
|
||||
Instructors
|
||||
</SidebarLink>
|
||||
<SidebarLink to="Media" onClick={toggle}>
|
||||
Media
|
||||
</SidebarLink>
|
||||
<SidebarLink to="More" onClick={toggle}>
|
||||
More
|
||||
</SidebarLink>
|
||||
</SidebarMenu>
|
||||
</SidebarWrapper>
|
||||
</SidebarContainer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
BIN
src/images/book_cover.jpg
Normal file
BIN
src/images/book_cover.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 282 KiB |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user