"cacheflow/master/simple_frontend.py" did not exist on "1132fae0ca7f6103b0dd7b96932c75f5ed780288"
Image Segmentation Blog Post.ipynb 49.1 KB
Newer Older
Raymond Yuan's avatar
Raymond Yuan committed
1
2
{
 "cells": [
Raymond Yuan's avatar
Raymond Yuan committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Finding visual objects in images - Image Segmentation with tf.keras "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\"><td>\n",
    "<a target=\"_blank\"  href=\"https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/generative_examples/image_captioning_with_attention.ipynb\">\n",
    "    <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>  \n",
    "</td><td>\n",
    "<a target=\"_blank\"  href=\"https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/generative_examples/image_captioning_with_attention.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a></td></table>"
   ]
  },
Raymond Yuan's avatar
Raymond Yuan committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "cl79rk4KKol8"
   },
   "source": [
    "In this tutorial we will learn how to segment images. **Segmentation** is the process of generating pixel-wise segmentations giving the class of the object visible at each pixel. For example, we could be identifying the location and boundaries of people within an image or identifying cell nuclei from an image. Formally, image segmentation refers to the process of partitioning an image into a set of pixels that we desire to identify (our target) and the background. \n",
    "\n",
    "Specifically, in this tutorial we will be using the [Kaggle Carvana Image Masking Challenge Dataset](https://www.kaggle.com/c/carvana-image-masking-challenge). \n",
    "\n",
    "This dataset contains a large number of car images, with each car taken from different angles. In addition, for each car image, we have an associated manually cutout mask; our task will be to automatically create these cutout masks for unseen data. \n",
    "\n",
    "## Specific concepts that will be covered:\n",
    "In the process, we will build practical experience and develop intuition around the following concepts:\n",
    "* **[Functional API](https://keras.io/getting-started/functional-api-guide/)** - we will be implementing UNet, a convolutional network model classically used for biomedical image segmentation with the Functional API. \n",
    "  * This model has layers that require multiple input/outputs. This requires the use of the functional API\n",
    "  * Check out the original [paper](https://arxiv.org/abs/1505.04597), \n",
    "U-Net: Convolutional Networks for Biomedical Image Segmentation by Olaf Ronneberger!\n",
    "* **Custom Loss Functions and Metrics** - We'll implement a custom loss function using binary [**cross entropy**](https://developers.google.com/machine-learning/glossary/#cross-entropy) and **dice loss**. We'll also implement **dice coefficient** (which is used for our loss) and **mean intersection over union**, that will help us monitor our training process and judge how well we are performing. \n",
    "* **Saving and loading keras models** - We'll save our best model to disk. When we want to perform inference/evaluate our model, we'll load in the model from disk. \n",
    "\n",
    "### We will follow the general workflow:\n",
    "1. Visualize data/perform some exploratory data analysis\n",
    "2. Set up data pipeline and preprocessing\n",
    "3. Build model\n",
    "4. Train model\n",
    "5. Evaluate model\n",
    "6. Repeat\n",
    "\n",
    "**Audience:** This post is geared towards intermediate users who are comfortable with basic machine learning concepts.\n",
    "Note that if you wish to run this notebook, it is highly recommended that you do so with a GPU. \n",
    "\n",
Raymond Yuan's avatar
Raymond Yuan committed
54
55
56
    "**Time Estimated**: 60 min\n",
    "\n",
    "By: Raymond Yuan, Software Engineering Intern"
Raymond Yuan's avatar
Raymond Yuan committed
57
58
59
60
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
61
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "ODNLPGHKKgr-"
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "import glob\n",
Raymond Yuan's avatar
Raymond Yuan committed
78
    "import zipfile\n",
Raymond Yuan's avatar
Raymond Yuan committed
79
80
81
82
83
84
85
86
87
    "from sklearn.model_selection import train_test_split\n",
    "import matplotlib.image as mpimg\n",
    "import pandas as pd\n",
    "from PIL import Image\n",
    "import functools"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
88
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "YQ9VRReUQxXi"
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import tensorflow.contrib as tfcontrib\n",
    "from tensorflow.python.keras import layers\n",
    "from tensorflow.python.keras import losses\n",
    "from tensorflow.python.keras import models\n",
    "from tensorflow.python.keras import backend as K  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "RW9gk331S0KA"
   },
   "source": [
Raymond Yuan's avatar
Raymond Yuan committed
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    "# Get all the files \n",
    "Since this tutorial will be using a dataset from Kaggle, it requires [creating an API Token](https://github.com/Kaggle/kaggle-api) for your Kaggle acccount, and uploading it. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# Upload the API token.\n",
    "def get_kaggle_credentials():\n",
    "  token_dir = os.path.join(os.path.expanduser(\"~\"),\".kaggle\")\n",
    "  token_file = os.path.join(token_dir, \"kaggle.json\")\n",
    "  if not os.path.isdir(token_dir):\n",
    "    os.mkdir(token_dir)\n",
    "  try:\n",
    "    with open(token_file,'r') as f:\n",
    "      pass\n",
    "  except IOError as no_file:\n",
    "    try:\n",
    "      from google.colab import files\n",
    "    except ImportError:\n",
    "      raise no_file\n",
    "    \n",
    "    uploaded = files.upload()\n",
    "    with open(token_file, \"w\") as f:\n",
    "      f.write(uploaded[\"kaggle.json\"])\n",
    "    os.chmod(token_file, 600)\n",
    "\n",
    "get_kaggle_credentials()\n",
    "# Note: Only import kaggle after adding the credentials.\n",
    "import kaggle"
Raymond Yuan's avatar
Raymond Yuan committed
151
152
   ]
  },
