|
a |
|
b/2020/scripts/AIforGenomics.ipynb |
|
|
1 |
{ |
|
|
2 |
"nbformat": 4, |
|
|
3 |
"nbformat_minor": 0, |
|
|
4 |
"metadata": { |
|
|
5 |
"colab": { |
|
|
6 |
"name": "AIforGenomics.ipynb", |
|
|
7 |
"provenance": [], |
|
|
8 |
"collapsed_sections": [] |
|
|
9 |
}, |
|
|
10 |
"kernelspec": { |
|
|
11 |
"name": "python3", |
|
|
12 |
"display_name": "Python 3" |
|
|
13 |
}, |
|
|
14 |
"accelerator": "GPU" |
|
|
15 |
}, |
|
|
16 |
"cells": [ |
|
|
17 |
{ |
|
|
18 |
"cell_type": "markdown", |
|
|
19 |
"metadata": { |
|
|
20 |
"id": "bBEeSQ6u2-H-", |
|
|
21 |
"colab_type": "text" |
|
|
22 |
}, |
|
|
23 |
"source": [ |
|
|
24 |
"# Interpretability: PyTorch pipeline, Saliency Maps and Deep Dream\n" |
|
|
25 |
] |
|
|
26 |
}, |
|
|
27 |
{ |
|
|
28 |
"cell_type": "markdown", |
|
|
29 |
"metadata": { |
|
|
30 |
"id": "XkBPghB1wkgy", |
|
|
31 |
"colab_type": "text" |
|
|
32 |
}, |
|
|
33 |
"source": [ |
|
|
34 |
"## Part 1: PyTorch Deep Learning Pipeline" |
|
|
35 |
] |
|
|
36 |
}, |
|
|
37 |
{ |
|
|
38 |
"cell_type": "markdown", |
|
|
39 |
"metadata": { |
|
|
40 |
"id": "vA48M5TADk9P", |
|
|
41 |
"colab_type": "text" |
|
|
42 |
}, |
|
|
43 |
"source": [ |
|
|
44 |
"\n", |
|
|
45 |
"In this part, we’ll walk through an end-to-end pipeline for a classification task on the MNIST dataset in Pytorch.\n", |
|
|
46 |
"\n", |
|
|
47 |
"We will implement the following steps - \n", |
|
|
48 |
"\n", |
|
|
49 |
"1. Download the dataset \n", |
|
|
50 |
"2. Load the dataset\n", |
|
|
51 |
"2. Define the model\n", |
|
|
52 |
"1. Define the loss function and optimizer\n", |
|
|
53 |
"2. Define the evaluation metric\n", |
|
|
54 |
"1. Train the network on the training data\n", |
|
|
55 |
"2. Report results on the train and test data (using the evaluation metric)\n", |
|
|
56 |
"\n", |
|
|
57 |
"\n", |
|
|
58 |
"Modified from - https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py\n" |
|
|
59 |
] |
|
|
60 |
}, |
|
|
61 |
{ |
|
|
62 |
"cell_type": "markdown", |
|
|
63 |
"metadata": { |
|
|
64 |
"id": "HfEuIgy8ZPCe", |
|
|
65 |
"colab_type": "text" |
|
|
66 |
}, |
|
|
67 |
"source": [ |
|
|
68 |
"### Download Data" |
|
|
69 |
] |
|
|
70 |
}, |
|
|
71 |
{ |
|
|
72 |
"cell_type": "code", |
|
|
73 |
"metadata": { |
|
|
74 |
"id": "l3aQ4JEzX8C7", |
|
|
75 |
"colab_type": "code", |
|
|
76 |
"outputId": "827f72fa-1528-4bdd-e7d1-9d3d99bd2bf6", |
|
|
77 |
"colab": { |
|
|
78 |
"base_uri": "https://localhost:8080/", |
|
|
79 |
"height": 34 |
|
|
80 |
} |
|
|
81 |
}, |
|
|
82 |
"source": [ |
|
|
83 |
"!pip install pypng" |
|
|
84 |
], |
|
|
85 |
"execution_count": 0, |
|
|
86 |
"outputs": [ |
|
|
87 |
{ |
|
|
88 |
"output_type": "stream", |
|
|
89 |
"text": [ |
|
|
90 |
"Requirement already satisfied: pypng in /usr/local/lib/python3.6/dist-packages (0.0.20)\n" |
|
|
91 |
], |
|
|
92 |
"name": "stdout" |
|
|
93 |
} |
|
|
94 |
] |
|
|
95 |
}, |
|
|
96 |
{ |
|
|
97 |
"cell_type": "code", |
|
|
98 |
"metadata": { |
|
|
99 |
"id": "orUb96aWYsaN", |
|
|
100 |
"colab_type": "code", |
|
|
101 |
"colab": {} |
|
|
102 |
}, |
|
|
103 |
"source": [ |
|
|
104 |
"from tqdm import *" |
|
|
105 |
], |
|
|
106 |
"execution_count": 0, |
|
|
107 |
"outputs": [] |
|
|
108 |
}, |
|
|
109 |
{ |
|
|
110 |
"cell_type": "code", |
|
|
111 |
"metadata": { |
|
|
112 |
"id": "8ngVVUx6YFXw", |
|
|
113 |
"colab_type": "code", |
|
|
114 |
"outputId": "c361986d-f0f8-4843-e553-e951a4e0da78", |
|
|
115 |
"colab": { |
|
|
116 |
"base_uri": "https://localhost:8080/", |
|
|
117 |
"height": 809 |
|
|
118 |
} |
|
|
119 |
}, |
|
|
120 |
"source": [ |
|
|
121 |
"!wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\n", |
|
|
122 |
"!wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\n", |
|
|
123 |
"!wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\n", |
|
|
124 |
"!wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\n", |
|
|
125 |
"!gunzip t*.gz" |
|
|
126 |
], |
|
|
127 |
"execution_count": 0, |
|
|
128 |
"outputs": [ |
|
|
129 |
{ |
|
|
130 |
"output_type": "stream", |
|
|
131 |
"text": [ |
|
|
132 |
"--2020-03-27 19:02:28-- http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\n", |
|
|
133 |
"Resolving yann.lecun.com (yann.lecun.com)... 104.28.6.204, 104.28.7.204, 2606:4700:3033::681c:7cc, ...\n", |
|
|
134 |
"Connecting to yann.lecun.com (yann.lecun.com)|104.28.6.204|:80... connected.\n", |
|
|
135 |
"HTTP request sent, awaiting response... 200 OK\n", |
|
|
136 |
"Length: 9912422 (9.5M) [application/x-gzip]\n", |
|
|
137 |
"Saving to: ‘train-images-idx3-ubyte.gz’\n", |
|
|
138 |
"\n", |
|
|
139 |
"train-images-idx3-u 100%[===================>] 9.45M 16.2MB/s in 0.6s \n", |
|
|
140 |
"\n", |
|
|
141 |
"2020-03-27 19:02:29 (16.2 MB/s) - ‘train-images-idx3-ubyte.gz’ saved [9912422/9912422]\n", |
|
|
142 |
"\n", |
|
|
143 |
"--2020-03-27 19:02:29-- http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\n", |
|
|
144 |
"Resolving yann.lecun.com (yann.lecun.com)... 104.28.6.204, 104.28.7.204, 2606:4700:3033::681c:7cc, ...\n", |
|
|
145 |
"Connecting to yann.lecun.com (yann.lecun.com)|104.28.6.204|:80... connected.\n", |
|
|
146 |
"HTTP request sent, awaiting response... 200 OK\n", |
|
|
147 |
"Length: 28881 (28K) [application/x-gzip]\n", |
|
|
148 |
"Saving to: ‘train-labels-idx1-ubyte.gz’\n", |
|
|
149 |
"\n", |
|
|
150 |
"train-labels-idx1-u 100%[===================>] 28.20K --.-KB/s in 0.05s \n", |
|
|
151 |
"\n", |
|
|
152 |
"2020-03-27 19:02:30 (535 KB/s) - ‘train-labels-idx1-ubyte.gz’ saved [28881/28881]\n", |
|
|
153 |
"\n", |
|
|
154 |
"--2020-03-27 19:02:30-- http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\n", |
|
|
155 |
"Resolving yann.lecun.com (yann.lecun.com)... 104.28.6.204, 104.28.7.204, 2606:4700:3033::681c:7cc, ...\n", |
|
|
156 |
"Connecting to yann.lecun.com (yann.lecun.com)|104.28.6.204|:80... connected.\n", |
|
|
157 |
"HTTP request sent, awaiting response... 200 OK\n", |
|
|
158 |
"Length: 1648877 (1.6M) [application/x-gzip]\n", |
|
|
159 |
"Saving to: ‘t10k-images-idx3-ubyte.gz’\n", |
|
|
160 |
"\n", |
|
|
161 |
"t10k-images-idx3-ub 100%[===================>] 1.57M 5.96MB/s in 0.3s \n", |
|
|
162 |
"\n", |
|
|
163 |
"2020-03-27 19:02:31 (5.96 MB/s) - ‘t10k-images-idx3-ubyte.gz’ saved [1648877/1648877]\n", |
|
|
164 |
"\n", |
|
|
165 |
"--2020-03-27 19:02:32-- http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\n", |
|
|
166 |
"Resolving yann.lecun.com (yann.lecun.com)... 104.28.6.204, 104.28.7.204, 2606:4700:3033::681c:7cc, ...\n", |
|
|
167 |
"Connecting to yann.lecun.com (yann.lecun.com)|104.28.6.204|:80... connected.\n", |
|
|
168 |
"HTTP request sent, awaiting response... 200 OK\n", |
|
|
169 |
"Length: 4542 (4.4K) [application/x-gzip]\n", |
|
|
170 |
"Saving to: ‘t10k-labels-idx1-ubyte.gz’\n", |
|
|
171 |
"\n", |
|
|
172 |
"t10k-labels-idx1-ub 100%[===================>] 4.44K --.-KB/s in 0s \n", |
|
|
173 |
"\n", |
|
|
174 |
"2020-03-27 19:02:32 (543 MB/s) - ‘t10k-labels-idx1-ubyte.gz’ saved [4542/4542]\n", |
|
|
175 |
"\n", |
|
|
176 |
"gzip: t10k-images-idx3-ubyte already exists; do you wish to overwrite (y or n)? " |
|
|
177 |
], |
|
|
178 |
"name": "stdout" |
|
|
179 |
} |
|
|
180 |
] |
|
|
181 |
}, |
|
|
182 |
{ |
|
|
183 |
"cell_type": "code", |
|
|
184 |
"metadata": { |
|
|
185 |
"id": "v0OL4yC9YVwp", |
|
|
186 |
"colab_type": "code", |
|
|
187 |
"colab": {} |
|
|
188 |
}, |
|
|
189 |
"source": [ |
|
|
190 |
"# source: https://github.com/myleott/mnist_png/blob/master/convert_mnist_to_png.py\n", |
|
|
191 |
"import os\n", |
|
|
192 |
"import struct\n", |
|
|
193 |
"import sys\n", |
|
|
194 |
"\n", |
|
|
195 |
"from array import array\n", |
|
|
196 |
"from os import path\n", |
|
|
197 |
"\n", |
|
|
198 |
"import png\n", |
|
|
199 |
"\n", |
|
|
200 |
"# source: http://abel.ee.ucla.edu/cvxopt/_downloads/mnist.py\n", |
|
|
201 |
"def read(dataset = \"training\", path = \".\"):\n", |
|
|
202 |
" if dataset is \"training\":\n", |
|
|
203 |
" fname_img = os.path.join(path, 'train-images-idx3-ubyte')\n", |
|
|
204 |
" fname_lbl = os.path.join(path, 'train-labels-idx1-ubyte')\n", |
|
|
205 |
" elif dataset is \"testing\":\n", |
|
|
206 |
" fname_img = os.path.join(path, 't10k-images-idx3-ubyte')\n", |
|
|
207 |
" fname_lbl = os.path.join(path, 't10k-labels-idx1-ubyte')\n", |
|
|
208 |
" else:\n", |
|
|
209 |
" raise ValueError(\"dataset must be 'testing' or 'training'\")\n", |
|
|
210 |
"\n", |
|
|
211 |
" flbl = open(fname_lbl, 'rb')\n", |
|
|
212 |
" magic_nr, size = struct.unpack(\">II\", flbl.read(8))\n", |
|
|
213 |
" lbl = array(\"b\", flbl.read())\n", |
|
|
214 |
" flbl.close()\n", |
|
|
215 |
"\n", |
|
|
216 |
" fimg = open(fname_img, 'rb')\n", |
|
|
217 |
" magic_nr, size, rows, cols = struct.unpack(\">IIII\", fimg.read(16))\n", |
|
|
218 |
" img = array(\"B\", fimg.read())\n", |
|
|
219 |
" fimg.close()\n", |
|
|
220 |
"\n", |
|
|
221 |
" return lbl, img, size, rows, cols\n", |
|
|
222 |
"\n", |
|
|
223 |
"def write_dataset(labels, data, size, rows, cols, output_dir):\n", |
|
|
224 |
" # create output directories\n", |
|
|
225 |
" output_dirs = [\n", |
|
|
226 |
" path.join(output_dir, str(i))\n", |
|
|
227 |
" for i in range(10)\n", |
|
|
228 |
" ]\n", |
|
|
229 |
" for dir in output_dirs:\n", |
|
|
230 |
" if not path.exists(dir):\n", |
|
|
231 |
" os.makedirs(dir)\n", |
|
|
232 |
"\n", |
|
|
233 |
" # write data\n", |
|
|
234 |
" for (i, label) in tqdm(enumerate(labels)):\n", |
|
|
235 |
" output_filename = path.join(output_dirs[label], str(i) + \".png\")\n", |
|
|
236 |
" with open(output_filename, \"wb\") as h:\n", |
|
|
237 |
" w = png.Writer(cols, rows, greyscale=True)\n", |
|
|
238 |
" data_i = [\n", |
|
|
239 |
" data[ (i*rows*cols + j*cols) : (i*rows*cols + (j+1)*cols) ]\n", |
|
|
240 |
" for j in range(rows)\n", |
|
|
241 |
" ]\n", |
|
|
242 |
" w.write(h, data_i)\n", |
|
|
243 |
"\n", |
|
|
244 |
"input_path = '/content'\n", |
|
|
245 |
"output_path = '/content/mnist'\n", |
|
|
246 |
"for dataset in [\"training\", \"testing\"]:\n", |
|
|
247 |
" labels, data, size, rows, cols = read(dataset, input_path)\n", |
|
|
248 |
" write_dataset(labels, data, size, rows, cols,\n", |
|
|
249 |
" path.join(output_path, dataset))" |
|
|
250 |
], |
|
|
251 |
"execution_count": 0, |
|
|
252 |
"outputs": [] |
|
|
253 |
}, |
|
|
254 |
{ |
|
|
255 |
"cell_type": "markdown", |
|
|
256 |
"metadata": { |
|
|
257 |
"id": "Zz84BWQTZv1z", |
|
|
258 |
"colab_type": "text" |
|
|
259 |
}, |
|
|
260 |
"source": [ |
|
|
261 |
"### Load and preprocess the dataset " |
|
|
262 |
] |
|
|
263 |
}, |
|
|
264 |
{ |
|
|
265 |
"cell_type": "code", |
|
|
266 |
"metadata": { |
|
|
267 |
"id": "sm9kkKrFgER1", |
|
|
268 |
"colab_type": "code", |
|
|
269 |
"colab": {} |
|
|
270 |
}, |
|
|
271 |
"source": [ |
|
|
272 |
"#Create csv files\n", |
|
|
273 |
"import glob \n", |
|
|
274 |
"import pandas as pd\n", |
|
|
275 |
"\n", |
|
|
276 |
"for split in ['training', 'testing']:\n", |
|
|
277 |
" rows = []\n", |
|
|
278 |
" for folder in glob.glob('/content/mnist/'+ split + '/*'):\n", |
|
|
279 |
" label = folder.split(\"/\")[-1]\n", |
|
|
280 |
" for image_path in glob.glob(folder+ \"/*\"):\n", |
|
|
281 |
" rows.append([image_path,label])\n", |
|
|
282 |
" df=pd.DataFrame(rows,columns=['Path','Label'])\n", |
|
|
283 |
" df.to_csv(split + \".csv\", index = False)\n" |
|
|
284 |
], |
|
|
285 |
"execution_count": 0, |
|
|
286 |
"outputs": [] |
|
|
287 |
}, |
|
|
288 |
{ |
|
|
289 |
"cell_type": "code", |
|
|
290 |
"metadata": { |
|
|
291 |
"id": "Py8ckf0VqgOK", |
|
|
292 |
"colab_type": "code", |
|
|
293 |
"colab": {} |
|
|
294 |
}, |
|
|
295 |
"source": [ |
|
|
296 |
"# Visualize the dataset \n", |
|
|
297 |
"\n", |
|
|
298 |
"import matplotlib.pyplot as plt\n", |
|
|
299 |
"import numpy as np\n", |
|
|
300 |
"import cv2\n", |
|
|
301 |
"\n", |
|
|
302 |
"def view_dataset(paths, labels, method='cv2'):\n", |
|
|
303 |
" fig, axs = plt.subplots(5, 5, figsize=(10, 10))\n", |
|
|
304 |
" flatted_axs = [item for one_ax in axs for item in one_ax]\n", |
|
|
305 |
" for ax, path, label in zip(flatted_axs, paths[:25], labels[:25]):\n", |
|
|
306 |
" if method == 'cv2':\n", |
|
|
307 |
" img = cv2.imread(path, 3)\n", |
|
|
308 |
" elif method == 'tf':\n", |
|
|
309 |
" img = try_tf_image(path)\n", |
|
|
310 |
" ax.imshow(img)\n", |
|
|
311 |
" ax.set_title(label)\n", |
|
|
312 |
" ax.axis('off')\n", |
|
|
313 |
" plt.show() \n", |
|
|
314 |
"\n", |
|
|
315 |
"\n", |
|
|
316 |
"df = pd.read_csv('/content/training.csv')\n", |
|
|
317 |
"paths = df['Path'][:25]\n", |
|
|
318 |
"labels = df['Label'][:25]\n", |
|
|
319 |
"\n", |
|
|
320 |
"view_dataset(paths, labels)" |
|
|
321 |
], |
|
|
322 |
"execution_count": 0, |
|
|
323 |
"outputs": [] |
|
|
324 |
}, |
|
|
325 |
{ |
|
|
326 |
"cell_type": "code", |
|
|
327 |
"metadata": { |
|
|
328 |
"id": "npVz8F15ipDi", |
|
|
329 |
"colab_type": "code", |
|
|
330 |
"colab": {} |
|
|
331 |
}, |
|
|
332 |
"source": [ |
|
|
333 |
"# Install Pytorch2\n", |
|
|
334 |
"# http://pytorch.org/\n", |
|
|
335 |
"#from os.path import exists\n", |
|
|
336 |
"#from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag\n", |
|
|
337 |
"#platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())\n", |
|
|
338 |
"#cuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\\.\\([0-9]*\\)\\.\\([0-9]*\\)$/cu\\1\\2/'\n", |
|
|
339 |
"#accelerator = cuda_output[0] if exists('/dev/nvidia0') else 'cpu'\n", |
|
|
340 |
"\n", |
|
|
341 |
"# !pip install -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.1-{platform}-linux_x86_64.whl torchvision\n", |
|
|
342 |
"\n", |
|
|
343 |
" \n", |
|
|
344 |
"!pip install torch \n", |
|
|
345 |
"import torch\n", |
|
|
346 |
"\n", |
|
|
347 |
"print(torch.__version__)" |
|
|
348 |
], |
|
|
349 |
"execution_count": 0, |
|
|
350 |
"outputs": [] |
|
|
351 |
}, |
|
|
352 |
{ |
|
|
353 |
"cell_type": "code", |
|
|
354 |
"metadata": { |
|
|
355 |
"id": "rQYdkPxSZ46b", |
|
|
356 |
"colab_type": "code", |
|
|
357 |
"colab": {} |
|
|
358 |
}, |
|
|
359 |
"source": [ |
|
|
360 |
"import pandas as pd\n", |
|
|
361 |
"from torch.utils.data import Dataset, DataLoader\n", |
|
|
362 |
"from PIL import Image\n", |
|
|
363 |
"\n", |
|
|
364 |
"class Dataset(Dataset):\n", |
|
|
365 |
" def __init__(self, data_split, toy=False):\n", |
|
|
366 |
" \n", |
|
|
367 |
" df = pd.read_csv(data_split)\n", |
|
|
368 |
" \n", |
|
|
369 |
" # Remove any paths for which the image files do not exist\n", |
|
|
370 |
" #df = df[df[\"Path\"].apply(os.path.exists)]\n", |
|
|
371 |
" \n", |
|
|
372 |
" #print (\"%s size %d\" % (data_split, df.shape[0]))\n", |
|
|
373 |
"\n", |
|
|
374 |
" #Could remove\n", |
|
|
375 |
" #if toy:\n", |
|
|
376 |
" #df = df.sample(frac=0.01)\n", |
|
|
377 |
"\n", |
|
|
378 |
" self.img_paths = df[\"Path\"].tolist()\n", |
|
|
379 |
"\n", |
|
|
380 |
" self.labels = df[\"Label\"].tolist()\n", |
|
|
381 |
"\n", |
|
|
382 |
" self.n_classes = len(self.labels)\n", |
|
|
383 |
"\n", |
|
|
384 |
" def __getitem__(self, index):\n", |
|
|
385 |
" img = np.array(Image.open(self.img_paths[index])).astype(np.float32) / 255.\n", |
|
|
386 |
" label = self.labels[index]\n", |
|
|
387 |
" label_vec = torch.LongTensor([label])\n", |
|
|
388 |
" return img, label_vec\n", |
|
|
389 |
" \n", |
|
|
390 |
"\n", |
|
|
391 |
" def __len__(self):\n", |
|
|
392 |
" return len(self.img_paths)" |
|
|
393 |
], |
|
|
394 |
"execution_count": 0, |
|
|
395 |
"outputs": [] |
|
|
396 |
}, |
|
|
397 |
{ |
|
|
398 |
"cell_type": "code", |
|
|
399 |
"metadata": { |
|
|
400 |
"id": "65LGWGMTvftr", |
|
|
401 |
"colab_type": "code", |
|
|
402 |
"colab": {} |
|
|
403 |
}, |
|
|
404 |
"source": [ |
|
|
405 |
"train_dataset = Dataset('training.csv')\n", |
|
|
406 |
"test_dataset = Dataset('testing.csv')\n", |
|
|
407 |
"\n", |
|
|
408 |
"\n", |
|
|
409 |
"train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=100,\n", |
|
|
410 |
" shuffle=True)\n", |
|
|
411 |
"test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=100,\n", |
|
|
412 |
" shuffle=True)\n", |
|
|
413 |
"\n", |
|
|
414 |
"print(len(train_loader))\n", |
|
|
415 |
"print(len(test_loader))" |
|
|
416 |
], |
|
|
417 |
"execution_count": 0, |
|
|
418 |
"outputs": [] |
|
|
419 |
}, |
|
|
420 |
{ |
|
|
421 |
"cell_type": "code", |
|
|
422 |
"metadata": { |
|
|
423 |
"id": "3BqLZzkD5qkp", |
|
|
424 |
"colab_type": "code", |
|
|
425 |
"colab": {} |
|
|
426 |
}, |
|
|
427 |
"source": [ |
|
|
428 |
"\"\"\" Step 2: Define the model\n", |
|
|
429 |
"\n", |
|
|
430 |
"We will implement LeNet\n", |
|
|
431 |
"\"\"\"\n", |
|
|
432 |
"import torch.nn as nn\n", |
|
|
433 |
"import torch.nn.functional as F\n", |
|
|
434 |
"\n", |
|
|
435 |
"class Flatten(nn.Module):\n", |
|
|
436 |
" def forward(self, input):\n", |
|
|
437 |
" return input.view(input.size(0), -1)\n", |
|
|
438 |
"\n", |
|
|
439 |
"class LeNet(nn.Module):\n", |
|
|
440 |
" def __init__(self):\n", |
|
|
441 |
" super(LeNet, self).__init__()\n", |
|
|
442 |
" self.conv1 = nn.Conv2d(1, 6, 5)\n", |
|
|
443 |
" self.conv2 = nn.Conv2d(6, 16, 5)\n", |
|
|
444 |
" self.fc1 = nn.Linear(256, 120)\n", |
|
|
445 |
" self.fc2 = nn.Linear(120, 84)\n", |
|
|
446 |
" self.fc3 = nn.Linear(84, 10)\n", |
|
|
447 |
"\n", |
|
|
448 |
" def forward(self, x):\n", |
|
|
449 |
" out = F.relu(self.conv1(x[:, None, :, :]))\n", |
|
|
450 |
" out = F.max_pool2d(out, 2)\n", |
|
|
451 |
" out = F.relu(self.conv2(out))\n", |
|
|
452 |
" out = F.max_pool2d(out, 2)\n", |
|
|
453 |
" out = out.view(out.size(0), -1)\n", |
|
|
454 |
" out = F.relu(self.fc1(out))\n", |
|
|
455 |
" out = F.relu(self.fc2(out))\n", |
|
|
456 |
" out = self.fc3(out)\n", |
|
|
457 |
" return out\n", |
|
|
458 |
"\n", |
|
|
459 |
"model = LeNet()" |
|
|
460 |
], |
|
|
461 |
"execution_count": 0, |
|
|
462 |
"outputs": [] |
|
|
463 |
}, |
|
|
464 |
{ |
|
|
465 |
"cell_type": "code", |
|
|
466 |
"metadata": { |
|
|
467 |
"id": "dNR2Huir8iDO", |
|
|
468 |
"colab_type": "code", |
|
|
469 |
"colab": {} |
|
|
470 |
}, |
|
|
471 |
"source": [ |
|
|
472 |
"\"\"\"Step 3: Define loss function and optimizer\n", |
|
|
473 |
"\n", |
|
|
474 |
"We will use the cross entropy loss and Adam optimizer\n", |
|
|
475 |
"\"\"\"\n", |
|
|
476 |
"import torch.optim as optim\n", |
|
|
477 |
"\n", |
|
|
478 |
"# Define the cost function\n", |
|
|
479 |
"criterion = nn.CrossEntropyLoss()\n", |
|
|
480 |
"\n", |
|
|
481 |
"# Define the optimizer, learning rate \n", |
|
|
482 |
"optimizer = optim.Adam(model.parameters(), lr=0.01)\n" |
|
|
483 |
], |
|
|
484 |
"execution_count": 0, |
|
|
485 |
"outputs": [] |
|
|
486 |
}, |
|
|
487 |
{ |
|
|
488 |
"cell_type": "code", |
|
|
489 |
"metadata": { |
|
|
490 |
"id": "FjYyhIyz8kzP", |
|
|
491 |
"colab_type": "code", |
|
|
492 |
"colab": {} |
|
|
493 |
}, |
|
|
494 |
"source": [ |
|
|
495 |
"\"\"\"\"\"Step 5: Train the network on the training data\n", |
|
|
496 |
"\"\"\"\n", |
|
|
497 |
"\n", |
|
|
498 |
"for epoch in range(2): \n", |
|
|
499 |
" for i, (inputs, labels) in enumerate(train_loader, 0):\n", |
|
|
500 |
" # zero the parameter gradients\n", |
|
|
501 |
" optimizer.zero_grad()\n", |
|
|
502 |
"\n", |
|
|
503 |
" # forward propogation\n", |
|
|
504 |
" outputs = model(inputs)\n", |
|
|
505 |
" \n", |
|
|
506 |
" # calculate the loss\n", |
|
|
507 |
" loss = criterion(outputs, labels.squeeze(1))\n", |
|
|
508 |
" \n", |
|
|
509 |
" # backpropogation + update parameters\n", |
|
|
510 |
" loss.backward()\n", |
|
|
511 |
" optimizer.step()\n", |
|
|
512 |
"\n", |
|
|
513 |
" # print statistics\n", |
|
|
514 |
" cost = loss.item()\n", |
|
|
515 |
" if i % 100 == 0: # print every 1000 iterations\n", |
|
|
516 |
" print('Epoch:' + str(epoch) + \", Iteration: \" + str(i) \n", |
|
|
517 |
" + \", training cost = \" + str(cost))\n" |
|
|
518 |
], |
|
|
519 |
"execution_count": 0, |
|
|
520 |
"outputs": [] |
|
|
521 |
}, |
|
|
522 |
{ |
|
|
523 |
"cell_type": "code", |
|
|
524 |
"metadata": { |
|
|
525 |
"id": "flMO9Gx68jYJ", |
|
|
526 |
"colab_type": "code", |
|
|
527 |
"colab": {} |
|
|
528 |
}, |
|
|
529 |
"source": [ |
|
|
530 |
"\"\"\"Step 4: Define evaluation metric\n", |
|
|
531 |
"\n", |
|
|
532 |
"We will use accuracy as an evaluation metric\n", |
|
|
533 |
"\"\"\"\n", |
|
|
534 |
"\n", |
|
|
535 |
"def calculate_accuracy(loader):\n", |
|
|
536 |
" total = 0\n", |
|
|
537 |
" correct = 0\n", |
|
|
538 |
" \n", |
|
|
539 |
" all_images = []\n", |
|
|
540 |
" all_preds = []\n", |
|
|
541 |
" all_labels = []\n", |
|
|
542 |
" with torch.no_grad():\n", |
|
|
543 |
" for data in loader:\n", |
|
|
544 |
" images, labels = data\n", |
|
|
545 |
" outputs = model(images)\n", |
|
|
546 |
" _, predicted = torch.max(outputs.data, 1)\n", |
|
|
547 |
" total += labels.size(0)\n", |
|
|
548 |
" correct += (predicted == labels.squeeze()).sum().item()\n", |
|
|
549 |
" \n", |
|
|
550 |
" all_images.append(images)\n", |
|
|
551 |
" all_preds.append(predicted.numpy())\n", |
|
|
552 |
" all_labels.append(labels)\n", |
|
|
553 |
"\n", |
|
|
554 |
" return 100 * correct / total, all_images, all_preds, all_labels" |
|
|
555 |
], |
|
|
556 |
"execution_count": 0, |
|
|
557 |
"outputs": [] |
|
|
558 |
}, |
|
|
559 |
{ |
|
|
560 |
"cell_type": "code", |
|
|
561 |
"metadata": { |
|
|
562 |
"id": "eRbRt1-18rks", |
|
|
563 |
"colab_type": "code", |
|
|
564 |
"colab": {} |
|
|
565 |
}, |
|
|
566 |
"source": [ |
|
|
567 |
"\"\"\"Step 6: Report results on the train and test data (using the evaluation metric)\n", |
|
|
568 |
"\"\"\"\n", |
|
|
569 |
" \n", |
|
|
570 |
"train_accuracy, _ , _, _ = calculate_accuracy(train_loader)\n", |
|
|
571 |
"test_accuracy, images, preds, labels = calculate_accuracy(test_loader)\n", |
|
|
572 |
"\n", |
|
|
573 |
"print('Train accuracy: %f' % train_accuracy)\n", |
|
|
574 |
"print('Test accuracy: %f' % test_accuracy)\n", |
|
|
575 |
"\n", |
|
|
576 |
"images = np.concatenate(images, axis=0)\n", |
|
|
577 |
"preds = np.concatenate(preds, axis=0)\n", |
|
|
578 |
"labels = np.squeeze(np.concatenate(labels, axis=0))" |
|
|
579 |
], |
|
|
580 |
"execution_count": 0, |
|
|
581 |
"outputs": [] |
|
|
582 |
}, |
|
|
583 |
{ |
|
|
584 |
"cell_type": "code", |
|
|
585 |
"metadata": { |
|
|
586 |
"id": "GUJzZQ7zey6O", |
|
|
587 |
"colab_type": "code", |
|
|
588 |
"colab": {} |
|
|
589 |
}, |
|
|
590 |
"source": [ |
|
|
591 |
"##### VIEW PREDICTIONS #####\n", |
|
|
592 |
"import matplotlib.pyplot as plt\n", |
|
|
593 |
"import numpy as np\n", |
|
|
594 |
"\n", |
|
|
595 |
"\n", |
|
|
596 |
"def unison_shuffled_copies(a, b, c):\n", |
|
|
597 |
" assert len(a) == len(b) == len(c)\n", |
|
|
598 |
" p = np.random.permutation(len(a))\n", |
|
|
599 |
" return a[p], b[p], c[p]\n", |
|
|
600 |
"\n", |
|
|
601 |
"images, labels, preds = unison_shuffled_copies(images, labels, preds)\n", |
|
|
602 |
"\n", |
|
|
603 |
"fig, axs = plt.subplots(5, 5, figsize=(10, 10))\n", |
|
|
604 |
"flatted_axs = [item for one_ax in axs for item in one_ax]\n", |
|
|
605 |
"for ax, img, label, pred in zip(flatted_axs, images[:25], labels[:25], preds[:25]):\n", |
|
|
606 |
" ax.imshow(np.reshape(img, (28,28)))\n", |
|
|
607 |
" ax.set_title('l:{},p:{}'.format(label, pred))\n", |
|
|
608 |
" ax.axis('off')\n", |
|
|
609 |
"plt.show() " |
|
|
610 |
], |
|
|
611 |
"execution_count": 0, |
|
|
612 |
"outputs": [] |
|
|
613 |
}, |
|
|
614 |
{ |
|
|
615 |
"cell_type": "markdown", |
|
|
616 |
"metadata": { |
|
|
617 |
"id": "W5eAVxqYbc2N", |
|
|
618 |
"colab_type": "text" |
|
|
619 |
}, |
|
|
620 |
"source": [ |
|
|
621 |
"### Saving/Loading a model\n", |
|
|
622 |
"\n", |
|
|
623 |
"We will look at how you would save a trained model and then load it again for evaluation.\n", |
|
|
624 |
"\n", |
|
|
625 |
"Reference - https://pytorch.org/tutorials/beginner/saving_loading_models.html" |
|
|
626 |
] |
|
|
627 |
}, |
|
|
628 |
{ |
|
|
629 |
"cell_type": "code", |
|
|
630 |
"metadata": { |
|
|
631 |
"id": "1PwE0NcNbuTf", |
|
|
632 |
"colab_type": "code", |
|
|
633 |
"colab": {} |
|
|
634 |
}, |
|
|
635 |
"source": [ |
|
|
636 |
"\"\"\"Save a model\n", |
|
|
637 |
"\"\"\"\n", |
|
|
638 |
"\n", |
|
|
639 |
"# Create a very simple model and save the weights\n", |
|
|
640 |
"v1 = torch.randn(3)\n", |
|
|
641 |
"v2 = torch.randn(5)\n", |
|
|
642 |
"\n", |
|
|
643 |
"# Save variables\n", |
|
|
644 |
"torch.save(v1, 'v1.pth')\n", |
|
|
645 |
"torch.save(v2, 'v2.pth')\n", |
|
|
646 |
"\n", |
|
|
647 |
"# Print values at v1 and v2 to verify later\n", |
|
|
648 |
"print(v1)\n", |
|
|
649 |
"print(v2)" |
|
|
650 |
], |
|
|
651 |
"execution_count": 0, |
|
|
652 |
"outputs": [] |
|
|
653 |
}, |
|
|
654 |
{ |
|
|
655 |
"cell_type": "code", |
|
|
656 |
"metadata": { |
|
|
657 |
"id": "wRo8lso2nagN", |
|
|
658 |
"colab_type": "code", |
|
|
659 |
"colab": {} |
|
|
660 |
}, |
|
|
661 |
"source": [ |
|
|
662 |
"\"\"\" Load a model\n", |
|
|
663 |
"\"\"\"\n", |
|
|
664 |
"\n", |
|
|
665 |
"# Load variables v1 and v2 \n", |
|
|
666 |
"v1 = torch.load('v1.pth')\n", |
|
|
667 |
"v2 = torch.load('v2.pth')\n", |
|
|
668 |
"\n", |
|
|
669 |
"# Check the values of the variables\n", |
|
|
670 |
"print(v1)\n", |
|
|
671 |
"print(v2)" |
|
|
672 |
], |
|
|
673 |
"execution_count": 0, |
|
|
674 |
"outputs": [] |
|
|
675 |
}, |
|
|
676 |
{ |
|
|
677 |
"cell_type": "markdown", |
|
|
678 |
"metadata": { |
|
|
679 |
"id": "cXK_MJbtcMel", |
|
|
680 |
"colab_type": "text" |
|
|
681 |
}, |
|
|
682 |
"source": [ |
|
|
683 |
"For more help getting started with Pytorch check out: http://cs230.stanford.edu/blog/pytorch/" |
|
|
684 |
] |
|
|
685 |
}, |
|
|
686 |
{ |
|
|
687 |
"cell_type": "markdown", |
|
|
688 |
"metadata": { |
|
|
689 |
"id": "uO8S-By3yBMo", |
|
|
690 |
"colab_type": "text" |
|
|
691 |
}, |
|
|
692 |
"source": [ |
|
|
693 |
"## Part 2: Feature importance techniques\n", |
|
|
694 |
"\n", |
|
|
695 |
"In this part, we will implement two feature visualization techniques:\n", |
|
|
696 |
"- Saliency Maps\n", |
|
|
697 |
"- Deep Dream" |
|
|
698 |
] |
|
|
699 |
}, |
|
|
700 |
{ |
|
|
701 |
"cell_type": "markdown", |
|
|
702 |
"metadata": { |
|
|
703 |
"id": "r9gbMifYb1jE", |
|
|
704 |
"colab_type": "text" |
|
|
705 |
}, |
|
|
706 |
"source": [ |
|
|
707 |
"### Saliency Map" |
|
|
708 |
] |
|
|
709 |
}, |
|
|
710 |
{ |
|
|
711 |
"cell_type": "markdown", |
|
|
712 |
"metadata": { |
|
|
713 |
"id": "SeMDRB2SHm67", |
|
|
714 |
"colab_type": "text" |
|
|
715 |
}, |
|
|
716 |
"source": [ |
|
|
717 |
"You can change the class whose gradient is computed" |
|
|
718 |
] |
|
|
719 |
}, |
|
|
720 |
{ |
|
|
721 |
"cell_type": "code", |
|
|
722 |
"metadata": { |
|
|
723 |
"id": "NM2RoMlTHltn", |
|
|
724 |
"colab_type": "code", |
|
|
725 |
"colab": {} |
|
|
726 |
}, |
|
|
727 |
"source": [ |
|
|
728 |
"idx = 5 # class whose gradient will be computed" |
|
|
729 |
], |
|
|
730 |
"execution_count": 0, |
|
|
731 |
"outputs": [] |
|
|
732 |
}, |
|
|
733 |
{ |
|
|
734 |
"cell_type": "code", |
|
|
735 |
"metadata": { |
|
|
736 |
"id": "SzF6QEQhy-Sc", |
|
|
737 |
"colab_type": "code", |
|
|
738 |
"colab": {} |
|
|
739 |
}, |
|
|
740 |
"source": [ |
|
|
741 |
"def plot_saliency(idx):\n", |
|
|
742 |
" # Forward pass\n", |
|
|
743 |
" data = next(iter(test_loader))\n", |
|
|
744 |
" images, labels = data\n", |
|
|
745 |
" images.requires_grad = True # the gradient with respect to the input will be computed\n", |
|
|
746 |
" outputs = model(images)\n", |
|
|
747 |
"\n", |
|
|
748 |
" # Backward pass\n", |
|
|
749 |
" loss = outputs[:, idx: idx+1].sum()\n", |
|
|
750 |
" loss.backward(retain_graph=True)\n", |
|
|
751 |
" heatmaps = images.grad.detach().numpy() # The heatmap is the gradient with respect to the input\n", |
|
|
752 |
"\n", |
|
|
753 |
" # Plot\n", |
|
|
754 |
" fig, axs = plt.subplots(4, 4, figsize=(10, 10))\n", |
|
|
755 |
" fig.suptitle(\"Saliency maps with respect to class \" + str(idx) + \", green corresponds to positive gradient and red to negative\")\n", |
|
|
756 |
" for i in range(4):\n", |
|
|
757 |
" for j in range(2):\n", |
|
|
758 |
" axs[i, 2*j].imshow(images[2*i + j].detach())\n", |
|
|
759 |
" axs[i, 2*j].axis('off')\n", |
|
|
760 |
" axs[i, 2*j+1].imshow(heatmaps[2*i + j], cmap=\"PiYG\", vmin=-1, vmax=1)\n", |
|
|
761 |
" axs[i, 2*j+1].axis('off')\n", |
|
|
762 |
" plt.show()" |
|
|
763 |
], |
|
|
764 |
"execution_count": 0, |
|
|
765 |
"outputs": [] |
|
|
766 |
}, |
|
|
767 |
{ |
|
|
768 |
"cell_type": "code", |
|
|
769 |
"metadata": { |
|
|
770 |
"id": "Ujfua2GTzbvi", |
|
|
771 |
"colab_type": "code", |
|
|
772 |
"colab": {} |
|
|
773 |
}, |
|
|
774 |
"source": [ |
|
|
775 |
"plot_saliency(idx=1)" |
|
|
776 |
], |
|
|
777 |
"execution_count": 0, |
|
|
778 |
"outputs": [] |
|
|
779 |
}, |
|
|
780 |
{ |
|
|
781 |
"cell_type": "markdown", |
|
|
782 |
"metadata": { |
|
|
783 |
"id": "s3jl5qoJb7EY", |
|
|
784 |
"colab_type": "text" |
|
|
785 |
}, |
|
|
786 |
"source": [ |
|
|
787 |
"### Deep Dream" |
|
|
788 |
] |
|
|
789 |
}, |
|
|
790 |
{ |
|
|
791 |
"cell_type": "markdown", |
|
|
792 |
"metadata": { |
|
|
793 |
"id": "AW4SHVmYG7U0", |
|
|
794 |
"colab_type": "text" |
|
|
795 |
}, |
|
|
796 |
"source": [ |
|
|
797 |
"Play with the following parameters and see what happens!" |
|
|
798 |
] |
|
|
799 |
}, |
|
|
800 |
{ |
|
|
801 |
"cell_type": "code", |
|
|
802 |
"metadata": { |
|
|
803 |
"id": "iRvtXZSWHAEF", |
|
|
804 |
"colab_type": "code", |
|
|
805 |
"colab": {} |
|
|
806 |
}, |
|
|
807 |
"source": [ |
|
|
808 |
"idx = 3 # class whose gradient will be computed\n", |
|
|
809 |
"lr = 0.05 # Learning rate for deep dream\n", |
|
|
810 |
"n_iter = 60 # Number of iterations for Deep Dream" |
|
|
811 |
], |
|
|
812 |
"execution_count": 0, |
|
|
813 |
"outputs": [] |
|
|
814 |
}, |
|
|
815 |
{ |
|
|
816 |
"cell_type": "code", |
|
|
817 |
"metadata": { |
|
|
818 |
"id": "Mp55OBKSsQMl", |
|
|
819 |
"colab_type": "code", |
|
|
820 |
"colab": {} |
|
|
821 |
}, |
|
|
822 |
"source": [ |
|
|
823 |
"# Forward pass\n", |
|
|
824 |
"data = next(iter(test_loader))\n", |
|
|
825 |
"images, labels = data\n", |
|
|
826 |
"images.requires_grad = True # the gradient with respect to the input will be computed\n", |
|
|
827 |
"outputs = model(images)" |
|
|
828 |
], |
|
|
829 |
"execution_count": 0, |
|
|
830 |
"outputs": [] |
|
|
831 |
}, |
|
|
832 |
{ |
|
|
833 |
"cell_type": "markdown", |
|
|
834 |
"metadata": { |
|
|
835 |
"id": "dz3R-eaCHKPc", |
|
|
836 |
"colab_type": "text" |
|
|
837 |
}, |
|
|
838 |
"source": [ |
|
|
839 |
"The Deep Dream procedure:" |
|
|
840 |
] |
|
|
841 |
}, |
|
|
842 |
{ |
|
|
843 |
"cell_type": "code", |
|
|
844 |
"metadata": { |
|
|
845 |
"id": "AqzLn8Izb-Jv", |
|
|
846 |
"colab_type": "code", |
|
|
847 |
"colab": {} |
|
|
848 |
}, |
|
|
849 |
"source": [ |
|
|
850 |
"img = images\n", |
|
|
851 |
"\n", |
|
|
852 |
"for _ in range(n_iter):\n", |
|
|
853 |
" model.zero_grad()\n", |
|
|
854 |
" outputs = model(img)\n", |
|
|
855 |
" loss = outputs[:, idx: idx+1].sum() # maximize the class idx\n", |
|
|
856 |
" loss.backward(retain_graph=True)\n", |
|
|
857 |
" img = img + lr * img.grad # The gradient is added to the image\n", |
|
|
858 |
" img.data = torch.clamp(img.data, min=0)\n", |
|
|
859 |
"\n", |
|
|
860 |
" # Trick to forget the computation graph\n", |
|
|
861 |
" img = img.detach().numpy()\n", |
|
|
862 |
" img = torch.Tensor(img)\n", |
|
|
863 |
" img.requires_grad = True\n" |
|
|
864 |
], |
|
|
865 |
"execution_count": 0, |
|
|
866 |
"outputs": [] |
|
|
867 |
}, |
|
|
868 |
{ |
|
|
869 |
"cell_type": "markdown", |
|
|
870 |
"metadata": { |
|
|
871 |
"id": "hZjL5g6cHSkZ", |
|
|
872 |
"colab_type": "text" |
|
|
873 |
}, |
|
|
874 |
"source": [ |
|
|
875 |
"Visualize Before/After:\n", |
|
|
876 |
"\n", |
|
|
877 |
"The dreamed image is on the right of the corresponding original image" |
|
|
878 |
] |
|
|
879 |
}, |
|
|
880 |
{ |
|
|
881 |
"cell_type": "code", |
|
|
882 |
"metadata": { |
|
|
883 |
"id": "emFRVlDmrV99", |
|
|
884 |
"colab_type": "code", |
|
|
885 |
"colab": {} |
|
|
886 |
}, |
|
|
887 |
"source": [ |
|
|
888 |
"fig, axs = plt.subplots(4, 4, figsize=(10, 10))\n", |
|
|
889 |
"fig.suptitle(\"Deep Dreaming numbers \" + str(idx))\n", |
|
|
890 |
"for i in range(4):\n", |
|
|
891 |
" for j in range(2):\n", |
|
|
892 |
" axs[i, 2*j].imshow(images[2*i + j].detach())\n", |
|
|
893 |
" axs[i, 2*j].axis('off')\n", |
|
|
894 |
" axs[i, 2*j+1].imshow(img[2*i + j].detach())\n", |
|
|
895 |
" axs[i, 2*j+1].axis('off')\n", |
|
|
896 |
"plt.show()" |
|
|
897 |
], |
|
|
898 |
"execution_count": 0, |
|
|
899 |
"outputs": [] |
|
|
900 |
} |
|
|
901 |
] |
|
|
902 |
} |