├── .gitignore
├── Exercise_03_1.ipynb
├── Exercise_03_2.ipynb
├── Exercise_03_2_solution.ipynb
├── Exercise_03_3.ipynb
├── Exercise_03_3_solution.ipynb
├── Exercise_04.ipynb
├── Exercise_04_1.ipynb
├── Exercise_04_1_solution.ipynb
├── Exercise_04_2.ipynb
├── Exercise_04_2_solution.ipynb
├── Exercise_04_3.ipynb
├── Exercise_04_3_solution.ipynb
├── Exercise_05_1.ipynb
├── Exercise_05_1_solution.ipynb
├── Exercise_05_2.ipynb
├── Exercise_05_2_solution.ipynb
├── Exercise_05_3.ipynb
├── Exercise_05_3_solution.ipynb
├── Exercise_07_1.ipynb
├── Exercise_07_1_solution.ipynb
├── Exercise_07_2.ipynb
├── Exercise_07_2_solution.ipynb
├── Exercise_08_1.ipynb
├── Exercise_08_1_solution.ipynb
├── Exercise_08_2.ipynb
├── Exercise_08_2_solution.ipynb
├── Exercise_09_1.ipynb
├── Exercise_09_2.ipynb
├── Exercise_09_2_solution.ipynb
├── Exercise_10_1.ipynb
├── Exercise_10_1_solution.ipynb
├── Exercise_11_1.ipynb
├── Exercise_11_1_solution.ipynb
├── Exercise_12_1.ipynb
├── Exercise_12_1_solution.ipynb
├── Exercise_12_2.ipynb
├── Exercise_12_2_solution.ipynb
├── Exercise_12_3.ipynb
├── Exercise_12_3_solution.ipynb
├── Exercise_16_1.ipynb
├── Exercise_16_1_solution.ipynb
├── Exercise_17_1.ipynb
├── Exercise_17_1_solution.ipynb
├── Exercise_18_1.ipynb
├── Exercise_18_1_solution.ipynb
├── Exercise_18_2.ipynb
├── Exercise_18_2_solution.ipynb
├── LICENSE.md
├── README.md
├── _config.yml
├── edgeconv.py
├── images
├── checkerboard_3_2_task_1.png
├── checkerboard_3_2_task_3.png
├── checkerboard_l1.png
├── checkerboard_l2_high.png
├── checkerboard_l2_low.png
├── checkerboard_l2_moderate.png
├── checkerboard_overtraining.png
├── checkerboard_regularization.png
└── checkerboard_tf_playground.png
├── index.md
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | weights-*
2 | .ipynb_checkpoints/
3 | *.npz
4 | __pycache__/
5 |
--------------------------------------------------------------------------------
/Exercise_03_1.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 3.1\n",
8 | "\n",
9 | "Congratulations - you have successfully navigated to the exercise page for the book **Deep Learning for Physics Research** \n",
10 | "\n",
11 | "This page hosts additional descriptions as well (where appropriate) example solutions to the exercise problems. While the solutions are available, we recommend you first attempt to solve the problem yourself, before looking up the answer. As many problems are open-ended, the presented solution of course often only represents one possible option how the problem could be solved.\n",
12 | "\n",
13 | "Some helpful links:\n",
14 | " * Python Tutorial (https://docs.python.org/3.7/tutorial/index.html): an introduction to the Python programming language\n",
15 | " \n",
16 | " * Google Colab (https://colab.research.google.com/): for Python development in your web-browser\n",
17 | " * Anaconda (https://www.anaconda.com/products/individual): a Python distribution for local installation\n",
18 | " \n",
19 | " * numpy (https://numpy.org/doc/stable/user/quickstart.html): a widely used library for mathematical operations in Python\n",
20 | " \n",
21 | " * Keras (https://keras.io/): a beginner-friendly deep learning library used in these exercises\n",
22 | " \n",
23 | " * Tensor Flow (https://www.tensorflow.org/): a useful backend for deep learning development\n",
24 | "\n",
25 | " * SciKit Learn (https://scikit-learn.org/stable/): helpful machine learning library \n",
26 | " \n",
27 | " * Seaborn (https://seaborn.pydata.org/): a library for creating nice looking graphs and figures\n"
28 | ]
29 | }
30 | ],
31 | "metadata": {
32 | "kernelspec": {
33 | "display_name": "Python 3",
34 | "language": "python",
35 | "name": "python3"
36 | },
37 | "language_info": {
38 | "codemirror_mode": {
39 | "name": "ipython",
40 | "version": 3
41 | },
42 | "file_extension": ".py",
43 | "mimetype": "text/x-python",
44 | "name": "python",
45 | "nbconvert_exporter": "python",
46 | "pygments_lexer": "ipython3",
47 | "version": "3.7.6"
48 | }
49 | },
50 | "nbformat": 4,
51 | "nbformat_minor": 4
52 | }
53 |
--------------------------------------------------------------------------------
/Exercise_03_2.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "id": "rF2trPuyzm9C"
7 | },
8 | "source": [
9 | "# Exercise 3.2\n"
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": 1,
15 | "metadata": {
16 | "id": "ipcsUFDUzm9C"
17 | },
18 | "outputs": [],
19 | "source": [
20 | "import numpy as np\n",
21 | "import matplotlib.pyplot as plt"
22 | ]
23 | },
24 | {
25 | "cell_type": "markdown",
26 | "metadata": {
27 | "id": "MCJe_ITJzm9G"
28 | },
29 | "source": [
30 | "**Linear Regression**\n",
31 | "\n",
32 | "The goal of this exercise is to explore a simple linear regression problem based on Portugese white wine.\n",
33 | "\n",
34 | "The dataset is based on \n",
35 | "Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis. **Modeling wine preferences by data mining from physicochemical properties**. Published in Decision Support Systems, Elsevier, 47(4):547-553, 2009. \n",
36 | "\n"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": 3,
42 | "metadata": {
43 | "colab": {
44 | "base_uri": "https://localhost:8080/"
45 | },
46 | "id": "NopU99AT9G7s",
47 | "outputId": "d7e8848e-b9c0-4eb4-8f18-5acda9d8c343"
48 | },
49 | "outputs": [
50 | {
51 | "name": "stdout",
52 | "output_type": "stream",
53 | "text": [
54 | "/bin/sh: wget: command not found\r\n"
55 | ]
56 | }
57 | ],
58 | "source": [
59 | "# The code snippet below is responsible for downloading the dataset\n",
60 | "# - for example when running via Google Colab.\n",
61 | "#\n",
62 | "# You can also directly download the file using the link if you work\n",
63 | "# with a local setup (in that case, ignore the !wget)\n",
64 | "\n",
65 | "!wget https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "metadata": {
71 | "id": "zEiZ19s5zm9G"
72 | },
73 | "source": [
74 | "**Before we start**\n",
75 | "\n",
76 | "The downloaded file contains data on 4989 wines. For each wine 11 features are recorded (column 0 to 10). The final columns contains the quality of the wine. This is what we want to predict. More information on the features and the quality measurement is provided in the original publication.\n",
77 | "\n",
78 | "List of columns/features: \n",
79 | "0. fixed acidity\n",
80 | "1. volatile acidity\n",
81 | "2. citric acid\n",
82 | "3. residual sugar\n",
83 | "4. chlorides\n",
84 | "5. free sulfur dioxide\n",
85 | "6. total sulfur dioxide\n",
86 | "7. density\n",
87 | "8. pH\n",
88 | "9. sulphates\n",
89 | "10. alcohol\n",
90 | "11. quality\n",
91 | "\n",
92 | "\n",
93 | "\n",
94 | "[file]: https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"
95 | ]
96 | },
97 | {
98 | "cell_type": "code",
99 | "execution_count": null,
100 | "metadata": {
101 | "colab": {
102 | "base_uri": "https://localhost:8080/"
103 | },
104 | "id": "5ONqeI5Uzm9H",
105 | "outputId": "d31ba8d4-cf0a-4f25-8a93-9091c0dd041a"
106 | },
107 | "outputs": [
108 | {
109 | "name": "stdout",
110 | "output_type": "stream",
111 | "text": [
112 | "('data:', (4898, 12))\n",
113 | "First example:\n",
114 | "('Features:', array([7.600e+00, 3.800e-01, 2.800e-01, 4.200e+00, 2.900e-02, 7.000e+00,\n",
115 | " 1.120e+02, 9.906e-01, 3.000e+00, 4.100e-01, 1.260e+01]))\n",
116 | "('Quality:', 6.0)\n"
117 | ]
118 | }
119 | ],
120 | "source": [
121 | "# Before working with the data, \n",
122 | "# we download and prepare all features\n",
123 | "\n",
124 | "# load all examples from the file\n",
125 | "data = np.genfromtxt('winequality-white.csv',delimiter=\";\",skip_header=1)\n",
126 | "\n",
127 | "print(\"data:\", data.shape)\n",
128 | "\n",
129 | "# Prepare for proper training\n",
130 | "np.random.shuffle(data) # randomly sort examples\n",
131 | "\n",
132 | "# take the first 3000 examples for training\n",
133 | "# (remember array slicing from last week)\n",
134 | "X_train = data[:3000,:11] # all features except last column\n",
135 | "y_train = data[:3000,11] # quality column\n",
136 | "\n",
137 | "# and the remaining examples for testing\n",
138 | "X_test = data[3000:,:11] # all features except last column\n",
139 | "y_test = data[3000:,11] # quality column\n",
140 | "\n",
141 | "print(\"First example:\")\n",
142 | "print(\"Features:\", X_train[0])\n",
143 | "print(\"Quality:\", y_train[0])"
144 | ]
145 | },
146 | {
147 | "cell_type": "markdown",
148 | "metadata": {
149 | "id": "jiwnyNHpzm9L"
150 | },
151 | "source": [
152 | "# Problems\n",
153 | "\n",
154 | "\n",
155 | "* First we want to understand the data better. Plot (`plt.hist`) the distribution of each of the features for the training data as well as the 2D distribution (either `plt.scatter` or `plt.hist2d`) of each feature versus quality. Also calculate the correlation coefficient (`np.corrcoef`) for each feature with quality. Which feature by itself seems most predictive for the quality?\n",
156 | "\n",
157 | "* Calculate the linear regression weights. Numpy provides functions for matrix multiplication (`np.matmul`), matrix transposition (`.T`) and matrix inversion (`np.linalg.inv`).\n",
158 | "\n",
159 | "* Use the weights to predict the quality for the test dataset. How\n",
160 | "does your predicted quality compare with the true quality of the test data? Calculate the correlation coefficient between predicted and true quality and draw a scatter plot."
161 | ]
162 | },
163 | {
164 | "cell_type": "markdown",
165 | "metadata": {},
166 | "source": [
167 | "# Hints"
168 | ]
169 | },
170 | {
171 | "cell_type": "markdown",
172 | "metadata": {},
173 | "source": [
174 | "Formally, we want to find weights $w_i$ that minimize:\n",
175 | "$$\n",
176 | "\\sum_{j}\\left(\\sum_{i} X_{i j} w_{i}-y_{j}\\right)^{2}\n",
177 | "$$\n",
178 | "The index $i$ denotes the different features (properties of the wines) while the index $j$ runs over the different wines. The matrix $X_{ij}$ contains the training data, $y_j$ is the 'true' quality for sample $j$. The weights can be found by taking the first derivative of the above expression with respect to the weights and setting it to zero (the standard strategy for finding an extremum), and solving the corresponding system of equations (for a detailed derivation, see [here](https://en.wikipedia.org/wiki/Ordinary_least_squares)). The result is:\n",
179 | "$$\n",
180 | "\\overrightarrow{\\mathbf{w}}=\\left(\\mathbf{X}^{T} \\mathbf{X}\\right)^{-1} \\mathbf{X}^{T} \\overrightarrow{\\mathbf{y}}\n",
181 | "$$\n",
182 | "\n",
183 | "In the end, you should have as many components of $w_i$ as there are features in the data (i.e. eleven in this case). \n",
184 | "\n",
185 | "You can use `.shape` to inspect the dimensions of numpy tensors.\n"
186 | ]
187 | }
188 | ],
189 | "metadata": {
190 | "colab": {
191 | "collapsed_sections": [],
192 | "name": "Exercise 4",
193 | "provenance": []
194 | },
195 | "kernelspec": {
196 | "display_name": "Python 3",
197 | "language": "python",
198 | "name": "python3"
199 | },
200 | "language_info": {
201 | "codemirror_mode": {
202 | "name": "ipython",
203 | "version": 3
204 | },
205 | "file_extension": ".py",
206 | "mimetype": "text/x-python",
207 | "name": "python",
208 | "nbconvert_exporter": "python",
209 | "pygments_lexer": "ipython3",
210 | "version": "3.6.9"
211 | }
212 | },
213 | "nbformat": 4,
214 | "nbformat_minor": 1
215 | }
216 |
--------------------------------------------------------------------------------
/Exercise_03_3.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 3.3\n",
8 | "## Checkerboard\n",
9 | "\n",
10 | "Open the Tensorflow Playground (www.playground.tensorflow.org) and select on the left the checkerboard pattern as the data basis.\n",
11 | "\n",
12 | "The data is taken from a two-dimensional probability distribution and is represented by the value pairs $x_1$ and $x_2$. The regions $x1$, $x_2 > 0$ and $x_1$, $x_2 < 0$ are shown by one color. For value pairs with $x_1 > 0$, $x_2 < 0$ and $x_1 < 0$, $x_2 > 0$, the regions are indicated by a different color. \n",
13 | "\n",
14 | "In features, select the two independent variables $x_1$ and $x_2$ and start the network training. The network learns that $x_1$ and $x_2$ are for these data not independent variables, but are taken from the probability distribution of the checkerboard pattern.\n",
15 | "\n",
16 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=4,2&seed=0.20784&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false)\n",
17 | "\n",
18 | "## Tasks\n",
19 | "1. Try various settings for the number of layers and neurons using `ReLU` as activation function. What is the smallest network that gives a good fit result?\n",
20 | "2. What do you observe when training networks with the same settings multiple times? Explain your observations.\n",
21 | "3. Try additional input features: Which one is most helpful?\n"
22 | ]
23 | }
24 | ],
25 | "metadata": {
26 | "kernelspec": {
27 | "display_name": "Python 3",
28 | "language": "python",
29 | "name": "python3"
30 | },
31 | "language_info": {
32 | "codemirror_mode": {
33 | "name": "ipython",
34 | "version": 3
35 | },
36 | "file_extension": ".py",
37 | "mimetype": "text/x-python",
38 | "name": "python",
39 | "nbconvert_exporter": "python",
40 | "pygments_lexer": "ipython3",
41 | "version": "3.6.9"
42 | }
43 | },
44 | "nbformat": 4,
45 | "nbformat_minor": 4
46 | }
47 |
--------------------------------------------------------------------------------
/Exercise_03_3_solution.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 3.3 - Solution\n",
8 | "## Checkerboard\n",
9 | "\n",
10 | "Open the Tensorflow Playground (www.playground.tensorflow.org) and select on the left the checkerboard pattern as the data basis.\n",
11 | "\n",
12 | "The data is taken from a two-dimensional probability distribution and is represented by the value pairs $x_1$ and $x_2$. The regions $x1$, $x_2 > 0$ and $x_1$, $x_2 < 0$ are shown by one color. For value pairs with $x_1 > 0$, $x_2 < 0$ and $x_1 < 0$, $x_2 > 0$, the regions are indicated by a different color. \n",
13 | "\n",
14 | "In features, select the two independent variables $x_1$ and $x_2$ and start the network training. The network learns that $x_1$ and $x_2$ are for these data not independent variables, but are taken from the probability distribution of the checkerboard pattern.\n",
15 | "\n",
16 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=4,2&seed=0.20784&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false)\n",
17 | "\n",
18 | "## Tasks\n",
19 | "1. Try various settings for the number of layers and neurons using `ReLU` as activation function. What is the smallest network that gives a good fit result?\n",
20 | "2. What do you observe when training networks with the same settings multiple times? Explain your observations.\n",
21 | "3. Try additional input features: Which one is most helpful?\n"
22 | ]
23 | },
24 | {
25 | "cell_type": "markdown",
26 | "metadata": {},
27 | "source": [
28 | "## Solutions\n",
29 | "Hint: click on the images to open the correct playground settings needed to solve the task, respectively."
30 | ]
31 | },
32 | {
33 | "cell_type": "markdown",
34 | "metadata": {},
35 | "source": [
36 | "### Task 1\n",
37 | "Try various settings for the number of layers and neurons using ReLU as activation function. What is the smallest network that gives a good fit result?\n"
38 | ]
39 | },
40 | {
41 | "cell_type": "markdown",
42 | "metadata": {},
43 | "source": [
44 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=3&seed=0.10528&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false)\n",
45 | "\n",
46 | " A network with a single layer holding 3 nodes. However, this configuration is not stable.\n",
47 | "\n",
48 | "A network with a single layer, holding 4 nodes, is way more stable. "
49 | ]
50 | },
51 | {
52 | "cell_type": "markdown",
53 | "metadata": {},
54 | "source": [
55 | "### Task 2\n",
56 | "What do you observe when training networks with the same settings multiple times? Explain your observations."
57 | ]
58 | },
59 | {
60 | "cell_type": "markdown",
61 | "metadata": {},
62 | "source": [
63 | " Due to the random initialization of weights, the network training always develops a little bit differently, leading to different results. "
64 | ]
65 | },
66 | {
67 | "cell_type": "markdown",
68 | "metadata": {},
69 | "source": [
70 | "### Task 3\n",
71 | "Try additional input features: Which one is most helpful?"
72 | ]
73 | },
74 | {
75 | "cell_type": "markdown",
76 | "metadata": {},
77 | "source": [
78 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=&seed=0.10528&showTestData=false&discretize=false&percTrainData=50&x=false&y=false&xTimesY=true&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false)\n",
79 | "\n",
80 | " Obviously, the $x_1\\cdot x_2$ feature is most helpful. "
81 | ]
82 | }
83 | ],
84 | "metadata": {
85 | "kernelspec": {
86 | "display_name": "Python 3",
87 | "language": "python",
88 | "name": "python3"
89 | },
90 | "language_info": {
91 | "codemirror_mode": {
92 | "name": "ipython",
93 | "version": 3
94 | },
95 | "file_extension": ".py",
96 | "mimetype": "text/x-python",
97 | "name": "python",
98 | "nbconvert_exporter": "python",
99 | "pygments_lexer": "ipython3",
100 | "version": "3.6.9"
101 | }
102 | },
103 | "nbformat": 4,
104 | "nbformat_minor": 4
105 | }
106 |
--------------------------------------------------------------------------------
/Exercise_04.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "id": "rF2trPuyzm9C"
7 | },
8 | "source": [
9 | "# In-Class Basics\n"
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": null,
15 | "metadata": {
16 | "id": "ipcsUFDUzm9C"
17 | },
18 | "outputs": [],
19 | "source": [
20 | "import numpy as np\n",
21 | "import matplotlib.pyplot as plt"
22 | ]
23 | },
24 | {
25 | "cell_type": "markdown",
26 | "metadata": {
27 | "id": "MCJe_ITJzm9G"
28 | },
29 | "source": [
30 | "**Linear Regression**\n",
31 | "\n",
32 | "The goal of this week's exercise is to explore a simple linear regression problem based on Portugese white wine.\n",
33 | "\n",
34 | "The dataset is based on \n",
35 | "Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis. **Modeling wine preferences by data mining from physicochemical properties**. Published in Decision Support Systems, Elsevier, 47(4):547-553, 2009. \n",
36 | "\n"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": null,
42 | "metadata": {
43 | "colab": {
44 | "base_uri": "https://localhost:8080/"
45 | },
46 | "id": "NopU99AT9G7s",
47 | "outputId": "d7e8848e-b9c0-4eb4-8f18-5acda9d8c343",
48 | "scrolled": true
49 | },
50 | "outputs": [
51 | {
52 | "name": "stdout",
53 | "output_type": "stream",
54 | "text": [
55 | "--2021-05-10 08:16:34-- https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
56 | "Resolving archive.ics.uci.edu (archive.ics.uci.edu)... 128.195.10.252\n",
57 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
58 | "Retrying.\n",
59 | "\n",
60 | "--2021-05-10 08:17:07-- (try: 2) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
61 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
62 | "Retrying.\n",
63 | "\n",
64 | "--2021-05-10 08:17:41-- (try: 3) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
65 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
66 | "Retrying.\n",
67 | "\n",
68 | "--2021-05-10 08:18:16-- (try: 4) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
69 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
70 | "Retrying.\n",
71 | "\n",
72 | "--2021-05-10 08:18:52-- (try: 5) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
73 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
74 | "Retrying.\n",
75 | "\n",
76 | "--2021-05-10 08:19:28-- (try: 6) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
77 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
78 | "Retrying.\n",
79 | "\n",
80 | "--2021-05-10 08:20:06-- (try: 7) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
81 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
82 | "Retrying.\n",
83 | "\n",
84 | "--2021-05-10 08:20:45-- (try: 8) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
85 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
86 | "Retrying.\n",
87 | "\n",
88 | "--2021-05-10 08:21:25-- (try: 9) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
89 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
90 | "Retrying.\n",
91 | "\n",
92 | "--2021-05-10 08:22:06-- (try:10) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
93 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
94 | "Retrying.\n",
95 | "\n",
96 | "--2021-05-10 08:22:48-- (try:11) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
97 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
98 | "Retrying.\n",
99 | "\n",
100 | "--2021-05-10 08:23:30-- (try:12) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
101 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
102 | "Retrying.\n",
103 | "\n",
104 | "--2021-05-10 08:24:12-- (try:13) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
105 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
106 | "Retrying.\n",
107 | "\n",
108 | "--2021-05-10 08:24:54-- (try:14) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
109 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
110 | "Retrying.\n",
111 | "\n",
112 | "--2021-05-10 08:25:36-- (try:15) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
113 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
114 | "Retrying.\n",
115 | "\n",
116 | "--2021-05-10 08:26:18-- (try:16) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
117 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
118 | "Retrying.\n",
119 | "\n",
120 | "--2021-05-10 08:27:00-- (try:17) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
121 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
122 | "Retrying.\n",
123 | "\n",
124 | "--2021-05-10 08:27:42-- (try:18) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
125 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
126 | "Retrying.\n",
127 | "\n",
128 | "--2021-05-10 08:28:24-- (try:19) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
129 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
130 | "Retrying.\n",
131 | "\n",
132 | "--2021-05-10 08:29:06-- (try:20) https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
133 | "Connecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... failed: Connection timed out.\n",
134 | "Giving up.\n",
135 | "\n"
136 | ]
137 | }
138 | ],
139 | "source": [
140 | "# The code snippet below is responsible for downloading the dataset to\n",
141 | "# Google. You can directly download the file using the link\n",
142 | "# if you work with a local anaconda setup\n",
143 | "\n",
144 | "# Temporarily replaced link as the ML dataset archive seems to be down\n",
145 | "#!wget https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\n",
146 | "!wget https://raw.githubusercontent.com/zygmuntz/wine-quality/master/winequality/winequality-white.csv"
147 | ]
148 | },
149 | {
150 | "cell_type": "markdown",
151 | "metadata": {
152 | "id": "zEiZ19s5zm9G"
153 | },
154 | "source": [
155 | "**Before we start**\n",
156 | "\n",
157 | "The downloaded file contains data on 4989 wines. For each wine 11 features are recorded (column 0 to 10). The final columns contains the quality of the wine. This is what we want to predict.\n",
158 | "\n",
159 | "List of columns/features: \n",
160 | "0. fixed acidity\n",
161 | "1. volatile acidity\n",
162 | "2. citric acid\n",
163 | "3. residual sugar\n",
164 | "4. chlorides\n",
165 | "5. free sulfur dioxide\n",
166 | "6. total sulfur dioxide\n",
167 | "7. density\n",
168 | "8. pH\n",
169 | "9. sulphates\n",
170 | "10. alcohol\n",
171 | "11. quality\n",
172 | "\n",
173 | "\n",
174 | "\n",
175 | "[file]: https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"
176 | ]
177 | },
178 | {
179 | "cell_type": "code",
180 | "execution_count": null,
181 | "metadata": {
182 | "colab": {
183 | "base_uri": "https://localhost:8080/"
184 | },
185 | "id": "5ONqeI5Uzm9H",
186 | "outputId": "d31ba8d4-cf0a-4f25-8a93-9091c0dd041a"
187 | },
188 | "outputs": [
189 | {
190 | "name": "stdout",
191 | "output_type": "stream",
192 | "text": [
193 | "('data:', (4898, 12))\n",
194 | "First example:\n",
195 | "('Features:', array([7.600e+00, 3.800e-01, 2.800e-01, 4.200e+00, 2.900e-02, 7.000e+00,\n",
196 | " 1.120e+02, 9.906e-01, 3.000e+00, 4.100e-01, 1.260e+01]))\n",
197 | "('Quality:', 6.0)\n"
198 | ]
199 | }
200 | ],
201 | "source": [
202 | "# load all examples from the file\n",
203 | "data = np.genfromtxt('winequality-white.csv',delimiter=\";\",skip_header=1)\n",
204 | "\n",
205 | "print(\"data:\", data.shape)\n",
206 | "\n",
207 | "# Prepare for proper training\n",
208 | "np.random.shuffle(data) # randomly sort examples\n",
209 | "\n",
210 | "# take the first 3000 examples for training\n",
211 | "# (remember array slicing from last week)\n",
212 | "X_train = data[:3000,:11] # all features except last column\n",
213 | "y_train = data[:3000,11] # quality column\n",
214 | "\n",
215 | "# and the remaining examples for testing\n",
216 | "X_test = data[3000:,:11] # all features except last column\n",
217 | "y_test = data[3000:,11] # quality column\n",
218 | "\n",
219 | "print(\"First example:\")\n",
220 | "print(\"Features:\", X_train[0])\n",
221 | "print(\"Quality:\", y_train[0])"
222 | ]
223 | },
224 | {
225 | "cell_type": "markdown",
226 | "metadata": {
227 | "id": "jiwnyNHpzm9L"
228 | },
229 | "source": [
230 | "# Homework\n",
231 | "\n",
232 | "1. First we want to understand the data better. Plot (`plt.hist`) the distribution of each of the features for the training data as well as the 2D distribution (either `plt.scatter` or `plt.hist2d`) of each feature versus quality. Also calculate the correlation coefficient (`np.corrcoef`) for each feature with quality. Which feature by itself seems most\n",
233 | " predictive for the quality?\n",
234 | "\n",
235 | "2. Calculate the linear regression weights as derived in the lecture. Numpy provides functions for matrix multiplication (`np.matmul`), matrix transposition (`.T`) and matrix inversion (`np.linalg.inv`).\n",
236 | "\n",
237 | "3. Use the weights to predict the quality for the test dataset. How does your predicted quality compare with the true quality of the test data? Calculate the correlation coefficient between predicted and true quality and draw the scatter plot. "
238 | ]
239 | },
240 | {
241 | "cell_type": "code",
242 | "execution_count": null,
243 | "metadata": {
244 | "id": "MzzCP2ST898a"
245 | },
246 | "outputs": [],
247 | "source": [
248 | "x = np.random.uniform(size=(3,4))"
249 | ]
250 | },
251 | {
252 | "cell_type": "code",
253 | "execution_count": null,
254 | "metadata": {
255 | "colab": {
256 | "base_uri": "https://localhost:8080/"
257 | },
258 | "id": "MlbmmHoA9BJQ",
259 | "outputId": "98e65963-3173-46c7-f47b-6b9a6714c187"
260 | },
261 | "outputs": [
262 | {
263 | "data": {
264 | "text/plain": [
265 | "array([[0.27061972, 0.85093187, 0.06038869, 0.6430975 ],\n",
266 | " [0.05802941, 0.1492127 , 0.93073299, 0.70555297],\n",
267 | " [0.4806267 , 0.27201085, 0.75607278, 0.88637951]])"
268 | ]
269 | },
270 | "execution_count": 27,
271 | "metadata": {
272 | "tags": []
273 | },
274 | "output_type": "execute_result"
275 | }
276 | ],
277 | "source": [
278 | "x"
279 | ]
280 | },
281 | {
282 | "cell_type": "code",
283 | "execution_count": null,
284 | "metadata": {
285 | "id": "MqRyPzzN-ar0"
286 | },
287 | "outputs": [],
288 | "source": []
289 | },
290 | {
291 | "cell_type": "code",
292 | "execution_count": null,
293 | "metadata": {
294 | "colab": {
295 | "base_uri": "https://localhost:8080/"
296 | },
297 | "id": "HiYXwCle9Fow",
298 | "outputId": "949146bf-7184-488f-a347-4af589917bf6"
299 | },
300 | "outputs": [
301 | {
302 | "data": {
303 | "text/plain": [
304 | "0.14921269768865764"
305 | ]
306 | },
307 | "execution_count": 28,
308 | "metadata": {
309 | "tags": []
310 | },
311 | "output_type": "execute_result"
312 | }
313 | ],
314 | "source": [
315 | "x[1,1]"
316 | ]
317 | },
318 | {
319 | "cell_type": "code",
320 | "execution_count": null,
321 | "metadata": {
322 | "colab": {
323 | "base_uri": "https://localhost:8080/"
324 | },
325 | "id": "0M56hD2R9VYo",
326 | "outputId": "7199e2d2-4d5d-4500-ea8a-37c9c12046b5"
327 | },
328 | "outputs": [
329 | {
330 | "name": "stdout",
331 | "output_type": "stream",
332 | "text": [
333 | "[[0.93073299 0.70555297]\n",
334 | " [0.75607278 0.88637951]]\n"
335 | ]
336 | }
337 | ],
338 | "source": [
339 | "f = x[1:,2:]\n",
340 | "print(f)"
341 | ]
342 | },
343 | {
344 | "cell_type": "code",
345 | "execution_count": null,
346 | "metadata": {
347 | "colab": {
348 | "base_uri": "https://localhost:8080/"
349 | },
350 | "id": "J3f29BC99cDK",
351 | "outputId": "91dd6002-c95f-47ea-de6f-ba4279175b8d"
352 | },
353 | "outputs": [
354 | {
355 | "name": "stdout",
356 | "output_type": "stream",
357 | "text": [
358 | "[[9.99000000e+02 7.05552973e-01]\n",
359 | " [7.56072781e-01 8.86379512e-01]]\n"
360 | ]
361 | }
362 | ],
363 | "source": [
364 | "f[0,0] = 999\n",
365 | "print(f)"
366 | ]
367 | },
368 | {
369 | "cell_type": "code",
370 | "execution_count": null,
371 | "metadata": {
372 | "colab": {
373 | "base_uri": "https://localhost:8080/"
374 | },
375 | "id": "ZnvjBmbs9hdq",
376 | "outputId": "c30f3f02-c9a9-42ae-da07-af13151e6596"
377 | },
378 | "outputs": [
379 | {
380 | "data": {
381 | "text/plain": [
382 | "array([[2.70619720e-01, 8.50931871e-01, 6.03886907e-02, 6.43097505e-01],\n",
383 | " [5.80294054e-02, 1.49212698e-01, 9.99000000e+02, 7.05552973e-01],\n",
384 | " [4.80626701e-01, 2.72010854e-01, 7.56072781e-01, 8.86379512e-01]])"
385 | ]
386 | },
387 | "execution_count": 35,
388 | "metadata": {
389 | "tags": []
390 | },
391 | "output_type": "execute_result"
392 | }
393 | ],
394 | "source": [
395 | "x"
396 | ]
397 | },
398 | {
399 | "cell_type": "code",
400 | "execution_count": null,
401 | "metadata": {
402 | "id": "c4kcHKQP-tTp"
403 | },
404 | "outputs": [],
405 | "source": []
406 | }
407 | ],
408 | "metadata": {
409 | "colab": {
410 | "collapsed_sections": [],
411 | "name": "Exercise 4",
412 | "provenance": []
413 | },
414 | "kernelspec": {
415 | "display_name": "Python 2",
416 | "language": "python",
417 | "name": "python2"
418 | },
419 | "language_info": {
420 | "codemirror_mode": {
421 | "name": "ipython",
422 | "version": 3
423 | },
424 | "file_extension": ".py",
425 | "mimetype": "text/x-python",
426 | "name": "python",
427 | "nbconvert_exporter": "python",
428 | "pygments_lexer": "ipython3",
429 | "version": "3.6.9"
430 | }
431 | },
432 | "nbformat": 4,
433 | "nbformat_minor": 1
434 | }
435 |
--------------------------------------------------------------------------------
/Exercise_04_1.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "id": "rF2trPuyzm9C"
7 | },
8 | "source": [
9 | "# Exercise 4.1\n"
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": 3,
15 | "metadata": {
16 | "id": "ipcsUFDUzm9C"
17 | },
18 | "outputs": [],
19 | "source": [
20 | "import numpy as np\n",
21 | "import matplotlib.pyplot as plt"
22 | ]
23 | },
24 | {
25 | "cell_type": "markdown",
26 | "metadata": {
27 | "id": "MCJe_ITJzm9G"
28 | },
29 | "source": [
30 | "**Disclaimer**\n",
31 | "\n",
32 | "The book mistakently refers to the page for Exercise 4.2 when introducting Exercise 4.1, etc. Of course, these numbers should match: Book Exercise 4.1 is discussed under Exercise 4.1 \n",
33 | "\n",
34 | "**Simple Network**\n",
35 | "\n",
36 | "We continue with the dataset first encountered in Exercise 3.2. Please refer to the discussion there for an introduction to the data and the learning objective.\n",
37 | "\n",
38 | "Here, we manually implement a simple network architecture"
39 | ]
40 | },
41 | {
42 | "cell_type": "code",
43 | "execution_count": 1,
44 | "metadata": {
45 | "colab": {
46 | "base_uri": "https://localhost:8080/"
47 | },
48 | "id": "NopU99AT9G7s",
49 | "outputId": "d7e8848e-b9c0-4eb4-8f18-5acda9d8c343"
50 | },
51 | "outputs": [
52 | {
53 | "name": "stdout",
54 | "output_type": "stream",
55 | "text": [
56 | "/bin/sh: wget: command not found\r\n"
57 | ]
58 | }
59 | ],
60 | "source": [
61 | "# The code snippet below is responsible for downloading the dataset\n",
62 | "# - for example when running via Google Colab.\n",
63 | "#\n",
64 | "# You can also directly download the file using the link if you work\n",
65 | "# with a local setup (in that case, ignore the !wget)\n",
66 | "\n",
67 | "!wget https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"
68 | ]
69 | },
70 | {
71 | "cell_type": "code",
72 | "execution_count": 5,
73 | "metadata": {
74 | "colab": {
75 | "base_uri": "https://localhost:8080/"
76 | },
77 | "id": "5ONqeI5Uzm9H",
78 | "outputId": "d31ba8d4-cf0a-4f25-8a93-9091c0dd041a"
79 | },
80 | "outputs": [
81 | {
82 | "name": "stdout",
83 | "output_type": "stream",
84 | "text": [
85 | "data: (4898, 12)\n",
86 | "First example:\n",
87 | "Features: [5.900e+00 3.400e-01 2.200e-01 2.400e+00 3.000e-02 1.900e+01 1.350e+02\n",
88 | " 9.894e-01 3.410e+00 7.800e-01 1.390e+01]\n",
89 | "Quality: 7.0\n"
90 | ]
91 | }
92 | ],
93 | "source": [
94 | "# Before working with the data, \n",
95 | "# we download and prepare all features\n",
96 | "\n",
97 | "# load all examples from the file\n",
98 | "data = np.genfromtxt('winequality-white.csv',delimiter=\";\",skip_header=1)\n",
99 | "\n",
100 | "print(\"data:\", data.shape)\n",
101 | "\n",
102 | "# Prepare for proper training\n",
103 | "np.random.shuffle(data) # randomly sort examples\n",
104 | "\n",
105 | "# take the first 3000 examples for training\n",
106 | "# (remember array slicing from last week)\n",
107 | "X_train = data[:3000,:11] # all features except last column\n",
108 | "y_train = data[:3000,11] # quality column\n",
109 | "\n",
110 | "# and the remaining examples for testing\n",
111 | "X_test = data[3000:,:11] # all features except last column\n",
112 | "y_test = data[3000:,11] # quality column\n",
113 | "\n",
114 | "print(\"First example:\")\n",
115 | "print(\"Features:\", X_train[0])\n",
116 | "print(\"Quality:\", y_train[0])"
117 | ]
118 | },
119 | {
120 | "cell_type": "markdown",
121 | "metadata": {
122 | "id": "jiwnyNHpzm9L"
123 | },
124 | "source": [
125 | "# Problems\n",
126 | "\n",
127 | "The goal is to implement the training of a neural network with one input layer, one hidden layer, and one output layer using gradient descent. We first (below) define the matrices and initialise with random values. We need W, b, W' and b'. The shapes will be:\n",
128 | " * W: (number of hidden nodes, number of inputs) named `W`\n",
129 | " * b: (number of hidden nodes) named `b`\n",
130 | " * W': (number of hidden nodes) named `Wp`\n",
131 | " * b': (one) named `bp`\n",
132 | "\n",
133 | "Your tasks are: \n",
134 | " * Implement a forward pass of the network as `dnn` (see below)\n",
135 | " * Implement a function that uses one data point to update the weights using gradient descent. You can follow the `update_weights` skeleton below\n",
136 | " * Now you can use the code below (training loop and evaluation) to train the network for multiple data points and even over several epochs. Try to find a set of hyperparameters (number of nodes in the hidden layer, learning rate, number of training epochs) that gives stable results. What is the best result (as measured by the loss on the training sample) you can get?"
137 | ]
138 | },
139 | {
140 | "cell_type": "code",
141 | "execution_count": 8,
142 | "metadata": {},
143 | "outputs": [
144 | {
145 | "name": "stdout",
146 | "output_type": "stream",
147 | "text": [
148 | "(50, 11)\n"
149 | ]
150 | }
151 | ],
152 | "source": [
153 | "# Initialise weights with suitable random distributions\n",
154 | "hidden_nodes = 50 # number of nodes in the hidden layer\n",
155 | "n_inputs = 11 # input features in the dataset\n",
156 | "\n",
157 | "# See section 4.3 of the book for more information on\n",
158 | "# how to initialise network parameters\n",
159 | "W = np.random.randn(hidden_nodes,11)*np.sqrt(2./n_inputs)\n",
160 | "b = np.random.randn(hidden_nodes)*np.sqrt(2./n_inputs)\n",
161 | "Wp = np.random.randn(hidden_nodes)*np.sqrt(2./hidden_nodes)\n",
162 | "bp = np.random.randn((1))\n",
163 | "\n",
164 | "print(W.shape)"
165 | ]
166 | },
167 | {
168 | "cell_type": "code",
169 | "execution_count": 6,
170 | "metadata": {},
171 | "outputs": [],
172 | "source": [
173 | "# You can use this implementation of the ReLu activation function\n",
174 | "def relu(x):\n",
175 | " return np.maximum(x, 0)"
176 | ]
177 | },
178 | {
179 | "cell_type": "code",
180 | "execution_count": 7,
181 | "metadata": {},
182 | "outputs": [],
183 | "source": [
184 | "def dnn(x,W,b,Wp,bp):\n",
185 | " # TODO Calculate and return network output of forward pass\n",
186 | " # See Hint 1 for additional information\n",
187 | " return -1 # change to the calculated output"
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": 11,
193 | "metadata": {},
194 | "outputs": [],
195 | "source": [
196 | "def update_weights(x,y, W, b, Wp, bp):\n",
197 | " \n",
198 | " learning_rate = 0.01\n",
199 | "\n",
200 | " # TODO: Calculate the network output (use the function dnn defined above)\n",
201 | " \n",
202 | " # TODO: Derive the gradient for each of W,b,Wp,bp by taking the partial\n",
203 | " # derivative of the loss function with respect to the variable and\n",
204 | " # then implement the resulting weight-update procedure\n",
205 | " # See Hint 2 for additional information\n",
206 | "\n",
207 | " # You might need these numpy functions:\n",
208 | " # np.dot, np.outer, np.heaviside\n",
209 | " # Hint: Use .shape and print statements to make sure all operations\n",
210 | " # do what you want them to \n",
211 | " \n",
212 | " # TODO: Update the weights/bias following the rule: weight_new = weight_old - learning_rate * gradient \n",
213 | "\n",
214 | " return -1 # no return value needed, you can modify the weights in-place"
215 | ]
216 | },
217 | {
218 | "cell_type": "markdown",
219 | "metadata": {},
220 | "source": [
221 | "# Training loop and evaluation below"
222 | ]
223 | },
224 | {
225 | "cell_type": "code",
226 | "execution_count": null,
227 | "metadata": {},
228 | "outputs": [],
229 | "source": [
230 | "# The code below implements the training.\n",
231 | "# If you correctly implement dnn and update_weights above, \n",
232 | "# you should not need to change anything below. \n",
233 | "# (apart from increasing the number of epochs)\n",
234 | "\n",
235 | "train_losses = []\n",
236 | "test_losses = []\n",
237 | "\n",
238 | "# How many epochs to train\n",
239 | "# This will just train for one epoch\n",
240 | "# You will want a higher number once everything works\n",
241 | "n_epochs = 1 \n",
242 | "\n",
243 | "# Loop over the epochs\n",
244 | "for ep in range(n_epochs):\n",
245 | " \n",
246 | " # Each epoch is a complete over the training data\n",
247 | " for i in range(X_train.shape[0]):\n",
248 | " \n",
249 | " # pick one example\n",
250 | " x = X_train[i]\n",
251 | " y = y_train[i]\n",
252 | "\n",
253 | " # use it to update the weights\n",
254 | " update_weights(x,y,W,b,Wp,bp)\n",
255 | " \n",
256 | " # Calculate predictions for the full training and testing sample\n",
257 | " y_pred_train = [dnn(x,W,b,Wp,bp)[0] for x in X_train]\n",
258 | " y_pred = [dnn(x,W,b,Wp,bp)[0] for x in X_test]\n",
259 | "\n",
260 | " # Calculate aver loss / example over the epoch\n",
261 | " train_loss = sum((y_pred_train-y_train)**2) / y_train.shape[0]\n",
262 | " test_loss = sum((y_pred-y_test)**2) / y_test.shape[0] \n",
263 | " \n",
264 | " # print some information\n",
265 | " print(\"Epoch:\",ep, \"Train Loss:\", train_loss, \"Test Loss:\", test_loss)\n",
266 | " \n",
267 | " # and store the losses for later use\n",
268 | " train_losses.append(train_loss)\n",
269 | " test_losses.append(test_loss)\n",
270 | " \n",
271 | " \n",
272 | "# After the training:\n",
273 | " \n",
274 | "# Prepare scatter plot\n",
275 | "y_pred = [dnn(x,W,b,Wp,bp)[0] for x in X_test]\n",
276 | "\n",
277 | "print(\"Best loss:\", min(test_losses), \"Final loss:\", test_losses[-1])\n",
278 | "\n",
279 | "print(\"Correlation coefficient:\", np.corrcoef(y_pred,y_test)[0,1])\n",
280 | "plt.scatter(y_pred_train,y_train)\n",
281 | "plt.xlabel(\"Predicted\")\n",
282 | "plt.ylabel(\"True\")\n",
283 | "plt.show()\n",
284 | "\n",
285 | "# Prepare and loss over time\n",
286 | "plt.plot(train_losses,label=\"train\")\n",
287 | "plt.plot(test_losses,label=\"test\")\n",
288 | "plt.legend()\n",
289 | "plt.xlabel(\"Epoch\")\n",
290 | "plt.ylabel(\"Loss\")\n",
291 | "plt.show()\n"
292 | ]
293 | },
294 | {
295 | "cell_type": "markdown",
296 | "metadata": {},
297 | "source": [
298 | "# Hint 1"
299 | ]
300 | },
301 | {
302 | "cell_type": "markdown",
303 | "metadata": {},
304 | "source": [
305 | "We want a network with one hidden layer. As activiation in the hidden layer $\\sigma$ we apply element-wise ReLu, while no activation is used for the output layer. The forward pass of the network then reads:\n",
306 | "$$\\hat{y}=\\mathbf{W}^{\\prime} \\sigma(\\mathbf{W} \\vec{x}+\\vec{b})+b^{\\prime}$$"
307 | ]
308 | },
309 | {
310 | "cell_type": "markdown",
311 | "metadata": {},
312 | "source": [
313 | "# Hint 2"
314 | ]
315 | },
316 | {
317 | "cell_type": "markdown",
318 | "metadata": {},
319 | "source": [
320 | "For the regression problem the objective function is the mean squared error between the prediction and the true label $y$: \n",
321 | "$$\n",
322 | "L=(\\hat{y}-y)^{2}\n",
323 | "$$\n",
324 | "\n",
325 | "Taking the partial derivatives - and diligently the applying chain rule - with respect to the different objects yields:\n",
326 | "\n",
327 | "$$\n",
328 | "\\begin{aligned}\n",
329 | "\\frac{\\partial L}{\\partial b^{\\prime}} &=2(\\hat{y}-y) \\\\\n",
330 | "\\frac{\\partial L}{\\partial b_{k}} &=2(\\hat{y}-y) \\mathbf{W}_{k}^{\\prime} \\theta\\left(\\sum_{i} \\mathbf{W}_{i k} x_{i}+b_{k}\\right) \\\\\n",
331 | "\\frac{\\partial L}{\\partial \\mathbf{W}_{k}^{\\prime}} &=2(\\hat{y}-y) \\sigma\\left(\\sum_{i} \\mathbf{W}_{i k} x_{i}+b_{k}\\right) \\\\\n",
332 | "\\frac{\\partial L}{\\partial \\mathbf{W}_{k m}} &=2(\\hat{y}-y) \\mathbf{W}_{m}^{\\prime} \\theta\\left(\\sum_{i} \\mathbf{W}_{i k} x_{i}+b_{m}\\right) x_{k}\n",
333 | "\\end{aligned}\n",
334 | "$$\n",
335 | "\n",
336 | "Here, $\\Theta$ denotes the Heaviside step function."
337 | ]
338 | },
339 | {
340 | "cell_type": "code",
341 | "execution_count": null,
342 | "metadata": {},
343 | "outputs": [],
344 | "source": []
345 | }
346 | ],
347 | "metadata": {
348 | "colab": {
349 | "collapsed_sections": [],
350 | "name": "Exercise 4",
351 | "provenance": []
352 | },
353 | "kernelspec": {
354 | "display_name": "Python 3",
355 | "language": "python",
356 | "name": "python3"
357 | },
358 | "language_info": {
359 | "codemirror_mode": {
360 | "name": "ipython",
361 | "version": 3
362 | },
363 | "file_extension": ".py",
364 | "mimetype": "text/x-python",
365 | "name": "python",
366 | "nbconvert_exporter": "python",
367 | "pygments_lexer": "ipython3",
368 | "version": "3.6.9"
369 | }
370 | },
371 | "nbformat": 4,
372 | "nbformat_minor": 1
373 | }
374 |
--------------------------------------------------------------------------------
/Exercise_04_2.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 4.2\n",
8 | "## Linear regression\n",
9 | "In this task we will design and train a linear model using [Keras](https://keras.io/).\n",
10 | "\n",
11 | "### Tasks\n",
12 | "1. Complete the implemetation of the `LinearLayer`\n",
13 | "2. Define a meaningful objective\n",
14 | "3. Implement gradient descent and train the linear model for 80 epochs."
15 | ]
16 | },
17 | {
18 | "cell_type": "code",
19 | "execution_count": 3,
20 | "metadata": {},
21 | "outputs": [],
22 | "source": [
23 | "import tensorflow as tf\n",
24 | "from tensorflow import keras\n",
25 | "import numpy as np\n",
26 | "import matplotlib.pyplot as plt\n",
27 | "\n",
28 | "layers = keras.layers"
29 | ]
30 | },
31 | {
32 | "cell_type": "markdown",
33 | "metadata": {},
34 | "source": [
35 | "### Simulation of data\n",
36 | "Let's first simulate some noisy data"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": 2,
42 | "metadata": {},
43 | "outputs": [
44 | {
45 | "name": "stdout",
46 | "output_type": "stream",
47 | "text": [
48 | "x.shape: (100, 1)\n",
49 | "y.shape: (100,)\n"
50 | ]
51 | }
52 | ],
53 | "source": [
54 | "np.random.seed(1904)\n",
55 | "x = np.float32(np.linspace(-1, 1, 100)[:,np.newaxis])\n",
56 | "y = np.float32(2 * x[:,0] + 0.3 * np.random.randn(100))\n",
57 | "print(\"x.shape:\", x.shape)\n",
58 | "print(\"y.shape:\", y.shape)"
59 | ]
60 | },
61 | {
62 | "cell_type": "markdown",
63 | "metadata": {},
64 | "source": [
65 | "### Implement linear model"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "metadata": {},
71 | "source": [
72 | "Now, we have to design a linear layer that maps from the input $x$ to the output $y$ using a single adaptive weight $w$:\n",
73 | " \n",
74 | "$$y = w \\cdot x$$\n",
75 | "\n",
76 | "### Task 1\n",
77 | "Complete the implementation of the `LinearLayer` by adding the linear transformation in the `call` function."
78 | ]
79 | },
80 | {
81 | "cell_type": "code",
82 | "execution_count": null,
83 | "metadata": {},
84 | "outputs": [],
85 | "source": [
86 | "class LinearLayer(layers.Layer):\n",
87 | "\n",
88 | " def __init__(self, units=1, input_dim=1): # when intializing the layer the weights have to be initialized\n",
89 | " super(LinearLayer, self).__init__()\n",
90 | " w_init = tf.random_normal_initializer()\n",
91 | " self.w = tf.Variable(initial_value=w_init(shape=(input_dim, units), dtype=\"float32\"),\n",
92 | " trainable=True)\n",
93 | "\n",
94 | " def call(self, inputs): # when calling the layer the linear transformation has to be performed\n",
95 | " return ..."
96 | ]
97 | },
98 | {
99 | "cell_type": "markdown",
100 | "metadata": {},
101 | "source": [
102 | "Build a model using the implemented layer."
103 | ]
104 | },
105 | {
106 | "cell_type": "code",
107 | "execution_count": null,
108 | "metadata": {},
109 | "outputs": [],
110 | "source": [
111 | "model = keras.models.Sequential()\n",
112 | "model.add(LinearLayer(units=1, input_dim=1))"
113 | ]
114 | },
115 | {
116 | "cell_type": "code",
117 | "execution_count": null,
118 | "metadata": {},
119 | "outputs": [],
120 | "source": [
121 | "model.build((None, 1))\n",
122 | "print(model.summary())"
123 | ]
124 | },
125 | {
126 | "cell_type": "markdown",
127 | "metadata": {},
128 | "source": [
129 | "### Performance before the training\n",
130 | "Plot data and model before the training"
131 | ]
132 | },
133 | {
134 | "cell_type": "code",
135 | "execution_count": null,
136 | "metadata": {},
137 | "outputs": [],
138 | "source": [
139 | "y_pred = model(x)\n",
140 | "\n",
141 | "fig, ax = plt.subplots(1)\n",
142 | "ax.plot(x, y, 'bo', label='data')\n",
143 | "ax.plot(x, y_pred, 'r-', label='model')\n",
144 | "ax.set(xlabel='$x$', ylabel='$y$')\n",
145 | "ax.grid()\n",
146 | "ax.legend(loc='lower right')\n",
147 | "plt.tight_layout()"
148 | ]
149 | },
150 | {
151 | "cell_type": "markdown",
152 | "metadata": {},
153 | "source": [
154 | "### Task 2: Define the objective function\n",
155 | "Define a meaningful objective here (regression task). \n",
156 | "Note that you can use `tf.reduce_mean()` to average your loss estimate over the full data set (100 points)."
157 | ]
158 | },
159 | {
160 | "cell_type": "code",
161 | "execution_count": null,
162 | "metadata": {},
163 | "outputs": [],
164 | "source": [
165 | "def loss(x, y):\n",
166 | " return ...."
167 | ]
168 | },
169 | {
170 | "cell_type": "markdown",
171 | "metadata": {},
172 | "source": [
173 | "### Task 3 - Train the model using gradient descent\n",
174 | "'Train' the linear model for 80 epochs (or iterations) with a meaningful learning rate and implement gradient descent. \n",
175 | "Hint: you can access the adaptive parameters using `model.trainable_weights` and perform $w' \\rightarrow w-z$ using `w.assign_sub(z)`"
176 | ]
177 | },
178 | {
179 | "cell_type": "code",
180 | "execution_count": null,
181 | "metadata": {},
182 | "outputs": [],
183 | "source": [
184 | "epochs = ... # number of epochs\n",
185 | "lr = ... # learning rate\n",
186 | "\n",
187 | "for epoch in range(epochs):\n",
188 | "\n",
189 | " with tf.GradientTape() as tape:\n",
190 | " output = model(x, training=True)\n",
191 | " # Compute loss value\n",
192 | " loss_value = loss(tf.convert_to_tensor(y), output)\n",
193 | " grads = tape.gradient(...)\n",
194 | " \n",
195 | " for weight, grad in zip(model.trainable_weights, grads):\n",
196 | " weight.assign_sub(...)\n",
197 | "\n",
198 | " print(\"Current loss at epoch %d: %.4f\" % (epoch, float(loss_value)))"
199 | ]
200 | },
201 | {
202 | "cell_type": "markdown",
203 | "metadata": {},
204 | "source": [
205 | "### Performance of the fitted model\n",
206 | "Plot data and model after the training"
207 | ]
208 | },
209 | {
210 | "cell_type": "code",
211 | "execution_count": null,
212 | "metadata": {},
213 | "outputs": [],
214 | "source": [
215 | "fig, ax = plt.subplots(1)\n",
216 | "\n",
217 | "y_pred = model(x)\n",
218 | "\n",
219 | "ax.plot(x, y, 'bo', label='data')\n",
220 | "ax.plot(x, y_pred, 'r-', label='model')\n",
221 | "ax.set(xlabel='$x$', ylabel='$y$')\n",
222 | "ax.grid()\n",
223 | "ax.legend(loc='lower right')\n",
224 | "plt.tight_layout()"
225 | ]
226 | }
227 | ],
228 | "metadata": {
229 | "kernelspec": {
230 | "display_name": "Python 3",
231 | "language": "python",
232 | "name": "python3"
233 | },
234 | "language_info": {
235 | "codemirror_mode": {
236 | "name": "ipython",
237 | "version": 3
238 | },
239 | "file_extension": ".py",
240 | "mimetype": "text/x-python",
241 | "name": "python",
242 | "nbconvert_exporter": "python",
243 | "pygments_lexer": "ipython3",
244 | "version": "3.6.9"
245 | }
246 | },
247 | "nbformat": 4,
248 | "nbformat_minor": 4
249 | }
250 |
--------------------------------------------------------------------------------
/Exercise_04_3.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 4.3\n",
8 | "## Classification\n",
9 | "In the following tasks, we will repeatedly use some basic functions (e.g., the softmax function or the cross-entropy) of the [Keras](https://keras.io/) Library. To familiarize with them, we will implement the most important of them ourselves in this task.\n",
10 | "\n",
11 | "Suppose we want to classify some data (4 samples) into 3 distinct classes: 0, 1, and 2.\n",
12 | "We have set up a network with a pre-activation output `z` in the last layer.\n",
13 | "Applying softmax will give the final model output.\n",
14 | "\n",
15 | "input X ---> some network --> `z`
\n",
16 | "--> `y_model = softmax(z)`\n",
17 | "\n",
18 | "We quantify the agreement between truth (y) and model using categorical cross-entropy.\n",
19 | "\n",
20 | "$$J = - \\sum_i (y_i * \\log(y_\\mathrm{model}(x_i))$$\n",
21 | "\n",
22 | "In the following you are to implement softmax and categorical cross-entropy\n",
23 | "and evaluate them values given the values for `z`."
24 | ]
25 | },
26 | {
27 | "cell_type": "code",
28 | "execution_count": 1,
29 | "metadata": {},
30 | "outputs": [],
31 | "source": [
32 | "import numpy as np"
33 | ]
34 | },
35 | {
36 | "cell_type": "markdown",
37 | "metadata": {},
38 | "source": [
39 | "##### Data: 4 samples with the following class labels (input features X irrelevant here)"
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": 2,
45 | "metadata": {},
46 | "outputs": [],
47 | "source": [
48 | "y_cl = np.array([0, 0, 2, 1])"
49 | ]
50 | },
51 | {
52 | "cell_type": "markdown",
53 | "metadata": {},
54 | "source": [
55 | "##### output of the last network layer before applying softmax"
56 | ]
57 | },
58 | {
59 | "cell_type": "code",
60 | "execution_count": 3,
61 | "metadata": {},
62 | "outputs": [],
63 | "source": [
64 | "z = np.array([\n",
65 | " [4, 5, 1],\n",
66 | " [-1, -2, -3],\n",
67 | " [0.1, 0.2, 0.3],\n",
68 | " [-1, 17, 1]\n",
69 | " ]).astype(np.float32)"
70 | ]
71 | },
72 | {
73 | "cell_type": "markdown",
74 | "metadata": {},
75 | "source": [
76 | "## Task 1)\n",
77 | "Write a function that turns any class labels `y_cl` into one-hot encodings `y`.\n",
78 | "\n",
79 | "0 --> (1, 0, 0)
\n",
80 | "1 --> (0, 1, 0)
\n",
81 | "2 --> (0, 0, 1)
\n",
82 | "\n",
83 | "Make sure that `np.shape(y) = (4, 3)` for `np.shape(y_cl) = (4)`.\n",
84 | "\n"
85 | ]
86 | },
87 | {
88 | "cell_type": "code",
89 | "execution_count": null,
90 | "metadata": {},
91 | "outputs": [],
92 | "source": []
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {},
97 | "source": [
98 | "## Task 2)\n",
99 | "Write a function that returns the softmax of the input `z` along the last axis"
100 | ]
101 | },
102 | {
103 | "cell_type": "code",
104 | "execution_count": null,
105 | "metadata": {},
106 | "outputs": [],
107 | "source": []
108 | },
109 | {
110 | "cell_type": "markdown",
111 | "metadata": {},
112 | "source": [
113 | "## Task 3)\n",
114 | "Compute the categorical cross-entropy between data and model"
115 | ]
116 | },
117 | {
118 | "cell_type": "code",
119 | "execution_count": null,
120 | "metadata": {},
121 | "outputs": [],
122 | "source": []
123 | },
124 | {
125 | "cell_type": "markdown",
126 | "metadata": {},
127 | "source": [
128 | "## Task 4)\n",
129 | "Determine which calsses are predicted by the model (maximum prediction)"
130 | ]
131 | },
132 | {
133 | "cell_type": "code",
134 | "execution_count": null,
135 | "metadata": {},
136 | "outputs": [],
137 | "source": []
138 | },
139 | {
140 | "cell_type": "markdown",
141 | "metadata": {},
142 | "source": [
143 | "## Task 5)\n",
144 | "Estimate how many samples are classified correctly (accuracy)"
145 | ]
146 | },
147 | {
148 | "cell_type": "code",
149 | "execution_count": null,
150 | "metadata": {},
151 | "outputs": [],
152 | "source": []
153 | }
154 | ],
155 | "metadata": {
156 | "kernelspec": {
157 | "display_name": "Python 3",
158 | "language": "python",
159 | "name": "python3"
160 | },
161 | "language_info": {
162 | "codemirror_mode": {
163 | "name": "ipython",
164 | "version": 3
165 | },
166 | "file_extension": ".py",
167 | "mimetype": "text/x-python",
168 | "name": "python",
169 | "nbconvert_exporter": "python",
170 | "pygments_lexer": "ipython3",
171 | "version": "3.6.9"
172 | }
173 | },
174 | "nbformat": 4,
175 | "nbformat_minor": 4
176 | }
177 |
--------------------------------------------------------------------------------
/Exercise_04_3_solution.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 4.3 - Solution\n",
8 | "## Classification\n",
9 | "In the following tasks, we will repeatedly use some basic functions (e.g., the softmax function or the cross-entropy) of the [Keras](https://keras.io/) Library. To familiarize with them, we will implement the most important of them ourselves in this task.\n",
10 | "\n",
11 | "Suppose we want to classify some data (4 samples) into 3 distinct classes: 0, 1, and 2.\n",
12 | "We have set up a network with a pre-activation output `z` in the last layer.\n",
13 | "Applying softmax will give the final model output.\n",
14 | "\n",
15 | "input X ---> some network --> `z`
\n",
16 | "--> `y_model = softmax(z)`\n",
17 | "\n",
18 | "We quantify the agreement between truth (y) and model using categorical cross-entropy.\n",
19 | "\n",
20 | "$$J = - \\sum_i (y_i * \\log(y_\\mathrm{model}(x_i))$$\n",
21 | "\n",
22 | "In the following you are to implement softmax and categorical cross-entropy\n",
23 | "and evaluate them values given the values for `z`."
24 | ]
25 | },
26 | {
27 | "cell_type": "code",
28 | "execution_count": 1,
29 | "metadata": {},
30 | "outputs": [],
31 | "source": [
32 | "import numpy as np"
33 | ]
34 | },
35 | {
36 | "cell_type": "markdown",
37 | "metadata": {},
38 | "source": [
39 | "##### Data: 4 samples with the following class labels (input features X irrelevant here)"
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": 2,
45 | "metadata": {},
46 | "outputs": [],
47 | "source": [
48 | "y_cl = np.array([0, 0, 2, 1])"
49 | ]
50 | },
51 | {
52 | "cell_type": "markdown",
53 | "metadata": {},
54 | "source": [
55 | "##### output of the last network layer before applying softmax"
56 | ]
57 | },
58 | {
59 | "cell_type": "code",
60 | "execution_count": 3,
61 | "metadata": {},
62 | "outputs": [],
63 | "source": [
64 | "z = np.array([\n",
65 | " [4, 5, 1],\n",
66 | " [-1, -2, -3],\n",
67 | " [0.1, 0.2, 0.3],\n",
68 | " [-1, 17, 1]\n",
69 | " ]).astype(np.float32)"
70 | ]
71 | },
72 | {
73 | "cell_type": "markdown",
74 | "metadata": {},
75 | "source": [
76 | "## Task 1)\n",
77 | "Write a function that turns any class labels `y_cl` into one-hot encodings `y`.\n",
78 | "\n",
79 | "0 --> (1, 0, 0)
\n",
80 | "1 --> (0, 1, 0)
\n",
81 | "2 --> (0, 0, 1)
\n",
82 | "\n",
83 | "Make sure that `np.shape(y) = (4, 3)` for `np.shape(y_cl) = (4)`.\n",
84 | "\n"
85 | ]
86 | },
87 | {
88 | "cell_type": "code",
89 | "execution_count": 4,
90 | "metadata": {},
91 | "outputs": [
92 | {
93 | "name": "stdout",
94 | "output_type": "stream",
95 | "text": [
96 | "one-hot encoding of data labels\n",
97 | "[[1. 0. 0.]\n",
98 | " [1. 0. 0.]\n",
99 | " [0. 0. 1.]\n",
100 | " [0. 1. 0.]]\n"
101 | ]
102 | }
103 | ],
104 | "source": [
105 | "def to_onehot(y_cl, num_classes):\n",
106 | " y = np.zeros((len(y_cl), num_classes))\n",
107 | " y[np.arange(4), y_cl] = 1\n",
108 | " return y\n",
109 | "\n",
110 | "y = to_onehot(y_cl, num_classes=3)\n",
111 | "print('one-hot encoding of data labels')\n",
112 | "print(y)"
113 | ]
114 | },
115 | {
116 | "cell_type": "markdown",
117 | "metadata": {},
118 | "source": [
119 | "## Task 2)\n",
120 | "Write a function that returns the softmax of the input `z` along the last axis"
121 | ]
122 | },
123 | {
124 | "cell_type": "code",
125 | "execution_count": 5,
126 | "metadata": {},
127 | "outputs": [
128 | {
129 | "name": "stdout",
130 | "output_type": "stream",
131 | "text": [
132 | "softmax(z)\n",
133 | "[[2.6538792e-01 7.2139925e-01 1.3212887e-02]\n",
134 | " [6.6524100e-01 2.4472848e-01 9.0030573e-02]\n",
135 | " [3.0060962e-01 3.3222499e-01 3.6716542e-01]\n",
136 | " [1.5229979e-08 9.9999994e-01 1.1253517e-07]]\n"
137 | ]
138 | }
139 | ],
140 | "source": [
141 | "def softmax(z):\n",
142 | " expz = np.exp(z).T\n",
143 | " return (expz / np.sum(expz, axis=0)).T\n",
144 | "\n",
145 | "y_model = softmax(z)\n",
146 | "print('softmax(z)')\n",
147 | "print(y_model)"
148 | ]
149 | },
150 | {
151 | "cell_type": "markdown",
152 | "metadata": {},
153 | "source": [
154 | "## Task 3)\n",
155 | "Compute the categorical cross-entropy between data and model"
156 | ]
157 | },
158 | {
159 | "cell_type": "code",
160 | "execution_count": 6,
161 | "metadata": {},
162 | "outputs": [
163 | {
164 | "name": "stdout",
165 | "output_type": "stream",
166 | "text": [
167 | "cross entropy = 0.684028\n"
168 | ]
169 | }
170 | ],
171 | "source": [
172 | "crossentropy = -np.mean(np.sum(y * np.log(y_model), axis=1))\n",
173 | "crossentropy = -np.mean(np.log(y_model[np.arange(4), y_cl])) # alternative formulation\n",
174 | "print('cross entropy = %f' % crossentropy)"
175 | ]
176 | },
177 | {
178 | "cell_type": "markdown",
179 | "metadata": {},
180 | "source": [
181 | "## Task 4)\n",
182 | "Determine which calsses are predicted by the model (maximum prediction)"
183 | ]
184 | },
185 | {
186 | "cell_type": "code",
187 | "execution_count": 7,
188 | "metadata": {},
189 | "outputs": [
190 | {
191 | "name": "stdout",
192 | "output_type": "stream",
193 | "text": [
194 | "\n",
195 | "true class labels = [0 0 2 1]\n",
196 | "predicted class labels = [1 0 2 1]\n"
197 | ]
198 | }
199 | ],
200 | "source": [
201 | "y_model_cl = np.argmax(y_model, axis=1)\n",
202 | "print('\\ntrue class labels = ', y_cl)\n",
203 | "print('predicted class labels =', y_model_cl)"
204 | ]
205 | },
206 | {
207 | "cell_type": "markdown",
208 | "metadata": {},
209 | "source": [
210 | "## Task 5)\n",
211 | "Estimate how many samples are classified correctly (accuracy)"
212 | ]
213 | },
214 | {
215 | "cell_type": "code",
216 | "execution_count": 8,
217 | "metadata": {},
218 | "outputs": [
219 | {
220 | "name": "stdout",
221 | "output_type": "stream",
222 | "text": [
223 | "accuracy = 0.75\n"
224 | ]
225 | }
226 | ],
227 | "source": [
228 | "accuracy = np.mean(y_model_cl == y_cl)\n",
229 | "print('accuracy = %.2f' % accuracy)"
230 | ]
231 | }
232 | ],
233 | "metadata": {
234 | "kernelspec": {
235 | "display_name": "Python 3",
236 | "language": "python",
237 | "name": "python3"
238 | },
239 | "language_info": {
240 | "codemirror_mode": {
241 | "name": "ipython",
242 | "version": 3
243 | },
244 | "file_extension": ".py",
245 | "mimetype": "text/x-python",
246 | "name": "python",
247 | "nbconvert_exporter": "python",
248 | "pygments_lexer": "ipython3",
249 | "version": "3.6.9"
250 | }
251 | },
252 | "nbformat": 4,
253 | "nbformat_minor": 4
254 | }
255 |
--------------------------------------------------------------------------------
/Exercise_05_1.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 5.1\n",
8 | "## Overtraining and Regularization:\n",
9 | "Open the Tensorflow Playground\n",
10 | "(https://playground.tensorflow.org) and select on the left the checkerboard\n",
11 | "pattern as the data basis (see [Exercise 3.3](Exercise_3_3.ipynb)). As input features, select the two\n",
12 | "independent variables $x_1$ and $x_2$ and set the noise to $50\\%$.\n",
13 | "\n",
14 | "\n",
15 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=50&networkShape=6,6,6,6,6&seed=0.82577&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=true)\n",
16 | "\n",
17 | "\n",
18 | "## Tasks\n",
19 | "1. Choose a deep (many layers) and wide (many nodes) network and train it for more than 1000 epochs. Comment on your observations.\n",
20 | "2. Apply L2 regularization to reduce overfitting. Try low and high regularization rates. What do you observe?\n",
21 | "3. Compare the effects of L1 and L2 regularization."
22 | ]
23 | }
24 | ],
25 | "metadata": {
26 | "kernelspec": {
27 | "display_name": "Python 3",
28 | "language": "python",
29 | "name": "python3"
30 | },
31 | "language_info": {
32 | "codemirror_mode": {
33 | "name": "ipython",
34 | "version": 3
35 | },
36 | "file_extension": ".py",
37 | "mimetype": "text/x-python",
38 | "name": "python",
39 | "nbconvert_exporter": "python",
40 | "pygments_lexer": "ipython3",
41 | "version": "3.6.9"
42 | }
43 | },
44 | "nbformat": 4,
45 | "nbformat_minor": 4
46 | }
47 |
--------------------------------------------------------------------------------
/Exercise_05_1_solution.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 5.1 - Solution\n",
8 | "## Overtraining and Regularization:\n",
9 | "Open the Tensorflow Playground\n",
10 | "(https://playground.tensorflow.org) and select on the left the checkerboard\n",
11 | "pattern as the data basis (see [Exercise 3.3](Exercise_3_3.ipynb)). As input features, select the two\n",
12 | "independent variables $x_1$ and $x_2$ and set the noise to $50\\%$.\n",
13 | "\n",
14 | "\n",
15 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=50&networkShape=6,6,6,6,6&seed=0.82577&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=true)\n",
16 | "\n",
17 | "## Tasks\n",
18 | "1. Choose a deep (many layers) and wide (many nodes) network and train it for more than 1000 epochs. Comment on your observations.\n",
19 | "2. Apply L2 regularization to reduce overfitting. Try low and high regularization rates. What do you observe?\n",
20 | "3. Compare the effects of L1 and L2 regularization."
21 | ]
22 | },
23 | {
24 | "cell_type": "markdown",
25 | "metadata": {},
26 | "source": [
27 | "## Solutions"
28 | ]
29 | },
30 | {
31 | "cell_type": "markdown",
32 | "metadata": {},
33 | "source": [
34 | "### Task 1.\n",
35 | "Choose a deep (many layers) and wide (many nodes) network and train it for more than 1000 epochs. Comment on your observations.\n"
36 | ]
37 | },
38 | {
39 | "cell_type": "markdown",
40 | "metadata": {},
41 | "source": [
42 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=50&networkShape=6,6,6,6&seed=0.38222&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=true)\n",
43 | "\n",
44 | "Overtraining is observed (the network learns statistical fluctuations)."
45 | ]
46 | },
47 | {
48 | "cell_type": "markdown",
49 | "metadata": {},
50 | "source": [
51 | "## Task 2\n",
52 | "Apply L2 regularization to reduce overfitting. Try low and high regularization rates. What do you observe?\n",
53 | "\n",
54 | "#### Low regularization rates"
55 | ]
56 | },
57 | {
58 | "cell_type": "markdown",
59 | "metadata": {},
60 | "source": [
61 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0.001&noise=50&networkShape=6,6,6,6,6&seed=0.82577&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=true)\n",
62 | "\n",
63 | " For very low regularization rates ($\\lambda \\rightarrow 0$), the L2 norm penalty is only hardly considered in the training. Thus, the network is still overfitting. \n",
64 | "\n",
65 | "#### High regularization rates\n",
66 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=10&noise=50&networkShape=6,6,6,6,6&seed=0.82577&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=true)\n",
67 | "\n",
68 | "\n",
69 | " For high regularization rates ($\\lambda >> 0$), almost only the L2 norm penalty is considered in training. Thus, all adaptive parameters are pushed to zero. \n",
70 | "\n",
71 | "#### Moderate regularization rates\n",
72 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=10&noise=50&networkShape=6,6,6,6,6&seed=0.82577&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=true)\n",
73 | "\n",
74 | " For moderate regularization rates, no overtraining can be observed.\n"
75 | ]
76 | },
77 | {
78 | "cell_type": "markdown",
79 | "metadata": {},
80 | "source": [
81 | "## Task 3\n",
82 | "Compare the effects of L1 and L2 regularization."
83 | ]
84 | },
85 | {
86 | "cell_type": "markdown",
87 | "metadata": {},
88 | "source": [
89 | "[](https://playground.tensorflow.org/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=50&networkShape=6,6,6,6,6&seed=0.82577&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=true)\n",
90 | "\n",
91 | "As was observed in Task 1 and Task 2, L2 regularization with moderate regularization rates pushes the weights to smaller values — but not to zero. \n",
92 | "\n",
93 | "In contrast, L1 regularization pushes certain, unimportant weights to zero. Therefore, L1 regularization can, in principle, be used as a feature-selection technique."
94 | ]
95 | }
96 | ],
97 | "metadata": {
98 | "kernelspec": {
99 | "display_name": "Python 3",
100 | "language": "python",
101 | "name": "python3"
102 | },
103 | "language_info": {
104 | "codemirror_mode": {
105 | "name": "ipython",
106 | "version": 3
107 | },
108 | "file_extension": ".py",
109 | "mimetype": "text/x-python",
110 | "name": "python",
111 | "nbconvert_exporter": "python",
112 | "pygments_lexer": "ipython3",
113 | "version": "3.6.9"
114 | }
115 | },
116 | "nbformat": 4,
117 | "nbformat_minor": 4
118 | }
119 |
--------------------------------------------------------------------------------
/Exercise_05_2.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 5.2\n",
8 | "## Interpolation\n",
9 | "In this task, we implement a simple NN to learn a complicated function."
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": 2,
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "import numpy as np\n",
19 | "from tensorflow import keras\n",
20 | "import matplotlib.pyplot as plt\n",
21 | "\n",
22 | "layers = keras.layers"
23 | ]
24 | },
25 | {
26 | "cell_type": "markdown",
27 | "metadata": {},
28 | "source": [
29 | "### Generation of data"
30 | ]
31 | },
32 | {
33 | "cell_type": "code",
34 | "execution_count": 2,
35 | "metadata": {},
36 | "outputs": [],
37 | "source": [
38 | "def some_complicated_function(x):\n",
39 | " return (\n",
40 | " (np.abs(x)) ** 0.5\n",
41 | " + 0.1 * x\n",
42 | " + 0.01 * x ** 2\n",
43 | " + 1\n",
44 | " - np.sin(x)\n",
45 | " + 0.5 * np.exp(x / 10.0)\n",
46 | " ) / (0.5 + np.abs(np.cos(x)))"
47 | ]
48 | },
49 | {
50 | "cell_type": "markdown",
51 | "metadata": {},
52 | "source": [
53 | "Let's simulate the train data"
54 | ]
55 | },
56 | {
57 | "cell_type": "code",
58 | "execution_count": 3,
59 | "metadata": {},
60 | "outputs": [],
61 | "source": [
62 | "N_train = 10 ** 4 # number of training samples\n",
63 | "# Note: \"[:, np.newaxis]\" reshapes array to (N,1) as required by our DNN (we input one feature per sample)\n",
64 | "xtrain = np.random.uniform(-10, 10, N_train)[:, np.newaxis]\n",
65 | "ytrain = some_complicated_function(xtrain) + np.random.randn(xtrain.shape[0]) # train data includes some noise"
66 | ]
67 | },
68 | {
69 | "cell_type": "code",
70 | "execution_count": 4,
71 | "metadata": {},
72 | "outputs": [
73 | {
74 | "name": "stdout",
75 | "output_type": "stream",
76 | "text": [
77 | "xtrain.shape (10000, 1)\n",
78 | "ytrain.shape (10000, 10000)\n"
79 | ]
80 | }
81 | ],
82 | "source": [
83 | "print(\"xtrain.shape\", xtrain.shape)\n",
84 | "print(\"ytrain.shape\", ytrain.shape)"
85 | ]
86 | },
87 | {
88 | "cell_type": "markdown",
89 | "metadata": {},
90 | "source": [
91 | "Simulate test data"
92 | ]
93 | },
94 | {
95 | "cell_type": "code",
96 | "execution_count": 5,
97 | "metadata": {},
98 | "outputs": [],
99 | "source": [
100 | "N_test = 10000 # number of testing samples\n",
101 | "xtest = np.linspace(-10, 10, N_test)\n",
102 | "ytest = some_complicated_function(xtest)"
103 | ]
104 | },
105 | {
106 | "cell_type": "code",
107 | "execution_count": 6,
108 | "metadata": {},
109 | "outputs": [
110 | {
111 | "name": "stdout",
112 | "output_type": "stream",
113 | "text": [
114 | "xtest.shape (10000,)\n",
115 | "ytest.shape (10000,)\n"
116 | ]
117 | }
118 | ],
119 | "source": [
120 | "print(\"xtest.shape\", xtest.shape)\n",
121 | "print(\"ytest.shape\", ytest.shape)"
122 | ]
123 | },
124 | {
125 | "cell_type": "markdown",
126 | "metadata": {},
127 | "source": [
128 | "### Define Model\n",
129 | "\n",
130 | "Define the number of nodes, the number of layers, and choose an activation function.\n",
131 | "Use `keras.regularizers` to use parameter norm penalties or add a dropout layer via `layers.Dropout(fraction)`.\n",
132 | "\n",
133 | "You may use the skeleton below:"
134 | ]
135 | },
136 | {
137 | "cell_type": "code",
138 | "execution_count": null,
139 | "metadata": {},
140 | "outputs": [],
141 | "source": [
142 | "nb_nodes = 1\n",
143 | "nb_layers = 1\n",
144 | "activation = \"\"\n",
145 | "\n",
146 | "model = keras.models.Sequential(name=\"1Dfit\")\n",
147 | "model.add(layers.Dense(nb_nodes, activation=activation, input_dim=xtrain.shape[1])) # first layer\n",
148 | "\n",
149 | "model.add(layers.Dense(1)) # final layer\n",
150 | "\n",
151 | "print(model.summary())"
152 | ]
153 | },
154 | {
155 | "cell_type": "markdown",
156 | "metadata": {},
157 | "source": [
158 | "### Compile the model (set an objective and choose an optimizer)"
159 | ]
160 | },
161 | {
162 | "cell_type": "markdown",
163 | "metadata": {},
164 | "source": [
165 | "Choose an optimizer from `keras.optimizers`, e.g., `adam = keras.optimizers.Adam(lr=0.001)`.\n",
166 | "\n",
167 | "Further, choose the correct objective (loss) for this regression task."
168 | ]
169 | },
170 | {
171 | "cell_type": "code",
172 | "execution_count": 8,
173 | "metadata": {},
174 | "outputs": [],
175 | "source": [
176 | "model.compile(loss=\"\", optimizer=)"
177 | ]
178 | },
179 | {
180 | "cell_type": "markdown",
181 | "metadata": {},
182 | "source": [
183 | "### Train the model"
184 | ]
185 | },
186 | {
187 | "cell_type": "markdown",
188 | "metadata": {},
189 | "source": [
190 | "Train the network for a couple of epochs and save the model several times in between."
191 | ]
192 | },
193 | {
194 | "cell_type": "code",
195 | "execution_count": null,
196 | "metadata": {},
197 | "outputs": [],
198 | "source": [
199 | "epochs = \n",
200 | "save_period = # after how many epochs the model should be saved?\n",
201 | "\n",
202 | "chkpnt_saver = keras.callbacks.ModelCheckpoint(\"weights-{epoch:02d}.hdf5\", save_weights_only=True, save_freq=save_period)\n",
203 | "\n",
204 | "results = model.fit(\n",
205 | " xtrain,\n",
206 | " ytrain,\n",
207 | " batch_size=64,\n",
208 | " epochs=epochs,\n",
209 | " verbose=1,\n",
210 | " callbacks=[chkpnt_saver]\n",
211 | " )"
212 | ]
213 | },
214 | {
215 | "cell_type": "markdown",
216 | "metadata": {},
217 | "source": [
218 | "Compare the performance of the model during the training. You may use the skeleton below:"
219 | ]
220 | },
221 | {
222 | "cell_type": "code",
223 | "execution_count": null,
224 | "metadata": {},
225 | "outputs": [],
226 | "source": [
227 | "fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(12, 8))\n",
228 | "\n",
229 | "ax1.plot(xtest, ytest, color=\"black\", label=\"data\")\n",
230 | "saved_epochs = range(save_period, epochs + 1, save_period)\n",
231 | "\n",
232 | "colors = [plt.cm.jet((i + 1) / float(len(saved_epochs) + 1)) for i in range(len(saved_epochs))]\n",
233 | "\n",
234 | "for i, epoch in enumerate(saved_epochs):\n",
235 | " model.load_weights(\"weights-{epoch:02d}.hdf5\".format(epoch=epoch))\n",
236 | " ypredict = model.predict(xtest).squeeze()\n",
237 | " ax1.plot(xtest.squeeze(), ypredict, color=colors[i], label=epoch)\n",
238 | " ax2.plot(epoch, results.history[\"loss\"][epoch - 1], color=colors[i], marker=\"o\")\n",
239 | "\n",
240 | "ax1.set(xlabel=\"x\", ylabel=\"some_complicated_function(x)\", xlim=(-10, 13), title=\"\")\n",
241 | "ax1.grid(True)\n",
242 | "ax1.legend(loc=\"upper right\", title=\"Epochs\")\n",
243 | "\n",
244 | "ax2.plot(results.history[\"loss\"], color=\"black\")\n",
245 | "ax2.set(xlabel=\"epoch\", ylabel=\"loss\")\n",
246 | "ax2.grid(True)\n",
247 | "ax2.semilogy()\n",
248 | "\n",
249 | "plt.show()"
250 | ]
251 | }
252 | ],
253 | "metadata": {
254 | "kernelspec": {
255 | "display_name": "Python 3",
256 | "language": "python",
257 | "name": "python3"
258 | },
259 | "language_info": {
260 | "codemirror_mode": {
261 | "name": "ipython",
262 | "version": 3
263 | },
264 | "file_extension": ".py",
265 | "mimetype": "text/x-python",
266 | "name": "python",
267 | "nbconvert_exporter": "python",
268 | "pygments_lexer": "ipython3",
269 | "version": "3.6.9"
270 | }
271 | },
272 | "nbformat": 4,
273 | "nbformat_minor": 4
274 | }
275 |
--------------------------------------------------------------------------------
/Exercise_05_3.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "id": "WSW9BmePM7zZ"
7 | },
8 | "source": [
9 | "# Exercise 5.3: Neural Networks in Keras"
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": 1,
15 | "metadata": {
16 | "id": "t02FemO-M7za"
17 | },
18 | "outputs": [],
19 | "source": [
20 | "import numpy as np\n",
21 | "import matplotlib.pyplot as plt\n",
22 | "\n",
23 | "# See https://keras.io/\n",
24 | "# for extennsive documentation\n",
25 | "import tensorflow as tf\n",
26 | "from tensorflow import keras\n",
27 | "\n",
28 | "from keras.models import Sequential\n",
29 | "from keras.layers import Dense"
30 | ]
31 | },
32 | {
33 | "cell_type": "markdown",
34 | "metadata": {
35 | "id": "IrvyHKHTM7ze"
36 | },
37 | "source": [
38 | "Let us visit the problem of wine quality prediction previ- ously encountered in Exercises 3.2 and 4.1 one final time. After linear regression and a self-made network, we can now explore the comfort provided by the Keras library."
39 | ]
40 | },
41 | {
42 | "cell_type": "code",
43 | "execution_count": null,
44 | "metadata": {
45 | "colab": {
46 | "base_uri": "https://localhost:8080/"
47 | },
48 | "id": "-H-L5egsM7ze",
49 | "outputId": "82d3f95f-59b1-43e3-e8d7-4d939ea7eec6"
50 | },
51 | "outputs": [],
52 | "source": [
53 | "# The code snippet below is responsible for downloading the dataset to\n",
54 | "# Google. You can directly download the file using the link\n",
55 | "# if you work with a local anaconda setup\n",
56 | "!wget https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"
57 | ]
58 | },
59 | {
60 | "cell_type": "code",
61 | "execution_count": null,
62 | "metadata": {
63 | "colab": {
64 | "base_uri": "https://localhost:8080/"
65 | },
66 | "id": "mDToshKJNWGY",
67 | "outputId": "8cce4ba8-392b-43a1-d659-26aa95d21113"
68 | },
69 | "outputs": [],
70 | "source": [
71 | "# load all examples from the file\n",
72 | "data = np.genfromtxt('winequality-white.csv',delimiter=\";\",skip_header=1)\n",
73 | "\n",
74 | "print(\"data:\", data.shape)\n",
75 | "\n",
76 | "# Prepare for proper training\n",
77 | "np.random.shuffle(data) # randomly sort examples\n",
78 | "\n",
79 | "# take the first 3000 examples for training\n",
80 | "X_train = data[:3000,:11] # all features except last column\n",
81 | "y_train = data[:3000,11] # quality column\n",
82 | "\n",
83 | "# and the remaining examples for testing\n",
84 | "X_test = data[3000:,:11] # all features except last column\n",
85 | "y_test = data[3000:,11] # quality column\n",
86 | "\n",
87 | "print(\"First example:\")\n",
88 | "print(\"Features:\", X_train[0])\n",
89 | "print(\"Quality:\", y_train[0])\n"
90 | ]
91 | },
92 | {
93 | "cell_type": "markdown",
94 | "metadata": {
95 | "id": "VXx8BXB_M7zi"
96 | },
97 | "source": [
98 | "Below is the simple network from exercise 4.1 implemented using Keras. In addition to the network we define the loss function and optimiser."
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": null,
104 | "metadata": {
105 | "id": "Z0HMdw9eM7zi"
106 | },
107 | "outputs": [],
108 | "source": [
109 | "# See: https://keras.io/api/models/sequential/ and \n",
110 | "# https://keras.io/api/layers/core_layers/dense/\n",
111 | "# We can use the Sequential class to very easiliy\n",
112 | "# build a simple architecture\n",
113 | "model = Sequential()\n",
114 | "# 11 inputs, 20 outputs, relu\n",
115 | "model.add(Dense(20, input_dim=11, activation='relu')) \n",
116 | "# 20 inputs (automatically detected by Keras), 1 output, linear activation\n",
117 | "model.add(Dense(1, activation='linear'))\n",
118 | "\n",
119 | "\n",
120 | "# Set loss function and optimiser algorithm\n",
121 | "model.compile(loss='mse', # mean squared error\n",
122 | " optimizer='sgd'# stochastic gradient descent\n",
123 | " ) "
124 | ]
125 | },
126 | {
127 | "cell_type": "markdown",
128 | "metadata": {
129 | "id": "I98jdZcqM7zm"
130 | },
131 | "source": [
132 | "# Training and evaluation below\n",
133 | "\n",
134 | "The code below trains the network for 5 epochs using the loss function and optimiser defined above. Each example is individually passed to the network"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": null,
140 | "metadata": {},
141 | "outputs": [],
142 | "source": [
143 | "history = model.fit(X_train, y_train, \n",
144 | " validation_data=(X_test, y_test),\n",
145 | " epochs=5, batch_size=1)\n"
146 | ]
147 | },
148 | {
149 | "cell_type": "code",
150 | "execution_count": null,
151 | "metadata": {},
152 | "outputs": [],
153 | "source": [
154 | "# The history object returned by the model training above \n",
155 | "# contains the values of the loss function (the mean-squared-error)\n",
156 | "# at different epochs\n",
157 | "# We discard the first epoch as the loss value is very high,\n",
158 | "# obscuring the rest of the distribution\n",
159 | "train_loss = history.history[\"loss\"][1:]\n",
160 | "test_loss = history.history[\"val_loss\"][1:]"
161 | ]
162 | },
163 | {
164 | "cell_type": "code",
165 | "execution_count": null,
166 | "metadata": {},
167 | "outputs": [],
168 | "source": [
169 | "# Prepare and plot loss over time\n",
170 | "plt.plot(train_loss,label=\"train\")\n",
171 | "plt.plot(test_loss,label=\"test\")\n",
172 | "plt.legend()\n",
173 | "plt.xlabel(\"Epoch-1\")\n",
174 | "plt.ylabel(\"Loss\")\n",
175 | "plt.show()"
176 | ]
177 | },
178 | {
179 | "cell_type": "code",
180 | "execution_count": null,
181 | "metadata": {},
182 | "outputs": [],
183 | "source": [
184 | "# After the training:\n",
185 | "\n",
186 | "# Prepare scatter plot\n",
187 | "y_pred = model.predict(X_test)[:,0]\n",
188 | "\n",
189 | "print(\"Correlation coefficient:\", np.corrcoef(y_pred,y_test)[0,1])\n",
190 | "plt.scatter(y_pred,y_test)\n",
191 | "plt.xlabel(\"Predicted\")\n",
192 | "plt.ylabel(\"True\")\n",
193 | "plt.show()"
194 | ]
195 | },
196 | {
197 | "cell_type": "code",
198 | "execution_count": null,
199 | "metadata": {},
200 | "outputs": [],
201 | "source": [
202 | "np.corrcoef(y_pred,y_test)"
203 | ]
204 | },
205 | {
206 | "cell_type": "markdown",
207 | "metadata": {
208 | "id": "KI7zcK_uM7zp"
209 | },
210 | "source": [
211 | "\n",
212 | "# Problems\n",
213 | "\n",
214 | "* Use the notebook as starting point. It already contains the simple network from Exercise 4.1 implemented in Keras.\n",
215 | "\n",
216 | "* Currently, SGD is used without momentum. Try training with a momentum term. Replace SGD with the Adam optimizer and train using that. (See: https://keras.io/api/optimizers/)\n",
217 | "* Add two more hidden layers to the network (you can choose the number of nodes but make sure to apply the ReLu activation function after each) and train again.\n",
218 | "* Test differet numbers of examples (i.e. change the batch batch size) to be simulataneously used by the network. "
219 | ]
220 | },
221 | {
222 | "cell_type": "code",
223 | "execution_count": null,
224 | "metadata": {
225 | "id": "2mUTzx7h2mKJ"
226 | },
227 | "outputs": [],
228 | "source": []
229 | }
230 | ],
231 | "metadata": {
232 | "colab": {
233 | "collapsed_sections": [],
234 | "name": "Exercise 6 - Solution",
235 | "provenance": []
236 | },
237 | "kernelspec": {
238 | "display_name": "Python 3",
239 | "language": "python",
240 | "name": "python3"
241 | },
242 | "language_info": {
243 | "codemirror_mode": {
244 | "name": "ipython",
245 | "version": 3
246 | },
247 | "file_extension": ".py",
248 | "mimetype": "text/x-python",
249 | "name": "python",
250 | "nbconvert_exporter": "python",
251 | "pygments_lexer": "ipython3",
252 | "version": "3.7.6"
253 | }
254 | },
255 | "nbformat": 4,
256 | "nbformat_minor": 1
257 | }
258 |
--------------------------------------------------------------------------------
/Exercise_07_1.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 7.1\n",
8 | "### Classification of magnetic phases using fully-connected networks\n",
9 | "\n",
10 | "Imagine a 2-dimensional lattice arrangement of $n \\times n$ magnetic dipole moments (spins) that can be in one of two states ($+1$ or $−1$, Ising model).\n",
11 | "With interactions between spins being short ranged, each spin interacts only with its four neighbors.\n",
12 | "The probability to find a spin in one of the orientations is a function of temperature $T$ according to $p \\sim e^{−a/T},\\;a = \\mathrm{const.}$).\n",
13 | "\n",
14 | "At extremely low temperatures $T \\rightarrow 0$, neighboring spins have a very low probability of different orientations, so that a uniform overall state (ferromagnetic state) is adopted, characterized by $+1$ or $−1$.\n",
15 | "At very high temperatures $T \\rightarrow \\infty$, a paramagnetic phase with random spin alignment results, yielding $50\\%$ of $+1$ and $0%$ of $−1$ orientations.\n",
16 | "Below a critical temperature $0 < T < T_c$, stable ferromagnetic domains emerge, with both orientations being equally probable in the absence of an external magnetic field.\n",
17 | "The spin-spin correlation function diverges at $T_c$, whereas the correlation decays for $T > T_c$.\n",
18 | "\n",
19 | "The data for this task contain the $n \\times n$ dipole orientations on the lattice for different temperatures $T$.\n",
20 | "Classify the two magnetic phases (paramagnetic/ferromagnetic)!"
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": 6,
26 | "metadata": {},
27 | "outputs": [
28 | {
29 | "name": "stdout",
30 | "output_type": "stream",
31 | "text": [
32 | "keras version 2.4.0\n"
33 | ]
34 | }
35 | ],
36 | "source": [
37 | "from tensorflow import keras\n",
38 | "import numpy as np\n",
39 | "callbacks = keras.callbacks\n",
40 | "layers = keras.layers\n",
41 | "\n"
42 | ]
43 | },
44 | {
45 | "cell_type": "markdown",
46 | "metadata": {},
47 | "source": [
48 | "### Load and prepare dataset\n",
49 | "See https://doi.org/10.1038/nphys4035 for more information"
50 | ]
51 | },
52 | {
53 | "cell_type": "code",
54 | "execution_count": 2,
55 | "metadata": {},
56 | "outputs": [],
57 | "source": [
58 | "import gdown\n",
59 | "url = \"https://drive.google.com/u/0/uc?export=download&confirm=HgGH&id=1Ihxt1hb3Kyv0IrjHlsYb9x9QY7l7n2Sl\"\n",
60 | "output = 'ising_data.npz'\n",
61 | "gdown.download(url, output, quiet=True)\n",
62 | "\n",
63 | "f = np.load(output, allow_pickle=True)\n",
64 | "n_train = 20000\n",
65 | "\n",
66 | "x_train, x_test = f[\"C\"][:n_train], f[\"C\"][n_train:]\n",
67 | "T_train, T_test = f[\"T\"][:n_train], f[\"T\"][n_train:]"
68 | ]
69 | },
70 | {
71 | "cell_type": "code",
72 | "execution_count": 3,
73 | "metadata": {},
74 | "outputs": [
75 | {
76 | "data": {
77 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZkAAAEZCAYAAABFFVgWAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAA7tElEQVR4nO2df4xd1XXvv2vsMQPjGOwMMcbG2C2ZGiUvmBbh15eGEifpCxUpoamsJG2AKk+uWlVJlOrViKcq6WuqOpGaJm2TUkskkAYBF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OAXgFwAuVHbR+xpDH+V7IzHLWX4aU8bIb+VzDKsjlXBsXL4DdY2pm1pipdJIBACJ6jJkvq/SgNTJo55uCQbqGg3SuqRi0a5j7+cqtIA3DMAwjEJtkDMMwjGTUMclsquGYdTJo55uCQbqGg3SuqRi0a5j1+Vb+nYxhGIYxOJhcZhiGYSSj0kmGiN5NRLuI6GkiurHKY6eGiC4gogeJaCcR7SCij5aPLyKi7xDRD8t/F9Y91qbQ5ngBLGZS0OaYaWq8VCaXlYlWT6HI5t0DYCuADzDzzkoGkBgiWgJgCTM/TkSvQ1Hs770AbgBwmJk3lkG/kJk31DfSZtD2eAEsZmLT9phparxUuZK5HMDTzPxs2XjoTgDXVHj8pDDzPmZ+vPz/ywCeRFE19hoUZcpR/vveWgbYPFodL4DFTAJaHTNNjZcqJ5mlAJ53fhdLdzcdIloB4FIAjwJYzMz7yqf2A1hc17gaxsDEC2AxE4mBiZkmxYt98R8ZIpoP4B4AH2Pml9znyuZMZuczpmAxY/jQtHipcpLZC+AC5/fWle4uW8feA+B2Zv5a+fCBUkvtaKoH6xpfw2h9vAAWM5Fpfcw0MV6qnGS2AngjEa0konkA3g/gvgqPnxQiIhRVYp9k5s86T92Hokw50NJy5YlodbwAFjMJaHXMNDVeqq7C/OsAPgdgDoAvMfOfV3bwxBDRrwD4HoAfADhdPnwTCs10M4DlKCoKr2Pmw7UMsmG0OV4Ai5kUtDlmmhovlvFvGIZhJMO++DcMwzCSYZOMYRiGkQybZAzDMIxk2CRjGIZhJMMmGcMwDCMZNskYhmEYybBJxjAMw0iGTTKGYRhGMv4/mvIHrfTPapUAAAAASUVORK5CYII=\n",
78 | "text/plain": [
79 | ""
80 | ]
81 | },
82 | "metadata": {
83 | "needs_background": "light"
84 | },
85 | "output_type": "display_data"
86 | }
87 | ],
88 | "source": [
89 | "import matplotlib.pyplot as plt\n",
90 | "\n",
91 | "for i,j in enumerate(np.random.choice(n_train, 6)):\n",
92 | " plt.subplot(2,3,i+1)\n",
93 | " image = x_train[j]\n",
94 | " plot = plt.imshow(image)\n",
95 | " plt.title(\"T: %.2f\" % T_train[j])\n",
96 | "\n",
97 | "plt.tight_layout()\n",
98 | "plt.show()"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": 4,
104 | "metadata": {},
105 | "outputs": [
106 | {
107 | "data": {
108 | "text/plain": [
109 | "Text(0, 0.5, 'frequency')"
110 | ]
111 | },
112 | "execution_count": 4,
113 | "metadata": {},
114 | "output_type": "execute_result"
115 | },
116 | {
117 | "data": {
118 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYUAAAEGCAYAAACKB4k+AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAT+UlEQVR4nO3df7Ad5X3f8ffHCLCDMeKHoihCtmitxEM7BuM7VLY7HtfEiSEuYlxMYZwgM2TUprTFk860StomTZo/7DYxNWmKRzVOhevaptguKoEkjCCTaWfAvmCMsbHLDTWVFIEuv4RtGrtivv3jPFqOL1fSkXT3HOne92vmzHn22efsfncW8bn74+xJVSFJEsCrJl2AJOnYYShIkjqGgiSpYyhIkjqGgiSps2zSBRyNs846q9auXTvpMiTpuPLAAw88XVUr5pt3XIfC2rVrmZ6ennQZknRcSfLEgeZ5+kiS1DEUJEkdQ0GS1DEUJEkdQ0GS1DEUJEkdQ0GS1DEUJEkdQ0GS1Dmuv9Es6ZXWbv7Diaz3Ox/5+YmsVwvLIwVJUscjBUnHPY+OFk5vRwpJfjrJQ0OvF5J8OMkZSe5O8lh7P72NT5Ibk8wkeTjJBX3VJkmaX2+hUFXfrqrzq+p84K3Ai8CXgM3A9qpaB2xv0wAXA+vaaxNwU1+1SZLmN65rChcBf15VTwAbgK2tfytwWWtvAG6pgfuA5UlWjak+SRLjC4Urgc+29sqq2t3aTwIrW3s1sGPoMztb349IsinJdJLp2dnZvuq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2OZFp6p2V9WDrf1d4FEG35Aftqj29YjbvKi0ffe9Nnlie829U2YDsLW1bwMuSpIxlbigRtzeBbeoQ2EE8z1aY1H/w2re1g5J70ry1yZdzEJqpwvewuCvqmGLdl8fZJthke3rJCckeQjYA9xdVQfcz1W1D9gLnDnWIhfQCNsL8HfaKdHbkqyZZ/5hWeqhsBQ9CLyhqs4Dfg/4b5MtZ+EkeS3wBeDDVfXCpOsZh0Ns86Lb11X1UlWdz+CJBxcm+esTLqlXI2zvfwfWVtWbgbt5+SjpiC31UFhyj9aoqhf2H5JW1Z3AiUnOmnBZRy3JiQz+5/iZqvriPEMW3b4+1DYv1n0NUFXPA/cC750zq9vPSZYBpwHPjLW4Hhxoe6vqmar6QZv8JPDWo13XUg+FbcDV7c6U9cDeqto96aL6lOQn9p9jTXIhg/8Gjut/NG17bgYeraqPHWDYotrXo2zzYtvXSVYkWd7arwHeA3xrzrBtwMbWvhy4p9oV2ePNKNs757rYpQyuLR2VY+YxF31I8lkGd2CclWQn8BsMLtZQVZ8A7mRwV8oM8CJwzWQqXTgjbPPlwC8n2Qf8X+DK4/UfzZB3AL8IfL2dfwX4NeD1sGj39SjbvNj29SpgawY/yPUq4NaquiPJbwHTVbWNQVB+OskMgxsurpxcuUdtlO39x0kuBfYx2N4PHe1KfcyFJKmz1E8fSZKGGAqSpI6hIEnqGAqSpI6hIEnqLOpbUqVxSnImsL1N/gTwEjDbpi+sqh9OpDDpMHhLqtSDJP8K+F5V/c6ka5EOh6ePJEkdQ0GS1DEUJEkdQ0GS1DEUJEkdQ0GS1PGWVElSxyMFSVLHUJAkdQwFSVLHUJAkdQwFSVLHUJAkdQwFSVLn/wM5oOPmFcC43wAAAABJRU5ErkJggg==\n",
119 | "text/plain": [
120 | ""
121 | ]
122 | },
123 | "metadata": {
124 | "needs_background": "light"
125 | },
126 | "output_type": "display_data"
127 | }
128 | ],
129 | "source": [
130 | "plt.hist(T_test)\n",
131 | "plt.xlabel(\"T\")\n",
132 | "plt.ylabel(\"frequency\")"
133 | ]
134 | },
135 | {
136 | "cell_type": "markdown",
137 | "metadata": {},
138 | "source": [
139 | "#### Set up training data - define magnetic phases"
140 | ]
141 | },
142 | {
143 | "cell_type": "code",
144 | "execution_count": 5,
145 | "metadata": {},
146 | "outputs": [],
147 | "source": [
148 | "Tc = 2.27\n",
149 | "y_train, y_test = T_train > Tc, T_test > Tc"
150 | ]
151 | },
152 | {
153 | "cell_type": "markdown",
154 | "metadata": {},
155 | "source": [
156 | " ### Task\n",
157 | "\n",
158 | " - evaluate the test accuracy for a fully-connected network,\n",
159 | " - plot the test accuracy vs. temperature.\n"
160 | ]
161 | }
162 | ],
163 | "metadata": {
164 | "kernelspec": {
165 | "display_name": "Python 3",
166 | "language": "python",
167 | "name": "python3"
168 | },
169 | "language_info": {
170 | "codemirror_mode": {
171 | "name": "ipython",
172 | "version": 3
173 | },
174 | "file_extension": ".py",
175 | "mimetype": "text/x-python",
176 | "name": "python",
177 | "nbconvert_exporter": "python",
178 | "pygments_lexer": "ipython3",
179 | "version": "3.6.9"
180 | }
181 | },
182 | "nbformat": 4,
183 | "nbformat_minor": 4
184 | }
185 |
--------------------------------------------------------------------------------
/Exercise_08_1.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 8.1\n",
8 | "### Classification of magnetic phases using CNNs\n",
9 | "\n",
10 | "Imagine a 2-dimensional lattice arrangement of $n \\times n$ magnetic dipole moments (spins) that can be in one of two states ($+1$ or $−1$, Ising model).\n",
11 | "With interactions between spins being short ranged, each spin interacts only with its four neighbors.\n",
12 | "The probability to find a spin in one of the orientations is a function of temperature $T$ according to $p \\sim e^{−a/T},\\;a = \\mathrm{const.}$).\n",
13 | "\n",
14 | "At extremely low temperatures $T \\rightarrow 0$, neighboring spins have a very low probability of different orientations, so that a uniform overall state (ferromagnetic state) is adopted, characterized by $+1$ or $−1$.\n",
15 | "At very high temperatures $T \\rightarrow \\infty$, a paramagnetic phase with random spin alignment results, yielding $50\\%$ of $+1$ and $0%$ of $−1$ orientations.\n",
16 | "Below a critical temperature $0 < T < T_c$, stable ferromagnetic domains emerge, with both orientations being equally probable in the absence of an external magnetic field.\n",
17 | "The spin-spin correlation function diverges at $T_c$, whereas the correlation decays for $T > T_c$.\n",
18 | "\n",
19 | "The data for this task contain the $n \\times n$ dipole orientations on the lattice for different temperatures $T$.\n",
20 | "Classify the two magnetic phases (paramagnetic/ferromagnetic) using a convolutional neural network!"
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": 6,
26 | "metadata": {},
27 | "outputs": [
28 | {
29 | "name": "stdout",
30 | "output_type": "stream",
31 | "text": [
32 | "keras 2.4.0\n"
33 | ]
34 | }
35 | ],
36 | "source": [
37 | "from tensorflow import keras\n",
38 | "import numpy as np\n",
39 | "callbacks = keras.callbacks\n",
40 | "layers = keras.layers\n",
41 | "\n"
42 | ]
43 | },
44 | {
45 | "cell_type": "markdown",
46 | "metadata": {},
47 | "source": [
48 | "### Load and prepare dataset\n",
49 | "See https://doi.org/10.1038/nphys4035 for more information"
50 | ]
51 | },
52 | {
53 | "cell_type": "code",
54 | "execution_count": 2,
55 | "metadata": {},
56 | "outputs": [],
57 | "source": [
58 | "import gdown\n",
59 | "url = \"https://drive.google.com/u/0/uc?export=download&confirm=HgGH&id=1Ihxt1hb3Kyv0IrjHlsYb9x9QY7l7n2Sl\"\n",
60 | "output = 'ising_data.npz'\n",
61 | "gdown.download(url, output, quiet=True)\n",
62 | "\n",
63 | "f = np.load(output, allow_pickle=True)\n",
64 | "n_train = 20000\n",
65 | "\n",
66 | "x_train, x_test = f[\"C\"][:n_train], f[\"C\"][n_train:]\n",
67 | "T_train, T_test = f[\"T\"][:n_train], f[\"T\"][n_train:]"
68 | ]
69 | },
70 | {
71 | "cell_type": "code",
72 | "execution_count": 3,
73 | "metadata": {},
74 | "outputs": [
75 | {
76 | "data": {
77 | "image/png": "iVBORw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H3gvcrqpfL95+pdBS+5rqnqbm1zI6by9gNlMxnbeZNtpLnU7mCeB9InK6iCwAPgncX+P+kyIiQq9K7LOq+kVn0f30ypRDy0vc10yn7QXMZhLQaZtpq73UXYX5V4E/B+YBX1HVP6lt54kRkV8GHgGeAY4Wb19PTzO9G1hJr6LwOlV9rZFJtowu2wuYzaSgyzbTVnuxjH/DMAwjGfbFv2EYhpEMczKGYRhGMszJGIZhGMkwJ2MYhmEkw5yMYRiGkQxzMoZhGEYyzMkYhmEYyTAnYxiGYSTj/wNaFQ+APuEfWAAAAABJRU5ErkJggg==\n",
78 | "text/plain": [
79 | ""
80 | ]
81 | },
82 | "metadata": {
83 | "needs_background": "light"
84 | },
85 | "output_type": "display_data"
86 | }
87 | ],
88 | "source": [
89 | "import matplotlib.pyplot as plt\n",
90 | "\n",
91 | "for i,j in enumerate(np.random.choice(n_train, 6)):\n",
92 | " plt.subplot(2,3,i+1)\n",
93 | " image = x_train[j]\n",
94 | " plot = plt.imshow(image)\n",
95 | " plt.title(\"T: %.2f\" % T_train[j])\n",
96 | "\n",
97 | "plt.tight_layout()\n",
98 | "plt.show()"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": 4,
104 | "metadata": {},
105 | "outputs": [
106 | {
107 | "data": {
108 | "text/plain": [
109 | "Text(0, 0.5, 'frequency')"
110 | ]
111 | },
112 | "execution_count": 4,
113 | "metadata": {},
114 | "output_type": "execute_result"
115 | },
116 | {
117 | "data": {
118 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYUAAAEGCAYAAACKB4k+AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAT+UlEQVR4nO3df7Ad5X3f8ffHCLCDMeKHoihCtmitxEM7BuM7VLY7HtfEiSEuYlxMYZwgM2TUprTFk860StomTZo/7DYxNWmKRzVO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V8oM8CJwzWQqXTgjbPPlwC8n2Qf8X+DK4/UfzZB3AL8IfL2dfwX4NeD1sGj39SjbvNj29SpgawY/yPUq4NaquiPJbwHTVbWNQVB+OskMgxsurpxcuUdtlO39x0kuBfYx2N4PHe1KfcyFJKmz1E8fSZKGGAqSpI6hIEnqGAqSpI6hIEnqLOpbUqVxSnImsL1N/gTwEjDbpi+sqh9OpDDpMHhLqtSDJP8K+F5V/c6ka5EOh6ePJEkdQ0GS1DEUJEkdQ0GS1DEUJEkdQ0GS1PGWVElSxyMFSVLHUJAkdQwFSVLHUJAkdQwFSVLHUJAkdQwFSVLn/wM5oOPmFcC43wAAAABJRU5ErkJggg==\n",
119 | "text/plain": [
120 | ""
121 | ]
122 | },
123 | "metadata": {
124 | "needs_background": "light"
125 | },
126 | "output_type": "display_data"
127 | }
128 | ],
129 | "source": [
130 | "plt.hist(T_test)\n",
131 | "plt.xlabel(\"T\")\n",
132 | "plt.ylabel(\"frequency\")"
133 | ]
134 | },
135 | {
136 | "cell_type": "markdown",
137 | "metadata": {},
138 | "source": [
139 | "#### Set up training data - define magnetic phases"
140 | ]
141 | },
142 | {
143 | "cell_type": "code",
144 | "execution_count": 5,
145 | "metadata": {},
146 | "outputs": [],
147 | "source": [
148 | "Tc = 2.27\n",
149 | "y_train, y_test = T_train > Tc, T_test > Tc"
150 | ]
151 | },
152 | {
153 | "cell_type": "markdown",
154 | "metadata": {},
155 | "source": [
156 | " ### Task\n",
157 | "\n",
158 | " - evaluate the test accuracy for a convolutional network,\n",
159 | " - plot the test accuracy vs. temperature.\n",
160 | " - compare to the results obtained using a fully-connected network (Exercise 7.1)"
161 | ]
162 | }
163 | ],
164 | "metadata": {
165 | "kernelspec": {
166 | "display_name": "Python 3",
167 | "language": "python",
168 | "name": "python3"
169 | },
170 | "language_info": {
171 | "codemirror_mode": {
172 | "name": "ipython",
173 | "version": 3
174 | },
175 | "file_extension": ".py",
176 | "mimetype": "text/x-python",
177 | "name": "python",
178 | "nbconvert_exporter": "python",
179 | "pygments_lexer": "ipython3",
180 | "version": "3.6.9"
181 | }
182 | },
183 | "nbformat": 4,
184 | "nbformat_minor": 4
185 | }
186 |
--------------------------------------------------------------------------------
/Exercise_12_2.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Exercise 12.2\n",
8 | "## Activation maximization\n",
9 | "In this task, we use the approach of activation maximization to visualize to which patterns features of a CNN trained using on MNIST are sensitive. This will give us a deeper understanding of the working principle of CNNs."
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": 3,
15 | "metadata": {},
16 | "outputs": [
17 | {
18 | "name": "stdout",
19 | "output_type": "stream",
20 | "text": [
21 | "keras version 2.4.0\n"
22 | ]
23 | }
24 | ],
25 | "source": [
26 | "import tensorflow as tf\n",
27 | "from tensorflow import keras\n",
28 | "import numpy as np\n",
29 | "import matplotlib.pyplot as plt\n",
30 | "\n",
31 | "KTF = keras.backend\n",
32 | "layers = keras.layers\n",
33 | "\n"
34 | ]
35 | },
36 | {
37 | "cell_type": "markdown",
38 | "metadata": {},
39 | "source": [
40 | "### Download and preprocess data"
41 | ]
42 | },
43 | {
44 | "cell_type": "code",
45 | "execution_count": 2,
46 | "metadata": {},
47 | "outputs": [],
48 | "source": [
49 | "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
50 | "x_train = x_train.astype(np.float32)[...,np.newaxis] / 255.\n",
51 | "x_test = x_test.astype(np.float32)[...,np.newaxis] / 255.\n",
52 | "y_train = keras.utils.to_categorical(y_train, 10)\n",
53 | "y_test = keras.utils.to_categorical(y_test, 10)"
54 | ]
55 | },
56 | {
57 | "cell_type": "markdown",
58 | "metadata": {},
59 | "source": [
60 | "### Set up a convolutional neural network with at least 4 CNN layers."
61 | ]
62 | },
63 | {
64 | "cell_type": "code",
65 | "execution_count": null,
66 | "metadata": {},
67 | "outputs": [],
68 | "source": [
69 | "model = keras.models.Sequential()\n",
70 | "\n",
71 | "model.summary()"
72 | ]
73 | },
74 | {
75 | "cell_type": "markdown",
76 | "metadata": {},
77 | "source": [
78 | "#### compile and train model"
79 | ]
80 | },
81 | {
82 | "cell_type": "code",
83 | "execution_count": null,
84 | "metadata": {},
85 | "outputs": [],
86 | "source": [
87 | "model.compile(\n",
88 | " loss='categorical_crossentropy',\n",
89 | " optimizer=keras.optimizers.Adam(lr=1e-3),\n",
90 | " metrics=['accuracy'])\n",
91 | "\n",
92 | "\n",
93 | "results = model.fit(x_train, y_train,\n",
94 | " batch_size=100,\n",
95 | " epochs=3,\n",
96 | " verbose=1,\n",
97 | " validation_split=0.1\n",
98 | " )"
99 | ]
100 | },
101 | {
102 | "cell_type": "markdown",
103 | "metadata": {},
104 | "source": [
105 | "### Implementation of activation maximization\n",
106 | "Select a layer you want to visualize and perform activation maximization."
107 | ]
108 | },
109 | {
110 | "cell_type": "code",
111 | "execution_count": null,
112 | "metadata": {},
113 | "outputs": [],
114 | "source": [
115 | "gradient_updates = 50\n",
116 | "step_size = 1.\n",
117 | "\n",
118 | "def normalize(x):\n",
119 | " '''Normalize gradients via l2 norm'''\n",
120 | " return x / (KTF.sqrt(KTF.mean(KTF.square(x))) + KTF.epsilon())\n"
121 | ]
122 | },
123 | {
124 | "cell_type": "markdown",
125 | "metadata": {},
126 | "source": [
127 | "In the following, implement activation maximization to visualize to which patterns a specific feature map is sensitive:\n",
128 | "- Start from uniform distributed noise 'images' (note that the shape has to be `(1, 28, 28, 1)`, as we use a batch size of `1`).\n",
129 | "- Choose one specific feature map using 'filter_index'.\n",
130 | "- Create a scalar loss as discussed in Chapter 12 (maximize the average feature map activation).\n",
131 | "- Thereafter, add the calculated gradients to your start image (gradient ascent step) and repeat the procedure using gradient_updates = 50. \n",
132 | "You can calculate the gradients using the following expressions: \n",
133 | "`with tf.GradientTape() as gtape:\n",
134 | " grads = gtape.gradient(YOUR_OBJECTIVE, THE_VARIABLE_YOU_WANT_TO_OPTIMIZE) \n",
135 | " grads = normalize(grads)`\n",
136 | "\n",
137 | "- Finally, implement the gradient ascent step (you may use `assign_sub` or `assign_add` to adapt the parameters) and perform 50 updates.\n",
138 | "\n",
139 | "Remember to construct a Keras variable for the input (we want to find an input that 'maximizes' the output, so we build an input that holds adaptive parameters which we can train using TensorFlow / Keras)\n",
140 | "The following code snippet may help you to implement the maximization: "
141 | ]
142 | },
143 | {
144 | "cell_type": "code",
145 | "execution_count": null,
146 | "metadata": {},
147 | "outputs": [],
148 | "source": [
149 | "visualized_feature = []\n",
150 | "layer_dict = layer_dict = dict([(layer.name, layer) for layer in model.layers[:]])\n",
151 | "layer_name = \"conv2d_3\"\n",
152 | "\n",
153 | "layer_output = layer_dict[layer_name].output\n",
154 | "sub_model = keras.models.Model([model.inputs], [layer_output])\n",
155 | "\n",
156 | "for filter_index in range(layer_output.shape[-1]): # iterate over fiters\n",
157 | "\n",
158 | " print('Processing filter %d' % (filter_index+1))\n",
159 | " \n",
160 | " input_img = KTF.variable([0]) # instead of '[0]' use noise as the (start) input image with correct shape\n",
161 | "\n",
162 | " for i in range(gradient_updates):\n",
163 | "\n",
164 | " with tf.GradientTape() as gtape:\n",
165 | " # define a scalar loss using Keras.\n",
166 | " # remember: You would like to maximize the activations in the respective feature map!\n",
167 | " loss = 0 # <--: define your loss HERE\n",
168 | " "
169 | ]
170 | },
171 | {
172 | "cell_type": "markdown",
173 | "metadata": {},
174 | "source": [
175 | "#### Plot images to visualize to which patterns the respective feature maps are sensitive."
176 | ]
177 | },
178 | {
179 | "cell_type": "code",
180 | "execution_count": null,
181 | "metadata": {},
182 | "outputs": [],
183 | "source": [
184 | "def deprocess_image(x):\n",
185 | " # reprocess visualization to format of \"MNIST images\"\n",
186 | " x -= x.mean()\n",
187 | " x /= (x.std() + KTF.epsilon())\n",
188 | " # x *= 0.1\n",
189 | " x += 0.5\n",
190 | " x *= 255\n",
191 | " x = np.clip(x, 0, 255).astype('uint8')\n",
192 | " return x"
193 | ]
194 | },
195 | {
196 | "cell_type": "code",
197 | "execution_count": null,
198 | "metadata": {},
199 | "outputs": [],
200 | "source": [
201 | "plt.figure(figsize=(10,10))\n",
202 | "\n",
203 | "for i, feature_ in enumerate(visualized_feature):\n",
204 | " feature_image = deprocess_image(feature_)\n",
205 | " ax = plt.subplot(8,8, 1+i, )\n",
206 | " plt.imshow(feature_image.squeeze())\n",
207 | " ax.axis('off')\n",
208 | " plt.title(\"feature %s\" % i)\n",
209 | " \n",
210 | "plt.tight_layout()"
211 | ]
212 | }
213 | ],
214 | "metadata": {
215 | "kernelspec": {
216 | "display_name": "Python 3",
217 | "language": "python",
218 | "name": "python3"
219 | },
220 | "language_info": {
221 | "codemirror_mode": {
222 | "name": "ipython",
223 | "version": 3
224 | },
225 | "file_extension": ".py",
226 | "mimetype": "text/x-python",
227 | "name": "python",
228 | "nbconvert_exporter": "python",
229 | "pygments_lexer": "ipython3",
230 | "version": "3.6.9"
231 | }
232 | },
233 | "nbformat": 4,
234 | "nbformat_minor": 4
235 | }
236 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Creative Commons Attribution-NonCommercial 4.0 International Public
2 | License
3 |
4 | By exercising the Licensed Rights (defined below), You accept and agree
5 | to be bound by the terms and conditions of this Creative Commons
6 | Attribution-NonCommercial 4.0 International Public License ("Public
7 | License"). To the extent this Public License may be interpreted as a
8 | contract, You are granted the Licensed Rights in consideration of Your
9 | acceptance of these terms and conditions, and the Licensor grants You
10 | such rights in consideration of benefits the Licensor receives from
11 | making the Licensed Material available under these terms and
12 | conditions.
13 |
14 |
15 | Section 1 -- Definitions.
16 |
17 | a. Adapted Material means material subject to Copyright and Similar
18 | Rights that is derived from or based upon the Licensed Material
19 | and in which the Licensed Material is translated, altered,
20 | arranged, transformed, or otherwise modified in a manner requiring
21 | permission under the Copyright and Similar Rights held by the
22 | Licensor. For purposes of this Public License, where the Licensed
23 | Material is a musical work, performance, or sound recording,
24 | Adapted Material is always produced where the Licensed Material is
25 | synched in timed relation with a moving image.
26 |
27 | b. Adapter's License means the license You apply to Your Copyright
28 | and Similar Rights in Your contributions to Adapted Material in
29 | accordance with the terms and conditions of this Public License.
30 |
31 | c. Copyright and Similar Rights means copyright and/or similar rights
32 | closely related to copyright including, without limitation,
33 | performance, broadcast, sound recording, and Sui Generis Database
34 | Rights, without regard to how the rights are labeled or
35 | categorized. For purposes of this Public License, the rights
36 | specified in Section 2(b)(1)-(2) are not Copyright and Similar
37 | Rights.
38 | d. Effective Technological Measures means those measures that, in the
39 | absence of proper authority, may not be circumvented under laws
40 | fulfilling obligations under Article 11 of the WIPO Copyright
41 | Treaty adopted on December 20, 1996, and/or similar international
42 | agreements.
43 |
44 | e. Exceptions and Limitations means fair use, fair dealing, and/or
45 | any other exception or limitation to Copyright and Similar Rights
46 | that applies to Your use of the Licensed Material.
47 |
48 | f. Licensed Material means the artistic or literary work, database,
49 | or other material to which the Licensor applied this Public
50 | License.
51 |
52 | g. Licensed Rights means the rights granted to You subject to the
53 | terms and conditions of this Public License, which are limited to
54 | all Copyright and Similar Rights that apply to Your use of the
55 | Licensed Material and that the Licensor has authority to license.
56 |
57 | h. Licensor means the individual(s) or entity(ies) granting rights
58 | under this Public License.
59 |
60 | i. NonCommercial means not primarily intended for or directed towards
61 | commercial advantage or monetary compensation. For purposes of
62 | this Public License, the exchange of the Licensed Material for
63 | other material subject to Copyright and Similar Rights by digital
64 | file-sharing or similar means is NonCommercial provided there is
65 | no payment of monetary compensation in connection with the
66 | exchange.
67 |
68 | j. Share means to provide material to the public by any means or
69 | process that requires permission under the Licensed Rights, such
70 | as reproduction, public display, public performance, distribution,
71 | dissemination, communication, or importation, and to make material
72 | available to the public including in ways that members of the
73 | public may access the material from a place and at a time
74 | individually chosen by them.
75 |
76 | k. Sui Generis Database Rights means rights other than copyright
77 | resulting from Directive 96/9/EC of the European Parliament and of
78 | the Council of 11 March 1996 on the legal protection of databases,
79 | as amended and/or succeeded, as well as other essentially
80 | equivalent rights anywhere in the world.
81 |
82 | l. You means the individual or entity exercising the Licensed Rights
83 | under this Public License. Your has a corresponding meaning.
84 |
85 |
86 | Section 2 -- Scope.
87 |
88 | a. License grant.
89 |
90 | 1. Subject to the terms and conditions of this Public License,
91 | the Licensor hereby grants You a worldwide, royalty-free,
92 | non-sublicensable, non-exclusive, irrevocable license to
93 | exercise the Licensed Rights in the Licensed Material to:
94 |
95 | a. reproduce and Share the Licensed Material, in whole or
96 | in part, for NonCommercial purposes only; and
97 |
98 | b. produce, reproduce, and Share Adapted Material for
99 | NonCommercial purposes only.
100 |
101 | 2. Exceptions and Limitations. For the avoidance of doubt, where
102 | Exceptions and Limitations apply to Your use, this Public
103 | License does not apply, and You do not need to comply with
104 | its terms and conditions.
105 |
106 | 3. Term. The term of this Public License is specified in Section
107 | 6(a).
108 |
109 | 4. Media and formats; technical modifications allowed. The
110 | Licensor authorizes You to exercise the Licensed Rights in
111 | all media and formats whether now known or hereafter created,
112 | and to make technical modifications necessary to do so. The
113 | Licensor waives and/or agrees not to assert any right or
114 | authority to forbid You from making technical modifications
115 | necessary to exercise the Licensed Rights, including
116 | technical modifications necessary to circumvent Effective
117 | Technological Measures. For purposes of this Public License,
118 | simply making modifications authorized by this Section 2(a)
119 | (4) never produces Adapted Material.
120 |
121 | 5. Downstream recipients.
122 |
123 | a. Offer from the Licensor -- Licensed Material. Every
124 | recipient of the Licensed Material automatically
125 | receives an offer from the Licensor to exercise the
126 | Licensed Rights under the terms and conditions of this
127 | Public License.
128 |
129 | b. No downstream restrictions. You may not offer or impose
130 | any additional or different terms or conditions on, or
131 | apply any Effective Technological Measures to, the
132 | Licensed Material if doing so restricts exercise of the
133 | Licensed Rights by any recipient of the Licensed
134 | Material.
135 |
136 | 6. No endorsement. Nothing in this Public License constitutes or
137 | may be construed as permission to assert or imply that You
138 | are, or that Your use of the Licensed Material is, connected
139 | with, or sponsored, endorsed, or granted official status by,
140 | the Licensor or others designated to receive attribution as
141 | provided in Section 3(a)(1)(A)(i).
142 |
143 | b. Other rights.
144 |
145 | 1. Moral rights, such as the right of integrity, are not
146 | licensed under this Public License, nor are publicity,
147 | privacy, and/or other similar personality rights; however, to
148 | the extent possible, the Licensor waives and/or agrees not to
149 | assert any such rights held by the Licensor to the limited
150 | extent necessary to allow You to exercise the Licensed
151 | Rights, but not otherwise.
152 |
153 | 2. Patent and trademark rights are not licensed under this
154 | Public License.
155 |
156 | 3. To the extent possible, the Licensor waives any right to
157 | collect royalties from You for the exercise of the Licensed
158 | Rights, whether directly or through a collecting society
159 | under any voluntary or waivable statutory or compulsory
160 | licensing scheme. In all other cases the Licensor expressly
161 | reserves any right to collect such royalties, including when
162 | the Licensed Material is used other than for NonCommercial
163 | purposes.
164 |
165 |
166 | Section 3 -- License Conditions.
167 |
168 | Your exercise of the Licensed Rights is expressly made subject to the
169 | following conditions.
170 |
171 | a. Attribution.
172 |
173 | 1. If You Share the Licensed Material (including in modified
174 | form), You must:
175 |
176 | a. retain the following if it is supplied by the Licensor
177 | with the Licensed Material:
178 |
179 | i. identification of the creator(s) of the Licensed
180 | Material and any others designated to receive
181 | attribution, in any reasonable manner requested by
182 | the Licensor (including by pseudonym if
183 | designated);
184 |
185 | ii. a copyright notice;
186 |
187 | iii. a notice that refers to this Public License;
188 |
189 | iv. a notice that refers to the disclaimer of
190 | warranties;
191 |
192 | v. a URI or hyperlink to the Licensed Material to the
193 | extent reasonably practicable;
194 |
195 | b. indicate if You modified the Licensed Material and
196 | retain an indication of any previous modifications; and
197 |
198 | c. indicate the Licensed Material is licensed under this
199 | Public License, and include the text of, or the URI or
200 | hyperlink to, this Public License.
201 |
202 | 2. You may satisfy the conditions in Section 3(a)(1) in any
203 | reasonable manner based on the medium, means, and context in
204 | which You Share the Licensed Material. For example, it may be
205 | reasonable to satisfy the conditions by providing a URI or
206 | hyperlink to a resource that includes the required
207 | information.
208 |
209 | 3. If requested by the Licensor, You must remove any of the
210 | information required by Section 3(a)(1)(A) to the extent
211 | reasonably practicable.
212 |
213 | 4. If You Share Adapted Material You produce, the Adapter's
214 | License You apply must not prevent recipients of the Adapted
215 | Material from complying with this Public License.
216 |
217 |
218 | Section 4 -- Sui Generis Database Rights.
219 |
220 | Where the Licensed Rights include Sui Generis Database Rights that
221 | apply to Your use of the Licensed Material:
222 |
223 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right
224 | to extract, reuse, reproduce, and Share all or a substantial
225 | portion of the contents of the database for NonCommercial purposes
226 | only;
227 |
228 | b. if You include all or a substantial portion of the database
229 | contents in a database in which You have Sui Generis Database
230 | Rights, then the database in which You have Sui Generis Database
231 | Rights (but not its individual contents) is Adapted Material; and
232 |
233 | c. You must comply with the conditions in Section 3(a) if You Share
234 | all or a substantial portion of the contents of the database.
235 |
236 | For the avoidance of doubt, this Section 4 supplements and does not
237 | replace Your obligations under this Public License where the Licensed
238 | Rights include other Copyright and Similar Rights.
239 |
240 |
241 | Section 5 -- Disclaimer of Warranties and Limitation of Liability.
242 |
243 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
244 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
245 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
246 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
247 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
248 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
249 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
250 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
251 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
252 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
253 |
254 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
255 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
256 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
257 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
258 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
259 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
260 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
261 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
262 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
263 |
264 | c. The disclaimer of warranties and limitation of liability provided
265 | above shall be interpreted in a manner that, to the extent
266 | possible, most closely approximates an absolute disclaimer and
267 | waiver of all liability.
268 |
269 |
270 | Section 6 -- Term and Termination.
271 |
272 | a. This Public License applies for the term of the Copyright and
273 | Similar Rights licensed here. However, if You fail to comply with
274 | this Public License, then Your rights under this Public License
275 | terminate automatically.
276 |
277 | b. Where Your right to use the Licensed Material has terminated under
278 | Section 6(a), it reinstates:
279 |
280 | 1. automatically as of the date the violation is cured, provided
281 | it is cured within 30 days of Your discovery of the
282 | violation; or
283 |
284 | 2. upon express reinstatement by the Licensor.
285 |
286 | For the avoidance of doubt, this Section 6(b) does not affect any
287 | right the Licensor may have to seek remedies for Your violations
288 | of this Public License.
289 |
290 | c. For the avoidance of doubt, the Licensor may also offer the
291 | Licensed Material under separate terms or conditions or stop
292 | distributing the Licensed Material at any time; however, doing so
293 | will not terminate this Public License.
294 |
295 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
296 | License.
297 |
298 |
299 | Section 7 -- Other Terms and Conditions.
300 |
301 | a. The Licensor shall not be bound by any additional or different
302 | terms or conditions communicated by You unless expressly agreed.
303 |
304 | b. Any arrangements, understandings, or agreements regarding the
305 | Licensed Material not stated herein are separate from and
306 | independent of the terms and conditions of this Public License.
307 |
308 |
309 | Section 8 -- Interpretation.
310 |
311 | a. For the avoidance of doubt, this Public License does not, and
312 | shall not be interpreted to, reduce, limit, restrict, or impose
313 | conditions on any use of the Licensed Material that could lawfully
314 | be made without permission under this Public License.
315 |
316 | b. To the extent possible, if any provision of this Public License is
317 | deemed unenforceable, it shall be automatically reformed to the
318 | minimum extent necessary to make it enforceable. If the provision
319 | cannot be reformed, it shall be severed from this Public License
320 | without affecting the enforceability of the remaining terms and
321 | conditions.
322 |
323 | c. No term or condition of this Public License will be waived and no
324 | failure to comply consented to unless expressly agreed to by the
325 | Licensor.
326 |
327 | d. Nothing in this Public License constitutes or may be interpreted
328 | as a limitation upon, or waiver of, any privileges and immunities
329 | that apply to the Licensor or You, including from the legal
330 | processes of any jurisdiction or authority.
331 |
332 | =======================================================================
333 |
334 | Creative Commons is not a party to its public
335 | licenses. Notwithstanding, Creative Commons may elect to apply one of
336 | its public licenses to material it publishes and in those instances
337 | will be considered the “Licensor.” The text of the Creative Commons
338 | public licenses is dedicated to the public domain under the CC0 Public
339 | Domain Dedication. Except for the limited purpose of indicating that
340 | material is shared under a Creative Commons public license or as
341 | otherwise permitted by the Creative Commons policies published at
342 | creativecommons.org/policies, Creative Commons does not authorize the
343 | use of the trademark "Creative Commons" or any other trademark or logo
344 | of Creative Commons without its prior written consent including,
345 | without limitation, in connection with any unauthorized modifications
346 | to any of its public licenses or any other arrangements,
347 | understandings, or agreements concerning use of licensed material. For
348 | the avoidance of doubt, this paragraph does not form part of the
349 | public licenses.
350 |
351 | Creative Commons may be contacted at creativecommons.org.
352 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Deep Learning for Physics Research
3 |
4 | This repository contains additional material (exercises) for the textbook *Deep Learning for Physics Research* by
5 | [Martin Erdmann](https://www.physik.rwth-aachen.de/user/erdmann), [Jonas Glombitza](https://www.jonas-glombitza.com/), [Gregor Kasieczka](https://www.physik.uni-hamburg.de/iexp/gruppe-kasieczka.html), and Uwe Klemradt.
6 |
7 | The authors can be contacted under [authors@deeplearningphysics.org](mailto:authors@deeplearningphysics.org).
8 |
9 | For more information on the book, refer to the page by the [publisher](https://worldscientific.com/worldscibooks/10.1142/12294).
10 |
11 | ## Exercises
12 | You can find the exercise page at: http://deeplearningphysics.org
13 |
14 | You can directly open the exercise page in
15 |
16 | [](https://colab.research.google.com/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/master)
17 | [](https://mybinder.org/v2/gh/DeepLearningForPhysicsResearchBook/deep-learning-physics/HEAD)
18 |
19 | or using the CERN SWAN service
20 | [](https://cern.ch/swanserver/cgi-bin/go?projurl=https://github.com/DeepLearningForPhysicsResearchBook/deep-learning-physics.git)
21 |
22 | ### Software
23 | The exercises are based on [Keras](https://keras.io/) and [TensorFlow](https://www.tensorflow.org/) v2.4.0.
24 | If you download the repository you can install the software requirements via:
25 | ```bash
26 | pip install -r requirements.txt
27 | ```
28 |
29 |
30 | ## License
31 | [![CC BY-NC 4.0][cc-by-nc-image]][cc-by-nc]
32 | This work (repository) is licensed under a
33 | [Creative Commons Attribution-NonCommercial 4.0 International License][cc-by-nc].
34 |
35 | [cc-by-nc]: http://creativecommons.org/licenses/by-nc/4.0/
36 | [cc-by-nc-image]: https://licensebuttons.net/l/by-nc/4.0/88x31.png
37 | [cc-by-nc-shield]: https://img.shields.io/badge/License-CC%20BY--NC%204.0-lightgrey.svg
38 |
39 |
40 |
41 | ## Citation
42 |
43 | ```
44 | @book{doi:10.1142/12294,
45 | author = {Erdmann, Martin and Glombitza, Jonas and Kasieczka, Gregor and Klemradt, Uwe},
46 | title = {Deep Learning for Physics Research},
47 | publisher = {WORLD SCIENTIFIC},
48 | year = {2021},
49 | doi = {10.1142/12294},
50 | address = {},
51 | edition = {},
52 | URL = {http://deeplearningphysics.org},
53 | eprint = {https://worldscientific.com/doi/pdf/10.1142/12294}
54 | }
55 | ```
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-slate
2 | title: Deep Learning for Physics Research
3 | google_analytics: UA-203084223-2
4 |
5 |
--------------------------------------------------------------------------------
/edgeconv.py:
--------------------------------------------------------------------------------
1 | """Implementation of EdgeConv using arbitrary functions as h
2 | for more information see https://git.rwth-aachen.de/niklas.langner/edgeconv_keras
3 | authors: Jonas Glombitza, Niklas Lagner
4 | """
5 |
6 | import tensorflow as tf
7 | import tensorflow.keras.layers as lay
8 | from tensorflow import keras
9 |
10 |
11 | class SplitLayer(lay.Layer):
12 | """ Custom layer: split layer along specific axis.
13 | eg. split (1,9) into 9 x (1,1)
14 |
15 | Parameters
16 | ----------
17 | n_splits : int
18 | number of splits
19 | split_axis : int
20 | axis where to split tensor
21 | **kwargs : type
22 | Description of parameter `**kwargs`.
23 |
24 | Attributes
25 | ----------
26 | n_splits
27 | split_axis
28 |
29 | """
30 |
31 | def __init__(self, n_splits=12, split_axis=-1, **kwargs):
32 | self.n_splits = n_splits
33 | self.split_axis = split_axis
34 | super(SplitLayer, self).__init__(**kwargs)
35 |
36 | def get_config(self):
37 | config = {'n_splits': self.n_splits,
38 | 'split_axis': self.split_axis}
39 | base_config = super(SplitLayer, self).get_config()
40 | return dict(list(base_config.items()) + list(config.items()))
41 |
42 | def call(self, x):
43 | ''' return array of splitted tensors '''
44 | sub_tensors = tf.split(x, self.n_splits, axis=self.split_axis)
45 | return sub_tensors
46 |
47 | def compute_output_shape(self, input_shape):
48 | sub_tensor_shape = list(input_shape)
49 | num_channels = sub_tensor_shape[self.split_axis]
50 | sub_tensor_shape[self.split_axis] = int(num_channels / self.n_splits)
51 | sub_tensor_shape = tuple(sub_tensor_shape)
52 | list_of_output_shape = [sub_tensor_shape] * self.n_splits
53 | return list_of_output_shape
54 |
55 | def compute_mask(self, inputs, mask=None):
56 | return self.n_splits * [None]
57 |
58 |
59 | class EdgeConv(lay.Layer):
60 | '''
61 | Keras layer implementation of EdgeConv.
62 | # Arguments
63 | kernel_func: h-function applied on the points and it's k nearest neighbors. The function should take a list
64 | of two tensors. The first tensor is the vector v_i of the central point, the second tensor is the vector
65 | of one of its neighbors v_j.
66 | :param list: [v_i, v_j] with v_i and v_j being Keras tensors with shape (C_f, ).
67 | :return: Keras tensor of shape (C', ).
68 | next_neighbors: number k of nearest neighbors to consider
69 | agg_func: Aggregation function applied after h. Must take argument "axis=2" to
70 | aggregate over all neighbors.
71 | # Input shape
72 | List of two tensors [points, features] with shape:
73 | `[(batch, P, C_p), (batch, P, C_f)]`.
74 | or tensor with shape:
75 | `(batch, P, C)`
76 | if points (coordinates) and features are supposed to be the same.
77 | # Output shape
78 | Tensor with shape:
79 | `(batch, P, C_h)`
80 | with C_h being the output dimension of the h-function.
81 | '''
82 |
83 | def __init__(self, kernel_func, next_neighbors, agg_func=keras.backend.mean, **kwargs):
84 | self.kernel_func = kernel_func
85 | self.next_neighbors = next_neighbors
86 | self.agg_func = agg_func
87 | if type(agg_func) == str:
88 | raise ValueError("No such agg_func '%s'. When loading the model specify the agg_func '%s' via custom_objects" % (agg_func, agg_func))
89 | super(EdgeConv, self).__init__(**kwargs)
90 |
91 | def get_config(self):
92 | config = {'next_neighbors': self.next_neighbors,
93 | 'kernel_func': self.kernel_func,
94 | 'agg_func': self.agg_func}
95 | base_config = super(EdgeConv, self).get_config()
96 | return dict(list(base_config.items()) + list(config.items()))
97 |
98 | def build(self, input_shape):
99 | # Create a trainable weight variable for this layer.
100 | try:
101 | p_shape, f_shape = input_shape
102 | except ValueError:
103 | f_shape = input_shape
104 |
105 | if type(self.kernel_func) != keras.models.Model: # for not wrapping model around model when loading model
106 | x = lay.Input((f_shape.as_list()[-1] * 2,))
107 | a = lay.Reshape((2, f_shape.as_list()[-1]))(x)
108 | x1, x2 = SplitLayer(n_splits=2, split_axis=-2)(a) # (2, C)
109 | x1 = lay.Reshape((f_shape.as_list()[-1],))(x1)
110 | x2 = lay.Reshape((f_shape.as_list()[-1],))(x2)
111 | y = self.kernel_func([x1, x2])
112 | self.kernel_func = keras.models.Model(x, y)
113 |
114 | super(EdgeConv, self).build(input_shape) # Be sure to call this at the end
115 |
116 | def call(self, x):
117 | try:
118 | points, features = x
119 | except TypeError:
120 | points = features = x
121 |
122 | # distance
123 | D = batch_distance_matrix_general(points, points) # (N, P, P)
124 | _, indices = tf.nn.top_k(-D, k=self.next_neighbors + 1) # (N, P, K+1)
125 | indices = indices[:, :, 1:] # (N, P, K) remove self connection
126 | knn_fts = knn(indices, features) # (N, P, K, C)
127 | knn_fts_center = tf.tile(tf.expand_dims(features, axis=2), (1, 1, self.next_neighbors, 1)) # (N, P, K, C)
128 | knn_fts = tf.concat([knn_fts_center, knn_fts], axis=-1) # (N, P, K, 2*C)
129 | res = lay.TimeDistributed(lay.TimeDistributed(self.kernel_func))(knn_fts) # (N, P, K, C')
130 | # aggregation
131 | agg = self.agg_func(res, axis=2) # (N, P, C')
132 | return agg
133 |
134 | def compute_output_shape(self, input_shape):
135 | self.output_shape = self.kernel_func.get_output_shape_at(-1)
136 | return self.output_shape
137 |
138 |
139 | def batch_distance_matrix_general(A, B):
140 | ''' Calculate elements-wise distance between entries in two tensors '''
141 | with tf.name_scope('dmat'):
142 | r_A = tf.reduce_sum(A * A, axis=2, keepdims=True)
143 | r_B = tf.reduce_sum(B * B, axis=2, keepdims=True)
144 | m = tf.matmul(A, tf.transpose(B, perm=(0, 2, 1)))
145 | D = r_A - 2 * m + tf.transpose(r_B, perm=(0, 2, 1))
146 | return D
147 |
148 |
149 | def knn(topk_indices, features):
150 | # topk_indices: (N, P, K)
151 | # features: (N, P, C)
152 | # return: (N, P, K, C)
153 | with tf.name_scope('knn'):
154 | k = tf.shape(topk_indices)[-1]
155 | num_points = tf.shape(features)[-2]
156 | queries_shape = tf.shape(features)
157 | batch_size = queries_shape[0]
158 | batch_indices = tf.tile(tf.reshape(tf.range(batch_size), (-1, 1, 1, 1)), (1, num_points, k, 1))
159 | indices = tf.concat([batch_indices, tf.expand_dims(topk_indices, axis=3)], axis=3) # (N, P, K, 2)
160 | return tf.gather_nd(features, indices)
161 |
--------------------------------------------------------------------------------
/images/checkerboard_3_2_task_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DeepLearningForPhysicsResearchBook/deep-learning-physics/41171d6386ec9c8c33f3e4a0bc06022a98d29791/images/checkerboard_3_2_task_1.png
--------------------------------------------------------------------------------
/images/checkerboard_3_2_task_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DeepLearningForPhysicsResearchBook/deep-learning-physics/41171d6386ec9c8c33f3e4a0bc06022a98d29791/images/checkerboard_3_2_task_3.png
--------------------------------------------------------------------------------
/images/checkerboard_l1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DeepLearningForPhysicsResearchBook/deep-learning-physics/41171d6386ec9c8c33f3e4a0bc06022a98d29791/images/checkerboard_l1.png
--------------------------------------------------------------------------------
/images/checkerboard_l2_high.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DeepLearningForPhysicsResearchBook/deep-learning-physics/41171d6386ec9c8c33f3e4a0bc06022a98d29791/images/checkerboard_l2_high.png
--------------------------------------------------------------------------------
/images/checkerboard_l2_low.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DeepLearningForPhysicsResearchBook/deep-learning-physics/41171d6386ec9c8c33f3e4a0bc06022a98d29791/images/checkerboard_l2_low.png
--------------------------------------------------------------------------------
/images/checkerboard_l2_moderate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DeepLearningForPhysicsResearchBook/deep-learning-physics/41171d6386ec9c8c33f3e4a0bc06022a98d29791/images/checkerboard_l2_moderate.png
--------------------------------------------------------------------------------
/images/checkerboard_overtraining.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DeepLearningForPhysicsResearchBook/deep-learning-physics/41171d6386ec9c8c33f3e4a0bc06022a98d29791/images/checkerboard_overtraining.png
--------------------------------------------------------------------------------
/images/checkerboard_regularization.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DeepLearningForPhysicsResearchBook/deep-learning-physics/41171d6386ec9c8c33f3e4a0bc06022a98d29791/images/checkerboard_regularization.png
--------------------------------------------------------------------------------
/images/checkerboard_tf_playground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DeepLearningForPhysicsResearchBook/deep-learning-physics/41171d6386ec9c8c33f3e4a0bc06022a98d29791/images/checkerboard_tf_playground.png
--------------------------------------------------------------------------------
/index.md:
--------------------------------------------------------------------------------
1 |
2 | ## Information
3 |
4 | This page contains additional material for the textbook *Deep Learning for Physics Research* by
5 | [Martin Erdmann](https://www.physik.rwth-aachen.de/user/erdmann), [Jonas Glombitza](https://www.jonas-glombitza.com/), [Gregor Kasieczka](https://www.physik.uni-hamburg.de/iexp/gruppe-kasieczka.html), and Uwe Klemradt.
6 |
7 | The authors can be contacted under [authors@deeplearningphysics.org](mailto:authors@deeplearningphysics.org).
8 |
9 | For more information on the book, refer to the page by the [publisher](https://worldscientific.com/worldscibooks/10.1142/12294).
10 |
11 | ## Exercises
12 | ### Section 1 - Deep Learning Basics
13 | #### Chapter 3 - Building blocks of neural networks
14 | * **3.1: Introduction** ([Download](Exercise_03_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_03_1.ipynb))
15 | * **3.2: Linear regression (fit)**
16 | Problem ([Download](Exercise_03_2.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_03_2.ipynb)), Solution ([Download](Exercise_03_2_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_03_2_solution.ipynb))
17 | * **3.3: XOR classification**
18 | Problem ([Download](Exercise_03_3.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_03_3.ipynb)), Solution ([Download](Exercise_03_3_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_03_3_solution.ipynb))
19 |
20 |
21 | #### Chapter 4 - Optimization of network parameters
22 | * **4.1: Manual definition of regression network**
23 | Problem ([Download](Exercise_04_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_04_1.ipynb)), Solution ([Download](Exercise_04_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_04_1_solution.ipynb))
24 | * **4.2: Linear regression using Keras**
25 | Problem ([Download](Exercise_04_2.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_04_2.ipynb)), Solution ([Download](Exercise_04_2_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_04_2_solution.ipynb))
26 | * **4.3: Classification: metrics, classes, and one-hot encoding**
27 | Problem ([Download](Exercise_04_3.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_04_3.ipynb)), Solution ([Download](Exercise_04_3_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_04_3_solution.ipynb))
28 |
29 | #### Chapter 5 - Mastering model building
30 | * **5.1: Regularization and parameter norm penalties**
31 | Problem ([Download](Exercise_05_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_05_1.ipynb)), Solution ([Download](Exercise_05_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_05_1_solution.ipynb))
32 | * **5.2: Interpolation: train a DNN to learn a complicated function**
33 | Problem ([Download](Exercise_05_2.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_05_2.ipynb)), Solution ([Download](Exercise_05_2_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_05_2_solution.ipynb))
34 | * **5.3: Regression with Keras**
35 | Problem ([Download](Exercise_05_3.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_05_3.ipynb)), Solution ([Download](Exercise_05_3_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_05_3_solution.ipynb))
36 |
37 |
38 | ---
39 | ### Section 2 - Standard Architectures of Deep Networks
40 |
41 | #### Chapter 7 - Fully-connected networks: improving the classic all-rounder
42 | * **7.1: Classification of magnetic phases using fully-connected networks**
43 | Problem ([Download](Exercise_07_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_07_1.ipynb)), Solution ([Download](Exercise_07_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_07_1_solution.ipynb))
44 | * **7.2: Energy reconstruction of air showers using fully-connected networks**
45 | Problem ([Download](Exercise_07_2.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_07_2.ipynb)), Solution ([Download](Exercise_07_2_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_07_2_solution.ipynb))
46 |
47 |
48 | #### Chapter 8 - Convolutional neural networks and analysis of image-like data
49 | * **8.1: Classification of magnetic phases using convolutional networks**
50 | Problem ([Download](Exercise_08_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_08_1.ipynb)), Solution ([Download](Exercise_08_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_08_1_solution.ipynb))
51 | * **8.2: Energy reconstruction of air showers using convolutional networks**
52 | Problem ([Download](Exercise_08_2.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_08_2.ipynb)), Solution ([Download](Exercise_08_2_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_08_2_solution.ipynb))
53 |
54 |
55 |
56 | #### Chapter 9 - Recurrent neural networks: time series and variable input
57 | * **9.1: Get in touch with RNNs: learn a sine wave**
58 | Problem ([Download](Exercise_09_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_09_1.ipynb))
59 | * **9.2: Identification of radio signals using RNNs**
60 | Problem ([Download](Exercise_09_2.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_09_2.ipynb)), Solution ([Download](Exercise_09_2_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_09_2_solution.ipynb))
61 |
62 | #### Chapter 10 - Graph networks and convolutions beyond Euclidean domains
63 | * **10.1: Signal Classification using Dynamic Graph Convolutional Neural Networks**
64 | Problem ([Download](Exercise_10_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_10_1.ipynb)), Solution ([Download](Exercise_10_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_10_1_solution.ipynb))
65 | * **(16.1: Semi-supervised node classification using graph convolutional networks)**
66 | Problem ([Download](Exercise_16_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_16_1.ipynb)), Solution ([Download](Exercise_16_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_16_1_solution.ipynb))
67 |
68 | #### Chapter 11 - Multi-task learning, hybrid architectures, and operational reality
69 | * **11.1: Reconstruction of cosmic-ray-induced air showers**
70 | Problem ([Download](Exercise_11_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_11_1.ipynb)), Solution ([Download](Exercise_11_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_11_1_solution.ipynb))
71 |
72 | ---
73 | ### Section 3 - Introspection, Uncertainties, Objectives
74 | * **12.1: Visualization of weights and activations**
75 | Problem ([Download](Exercise_12_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_12_1.ipynb)), Solution ([Download](Exercise_12_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_12_1_solution.ipynb))
76 | * **12.2: Feature visualization using activation maximization**
77 | Problem ([Download](Exercise_12_2.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_12_2.ipynb)), Solution ([Download](Exercise_12_2_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_12_2_solution.ipynb))
78 | * **12.3: Discriminative Localization**
79 | Problem ([Download](Exercise_12_3.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_12_3.ipynb)), Solution ([Download](Exercise_12_3_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_12_3_solution.ipynb))
80 |
81 | ---
82 | ### Section 4 - Deep Learning Advanced Concepts
83 |
84 | #### Chapter 16 - Weakly-supervised classification
85 | * **16.1: Zachary’s karate club - semi-supervised node classification**
86 | Problem ([Download](Exercise_16_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_16_1.ipynb)), Solution ([Download](Exercise_16_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_16_1_solution.ipynb))
87 |
88 | #### Chapter 17 - Autoencoders: finding and compressing structures in data
89 | * **17.1: Speckle removal with denoising autoencoders**
90 | Problem ([Download](Exercise_17_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_17_1.ipynb)), Solution ([Download](Exercise_17_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_17_1_solution.ipynb))
91 |
92 | #### Chapter 18 - Generative models: data from noise
93 | * **18.1: Generation of fashion images using Generative Adversarial Networks**
94 | Problem ([Download](Exercise_18_1.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_18_1.ipynb)), Solution ([Download](Exercise_18_1_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_18_1_solution.ipynb))
95 | * **18.2: Generation of air-shower footprints using WGAN**
96 | Problem ([Download](Exercise_18_2.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_18_2.ipynb)), Solution ([Download](Exercise_18_2_solution.ipynb) - [View](https://nbviewer.jupyter.org/github/DeepLearningForPhysicsResearchBook/deep-learning-physics/blob/main/Exercise_18_2_solution.ipynb))
97 |
98 | ---
99 |
100 |
101 | ### Citation
102 |
103 | ```
104 | @book{doi:10.1142/12294,
105 | author = {Erdmann, Martin and Glombitza, Jonas and Kasieczka, Gregor and Klemradt, Uwe},
106 | title = {Deep Learning for Physics Research},
107 | publisher = {WORLD SCIENTIFIC},
108 | year = {2021},
109 | doi = {10.1142/12294},
110 | address = {},
111 | edition = {},
112 | URL = {http://deeplearningphysics.org},
113 | eprint = {https://worldscientific.com/doi/pdf/10.1142/12294}
114 | }
115 | ```
116 |
117 |
118 | ## Errata
119 |
120 | Please report mistakes to [authors@deeplearningphysics.org](mailto:authors@deeplearningphysics.org).
121 |
122 | So far, no errors are known.
123 |
124 | ## Usage
125 |
126 | Note: To improve the exercise page and potentially improve and extend
127 | the scope, we measure the use of the task templates and the interest in
128 | the solutions with the tool Google Analytics.
129 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | matplotlib
2 | numpy
3 | tensorflow==2.4.0
4 | seaborn
5 | spektral
6 | gdown
--------------------------------------------------------------------------------