Raymond Yuan's avatar
Raymond Yuan committed
153
154
155
156
157
158
159
160
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### We'll download the data from Kaggle\n",
    "Caution, large download ahead - downloading all files will require 14GB of diskspace. "
   ]
  },
Raymond Yuan's avatar
Raymond Yuan committed
161
162
163
164
165
166
167
168
169
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "competition_name = 'carvana-image-masking-challenge'"
   ]
  },
Raymond Yuan's avatar
Raymond Yuan committed
170
171
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Download data from Kaggle and create a DataFrame.\n",
    "def load_data_from_zip(competition, file):\n",
    "  with zipfile.ZipFile(os.path.join(competition, file), \"r\") as zip_ref:\n",
    "    unzipped_file = zip_ref.namelist()[0]\n",
    "    zip_ref.extractall(competition)\n",
    "\n",
    "def get_data(competition):\n",
    "    kaggle.api.competition_download_files(competition, competition)\n",
    "    load_data_from_zip(competition, 'train.zip')\n",
    "    load_data_from_zip(competition, 'train_masks.zip')\n",
    "    load_data_from_zip(competition, 'train_masks.csv.zip')\n",
    "    \n",
    "get_data(competition_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
194
195
196
197
198
199
200
201
202
203
204
205
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "wT1kb3q0ghhi"
   },
   "outputs": [],
   "source": [
Raymond Yuan's avatar
Raymond Yuan committed
206
207
    "img_dir = os.path.join(competition_name, \"train\")\n",
    "label_dir = os.path.join(competition_name, \"train_masks\")"
Raymond Yuan's avatar
Raymond Yuan committed
208
209
210
211
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
212
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
213
214
215
216
217
218
219
220
221
222
223
224
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "9ej-e6cqmRgd"
   },
   "outputs": [],
   "source": [
Raymond Yuan's avatar
Raymond Yuan committed
225
    "df_train = pd.read_csv(os.path.join(competition_name, 'train_masks.csv'))\n",
Raymond Yuan's avatar
Raymond Yuan committed
226
227
228
229
230
    "ids_train = df_train['img'].map(lambda s: s.split('.')[0])"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
231
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "33i4xFXweztH"
   },
   "outputs": [],
   "source": [
    "x_train_filenames = []\n",
    "y_train_filenames = []\n",
    "for img_id in ids_train:\n",
    "  x_train_filenames.append(os.path.join(img_dir, \"{}.jpg\".format(img_id)))\n",
    "  y_train_filenames.append(os.path.join(label_dir, \"{}_mask.gif\".format(img_id)))"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
253
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "DtutNudKbf70"
   },
   "outputs": [],
   "source": [
    "x_train_filenames, x_val_filenames, y_train_filenames, y_val_filenames = \\\n",
    "                    train_test_split(x_train_filenames, y_train_filenames, test_size=0.2, random_state=42)"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
272
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 53
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 22,
     "status": "ok",
     "timestamp": 1532637435791,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "zDycQekHaMqq",
    "outputId": "67741e71-5a68-4564-9c62-8a7490b440c3"
   },
Raymond Yuan's avatar
Raymond Yuan committed
296
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
   "source": [
    "num_train_examples = len(x_train_filenames)\n",
    "num_val_examples = len(x_val_filenames)\n",
    "\n",
    "print(\"Number of training examples: {}\".format(num_train_examples))\n",
    "print(\"Number of validation examples: {}\".format(num_val_examples))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Nhda5fkPS3JD"
   },
   "source": [
    "### Here's what the paths look like "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
317
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 197
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 28,
     "status": "ok",
     "timestamp": 1532637436466,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "Di1N83ArilzR",
    "outputId": "01e90e68-e9b4-4169-a18a-0bc98ab63bf1"
   },
Raymond Yuan's avatar
Raymond Yuan committed
341
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
342
343
344
345
346
347
   "source": [
    "x_train_filenames[:10]"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
348
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 197
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 21,
     "status": "ok",
     "timestamp": 1532637436753,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "Gc-BDv1Zio1z",
    "outputId": "d5443981-33de-4966-974d-58188c4e4f07"
   },
Raymond Yuan's avatar
Raymond Yuan committed
372
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
   "source": [
    "y_train_filenames[:10]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "mhvDoZkbcUa1"
   },
   "source": [
    "# Visualize\n",
    "Let's take a look at some of the examples of different images in our dataset. "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
390
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 971
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 1862,
     "status": "ok",
     "timestamp": 1532643134917,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "qUA6SDLhozjj",
    "outputId": "0f2dd704-2a30-429f-e68c-2b5c0f2ee31e"
   },
