" <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a> \n",
},
"</td><td>\n",
"cell_type": "markdown",
"<a target=\"_blank\" href=\"https://github.com/tensorflow/models/blob/segmentation_blogpost/samples/outreach/blogs/segmentation_blogpost/image_segmentation.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a></td></table>"
"source": [
]
"# Image Segmentation with `tf.keras`"
},
]
{
},
"cell_type": "markdown",
{
"metadata": {
"metadata": {
"colab_type": "text",
"id": "7Plun_k1dAML",
"id": "cl79rk4KKol8"
"colab_type": "text"
},
},
"source": [
"cell_type": "markdown",
"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",
"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",
" <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a> \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",
"</td><td>\n",
"\n",
"<a target=\"_blank\" href=\"https://github.com/tensorflow/models/blob/segmentation_blogpost/samples/outreach/blogs/segmentation_blogpost/image_segmentation.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a></td></table>"
"## 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",
"metadata": {
" * Check out the original [paper](https://arxiv.org/abs/1505.04597), \n",
"id": "cl79rk4KKol8",
"U-Net: Convolutional Networks for Biomedical Image Segmentation by Olaf Ronneberger!\n",
"colab_type": "text"
"* **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",
"cell_type": "markdown",
"\n",
"source": [
"### We will follow the general workflow:\n",
"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",
"1. Visualize data/perform some exploratory data analysis\n",
"\n",
"2. Set up data pipeline and preprocessing\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",
"3. Build model\n",
"\n",
"4. Train model\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",
"5. Evaluate model\n",
"\n",
"6. Repeat\n",
"## Specific concepts that will be covered:\n",
"\n",
"In the process, we will build practical experience and develop intuition around the following concepts:\n",
"**Audience:** This post is geared towards intermediate users who are comfortable with basic machine learning 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",
"Note that if you wish to run this notebook, it is highly recommended that you do so with a GPU. \n",
" * This model has layers that require multiple input/outputs. This requires the use of the functional API\n",
"\n",
" * Check out the original [paper](https://arxiv.org/abs/1505.04597), \n",
"**Time Estimated**: 60 min\n",
"U-Net: Convolutional Networks for Biomedical Image Segmentation by Olaf Ronneberger!\n",
"\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",
"By: Raymond Yuan, Software Engineering Intern"
"* **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",
"cell_type": "code",
"2. Set up data pipeline and preprocessing\n",
"execution_count": 0,
"3. Build model\n",
"metadata": {
"4. Train model\n",
"colab": {},
"5. Evaluate model\n",
"colab_type": "code",
"6. Repeat\n",
"id": "bJcQiA3OdCY6"
"\n",
},
"**Audience:** This post is geared towards intermediate users who are comfortable with basic machine learning concepts.\n",
"outputs": [],
"Note that if you wish to run this notebook, it is highly recommended that you do so with a GPU. \n",
"from tensorflow.python.keras import backend as K "
{
]
"metadata": {
},
"id": "YQ9VRReUQxXi",
{
"colab_type": "code",
"cell_type": "markdown",
"colab": {}
"metadata": {
},
"colab_type": "text",
"cell_type": "code",
"id": "RW9gk331S0KA"
"source": [
},
"import tensorflow as tf\n",
"source": [
"import tensorflow.contrib as tfcontrib\n",
"# Get all the files \n",
"from tensorflow.python.keras import layers\n",
"Since this tutorial will be using a dataset from Kaggle, it requires [creating an API Token](https://github.com/Kaggle/kaggle-api#api-credentials) for your Kaggle acccount, and uploading it. "
"from tensorflow.python.keras import losses\n",
]
"from tensorflow.python.keras import models\n",
},
"from tensorflow.python.keras import backend as K "
{
],
"cell_type": "code",
"execution_count": 0,
"execution_count": 0,
"outputs": []
"metadata": {
},
"colab": {},
{
"colab_type": "code",
"metadata": {
"id": "sAVM1ZTmdAMR"
"id": "RW9gk331S0KA",
},
"colab_type": "text"
"outputs": [],
},
"source": [
"cell_type": "markdown",
"import os\n",
"source": [
"\n",
"# Get all the files \n",
"# Upload the API token.\n",
"Since this tutorial will be using a dataset from Kaggle, it requires [creating an API Token](https://github.com/Kaggle/kaggle-api#api-credentials) for your Kaggle acccount, and uploading it. "
"plt.suptitle(\"Examples of Images and their Masks\")\n",
" y_pathname = y_train_filenames[img_num]\n",
"plt.show()"
" \n",
]
" plt.subplot(display_num, 2, i + 1)\n",
},
" plt.imshow(mpimg.imread(x_pathname))\n",
{
" plt.title(\"Original Image\")\n",
"cell_type": "markdown",
" \n",
"metadata": {
" example_labels = Image.open(y_pathname)\n",
"colab_type": "text",
" label_vals = np.unique(example_labels)\n",
"id": "d4CPgvPiToB_"
" \n",
},
" plt.subplot(display_num, 2, i + 2)\n",
"source": [
" plt.imshow(example_labels)\n",
"# Set up "
" plt.title(\"Masked Image\") \n",
]
" \n",
},
"plt.suptitle(\"Examples of Images and their Masks\")\n",
{
"plt.show()"
"cell_type": "markdown",
],
"metadata": {
"execution_count": 0,
"colab_type": "text",
"outputs": []
"id": "HfeMRgyoa2n6"
},
},
{
"source": [
"metadata": {
"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: "
"id": "d4CPgvPiToB_",
]
"colab_type": "text"
},
},
{
"cell_type": "markdown",
"cell_type": "code",
"source": [
"execution_count": 0,
"# Set up "
"metadata": {
]
"colab": {},
},
"colab_type": "code",
{
"id": "oeDoiSFlothe"
"metadata": {
},
"id": "HfeMRgyoa2n6",
"outputs": [],
"colab_type": "text"
"source": [
},
"img_shape = (256, 256, 3)\n",
"cell_type": "markdown",
"batch_size = 3\n",
"source": [
"epochs = 5"
"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": "markdown",
"metadata": {
"metadata": {
"id": "oeDoiSFlothe",
"colab_type": "text",
"colab_type": "code",
"id": "8_d5ATP21npW"
"colab": {}
},
},
"source": [
"cell_type": "code",
"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",
"source": [
"\n",
"img_shape = (256, 256, 3)\n",
"\n",
"batch_size = 3\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",
"epochs = 5"
"\n",
],
"\n",
"execution_count": 0,
"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"
"outputs": []
]
},
},
{
{
"metadata": {
"cell_type": "markdown",
"id": "8_d5ATP21npW",
"metadata": {
"colab_type": "text"
"colab_type": "text",
},
"id": "_HONB9JbXxDM"
"cell_type": "markdown",
},
"source": [
"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",
"# Build our input pipeline with `tf.data`\n",
"\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",
"\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",
"### Our input pipeline will consist of the following steps:\n",
"\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",
"\n",
"2. Decode the bytes into an image format\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"
"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",
"metadata": {
" * `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",
"id": "_HONB9JbXxDM",
" * `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",
"colab_type": "text"
" * `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",
"cell_type": "markdown",
"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",
"source": [
"\n",
"# Build our input pipeline with `tf.data`\n",
"It is important to note that these transformations that occur in your data pipeline must be symbolic transformations. "
"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",
"cell_type": "markdown",
"2. Decode the bytes into an image format\n",
"metadata": {
"3. Apply image transformations: (optional, according to input parameters)\n",
"colab_type": "text",
" * `resize` - Resize our images to a standard size (as determined by eda or computation/memory restrictions)\n",
"id": "EtRA8vILbx2_"
" * 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",
"source": [
" * `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",
"#### Why do we do these image transformations?\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",
"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."
" * `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",
"cell_type": "markdown",
"It is important to note that these transformations that occur in your data pipeline must be symbolic transformations. "
"metadata": {
]
"colab_type": "text",
},
"id": "3aGi28u8Cq9M"
{
},
"metadata": {
"source": [
"id": "EtRA8vILbx2_",
"## Processing each pathname"
"colab_type": "text"
]
},
},
"cell_type": "markdown",
{
"source": [
"cell_type": "code",
"#### Why do we do these image transformations?\n",
"execution_count": 0,
"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."
"metadata": {
]
"colab": {},
},
"colab_type": "code",
{
"id": "Fb_psznAggwr"
"metadata": {
},
"id": "3aGi28u8Cq9M",
"outputs": [],
"colab_type": "text"
"source": [
},
"def _process_pathnames(fname, label_path):\n",
"cell_type": "markdown",
" # We map this function onto each pathname pair \n",
" # Running next element in our graph will produce a batch of images\n",
"metadata": {
" plt.figure(figsize=(10, 10))\n",
"colab_type": "text",
" img = batch_of_imgs[0]\n",
"id": "fvtxCncKsoRd"
"\n",
},
" plt.subplot(1, 2, 1)\n",
"source": [
" plt.imshow(img)\n",
"# Build the model\n",
"\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",
" plt.subplot(1, 2, 2)\n",
"\n",
" plt.imshow(label[0, :, :, 0])\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",
" plt.show()"
"## 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",
"execution_count": 0,
" * To see more examples check out the [get started guide](https://keras.io/getting-started/functional-api-guide/). \n",
"outputs": []
" \n",
},
" \n",
{
" We'll build these helper functions that will allow us to ensemble our model block operations easily and simply. "
"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",
"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 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",
"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. "
"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",
"metadata": {
"\n",
"id": "luDqDqu8c1AX",
"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. "
"colab_type": "text"
]
},
},
"cell_type": "markdown",
{
"source": [
"cell_type": "code",
"## Define your model\n",
"execution_count": 0,
"Using functional API, you must define your model by specifying the inputs and outputs associated with the model. "
"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. "
},
]
"outputs": [],
},
"source": [
{
"def dice_loss(y_true, y_pred):\n",
"metadata": {
" loss = 1 - dice_coeff(y_true, y_pred)\n",
"id": "sfuBVut0fogM",
" return loss"
"colab_type": "text"
]
},
},
"cell_type": "markdown",
{
"source": [
"cell_type": "markdown",
"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",
"metadata": {
"\n",
"colab_type": "text",
"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. "
"id": "qqClGNFJdANU"
]
},
},
"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). Try out your own custom losses to measure performance (e.g. bce + log(dice_loss), only bce, etc.)!"
" loss = losses.binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)\n",
" return score"
" return loss"
],
]
"execution_count": 0,
},
"outputs": []
{
},
"cell_type": "markdown",
{
"metadata": {
"metadata": {
"colab_type": "text",
"id": "4DgINhlpNaxP",
"id": "LifmpjXNc9Gz"
"colab_type": "code",
},
"colab": {}
"source": [
},
"## Compile your model\n",
"cell_type": "code",
"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. "
"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). "
]
]
},
},
{
{
"cell_type": "markdown",
"metadata": {
"metadata": {
"id": "udrfi9JGB-bL",
"colab_type": "text",
"colab_type": "code",
"id": "8WG_8iZ_dMbK"
"colab": {}
},
},
"source": [
"cell_type": "code",
"## Train your model\n",
"source": [
"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",
"def bce_dice_loss(y_true, y_pred):\n",
"\n",
" loss = losses.binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)\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."
" return loss"
]
],
},
"execution_count": 0,
{
"outputs": []
"cell_type": "code",
},
"execution_count": 0,
{
"metadata": {
"metadata": {
"colab": {},
"id": "LifmpjXNc9Gz",
"colab_type": "code",
"colab_type": "text"
"id": "1nHnj6199elZ"
},
},
"cell_type": "markdown",
"outputs": [],
"source": [
"source": [
"## Compile your model\n",
"save_model_path = '/tmp/weights.hdf5'\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. "
"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",
"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."
"```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",
"plt.title('Training and Validation Loss')\n",
"\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)!"
"plt.show()"
]
],
},
"execution_count": 0,
{
"outputs": []
"cell_type": "code",
},
"execution_count": 0,
{
"metadata": {
"metadata": {
"colab": {},
"id": "dWPhb87GdhkG",
"colab_type": "code",
"colab_type": "text"
"id": "5Ph7acmrCXm6"
},
},
"cell_type": "markdown",
"outputs": [],
"source": [
"source": [
"Even with only 5 epochs, we see strong performance."
"# Alternatively, load the weights directly: model.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",
"\n",
" plt.subplot(5, 3, 3 * i + 1)\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",
" plt.imshow(img)\n",
"\n",
" plt.title(\"Input image\")\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)!"
" \n",
]
" plt.subplot(5, 3, 3 * i + 2)\n",
},
" plt.imshow(label[0, :, :, 0])\n",
{
" plt.title(\"Actual Mask\")\n",
"metadata": {
" plt.subplot(5, 3, 3 * i + 3)\n",
"id": "5Ph7acmrCXm6",
" plt.imshow(predicted_label[:, :, 0])\n",
"colab_type": "code",
" plt.title(\"Predicted Mask\")\n",
"colab": {}
"plt.suptitle(\"Examples of Input Image, Label, and Prediction\")\n",
},
"plt.show()"
"cell_type": "code",
]
"source": [
},
"# Alternatively, load the weights directly: model.load_weights(save_model_path)\n",
"In this tutorial we learned how to train a network to automatically detect and create cutouts of cars from images! \n",
"id": "0GnwZ7CPaamI",
"\n",
"colab_type": "code",
"## Specific concepts that will we covered:\n",
"colab": {}
"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",
"cell_type": "code",
"* **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",
"source": [
"* **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. "
"plt.suptitle(\"Examples of Input Image, Label, and Prediction\")\n",
"file_extension": ".py",
"plt.show()"
"mimetype": "text/x-python",
],
"name": "python",
"execution_count": 0,
"nbconvert_exporter": "python",
"outputs": []
"pygments_lexer": "ipython3",
},
"version": "3.6.4"
{
}
"metadata": {
},
"id": "iPV7RMA9TjPC",
"nbformat": 4,
"colab_type": "text"
"nbformat_minor": 1
},
}
"cell_type": "markdown",
"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. "