Raymond Yuan's avatar
Raymond Yuan committed
414
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
   "source": [
    "display_num = 5\n",
    "\n",
    "r_choices = np.random.choice(num_train_examples, display_num)\n",
    "\n",
    "plt.figure(figsize=(10, 15))\n",
    "for i in range(0, display_num * 2, 2):\n",
    "  img_num = r_choices[i // 2]\n",
    "  x_pathname = x_train_filenames[img_num]\n",
    "  y_pathname = y_train_filenames[img_num]\n",
    "  \n",
    "  plt.subplot(display_num, 2, i + 1)\n",
    "  plt.imshow(mpimg.imread(x_pathname))\n",
    "  plt.title(\"Original Image\")\n",
    "  \n",
    "  example_labels = Image.open(y_pathname)\n",
    "  label_vals = np.unique(example_labels)\n",
    "  \n",
    "  plt.subplot(display_num, 2, i + 2)\n",
    "  plt.imshow(example_labels)\n",
    "  plt.title(\"Masked Image\")  \n",
    "  \n",
    "plt.suptitle(\"Examples of Images and their Masks\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "d4CPgvPiToB_"
   },
   "source": [
    "# Set up "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "HfeMRgyoa2n6"
   },
   "source": [
    "Let’s begin by setting up some parameters. We’ll standardize and resize all the shapes of the images. We’ll also set up some training parameters: "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
463
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "oeDoiSFlothe"
   },
   "outputs": [],
   "source": [
    "img_shape = (256, 256, 3)\n",
    "batch_size = 3\n",
    "epochs = 5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8_d5ATP21npW"
   },
   "source": [
    "Using these exact same parameters may be too computationally intensive for your hardware, so tweak the parameters accordingly. Also, it is important to note that due to the architecture of our UNet version, the size of the image must be evenly divisible by a factor of 32, as we down sample the spatial resolution by a factor of 2 with each `MaxPooling2Dlayer`.\n",
    "\n",
    "\n",
    "If your machine can support it, you will achieve better performance using a higher resolution input image (e.g. 512 by 512) as this will allow more precise localization and less loss of information during encoding. In addition, you can also make the model deeper.\n",
    "\n",
    "\n",
    "Alternatively, if your machine cannot support it, lower the image resolution and/or batch size. Note that lowering the image resolution will decrease performance and lowering batch size will increase training time.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "_HONB9JbXxDM"
   },
   "source": [
    "# Build our input pipeline with `tf.data`\n",
    "Since we begin with filenames, we will need to build a robust and scalable data pipeline that will play nicely with our model. If you are unfamiliar with **tf.data** you should check out my other tutorial introducing the concept! \n",
    "\n",
    "### Our input pipeline will consist of the following steps:\n",
    "1. Read the bytes of the file in from the filename - for both the image and the label. Recall that our labels are actually images with each pixel annotated as car or background (1, 0). \n",
    "2. Decode the bytes into an image format\n",
    "3. Apply image transformations: (optional, according to input parameters)\n",
    "  * `resize` - Resize our images to a standard size (as determined by eda or computation/memory restrictions)\n",
    "    * The reason why this is optional is that U-Net is a fully convolutional network (e.g. with no fully connected units) and is thus not dependent on the input size. However, if you choose to not resize the images, you must use a batch size of 1, since you cannot batch variable image size together\n",
    "    * Alternatively, you could also bucket your images together and resize them per mini-batch to avoid resizing images as much, as resizing may affect your performance through interpolation, etc.\n",
    "  * `hue_delta` - Adjusts the hue of an RGB image by a random factor. This is only applied to the actual image (not our label image). The `hue_delta` must be in the interval `[0, 0.5]` \n",
    "  * `horizontal_flip` - flip the image horizontally along the central axis with a 0.5 probability. This transformation must be applied to both the label and the actual image. \n",
    "  * `width_shift_range` and `height_shift_range` are ranges (as a fraction of total width or height) within which to randomly translate the image either horizontally or vertically. This transformation must be applied to both the label and the actual image. \n",
    "  * `rescale` - rescale the image by a certain factor, e.g. 1/ 255.\n",
    "4. Shuffle the data, repeat the data (so we can iterate over it multiple times across epochs), batch the data, then prefetch a batch (for efficiency).\n",
    "\n",
    "It is important to note that these transformations that occur in your data pipeline must be symbolic transformations. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "EtRA8vILbx2_"
   },
   "source": [
    "#### Why do we do these image transformations?\n",
    "This is known as **data augmentation**. Data augmentation \"increases\" the amount of training data by augmenting them via a number of random transformations. During training time, our model would never see twice the exact same picture. This helps prevent [overfitting](https://developers.google.com/machine-learning/glossary/#overfitting) and helps the model generalize better to unseen data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "3aGi28u8Cq9M"
   },
   "source": [
    "## Processing each pathname"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
547
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "Fb_psznAggwr"
   },
   "outputs": [],
   "source": [
    "def _process_pathnames(fname, label_path):\n",
    "  # We map this function onto each pathname pair  \n",
    "  img_str = tf.read_file(fname)\n",
Raymond Yuan's avatar
Raymond Yuan committed
563
    "  img = tf.image.decode_jpeg(img_str, channels=3)\n",
Raymond Yuan's avatar
Raymond Yuan committed
564
565
566
    "\n",
    "  label_img_str = tf.read_file(label_path)\n",
    "  # These are gif images so they return as (num_frames, h, w, c)\n",
Raymond Yuan's avatar
Raymond Yuan committed
567
    "  label_img = tf.image.decode_gif(label_img_str)[0]\n",
Raymond Yuan's avatar
Raymond Yuan committed
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    "  # The label image should only have values of 1 or 0, indicating pixel wise\n",
    "  # object (car) or not (background). We take the first channel only. \n",
    "  label_img = label_img[:, :, 0]\n",
    "  label_img = tf.expand_dims(label_img, axis=-1)\n",
    "  return img, label_img"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Y4UE28JiCuOk"
   },
   "source": [
    "## Shifting the image"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
587
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "xdY046OqtGVH"
   },
   "outputs": [],
   "source": [
    "def shift_img(output_img, label_img, width_shift_range, height_shift_range):\n",
    "  \"\"\"This fn will perform the horizontal or vertical shift\"\"\"\n",
    "  if width_shift_range or height_shift_range:\n",
    "      if width_shift_range:\n",
    "        width_shift_range = tf.random_uniform([], \n",
    "                                              -width_shift_range * img_shape[1],\n",
    "                                              width_shift_range * img_shape[1])\n",
    "      if height_shift_range:\n",
    "        height_shift_range = tf.random_uniform([],\n",
    "                                               -height_shift_range * img_shape[0],\n",
    "                                               height_shift_range * img_shape[0])\n",
    "      # Translate both \n",
    "      output_img = tfcontrib.image.translate(output_img,\n",
    "                                             [width_shift_range, height_shift_range])\n",
    "      label_img = tfcontrib.image.translate(label_img,\n",
    "                                             [width_shift_range, height_shift_range])\n",
    "  return output_img, label_img"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "qY253aZfCwd2"
   },
   "source": [
    "## Flipping the image randomly "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
631
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "OogLSplstur9"
   },
   "outputs": [],
   "source": [
    "def flip_img(horizontal_flip, tr_img, label_img):\n",
    "  if horizontal_flip:\n",
    "    flip_prob = tf.random_uniform([], 0.0, 1.0)\n",
    "    tr_img, label_img = tf.cond(tf.less(flip_prob, 0.5),\n",
    "                                lambda: (tf.image.flip_left_right(tr_img), tf.image.flip_left_right(label_img)),\n",
    "                                lambda: (tr_img, label_img))\n",
    "  return tr_img, label_img"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "_YIJLIr5Cyyr"
   },
   "source": [
    "## Assembling our transformations into our augment function"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
665
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "18WA0Sl3olyn"
   },
   "outputs": [],
   "source": [
    "def _augment(img,\n",
    "             label_img,\n",
    "             resize=None,  # Resize the image to some size e.g. [256, 256]\n",
    "             scale=1,  # Scale image e.g. 1 / 255.\n",
    "             hue_delta=0,  # Adjust the hue of an RGB image by random factor\n",
    "             horizontal_flip=False,  # Random left right flip,\n",
    "             width_shift_range=0,  # Randomly translate the image horizontally\n",
    "             height_shift_range=0):  # Randomly translate the image vertically \n",
    "  if resize is not None:\n",
    "    # Resize both images\n",
    "    label_img = tf.image.resize_images(label_img, resize)\n",
    "    img = tf.image.resize_images(img, resize)\n",
    "  \n",
    "  if hue_delta:\n",
    "    img = tf.image.random_hue(img, hue_delta)\n",
    "  \n",
    "  img, label_img = flip_img(horizontal_flip, img, label_img)\n",
    "  img, label_img = shift_img(img, label_img, width_shift_range, height_shift_range)\n",
    "  label_img = tf.to_float(label_img) * scale\n",
    "  img = tf.to_float(img) * scale \n",
    "  return img, label_img"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
703
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "tkNqQaR2HQbd"
   },
   "outputs": [],
   "source": [
    "def get_baseline_dataset(filenames, \n",
    "                         labels,\n",
    "                         preproc_fn=functools.partial(_augment),\n",
    "                         threads=5, \n",
    "                         batch_size=batch_size,\n",
    "                         shuffle=True):           \n",
    "  num_x = len(filenames)\n",
    "  # Create a dataset from the filenames and labels\n",
    "  dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))\n",
    "  # Map our preprocessing function to every element in our dataset, taking\n",
    "  # advantage of multithreading\n",
    "  dataset = dataset.map(_process_pathnames, num_parallel_calls=threads)\n",
    "  if preproc_fn.keywords is not None and 'resize' not in preproc_fn.keywords:\n",
    "    assert batch_size == 1, \"Batching images must be of the same size\"\n",
    "\n",
    "  dataset = dataset.map(preproc_fn, num_parallel_calls=threads)\n",
    "  \n",
    "  if shuffle:\n",
    "    dataset = dataset.shuffle(num_x)\n",
    "  \n",
    "  \n",
    "  # It's necessary to repeat our data for all epochs \n",
    "  dataset = dataset.repeat().batch(batch_size)\n",
    "  return dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "zwtgius5CRKc"
   },
   "source": [
    "## Set up train and validation datasets\n",
    "Note that we apply image augmentation to our training dataset but not our validation dataset. "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
755
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "iu5WmYmOwKrV"
   },
   "outputs": [],
   "source": [
    "tr_cfg = {\n",
    "    'resize': [img_shape[0], img_shape[1]],\n",
    "    'scale': 1 / 255.,\n",
    "    'hue_delta': 0.1,\n",
    "    'horizontal_flip': True,\n",
    "    'width_shift_range': 0.1,\n",
    "    'height_shift_range': 0.1\n",
    "}\n",
    "tr_preprocessing_fn = functools.partial(_augment, **tr_cfg)"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
781
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "RtzLkDFMpF0T"
   },
   "outputs": [],
   "source": [
    "val_cfg = {\n",
    "    'resize': [img_shape[0], img_shape[1]],\n",
    "    'scale': 1 / 255.,\n",
    "}\n",
    "val_preprocessing_fn = functools.partial(_augment, **val_cfg)"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
803
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "5cNpECdkaafo"
   },
   "outputs": [],
   "source": [
    "train_ds = get_baseline_dataset(x_train_filenames,\n",
    "                                y_train_filenames,\n",
    "                                preproc_fn=tr_preprocessing_fn,\n",
    "                                batch_size=batch_size)\n",
    "val_ds = get_baseline_dataset(x_val_filenames,\n",
    "                              y_val_filenames, \n",
    "                              preproc_fn=val_preprocessing_fn,\n",
    "                              batch_size=batch_size)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Yasuvr5IbFlM"
   },
   "source": [
    "## Let's see if our image augmentor data pipeline is producing expected results"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
838
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 306
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 885,
     "status": "ok",
     "timestamp": 1532637487047,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "hjoUqbPdHQej",
    "outputId": "91e45062-1cc8-4be9-92ae-46461303fbb3"
   },
Raymond Yuan's avatar
Raymond Yuan committed
862
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
   "source": [
    "temp_ds = get_baseline_dataset(x_train_filenames, \n",
    "                               y_train_filenames,\n",
    "                               preproc_fn=tr_preprocessing_fn,\n",
    "                               batch_size=1,\n",
    "                               shuffle=False)\n",
    "# Let's examine some of these augmented images\n",
    "data_aug_iter = temp_ds.make_one_shot_iterator()\n",
    "next_element = data_aug_iter.get_next()\n",
    "with tf.Session() as sess: \n",
    "  batch_of_imgs, label = sess.run(next_element)\n",
    "\n",
    "  # Running next element in our graph will produce a batch of images\n",
    "  plt.figure(figsize=(10, 10))\n",
    "  img = batch_of_imgs[0]\n",
    "\n",
    "  plt.subplot(1, 2, 1)\n",
    "  plt.imshow(img)\n",
    "\n",
    "  plt.subplot(1, 2, 2)\n",
    "  plt.imshow(label[0, :, :, 0])\n",
    "  plt.show()"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
889
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 35
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 22,
     "status": "ok",
     "timestamp": 1532637489201,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "xszBW-gL1Cyq",
    "outputId": "a39bed1b-8b43-4928-d685-79810bccf605"
   },
Raymond Yuan's avatar
Raymond Yuan committed
913
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
914
915
916
917
918
919
   "source": [
    "label.shape"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
920
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 35
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 24,
     "status": "ok",
     "timestamp": 1532637489813,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "x1LfMEWjkluS",
    "outputId": "ac75e80a-00a1-4d88-84ed-549c41bd764b"
   },
Raymond Yuan's avatar
Raymond Yuan committed
944
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
   "source": [
    "train_ds"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "fvtxCncKsoRd"
   },
   "source": [
    "# Build the model\n",
    "We'll build the U-Net model. U-Net is especially good with segmentation tasks because it can localize well to provide high resolution segmentation masks. In addition, it works well with small datasets and is relatively robust against overfitting as the training data is in terms of the number of patches within an image, which is much larger than the number of training images itself. Unlike the original model, we will add batch normalization to each of our blocks. \n",
    "\n",
    "The Unet is built with an encoder portion and a decoder portion. The encoder portion is composed of a linear stack of [`Conv`](https://developers.google.com/machine-learning/glossary/#convolution), `BatchNorm`, and [`Relu`](https://developers.google.com/machine-learning/glossary/#ReLU) operations followed by a [`MaxPool`](https://developers.google.com/machine-learning/glossary/#pooling). Each `MaxPool` will reduce the spatial resolution of our feature map by a factor of 2. We keep track of the outputs of each block as we feed these high resolution feature maps with the decoder portion. The Decoder portion is comprised of UpSampling2D, Conv, BatchNorm, and Relus. Note that we concatenate the feature map of the same size on the decoder side. Finally, we add a final Conv operation that performs a convolution along the channels for each individual pixel (kernel size of (1, 1)) that outputs our final segmentation mask in grayscale. \n",
    "## The Keras Functional API\n",
    "The Keras functional API is used when you have multi-input/output models, shared layers, etc. It's a powerful API that allows you to manipulate tensors and build complex graphs with intertwined datastreams easily. In addition it makes **layers** and **models** both callable on tensors. \n",
    "  * To see more examples check out the [get started guide](https://keras.io/getting-started/functional-api-guide/). \n",
    "  \n",
    "  \n",
    "  We'll build these helper functions that will allow us to ensemble our model block operations easily and simply. "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
970
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "zfew1i1F6bK-"
   },
   "outputs": [],
   "source": [
    "def conv_block(input_tensor, num_filters):\n",
    "  encoder = layers.Conv2D(num_filters, (3, 3), padding='same')(input_tensor)\n",
    "  encoder = layers.BatchNormalization()(encoder)\n",
    "  encoder = layers.Activation('relu')(encoder)\n",
    "  encoder = layers.Conv2D(num_filters, (3, 3), padding='same')(encoder)\n",
    "  encoder = layers.BatchNormalization()(encoder)\n",
    "  encoder = layers.Activation('relu')(encoder)\n",
    "  return encoder\n",
    "\n",
    "def encoder_block(input_tensor, num_filters):\n",
    "  encoder = conv_block(input_tensor, num_filters)\n",
    "  encoder_pool = layers.MaxPooling2D((2, 2), strides=(2, 2))(encoder)\n",
    "  \n",
    "  return encoder_pool, encoder\n",
    "\n",
    "def decoder_block(input_tensor, concat_tensor, num_filters):\n",
    "  decoder = layers.Conv2DTranspose(num_filters, (2, 2), strides=(2, 2), padding='same')(input_tensor)\n",
    "  decoder = layers.concatenate([concat_tensor, decoder], axis=-1)\n",
    "  decoder = layers.BatchNormalization()(decoder)\n",
    "  decoder = layers.Activation('relu')(decoder)\n",
    "  decoder = layers.Conv2D(num_filters, (3, 3), padding='same')(decoder)\n",
    "  decoder = layers.BatchNormalization()(decoder)\n",
    "  decoder = layers.Activation('relu')(decoder)\n",
    "  decoder = layers.Conv2D(num_filters, (3, 3), padding='same')(decoder)\n",
    "  decoder = layers.BatchNormalization()(decoder)\n",
    "  decoder = layers.Activation('relu')(decoder)\n",
    "  return decoder"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1014
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "xRLp21S_hpTn"
   },
   "outputs": [],
   "source": [
    "inputs = layers.Input(shape=img_shape)\n",
    "# 256\n",
    "\n",
    "encoder0_pool, encoder0 = encoder_block(inputs, 32)\n",
    "# 128\n",
    "\n",
    "encoder1_pool, encoder1 = encoder_block(encoder0_pool, 64)\n",
    "# 64\n",
    "\n",
    "encoder2_pool, encoder2 = encoder_block(encoder1_pool, 128)\n",
    "# 32\n",
    "\n",
    "encoder3_pool, encoder3 = encoder_block(encoder2_pool, 256)\n",
    "# 16\n",
    "\n",
    "encoder4_pool, encoder4 = encoder_block(encoder3_pool, 512)\n",
    "# 8\n",
    "\n",
    "center = conv_block(encoder4_pool, 1024)\n",
    "# center\n",
    "\n",
    "decoder4 = decoder_block(center, encoder4, 512)\n",
    "# 16\n",
    "\n",
    "decoder3 = decoder_block(decoder4, encoder3, 256)\n",
    "# 32\n",
    "\n",
    "decoder2 = decoder_block(decoder3, encoder2, 128)\n",
    "# 64\n",
    "\n",
    "decoder1 = decoder_block(decoder2, encoder1, 64)\n",
    "# 128\n",
    "\n",
    "decoder0 = decoder_block(decoder1, encoder0, 32)\n",
    "# 256\n",
    "\n",
    "outputs = layers.Conv2D(1, (1, 1), activation='sigmoid')(decoder0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "luDqDqu8c1AX"
   },
   "source": [
    "## Define your model\n",
    "Using functional API, you must define your model by specifying the inputs and outputs associated with the model. "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1079
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "76QkTzXVczgc"
   },
   "outputs": [],
   "source": [
    "model = models.Model(inputs=[inputs], outputs=[outputs])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "p0tNnmyOdtyr"
   },
   "source": [
    "# Defining custom metrics and loss functions\n",
Raymond Yuan's avatar
Raymond Yuan committed
1103
    "Defining loss and metric functions are simple with Keras. Simply define a function that takes both the True labels for a given example and the Predicted labels for the same given example. "
Raymond Yuan's avatar
Raymond Yuan committed
1104
1105
1106
1107
1108
1109
1110
1111
1112
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "sfuBVut0fogM"
   },
   "source": [
Raymond Yuan's avatar
Raymond Yuan committed
1113
    "Dice loss is a metric that measures overlap. More info on optimizing for Dice coefficient (our dice loss) can be found in the [paper](http://campar.in.tum.de/pub/milletari2016Vnet/milletari2016Vnet.pdf), where it was introduced. \n",
Raymond Yuan's avatar
Raymond Yuan committed
1114
1115
1116
1117
1118
1119
    "\n",
    "We use dice loss here because it performs better at class imbalanced problems by design. In addition, maximizing the dice coefficient and IoU metrics are the actual objectives and goals of our segmentation task. Using cross entropy is more of a proxy which is easier to maximize. Instead, we maximize our objective directly. "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1120
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "t_8_hbHECUAW"
   },
   "outputs": [],
   "source": [
    "def dice_coeff(y_true, y_pred):\n",
    "    smooth = 1.\n",
    "    # Flatten\n",
    "    y_true_f = tf.reshape(y_true, [-1])\n",
    "    y_pred_f = tf.reshape(y_pred, [-1])\n",
    "    intersection = tf.reduce_sum(y_true_f * y_pred_f)\n",
    "    score = (2. * intersection + smooth) / (tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) + smooth)\n",
    "    return score"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1145
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "4DgINhlpNaxP"
   },
   "outputs": [],
   "source": [
    "def dice_loss(y_true, y_pred):\n",
    "    loss = 1 - dice_coeff(y_true, y_pred)\n",
    "    return loss"
   ]
  },
Raymond Yuan's avatar
Raymond Yuan committed
1163
1164
1165
1166
1167
1168
1169
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, we'll use a specialized loss function that combines binary cross entropy and our dice loss. This is based on [individuals who competed within this competition obtaining better results empirically](https://www.kaggle.com/c/carvana-image-masking-challenge/discussion/40199). "
   ]
  },
Raymond Yuan's avatar
Raymond Yuan committed
1170
1171
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1172
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "udrfi9JGB-bL"
   },
   "outputs": [],
   "source": [
    "def bce_dice_loss(y_true, y_pred):\n",
    "    loss = losses.binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)\n",
    "    return loss"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "LifmpjXNc9Gz"
   },
   "source": [
    "## Compile your model\n",
    "We use our custom loss function to minimize. In addition, we specify what metrics we want to keep track of as we train. Note that metrics are not actually used during the training process to tune the parameters, but are instead used to measure performance of the training process. "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1203
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 3581
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 2288,
     "status": "ok",
     "timestamp": 1532637658541,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "gflcWk2Cc8Bi",
    "outputId": "32fe74fc-f9fb-48ea-8455-8ea2764dae7c"
   },
Raymond Yuan's avatar
Raymond Yuan committed
1227
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
1228
   "source": [
Raymond Yuan's avatar
Raymond Yuan committed
1229
    "model.compile(optimizer='adam', loss=bce_dice_loss, metrics=[dice_loss])\n",
Raymond Yuan's avatar
Raymond Yuan committed
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
    "\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8WG_8iZ_dMbK"
   },
   "source": [
    "## Train your model\n",
    "Training your model with `tf.data` involves simply providing the model's `fit` function with your training/validation dataset, the number of steps, and epochs.  \n",
    "\n",
    "We also include a Model callback, [`ModelCheckpoint`](https://keras.io/callbacks/#modelcheckpoint) that will save the model to disk after each epoch. We configure it such that it only saves our highest performing model. Note that saving the model capture more than just the weights of the model: by default, it saves the model architecture, weights, as well as information about the training process such as the state of the optimizer, etc."
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1249
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "1nHnj6199elZ"
   },
   "outputs": [],
   "source": [
    "save_model_path = '/tmp/weights.hdf5'\n",
Raymond Yuan's avatar
Raymond Yuan committed
1263
    "cp = tf.keras.callbacks.ModelCheckpoint(filepath=save_model_path, monitor='val_dice_loss', mode='max', save_best_only=True)"
Raymond Yuan's avatar
Raymond Yuan committed
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "vJP_EvuTb4hH"
   },
   "source": [
    "Don't forget to specify our model callback in the `fit` function call. "
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1278
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 217
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 4795763,
     "status": "ok",
     "timestamp": 1532642466206,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "UMZcOrq5aaj1",
    "outputId": "4627093e-b6bf-4fa3-fde4-6e4acd5e84a5"
   },
Raymond Yuan's avatar
Raymond Yuan committed
1302
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
   "source": [
    "history = model.fit(train_ds, \n",
    "                   steps_per_epoch=int(np.ceil(num_train_examples / float(batch_size))),\n",
    "                   epochs=epochs,\n",
    "                   validation_data=val_ds,\n",
    "                   validation_steps=int(np.ceil(num_val_examples / float(batch_size))),\n",
    "                   callbacks=[cp])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "gCAUsoxfTTrh"
   },
   "source": [
    "# Visualize training process"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1324
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 529
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 688,
     "status": "ok",
     "timestamp": 1532642819636,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "AvntxymYn8rM",
    "outputId": "5add7737-4eca-4713-bb9d-e64001801778"
   },
Raymond Yuan's avatar
Raymond Yuan committed
1348
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
1349
   "source": [
Raymond Yuan's avatar
Raymond Yuan committed
1350
1351
    "dice = = history.history['dice_loss']\n",
    "val_dice = history.history['val_dice_loss']\n",
Raymond Yuan's avatar
Raymond Yuan committed
1352
1353
1354
1355
1356
1357
1358
    "\n",
    "loss = history.history['loss']\n",
    "val_loss = history.history['val_loss']\n",
    "\n",
    "epochs_range = range(epochs)\n",
    "\n",
    "plt.figure(figsize=(16, 8))\n",
Raymond Yuan's avatar
Raymond Yuan committed
1359
1360
1361
1362
1363
    "plt.subplot(1, 2, 1)\n",
    "plt.plot(epochs_range, dice, label='Training Dice Loss')\n",
    "plt.plot(epochs_range, val_dice, label='Validation Dice Loss')\n",
    "plt.legend(loc='upper right')\n",
    "plt.title('Training and Validation Dice Loss')\n",
Raymond Yuan's avatar
Raymond Yuan committed
1364
    "\n",
Raymond Yuan's avatar
Raymond Yuan committed
1365
    "plt.subplot(1, 2, 2)\n",
Raymond Yuan's avatar
Raymond Yuan committed
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
    "plt.plot(epochs_range, loss, label='Training Loss')\n",
    "plt.plot(epochs_range, val_loss, label='Validation Loss')\n",
    "plt.legend(loc='upper right')\n",
    "plt.title('Training and Validation Loss')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "dWPhb87GdhkG"
   },
   "source": [
    "Even with only 5 epochs, we see strong performance."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "MGFKf8yCTYbw"
   },
   "source": [
    "# Visualize actual performance \n",
    "We'll visualize our performance on the validation set.\n",
    "\n",
    "Note that in an actual setting (competition, deployment, etc.) we'd evaluate on the test set with the full image resolution. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "oIddsUcM_KeI"
   },
   "source": [
    "To load our model we have two options:\n",
    "1. Since our model architecture is already in memory, we can simply call `load_weights(save_model_path)`\n",
    "2. If you wanted to load the model from scratch (in a different setting without already having the model architecture in memory) we simply call \n",
    "\n",
    "```model = models.load_model(save_model_path, custom_objects={'bce_dice_loss': bce_dice_loss, 'mean_iou': mean_iou,'dice_coeff': dice_coeff})```, specificing the necessary custom objects, loss and metrics, that we used to train our model. \n",
    "\n",
    "If you want to see more examples, check our the [keras guide](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model)!"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1415
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "id": "5Ph7acmrCXm6"
   },
   "outputs": [],
   "source": [
    "# Alternatively, load the weights directly: model.load_weights(save_model_path)\n",
    "model = models.load_model(save_model_path, custom_objects={'bce_dice_loss': bce_dice_loss,\n",
    "                                                           'dice_coeff': dice_coeff})"
   ]
  },
  {
   "cell_type": "code",
Raymond Yuan's avatar
Raymond Yuan committed
1435
   "execution_count": null,
Raymond Yuan's avatar
Raymond Yuan committed
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
   "metadata": {
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "height": 1199
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 8709,
     "status": "ok",
     "timestamp": 1532643022136,
     "user": {
      "displayName": "Raymond Yuan",
      "photoUrl": "https://lh3.googleusercontent.com/a/default-user=s128",
      "userId": "102421170646657749851"
     },
     "user_tz": 420
    },
    "id": "0GnwZ7CPaamI",
    "outputId": "05b4db7c-d136-46db-c04b-ea9fa374cb66"
   },
Raymond Yuan's avatar
Raymond Yuan committed
1459
   "outputs": [],
Raymond Yuan's avatar
Raymond Yuan committed
1460
1461
1462
1463
1464
1465
   "source": [
    "# Let's visualize some of the outputs \n",
    "data_aug_iter = val_ds.make_one_shot_iterator()\n",
    "next_element = data_aug_iter.get_next()\n",
    "\n",
    "# Running next element in our graph will produce a batch of images\n",
Raymond Yuan's avatar
Raymond Yuan committed
1466
    "plt.figure(figsize=(10, 20))\n",
Raymond Yuan's avatar
Raymond Yuan committed
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
    "for i in range(5):\n",
    "  batch_of_imgs, label = tf.keras.backend.get_session().run(next_element)\n",
    "  img = batch_of_imgs[0]\n",
    "  predicted_label = model.predict(batch_of_imgs)[0]\n",
    "\n",
    "  plt.subplot(5, 3, 3 * i + 1)\n",
    "  plt.imshow(img)\n",
    "  plt.title(\"Input image\")\n",
    "  \n",
    "  plt.subplot(5, 3, 3 * i + 2)\n",
    "  plt.imshow(label[0, :, :, 0])\n",
    "  plt.title(\"Actual Mask\")\n",
    "  plt.subplot(5, 3, 3 * i + 3)\n",
    "  plt.imshow(predicted_label[:, :, 0])\n",
    "  plt.title(\"Predicted Mask\")\n",
Raymond Yuan's avatar
Raymond Yuan committed
1482
1483
    "plt.save\n",
    "plt.suptitle(\"Examples of Input Image, Label, and Prediction\")\n",
Raymond Yuan's avatar
Raymond Yuan committed
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "iPV7RMA9TjPC"
   },
   "source": [
    "# Key Takeaways\n",
    "In this tutorial we learned how to train a network to automatically detect and create cutouts of cars from images! \n",
    "\n",
    "## Specific concepts that will we covered:\n",
    "In the process, we hopefully built some practical experience and developed intuition around the following concepts\n",
    "* [**Functional API**](https://keras.io/getting-started/functional-api-guide/) - we implemented UNet with the Functional API. Functional API gives a lego-like API that allows us to build pretty much any network.  \n",
    "* **Custom Losses and Metrics** - We implemented custom metrics that allow us to see exactly what we need during training time. In addition, we wrote a custom loss function that is specifically suited to our task.  \n",
    "* **Save and load our model** - We saved our best model that we encountered according to our specified metric. When we wanted to perform inference with out best model, we loaded it from disk. Note that saving the model capture more than just the weights of the model: by default, it saves the model architecture, weights, as well as information about the training process such as the state of the optimizer, etc. "
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "default_view": {},
   "last_runtime": {
    "build_target": "",
    "kind": "local"
   },
   "name": "5. Image Segmentation",
   "provenance": [
    {
     "file_id": "1bYutJEjOZ6R0bhNgp7qdM5nMoIW4YdLY",
     "timestamp": 1528473339030
    }
   ],
   "version": "0.3.2",
   "views": {}
  },
  "kernelspec": {
Raymond Yuan's avatar
Raymond Yuan committed
1524
   "display_name": "Python [conda env:anaconda3]",
Raymond Yuan's avatar
Raymond Yuan committed
1525
   "language": "python",
Raymond Yuan's avatar
Raymond Yuan committed
1526
   "name": "conda-env-anaconda3-py"
Raymond Yuan's avatar
Raymond Yuan committed
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}