<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ayush Thakur on Medium]]></title>
        <description><![CDATA[Stories by Ayush Thakur on Medium]]></description>
        <link>https://medium.com/@mein2work?source=rss-568907d77025------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Zx3woiGuLkIjVSCy.jpg</url>
            <title>Stories by Ayush Thakur on Medium</title>
            <link>https://medium.com/@mein2work?source=rss-568907d77025------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:18:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mein2work/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Object Localization with Keras]]></title>
            <link>https://medium.com/analytics-vidhya/object-localization-with-keras-2f272f79e03c?source=rss-568907d77025------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f272f79e03c</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[wandb]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[object-localization]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Ayush Thakur]]></dc:creator>
            <pubDate>Tue, 03 Nov 2020 19:46:38 GMT</pubDate>
            <atom:updated>2020-11-06T17:06:12.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object Localization with Keras and W&amp;B</h3><h4><strong>This report explores object localization using the bounding box regression technique in Keras and interactively visualizes the model’s prediction in Weights &amp; Biases</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fCMI0Kwfxpqfus56" /><figcaption>Photo by <a href="https://unsplash.com/@nhillier?utm_source=medium&amp;utm_medium=referral">Nick Hillier</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><a href="https://wandb.ai/wandb/object_localization/reports/Object-Localization-with-Keras-and-W-B--VmlldzoyNzA2Mzk">Interactive Report</a> | <a href="https://colab.research.google.com/drive/1LWbgjNbQLQHgfY2WH0lKBEFRIZXdqT86?usp=sharing">Colab Notebook</a></h4><h3>Introduction</h3><p>Object localization is the task of <strong>locating an instance of a particular object category</strong> in an image, typically by specifying a tightly cropped bounding box centered on the instance. Object detection, on the contrary, is the task of locating all the possible instances of all the target objects.</p><p>Object localization is also called “classification with localization”. This is because the architecture which performs image classification can be slightly modified to predict the bounding box coordinates. Check out <a href="https://www.youtube.com/watch?v=GSwYGkTfOKk">Andrew Ng’s lecture</a> on object localization or check out <a href="https://www.pyimagesearch.com/2020/10/05/object-detection-bounding-box-regression-with-keras-tensorflow-and-deep-learning/">Object detection: Bounding box regression with Keras, TensorFlow, and Deep Learning</a> by <a href="https://www.pyimagesearch.com/author/adrian/">Adrian Rosebrock</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sW8lbS9CwbyE5cXm.png" /><figcaption><strong>Figure 1</strong>: Difference between image classification, object localization and object detection. (<a href="http://datahacker.rs/deep-learning-object-localization/">Source</a>)</figcaption></figure><p>In this report, we will build an object localization model and train it on a synthetic dataset. We will <strong>interactively visualize our models’ predictions</strong> in Weights &amp; Biases.</p><h3>The Dataset</h3><p>We will use a synthetic dataset for our object localization task based on the MNIST dataset. This dataset is made by <a href="https://twitter.com/lmoroney">Laurence Moroney</a>. The idea is that instead of 28x28 pixel MNIST images, it could be NxN(100x100), and the task is to predict the bounding box for the digit location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*I2TprktWKDTjJD9Z.png" /><figcaption><strong>Figure 2</strong>: Samples from the dataset. Every image is 100x100 pixels.</figcaption></figure><h4>Download the dataset</h4><p>This <a href="https://github.com/lmoroney/synthetic_datasets">GitHub repo</a> is the original source of the dataset. However, due to this <a href="https://github.com/lmoroney/synthetic_datasets/issues/2">issue</a>, we will use <a href="https://github.com/ayulockin/synthetic_datasets">my fork</a> of the original repository.</p><p>We also have a .csv training and testing file with the name of the images, labels, and the bounding box coordinates. Note that the coordinates are scaled to [0, 1].</p><pre>!git clone https://github.com/ayulockin/synthetic_datasets<br>%cd synthetic_datasets/MNIST/<br>%mkdir images</pre><pre>!unzip -q MNIST_Converted_Training.zip -d images/<br>!unzip -q MNIST_Converted_Testing.zip -d images/</pre><h4>Dataloader using tf.data</h4><p>We will use tf.data.Dataset to build our input pipeline. Our model will have to predict the class of the image(object in question) and the bounding box coordinates given an input image.</p><p>In <em>the model</em> section, you will realize that the model is a multi-output architecture. Check out <a href="https://www.pyimagesearch.com/2018/06/04/keras-multiple-outputs-and-multiple-losses/">Keras: Multiple outputs and multiple losses</a> by <a href="https://www.pyimagesearch.com/author/adrian/">Adrian Rosebrock</a> to learn more about it.</p><p><strong>The </strong><strong>tf.data.Dataset pipeline shown below addresses multi-output training</strong>. We will return a dictionary of labels and bounding box coordinates along with the image. <strong>The name of the keys should be the same as the name of the output layers.</strong></p><pre>AUTO = tf.data.experimental.AUTOTUNE<br>BATCH_SIZE = 32</pre><pre>@tf.function<br>def preprocess_train(image_name, label, bbox):<br>    image = tf.io.read_file(TRAIN_IMG_PATH+image_name)<br>    image = tf.image.decode_png(image, channels=1)</pre><pre>    return image, {&#39;label&#39;: label, &#39;bbox&#39;: bbox} # Notice here</pre><pre>@tf.function<br>def preprocess_test(image_name, label, bbox):<br>    image = tf.io.read_file(TEST_IMG_PATH+image_name)<br>    image = tf.image.decode_png(image, channels=1)</pre><pre>    return image, {&#39;label&#39;: label, &#39;bbox&#39;: bbox} # Notice here</pre><pre>trainloader = tf.data.Dataset.from_tensor_slices((train_image_names, train_labels, train_bbox))<br>testloader = tf.data.Dataset.from_tensor_slices((test_image_names, test_labels, test_bbox))</pre><pre>trainloader = (<br>    trainloader<br>    .map(preprocess_train, num_parallel_calls=AUTO)<br>    .shuffle(1024)<br>    .batch(BATCH_SIZE)<br>    .prefetch(AUTO)<br>)</pre><pre>testloader = (<br>    testloader<br>    .map(preprocess_test, num_parallel_calls=AUTO)<br>    .batch(BATCH_SIZE)<br>    .prefetch(AUTO)<br>)</pre><h3>The Model</h3><h4>Bounding Box Regression</h4><p>Before we build our model, let’s briefly discuss bounding box regression. In machine learning literature regression is a task to map the input value X with the continuous output variable y.</p><p>Thus we return a number instead of a class, and in our case, we’re going to return 4 numbers (x1, y1, x2, y2) that are related to a bounding box. We will train this system with an image and a ground truth bounding box, and use L2 loss to calculate the loss between the predicted bounding box and the ground truth. Check out <a href="https://www.youtube.com/watch?v=LZRfHkTNQqo">this video</a> to learn more about bounding box regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*-7pdw0pSFbwNJmpL.png" /><figcaption><strong>Figure 3</strong>: The general model architecture for bounding box regression for object localization task. (<a href="https://leonardoaraujosantos.gitbook.io/artificial-inteligence/machine_learning/deep_learning/object_localization_and_detection#localize-objects-with-regression">Source</a>)</figcaption></figure><p>Going back to the model, figure 3 rightly summarizes the model architecture. The model constitutes three components — convolutional block(feature extractor), classification head, and regression head.</p><p>This is a multi-output configuration. As mentioned in <em>the dataset</em> section, the tf.data.Dataset input pipeline returns a dictionary, whose key names are the name of the output layer of the classification head and the regression head.</p><p>The code snippet shown below builds our model architecture for object localization.</p><pre>def get_model():<br>    inputs = Input(shape=(100,100,1))<br>    x = Conv2D(32, (3,3), activation=&#39;relu&#39;)(inputs)<br>    x = MaxPooling2D((3,3))(x)<br>    x = Conv2D(32, (3,3), activation=&#39;relu&#39;)(x)<br>    x = MaxPooling2D((3,3))(x)<br>    x = Conv2D(64, (3,3), activation=&#39;relu&#39;)(x)<br>    x = GlobalAveragePooling2D()(x)</pre><pre>    classifier_head = Dropout(0.3)(x)<br>    # Notice the name of the layer.<br>    classifier_head = Dense(10, activation=&#39;softmax&#39;, name=&#39;label&#39;)(classifier_head)</pre><pre>    reg_head = Dense(64, activation=&#39;relu&#39;)(x)<br>    reg_head = Dense(32, activation=&#39;relu&#39;)(reg_head)<br>    # Notice the name of the layer.<br>    reg_head = Dense(4, activation=&#39;sigmoid&#39;, name=&#39;bbox&#39;)(reg_head)</pre><pre>    return Model(inputs=[inputs], outputs=[classifier_head, reg_head])</pre><p>The names given to the multiple heads are used as keys for the losses dictionary. Note that the activation function for the classification head is softmax since it&#39;s a multi-class classification setup(0-9 digits). The activation function for the regression head is sigmoid since the bounding box coordinates are in the range of [0, 1].</p><p>The loss functions are appropriately selected. We can optionally give different weightage to different loss functions.</p><pre>losses = {&#39;label&#39;: &#39;sparse_categorical_crossentropy&#39;,<br>          &#39;bbox&#39;: &#39;mse&#39;}</pre><pre>loss_weights = {&#39;label&#39;: 1.0,<br>                &#39;bbox&#39;: 1.0}</pre><h3>The BBoxLogger - Interactive Visualization of Predictions</h3><p>When working on object localization or object detection, you can interactively visualize your models’ predictions in Weights &amp; Biases. You can log the sample images along with the ground truth and predicted bounding box values. You can even log multiple boxes and can log confidence scores, IoU scores, etc. Check out the documentation <a href="https://docs.wandb.com/library/log#images-and-overlays">here</a>.</p><p>The report <a href="https://wandb.ai/stacey/yolo-drive/reports/Bounding-Boxes-for-Object-Detection--Vmlldzo4Nzg4MQ">Bounding Boxes for Object Detection</a> by <a href="https://wandb.ai/stacey">Stacey Svetlichnaya</a> walk you through the interactive controls for this tool. It covers the various nuisances of logging images and bounding box coordinates.</p><p>The code snippets shown below is the helper function for our BBoxLogger callback. The function wandb_bbox returns the image, the predicted bounding box coordinates, and the ground truth coordinates in the required format. Note that the passed values have dtype which is JSON serializable. For example, if your pred_label should be float type and not ndarray.float.</p><pre>def wandb_bbox(image, p_bbox, pred_label, t_bbox, true_label, class_id_to_label):<br>    return wandb.Image(image, boxes={<br>        &quot;predictions&quot;: {<br>            &quot;box_data&quot;: [{<br>                &quot;position&quot;: {<br>                    &quot;minX&quot;: p_bbox[0],<br>                    &quot;maxX&quot;: p_bbox[2],<br>                    &quot;minY&quot;: p_bbox[1],<br>                    &quot;maxY&quot;: p_bbox[3]<br>                    },<br>                &quot;class_id&quot; : pred_label,<br>                &quot;box_caption&quot;: class_id_to_label[pred_label]<br>            }],<br>          &quot;class_labels&quot;: class_id_to_label<br>        },<br>        &quot;ground_truth&quot;: {<br>            &quot;box_data&quot;: [{<br>                &quot;position&quot;: {<br>                    &quot;minX&quot;: t_bbox[0],<br>                    &quot;maxX&quot;: t_bbox[2],<br>                    &quot;minY&quot;: t_bbox[1],<br>                    &quot;maxY&quot;: t_bbox[3]<br>                    },<br>                &quot;class_id&quot; : true_label,<br>                &quot;box_caption&quot;: class_id_to_label[true_label]<br>            }],<br>          &quot;class_labels&quot;: class_id_to_label<br>        }<br>    })</pre><p>Our BBoxLogger is a custom Keras callback. We can pass it to model.fit to log our model&#39;s predictions on a small validation set. Weights and Biases will automatically overlay the bounding box on the image.</p><pre>class BBoxLogger(tf.keras.callbacks.Callback):<br>    def __init__(self):<br>        super(BBoxLogger, self).__init__()<br>        self.val_images, label_bbox = next(iter(testloader))<br>        self.true_labels = label_bbox[&#39;label&#39;]<br>        self.true_bbox = label_bbox[&#39;bbox&#39;]<br><br>    def on_epoch_end(self, logs, epoch):<br>        localization_list = []<br><br>        for idx in range(len(self.val_images)):<br>            # get image<br>            image = self.val_images[idx]<br>            # get ground truth label and bbox coordinates.<br>            true_label = int(self.true_labels[idx].numpy())<br>            t_bbox = self.true_bbox[idx]<br>            # get model prediction.<br>            pred_label, p_bbox = model.predict(np.expand_dims(image, 0))<br>            # get argmax of the prediction<br>            pred_label = int(np.argmax(pred_label[0])) <br>            # get wandb image<br>            localization_list.append(wandb_bbox(image, <br>                                                p_bbox[0].tolist(),<br>                                                pred_label, <br>                                                t_bbox.numpy().tolist(), <br>                                                true_label, <br>                                                class_id_to_label))<br><br>        wandb.log({&quot;predictions&quot; : localization_list})</pre><p>We will soon look at the results.</p><h3>Results</h3><p>Now on to the exciting part. I have trained the model with early stopping with the patience of 10 epochs. Feel free to train the model for longer epochs and play with other hyperparameters. Try out the experiments in this colab notebook.</p><p><a href="https://colab.research.google.com/drive/1LWbgjNbQLQHgfY2WH0lKBEFRIZXdqT86?usp=sharing">Google Colaboratory</a></p><p>Since we have multiple losses associated with our task, we will have multiple metrics to log and monitor. Weights and Biases automatically log all the metrics using keras.WandbCallback callback.</p><p><strong>Check out this interactive report to see complete result.</strong></p><p><a href="https://wandb.ai/wandb/object_localization/reports/Object-Localization-with-Keras-and-W-B--VmlldzoyNzA2Mzk">Object Localization with Keras and W&amp;B</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*VBpxiXW7-VkZ-OAwTsGKPQ.png" /><figcaption><strong>Figure 4: </strong>Train and validation loss. (<a href="https://wandb.ai/wandb/object_localization/reports/Object-Localization-with-Keras-and-W-B--VmlldzoyNzA2Mzk">Source</a>)</figcaption></figure><p>The result of BBoxLogger is shown below. In the interactive report, click on the ⚙️ icon in the media panel below(Result of BBoxLogger) to check out the interaction controls. You can visualize both ground truth and predicted bounding boxes together or separately. You can even select the class which you don&#39;t want to visualize.</p><h4>Observations</h4><ul><li>The model is accurately classifying the images. This can be further confirmed by looking at the classification metrics shown above. For MNIST like datasets, it is expected to have high accuracy.</li><li>The prediction of the bounding box coordinates looks okayish. We should wait and admire the power of neural networks here. With just a few lines of code we are able to locate the digits.</li></ul><h4>Improvements</h4><p>Few things that we can do to improve the bounding box prediction are:</p><ul><li>Increase the depth of the regression network of our model and train. It might lead to overfitting but it’s worth a try.</li><li>Train the current model. Freeze the convolutional layer and the classification network and train the regression network forfew more epochs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*3d-X5HkuPRfSOFz2BJRAsA.png" /><figcaption><strong>Figure 5: </strong>Result of the BBoxLogger. (<a href="https://wandb.ai/wandb/object_localization/reports/Object-Localization-with-Keras-and-W-B--VmlldzoyNzA2Mzk">Source</a>)</figcaption></figure><h3>Conclusion</h3><p>I hope you like this short tutorial on how to build an object localization architecture using Keras and use interactive bounding box visualization tool to debug the bounding box predictions.</p><p>You can find more of my work <a href="https://wandb.ai/ayush-thakur/">here</a>. Check out the interactive report <a href="https://wandb.ai/wandb/object_localization/reports/Object-Localization-with-Keras-and-W-B--VmlldzoyNzA2Mzk">here</a>. Would love your feedbacks. :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f272f79e03c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/object-localization-with-keras-2f272f79e03c">Object Localization with Keras</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Segmentation Using Keras and W&B]]></title>
            <link>https://medium.com/data-science/image-segmentation-using-keras-and-w-b-98223c38e4d4?source=rss-568907d77025------2</link>
            <guid isPermaLink="false">https://medium.com/p/98223c38e4d4</guid>
            <category><![CDATA[wandb]]></category>
            <category><![CDATA[semantic-segmentation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Ayush Thakur]]></dc:creator>
            <pubDate>Tue, 22 Sep 2020 12:06:52 GMT</pubDate>
            <atom:updated>2020-10-09T21:04:16.948Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>This report explores semantic segmentation with a UNET like architecture in Keras and interactively visualizes the model’s prediction in Weights &amp; Biases.</strong></h4><h4>View interactive report <a href="https://wandb.ai/ayush-thakur/image-segmentation/reports/Image-Segmentation-Using-Keras-and-W-B--VmlldzoyNTE1Njc">here</a>. Colab notebook is available <a href="https://colab.research.google.com/drive/1rXV31gdyqEiXCtmSgff-H-VRuOSzv7IH?usp=sharing">here</a>.</h4><h3>Introduction</h3><p>Are you interested to know where an object is in the image? What is the shape of the object? Which pixels belong to the object? To accomplish this, we need to segment the image, i.e., classify each pixel of the image to the object it belongs to or give each pixel of the image a label contrary to giving one label to an image.</p><p><strong>Thus, image segmentation is the task of learning a pixel-wise mask for each object in the image.</strong> Unlike object detection, which gives the bounding box coordinates for each object present in the image, image segmentation gives a far more granular understanding of the object(s) in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*at8_d54v1l9DbWhF9SAovg.png" /><figcaption><strong>Figure 1</strong>: Semantic segmentation and Instance segmentation. (<a href="https://www.researchgate.net/figure/Semantic-segmentation-left-and-Instance-segmentation-right-8_fig1_339616270">Source</a>)</figcaption></figure><p>Image segmentation can be broadly divided into two types:</p><ul><li><strong>Semantic segmentation: </strong>Here, each pixel belongs to a particular class. The left image in figure 1 is an example of semantic segmentation. The pixels either belong to the person(a class) or background(another class).</li><li><strong>Instance segmentation: </strong>Here, each pixel belongs to a particular class. However, pixels belonging to discrete objects are labeled with a different color(mask value). The right image in figure 1 is an example of instance, segmentation. The pixels belonging to the person’s class are colored differently.</li></ul><p>This report will <strong>build a semantic segmentation model</strong> and train it on <a href="https://www.robots.ox.ac.uk/%7Evgg/data/pets/">Oxford-IIIT Pet Dataset</a>. We will <strong>interactively visualize our model’s predictions</strong> in Weights &amp; Biases.</p><h3>The Dataset</h3><p>We will use <a href="https://www.robots.ox.ac.uk/%7Evgg/data/pets/">Oxford-IIIT Pet Dataset</a> to train our UNET-like semantic segmentation model.</p><p>The dataset consists of images and their pixel-wise mask. The pixel-wise masks are labels for each pixel.</p><ul><li>Class 1: Pixels belonging to the pet.</li><li>Class 2: Pixels belonging to the outline of the pet.</li><li>Class 3: Pixels belonging to the background.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*YBiN4_DGAoLi6SpqrvUBBQ.png" /><figcaption><strong>Figure 2</strong>: Pets and their pixel-wise masks.</figcaption></figure><h4>Download the dataset</h4><pre>!curl -O <a href="http://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz">http://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz</a></pre><pre>!curl -O <a href="http://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz">http://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz</a></pre><pre>!tar -xf images.tar.gz<br>!tar -xf annotations.tar.gz</pre><h4>Dataset preparation</h4><p>The images/ and annotations/trimaps directories contain extracted images and their annotations(pixel-wise masks). The required images are in .jpg format while the annotations are in .png format. However, there are files in those directories which are not required for our purpose. We will thus prepare two lists - input_img_paths and annotation_img_paths which contains the paths to required images and annotations.</p><pre>IMG_PATH = &#39;images/&#39;<br>ANNOTATION_PATH = &#39;annotations/trimaps/&#39;<br><br>input_img_paths = sorted(<br>    [<br>        os.path.join(IMG_PATH, fname)<br>        for fname in os.listdir(IMG_PATH)<br>        if fname.endswith(&quot;.jpg&quot;)<br>    ]<br>)<br>annotation_img_paths = sorted(<br>    [<br>        os.path.join(ANNOTATION_PATH, fname)<br>        for fname in os.listdir(ANNOTATION_PATH)<br>        if fname.endswith(&quot;.png&quot;) and not fname.startswith(&quot;.&quot;)<br>    ]<br>)<br><br>print(len(input_img_paths), len(annotation_img_paths))</pre><p>There are a total of 7390 images and annotations. We shall use 1000 images and their annotations as the validation set.</p><h4>Dataloader using tf.data</h4><p>We will use tf.data.Dataset to build our input pipeline.</p><pre>IMG_SHAPE = 128<br>AUTO = tf.data.experimental.AUTOTUNE<br>BATCH_SIZE = 32<br><br>def scale_down(image, mask):<br>  # apply scaling to image and mask<br>  image = tf.cast(image, tf.float32) / 255.0<br>  mask -= 1<br>  return image, mask<br><br>def load_and_preprocess(img_filepath, mask_filepath):<br>   # load the image and resize it<br>    img = tf.io.read_file(img_filepath)<br>    img = tf.io.decode_jpeg(img, channels=3)<br>    img = tf.image.resize(img, [IMG_SHAPE, IMG_SHAPE])<br><br>    mask = tf.io.read_file(mask_filepath)<br>    mask = tf.io.decode_png(mask, channels=1)<br>    mask = tf.image.resize(mask, [IMG_SHAPE, IMG_SHAPE])<br><br>    img, mask = scale_down(img, mask)<br><br>    return img, mask<br><br># shuffle the paths and prepare train-test split<br>input_img_paths, annotation_img_paths = shuffle(input_img_paths, annotation_img_paths, random_state=42)<br>input_img_paths_train, annotation_img_paths_train = input_img_paths[: -1000], annotation_img_paths[: -1000]<br>input_img_paths_test, annotation_img_paths_test = input_img_paths[-1000:], annotation_img_paths[-1000:]<br><br>trainloader = tf.data.Dataset.from_tensor_slices((input_img_paths_train, annotation_img_paths_train))<br>testloader = tf.data.Dataset.from_tensor_slices((input_img_paths_test, annotation_img_paths_test))<br><br>trainloader = (<br>    trainloader<br>    .shuffle(1024)<br>    .map(load_and_preprocess, num_parallel_calls=AUTO)<br>    .batch(BATCH_SIZE)<br>    .prefetch(AUTO)<br>)<br><br>testloader = (<br>    testloader<br>    .map(load_and_preprocess, num_parallel_calls=AUTO)<br>    .batch(BATCH_SIZE)<br>    .prefetch(AUTO)<br>)</pre><h3>The Model</h3><p>The model being used here is vanilla <a href="https://arxiv.org/abs/1505.04597">UNET architecture</a>. It consists of an encoder and a decoder network. The input to this architecture is the image, while the output is the pixel-wise map. You can learn more about the encoder-decoder(Autoencoder) network in <a href="https://wandb.ai/ayush-thakur/keras-gan/reports/Towards-Deep-Generative-Modeling-with-W-B--Vmlldzo4MDI4Mw">Towards Deep Generative Modeling with W&amp;B</a> report.</p><p>The UNET-like architecture is commonly found in self-supervised deep learning tasks like <a href="https://www.wandb.com/articles/introduction-to-image-inpainting-with-deep-learning">Image Inpainting</a>.</p><p>You can learn more about UNET architecture in this <a href="https://towardsdatascience.com/unet-line-by-line-explanation-9b191c76baf5">Line by Line Explanation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*DtGOVs833TJOtWEbLTBoOg.png" /><figcaption><strong>Figure 3</strong>: A typical UNET architecture. (<a href="https://towardsdatascience.com/unet-line-by-line-explanation-9b191c76baf5">Source</a>)</figcaption></figure><p>The code snippet shown below builds our model architecture for semantic segmentation.</p><pre>class SegmentationModel:<br>  &#39;&#39;&#39;<br>  Build UNET like model for image inpaining task.<br>  &#39;&#39;&#39;<br>  def prepare_model(self, OUTPUT_CHANNEL, input_size=(IMG_SHAPE,IMG_SHAPE,3)):<br>    inputs = Input(input_size)<br><br>    # Encoder <br>    conv1, pool1 = self.__ConvBlock(32, (3,3), (2,2), &#39;relu&#39;, &#39;same&#39;, inputs) <br>    conv2, pool2 = self.__ConvBlock(64, (3,3), (2,2), &#39;relu&#39;, &#39;same&#39;, pool1)<br>    conv3, pool3 = self.__ConvBlock(128, (3,3), (2,2), &#39;relu&#39;, &#39;same&#39;, pool2) <br>    conv4, pool4 = self.__ConvBlock(256, (3,3), (2,2), &#39;relu&#39;, &#39;same&#39;, pool3) <br>    <br>    # Decoder<br>    conv5, up6 = self.__UpConvBlock(512, 256, (3,3), (2,2), (2,2), &#39;relu&#39;, &#39;same&#39;, pool4, conv4)<br>    conv6, up7 = self.__UpConvBlock(256, 128, (3,3), (2,2), (2,2), &#39;relu&#39;, &#39;same&#39;, up6, conv3)<br>    conv7, up8 = self.__UpConvBlock(128, 64, (3,3), (2,2), (2,2), &#39;relu&#39;, &#39;same&#39;, up7, conv2)<br>    conv8, up9 = self.__UpConvBlock(64, 32, (3,3), (2,2), (2,2), &#39;relu&#39;, &#39;same&#39;, up8, conv1)<br>    <br>    conv9 = self.__ConvBlock(32, (3,3), (2,2), &#39;relu&#39;, &#39;same&#39;, up9, False)<br>    <br>    # Notice OUTPUT_CHANNEL and activation<br>    outputs = Conv2D(OUTPUT_CHANNEL, (3, 3), activation=&#39;softmax&#39;, padding=&#39;same&#39;)(conv9)<br><br>    return Model(inputs=[inputs], outputs=[outputs])  <br><br>  def __ConvBlock(self, filters, kernel_size, pool_size, activation, padding, connecting_layer, pool_layer=True):<br>    conv = Conv2D(filters=filters, kernel_size=kernel_size, activation=activation, padding=padding)(connecting_layer)<br>    conv = Conv2D(filters=filters, kernel_size=kernel_size, activation=activation, padding=padding)(conv)<br>    if pool_layer:<br>      pool = MaxPooling2D(pool_size)(conv)<br>      return conv, pool<br>    else:<br>      return conv<br><br>  def __UpConvBlock(self, filters, up_filters, kernel_size, up_kernel, up_stride, activation, padding, connecting_layer, shared_layer):<br>    conv = Conv2D(filters=filters, kernel_size=kernel_size, activation=activation, padding=padding)(connecting_layer)<br>    conv = Conv2D(filters=filters, kernel_size=kernel_size, activation=activation, padding=padding)(conv)<br>    up = Conv2DTranspose(filters=up_filters, kernel_size=up_kernel, strides=up_stride, padding=padding)(conv)<br>    up = concatenate([up, shared_layer], axis=3)<br><br>    return conv, up</pre><p><strong>Notice</strong> that the OUTPUT_CHANNEL is 3 for our dataset. This is because there are three classes of pixels, as described in the dataset section. Consider that we are doing multi-class classification wherein each pixel can belong to either of the three classes.</p><p>Also, <strong>note</strong> that since it is a multi-class classification problem per pixel, the output activation function is softmax.</p><pre>OUTPUT_CHANNEL = 3<br><br>model = SegmentationModel().prepare_model(OUTPUT_CHANNEL)<br>model.compile(optimizer=&quot;adam&quot;, loss=&quot;sparse_categorical_crossentropy&quot;)</pre><p>Finally, the model is compiled with sparse_categorical_crossentropy. Sparse since the pixel-wise mask/annotation is in integer.</p><h3>The SemanticLogger Callback - Interactive Visualization of Predictions</h3><p>When working on semantic segmentation, you can interactively visualize your models’ predictions in Weights &amp; Biases. If you have images with masks for semantic segmentation, you can log the masks and toggle them on and off in the UI. Check out the official documentation <a href="https://docs.wandb.com/library/log#images-and-overlays">here</a>.</p><p>The report <a href="https://wandb.ai/stacey/deep-drive/reports/Image-Masks-for-Semantic-Segmentation--Vmlldzo4MTUwMw">Image Masks for Semantic Segmentation</a> by <a href="https://wandb.ai/stacey">Stacey Svetlichnaya</a> will walk you through the interactive controls for this tool. It covers the various nuisances of logging images and masks.</p><p>The code snippets shown below are the helper functions for our SemanticLogger callback. The function labels returns a dictionary where the key is the class value, and the value is the label. The function wandb_mask returns the image, the prediction mask, and the ground truth mask in the required format.</p><pre>segmentation_classes = [&#39;pet&#39;, &#39;pet_outline&#39;, &#39;background&#39;]<br><br># returns a dictionary of labels<br>def labels():<br>  l = {}<br>  for i, label in enumerate(segmentation_classes):<br>    l[i] = label<br>  return l<br><br># util function for generating interactive image mask from components<br>def wandb_mask(bg_img, pred_mask, true_mask):<br>  return wandb.Image(bg_img, masks={<br>      &quot;prediction&quot; : {<br>          &quot;mask_data&quot; : pred_mask, <br>          &quot;class_labels&quot; : labels()<br>      },<br>      &quot;ground truth&quot; : {<br>          &quot;mask_data&quot; : true_mask, <br>          &quot;class_labels&quot; : labels()<br>      }<br>    }<br>  )</pre><p>Our SemanticLogger is a custom Keras callback. We can pass it to model.fit to log our model&#39;s predictions on a small validation set. Weights and Biases will automatically overlay the mask on the image.</p><pre>class SemanticLogger(tf.keras.callbacks.Callback):<br>    def __init__(self):<br>        super(SemanticLogger, self).__init__()<br>        self.val_images, self.val_masks = next(iter(testloader))<br><br>    def on_epoch_end(self, logs, epoch):<br>        pred_masks = self.model.predict(self.val_images)<br>        pred_masks = np.argmax(pred_masks, axis=-1)<br>        # pred_masks = np.expand_dims(pred_masks, axis=-1)<br><br>        val_images = tf.image.convert_image_dtype(self.val_images, tf.uint8)<br>        val_masks = tf.image.convert_image_dtype(self.val_masks, tf.uint8)<br>        val_masks = tf.squeeze(val_masks, axis=-1)<br>        <br>        pred_masks = tf.image.convert_image_dtype(pred_masks, tf.uint8)<br><br>        mask_list = []<br>        for i in range(len(self.val_images)):<br>          mask_list.append(wandb_mask(val_images[i].numpy(), <br>                                      pred_masks[i].numpy(), <br>                                      val_masks[i].numpy()))<br><br>        wandb.log({&quot;predictions&quot; : mask_list})</pre><p>We will shortly look at the results.</p><h3>Results</h3><p>Now on to the exciting part. I have trained the model for 15 epochs. The loss and validation loss metrics are shown in the chart below. <em>Feel free to train the model for longer epochs and play with other hyper-parameters.</em></p><p><a href="https://colab.research.google.com/drive/1rXV31gdyqEiXCtmSgff-H-VRuOSzv7IH?usp=sharing">Google Colaboratory</a></p><p>The training and the validation loss is shown in <strong>figure 3</strong>. The model starts to overfit after some epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*pIf6-Ay_UXzHlHv4t-_caA.png" /><figcaption><strong>Figure 4</strong>: Training and Validation Loss Metric. (<a href="https://wandb.ai/ayush-thakur/image-segmentation/reports/Image-Segmentation-Using-Keras-and-W-B--VmlldzoyNTE1Njc">Check out the interactive report here.</a>)</figcaption></figure><p>The result of SemanticLogger is shown below. <strong>Click on the ⚙️ icon in </strong><a href="https://wandb.ai/ayush-thakur/image-segmentation/reports/Image-Segmentation-Using-Keras-and-W-B--VmlldzoyNTE1Njc#Results-7"><strong>the media panel</strong></a><strong> below(Result of SemanticLogger) to check out interaction controls</strong>. You can visualize images and masks separately and can choose which semantic class to visualize.</p><h3>Observations</h3><ul><li>The model learns to predict the pet and background class well.</li><li>We can see that the model is having a hard time segmenting pet_outline class. This is because of the high class imbalance, and the model is not regularized to counter this imbalance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*A6yZSwXxXP73pVLZddGm2g.png" /><figcaption><strong>Figure 5</strong>: Result of SemanticLogger Callback.(<a href="https://wandb.ai/ayush-thakur/image-segmentation/reports/Image-Segmentation-Using-Keras-and-W-B--VmlldzoyNTE1Njc">Check out the interactive report here.</a>)</figcaption></figure><h3>Conclusion and Final Thoughts</h3><p>I hope you enjoyed this report on Semantic Segmentation. The intention of this report was two folds:</p><ul><li>Make semantic segmentation technique more accessible to interested folks.</li><li>Show how Weights and Biases can help interactively visualize models’ predictions and metrics. Moreover, show the observations one can derive from these visualizations.</li></ul><p>On an ending note, here are some resources that might be a good read:</p><ul><li><a href="https://www.jeremyjordan.me/semantic-segmentation/">An overview of semantic image segmentation</a></li><li><a href="https://www.tensorflow.org/tutorials/images/segmentation">Image segmentation</a></li><li><a href="https://wandb.ai/stacey/deep-drive/reports/The-View-from-the-Driver-s-Seat--Vmlldzo1MTg5NQ">The View from the Driver’s Seat</a></li></ul><p>I would love to get your feedback in the comment section. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98223c38e4d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/image-segmentation-using-keras-and-w-b-98223c38e4d4">Image Segmentation Using Keras and W&amp;B</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interpretability in Deep Learning with W&B — CAM and GradCAM]]></title>
            <link>https://medium.com/data-science/interpretability-in-deep-learning-with-w-b-cam-and-gradcam-45ba5296a58a?source=rss-568907d77025------2</link>
            <guid isPermaLink="false">https://medium.com/p/45ba5296a58a</guid>
            <category><![CDATA[model-interpretability]]></category>
            <category><![CDATA[production-ml]]></category>
            <category><![CDATA[wandb]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Ayush Thakur]]></dc:creator>
            <pubDate>Fri, 22 May 2020 15:07:16 GMT</pubDate>
            <atom:updated>2020-05-22T15:07:16.685Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/production-ml">Machine Learning in Production</a></h4><h3>Interpretability in Deep Learning with W&amp;B — CAM and GradCAM</h3><h4>This report will review how Grad-CAM counters the common criticism that neural networks are not interpretable.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*xHx8RnZBd5lv0X1Iag94oQ.png" /></figure><h4>View interactive report <a href="https://app.wandb.ai/ayush-thakur/interpretability/reports/Interpretability-in-Deep-Learning-with-W%26B-CAM-and-GradCAM--Vmlldzo5MTIyNw">here</a>. All the code is available <a href="https://github.com/ayulockin/interpretabilitycnn/">here</a>.</h4><p>Training a classification model is interesting, but have you ever wondered how your model is making its predictions? Is your model actually looking at the dog in the image before classifying it as a dog with 98% accuracy? Interesting, isn’t it. In today’s report, we will explore why deep learning models need to be interpretable, and some interesting methods to peek under the hood of a deep learning model. Deep learning interpretability is a very exciting area of research and much progress is being made in this direction already.</p><p>So why should you care about interpretability? After all, the success of your business or your project is judged primarily by how good the accuracy of your model is. But in order to deploy our models in the real world, we need to consider other factors too. For instance, is racially biased? Or, what if it’s classifying humans with 97% accuracy, but while it classifies men with 99% accuracy, it only achieves 95% accuracy on women?</p><p>Understanding how a model makes its predictions can also help us debug your network. [Check out this blog post on ‘<a href="https://www.wandb.com/articles/debugging-neural-networks-with-pytorch-and-w-b-using-gradients-and-visualizations">Debugging Neural Networks with PyTorch and W&amp;B Using Gradients and Visualizations</a>’ for some other techniques that can help].</p><p>At this point, we are all familiar with the concept that deep learning models make predictions based on the learned representation expressed in terms of other simpler representations. That is, deep learning allows us to build complex concepts out of simpler concepts. Here’s an amazing <a href="https://distill.pub/2018/building-blocks/">Distill Pub</a> post to help you understand this concept better. We also know that these representations are learned while we train the model with our input data and the label, in case of some supervised learning task like image classification. One of the criticisms of this approach is that the learned features in a neural network are not interpretable.</p><p>Today we’ll look at 2techniques that address this criticism and shed light into neural networks’ “black-box” nature of learning.</p><ul><li>Class Activation Map(CAM)</li><li>Gradient CAM</li></ul><h3>Class Activation Maps</h3><p>It has been observed that convolution units of various layers of a convolutional neural network act as an object detector even though no such prior about the location of the object is provided while training the network for a classification task. Even though convolution has this remarkable property, it is lost when we use a fully connected layer for the classification task. To avoid the use of a fully connected network some architectures like <a href="https://arxiv.org/abs/1312.4400">Network in Network</a>(NiN) and <a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43022.pdf">GoogLeNet</a> are fully convolutional neural networks.</p><p>Global Average Pooling(GAP) is a very commonly used layer in such architectures. It is mainly used as a regularizer to prevent overfitting while training. The authors of <a href="https://arxiv.org/pdf/1512.04150.pdf">Learning Deep Features for Discriminative Localization</a> found out that by tweaking such an architecture, they can extend the advantages of GAP and can retain its localization ability until the last layer. Let’s try to quickly understand the procedure of generating CAM using GAP.</p><p><strong>The class activation map simply indicates the discriminative region in the image which the CNN uses to classify that image in a particular category.</strong> For this technique, the network consists of ConvNet and just before the Softmax layer(for multi-class classification), global average pooling is performed on the convolutional feature maps. The output of this layer is used as features for a fully-connected layer that produces the desired classification output. <strong>Given this simple connectivity structure, we can identify the importance of the image regions by projecting back the weights of the output layer on to the convolutional feature maps.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*xdd9O4J8faFnsIGr.png" /><figcaption><em>Figure 1: The network architecture ideal for CAM (</em><a href="https://arxiv.org/pdf/1512.04150.pdf"><em>Source</em></a><em>)</em></figcaption></figure><p>Let’s try to implement this. 😄</p><h4>Step 1: Modify Your Model</h4><p>Suppose you have built your deep classifier with Conv blocks and a few fully connected layers. We will have to modify this architecture such that there aren’t any fully connected layers. We will use the GlobalAveragePooling2D layer between the output layer (softmax/sigmoid) and the last convolutional block.</p><p>The CAMmodel provides a required modification to our cat and dog classifier. <strong>Here I am using pre-trained </strong><strong>VGG16 model to simulate my already trained cat-dog classifier.</strong></p><pre>def CAMmodel():<br>     ## Simulating my pretrained dog and cat classifier. <br>     vgg = VGG16(include_top=False, weights=&#39;imagenet&#39;)<br>     vgg.trainable = False<br>     ## Flatten the layer so that it&#39;s not nested in the sequential model.<br>     vgg_flat = flatten_model(vgg)<br>     ## Insert GAP<br>     vgg_flat.append(keras.layers.GlobalAveragePooling2D())<br>     vgg_flat.append(keras.layers.Dense(1, activation=&#39;sigmoid&#39;))<br>   <br>     model = keras.models.Sequential(vgg_flat)<br>     return model</pre><p>A simple utility flatten_model returns the list of layers in my pre-trained model. This is done so that the layers are not nested when modified using Sequential model and the last convolutional layer can be accessed and used as an output. I appended GlobalAveragePooling2D and Dense in the returned array from flatten_model. Finally, the Sequential model is returned.</p><pre>def flatten_model(model_nested):<br>    &#39;&#39;&#39;<br>    Utility to flatten pretrained model<br>    &#39;&#39;&#39;<br>    layers_flat = []<br>    for layer in model_nested.layers:<br>       try:<br>          layers_flat.extend(layer.layers)<br>       except AttributeError:<br>          layers_flat.append(layer)<br>      <br>    return layers_flat</pre><p>Next we call model.build() with the appropriate model input shape.</p><pre>keras.backend.clear_session()<br>model = CAMmodel()<br>model.build((None, None, None, 3)) # Note<br>model.summary()</pre><h4>Step 2: Retrain your model with CAMLogger callback</h4><p>Since a new layer was introduced, we have to retrain the model. But we don’t need to retrain the entire model. We can freeze the convolutional blocks by using vgg.trainable=False.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*mVbxn4u8MF86GpxgaTJE6g.png" /><figcaption>Figure 2: Metrics plot after retraining model.</figcaption></figure><p><strong>Observations:</strong></p><ul><li>There is a <strong>decline in the model performance</strong> in terms of both training and validation accuracy. The optimal train and validation accuracy that I achieved was 99.01% and 95.67% respectively.</li><li><strong>Thus for the implementation of CAM, we have to modify our architecture and thus a decline in model performance.</strong></li></ul><h4>Step 3: Use CAMLogger to see Class Activation Map</h4><p>In the __init__for the CAM class, we initialize cammodel. Notice there are two outputs from this cammodel:</p><ul><li>Output from the last convolutional layer (block5_conv3 here)</li><li>The model prediction (softmax/sigmoid).</li></ul><pre>class CAM:<br>  def __init__(self, model, layerName):<br>    self.model = model<br>    self.layerName = layerName<br>    ## Prepare cammodel<br>    last_conv_layer = self.model.get_layer(self.layerName).output<br>    self.cammodel = keras.models.Model(inputs=self.model.input,<br>                                       outputs=[last_conv_layer, self.model.output])<br>    <br>  def compute_heatmap(self, image, classIdx):<br>    ## Get the output of last conv layer and model prediction<br>    [conv_outputs, predictions] = self.cammodel.predict(image)<br>    conv_outputs = conv_outputs[0, :, :, :]<br>    conv_outputs = np.rollaxis(conv_outputs, 2)<br>    ## Get class weights between <br>    class_weights = self.model.layers[-1].get_weights()[0]<br>    ## Create the class activation map.<br>    caml = np.zeros(shape = conv_outputs.shape[1:3], dtype=np.float32)<br>    for i, w in enumerate(class_weights[:]):<br>      caml += w * conv_outputs[i, :, :]</pre><pre>    caml /= np.max(caml)<br>    caml = cv2.resize(caml, (image.shape[1], image.shape[2]))<br>    ## Prepare heat map<br>    heatmap = cv2.applyColorMap(np.uint8(255*caml), cv2.COLORMAP_JET)<br>    heatmap[np.where(caml &lt; 0.2)] = 0</pre><pre>    return heatmap<br>  def overlay_heatmap(self, heatmap, image):<br>    img = heatmap*0.5 + image<br>    img = img*255<br>    img = img.astype(&#39;uint8&#39;)<br>    return (heatmap, img)</pre><p>The compute_heatmap method is responsible for generating the heatmap which is the discriminative region used by CNN to identify the category (class of image).</p><ul><li>cammodel.predict() on the input image will give the feature map of the last convolutional layer of shape (1,7,7,512).</li><li>We also extract the weights of the output layer of shape (512,1).</li><li>Finally, the dot product of the extracted weights from the final layer and the feature map is calculated to produce the class activation map.</li></ul><p>Now we wrap everything in a callback. The CamLogger callback integrates wandb.log() method to log the generated activation maps onto the W&amp;B run page. The heatmap returned from the CAM is finally overlayed on the original image by calling overlay_heatmap() method.</p><h4>Step 4: Draw conclusions from the CAM</h4><p>We can draw lot of conclusions from the the plots as shown below. 👇 Note the examples chart contains validation images along with their prediction scores. If the prediction score is greater than 0.5, the network classifies the image as a dog, otherwise as a cat. While CAM charts have their corresponding class activation maps. Let&#39;s go through some observations:</p><ul><li>The model is classifying the images as dogs by looking at the facial region in the image. For some images it’s able to look at the entire body, except the paws.</li><li>The model is classifying the images as cats by looking at the ears, paws and whiskers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*jrcRwqLRID6NunkBhZI0gg.png" /><figcaption>Figure 3: Looking at dog’s face and cat’s whiskers, paws and ears.</figcaption></figure><ul><li>For a misclassified image the model is not looking at where it should be looking. <strong>Thus by using CAM we are able to interpret the reason behind this misclassification, which is really cool.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*vNPgqRWWQDHjT9goS_zNFw.png" /><figcaption>Figure 4: CNN was looking at something else.</figcaption></figure><p>Why is that? Even though the ears, paws and whiskers are present in the image why did it look at something else. One reason I can think of is that since we haven’t fine tuned our pretrained VGG16 on our cat-dog dataset, the CNN as feature extractor is not entirely familiar with the patterns (distributions) appearing in our dataset.</p><ul><li>When multiple instances of the same class are present in the image, the model looks only at one of them. But that is okay, given that we are not concerned about object detection. Note that the confidence is low because of this.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*dWDfYB3j5C-J4ciqXp2HKg.png" /><figcaption>Figure 5: Only looking at one occurrence.</figcaption></figure><p><strong>Other use cases:</strong></p><p>CAM can be used for a weakly supervised object localization task. The authors of the linked paper tested the ability of the CAM for a localization task on the ILSVRC 2014 benchmark dataset. The technique was able to achieve 37.1% top-5 error for object localization on this dataset, which is close to the 34.2% top-5 error achieved by a fully supervised CNN approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3GOWfjh_qNPIbhe0DE1HQ.png" /><figcaption>Figure 6: Some more examples. Click <a href="https://app.wandb.ai/ayush-thakur/interpretability/reports/Interpretability-in-Deep-Learning-with-W%26B-CAM-and-GradCAM--Vmlldzo5MTIyNw">here</a> for more such examples.</figcaption></figure><h3>Gradient-Weighted Class Activation Maps</h3><p><strong>Even though CAM was amazing it had some limitations:</strong></p><ul><li>The model needs to be modified in order to use CAM.</li><li>The modified model needs to be retrained, which is computationally expensive.</li><li>Since fully connected Dense layers are removed. the model performance will surely suffer. This means the prediction score doesn’t give the actual picture of the model’s ability.</li><li>The use case was bound by architectural constraints, i.e., architectures performing GAP over convolutional maps immediately before output layer.</li></ul><p><strong>What makes a good visual explanation?:</strong></p><ul><li>Certainly the technique should localize the class in the image. We saw this in CAM and it was worked remarkable good.</li><li>Finer details should be captured, i.e., the activation map should be high resolution.</li></ul><p>Thus the authors of <a href="https://arxiv.org/pdf/1610.02391.pdf">Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization</a>, a really amazing paper, came up with modifications to CAM and previous approaches. Their approach uses the gradients of any target prediction flowing into the final convolutional layer to produce a coarse localization map highlighting the important regions in the image for predicting the class of the image.</p><p>Thus Grad-CAM is a strict generalization over CAM. Beside overcoming the limitations of CAM it’s applicable to different deep learning tasks involving CNNs. It is applicable to:</p><ul><li>CNNs with fully-connected layers (e.g. VGG) without any modification to the network.</li><li>CNNs used for structured outputs like image captioning.</li><li>CNNs used in tasks with multi-modal inputs like visual Q&amp;A or reinforcement learning, without architectural changes or re-training.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*jeNioOxvury5V9Tn.png" /><figcaption><em>Figure 7: Grad-CAM overview (</em><a href="https://arxiv.org/pdf/1610.02391.pdf"><em>Source</em></a><em>)</em></figcaption></figure><p>Let’s implement this 😄</p><h4>Step 1: Your Deep Learning Task</h4><p>We will focus on the image classification task. Unlike CAM we don’t have to modify our model for this task and retrain it.</p><p>I have used a VGG16 model pretrained on ImageNet as my base model and I&#39;m simulating Transfer Learning with this.</p><p>The layers of the baseline model are turned to non-trainable by using vgg.trainable = False. Note how I have used fully connected layers in the model.</p><pre>def catdogmodel():<br>  inp = keras.layers.Input(shape=(224,224,3))<br>  vgg = tf.keras.applications.VGG16(include_top=False, weights=&#39;imagenet&#39;, input_tensor=inp,<br>                                            input_shape=(224,224,3))<br>  vgg.trainable = False<br>  <br>  x = vgg.get_layer(&#39;block5_pool&#39;).output<br>  x = tf.keras.layers.GlobalAveragePooling2D()(x)<br>  x = keras.layers.Dense(64, activation=&#39;relu&#39;)(x)<br>  output = keras.layers.Dense(1, activation=&#39;sigmoid&#39;)(x)</pre><pre>  model = tf.keras.models.Model(inputs = inp, outputs=output)<br>  <br>  return model</pre><p>You will find the class GradCAM in the <a href="https://github.com/ayulockin/interpretabilitycnn/">linked notebook</a>. This is a modified implementation from <a href="https://www.pyimagesearch.com/2020/03/09/grad-cam-visualize-class-activation-maps-with-keras-tensorflow-and-deep-learning/">Grad-CAM: Visualize class activation maps with Keras, TensorFlow, and Deep Learning</a>, an amazing blog post, by Adrian Rosebrook of PyImageSearch.com. I would highly suggest checking out the step by step implementation of the GradCAM class in that blog post.</p><p>I made two modifications to it:</p><ul><li>While doing transfer learning, that is, if your target (last) convolutional layer is non trainable, tape.gradient(loss, convOutputs) will return None. This is because tape.gradient() by default does not trace non-trainable variables/layers. Thus to use that layer for computing your gradients you need to allow GradientTape to watch it by calling tape.watch() on the target layer output (tensor). Hence the change,</li></ul><pre>with tf.GradientTape() as tape:<br>      tape.watch(self.gradModel.get_layer(self.layerName).output)<br>      inputs = tf.cast(image, tf.float32)<br>      (convOutputs, predictions) = self.gradModel(inputs)</pre><ul><li>The original implementation didn’t account for binary classification. The original authors also talked about softmax-ing the output. So in order to train a simple cat and dog classifier, I made a small modification. Hence the change,</li></ul><pre>if len(predictions)==1:<br>      # Binary Classification<br>      loss = predictions[0]<br>    else:<br>      loss = predictions[:, classIdx]</pre><p>The GRADCAM class can be used after the model is trained or as a callback. Here&#39;s a small excerpt from his blog post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*FoVXeEdOufHB5N46.png" /></figure><p>The third point motivated me to work on this project. I built a custom callback around this GRADCAM implementation and used wandb.log() to log the activation maps. Thus by using this callback you can use GradCAM while training.</p><h4>Step 3: Use GRADCamLogger and train</h4><p>Given we’re working with a simple dataset I have only trained for few epochs and the model seems to work well.</p><p><strong>Here’s the GradCAM custom callback.</strong></p><pre>class GRADCamLogger(tf.keras.callbacks.Callback):<br>    def __init__(self, validation_data, layer_name):<br>      super(GRADCamLogger, self).__init__()<br>      self.validation_data = validation_data<br>      self.layer_name = layer_name</pre><pre>    def on_epoch_end(self, logs, epoch):<br>      images = []<br>      grad_cam = []</pre><pre>      ## Initialize GRADCam Class<br>      cam = GradCAM(model, self.layer_name)</pre><pre>      for image in self.validation_data:<br>        image = np.expand_dims(image, 0)<br>        pred = model.predict(image)<br>        classIDx = np.argmax(pred[0])<br>  <br>        ## Compute Heatmap<br>        heatmap = cam.compute_heatmap(image, classIDx)<br>        <br>        image = image.reshape(image.shape[1:])<br>        image = image*255<br>        image = image.astype(np.uint8)</pre><pre>        ## Overlay heatmap on original image<br>        heatmap = cv2.resize(heatmap, (image.shape[0],image.shape[1]))<br>        (heatmap, output) = cam.overlay_heatmap(heatmap, image, alpha=0.5)</pre><pre>        images.append(image)<br>        grad_cam.append(output)</pre><pre>      wandb.log({&quot;images&quot;: [wandb.Image(image)<br>                            for image in images]})<br>      wandb.log({&quot;gradcam&quot;: [wandb.Image(cam)<br>                            for cam in grad_cam]})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*owrMTNburZCS9jklAIromw.png" /><figcaption>Figure 8: Metrics after training.</figcaption></figure><h4>Step 4: Draw conclusions from the GradCAM</h4><p>GradCAM being a strict generalization over CAM, should be preferred over CAM. To understand the theoretical underpinnings of this technique I recommend reading <a href="https://towardsdatascience.com/demystifying-convolutional-neural-networks-using-gradcam-554a85dd4e48">Demystifying Convolutional Neural Networks using GradCam</a> by Divyanshu Mishra or simply reading the linked paper. A couple interesting conclusions we can draw include:</p><ul><li>The model looks at the face of the dogs to classify them correctly, while I am unsure about the cat.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/0*Nc1UlMSZtayYPgO8.png" /><figcaption>Figure 8: Looking at dog’s face.</figcaption></figure><ul><li>The model is able to localize multiple instances of the class in an image, i.e. the prediction score is accounting for multiple dogs and cats in the image.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*iUJwQSU47cEUZ6OVSEkMTQ.png" /><figcaption>Figure 9: Looking at multiple occurrence.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xaAFU4WwUeiDbg4nGCt1g.png" /><figcaption>Figure 10: Some more examples. Click <a href="https://app.wandb.ai/ayush-thakur/interpretability/reports/Interpretability-in-Deep-Learning-with-W%26B-CAM-and-GradCAM--Vmlldzo5MTIyNw">here</a> for more such examples.</figcaption></figure><h3>Conclusion</h3><p><strong>Class Activation Maps</strong> and <strong>Grad-CAMs</strong> are a few approaches that introduce some explainability/interpretability into deep learning models, and are quite widely used. What’s most fascinating about these techniques is the ability to perform the object localization task, even without training the model with a location prior. GradCAM, when used for image captioning, can help us understand what region in the image is used to generate a certain word. When used for a Visual Q&amp;A task, it can help us understand why the model came to a particular answer. Even though Grad-CAM is class-discriminative and localizes the relevant image regions, it lacks the ability to highlight fine-grained details the way pixel-space gradient visualization methods like Guided backpropagation, and Deconvolution do. Thus the authors combined Grad-CAM with Guided backpropagation.</p><p>Thanks for reading this report until the end. I hope you find the callbacks introduced here helpful for your deep learning wizardry. Please feel free to reach out to me on Twitter(<a href="https://twitter.com/ayushthakur0">@ayushthakur0</a>) for any feedback on this report. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45ba5296a58a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/interpretability-in-deep-learning-with-w-b-cam-and-gradcam-45ba5296a58a">Interpretability in Deep Learning with W&amp;B — CAM and GradCAM</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging Neural Networks with PyTorch and W&B]]></title>
            <link>https://medium.com/data-science/debugging-neural-networks-with-pytorch-and-w-b-2e20667baf72?source=rss-568907d77025------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e20667baf72</guid>
            <category><![CDATA[production-ml]]></category>
            <category><![CDATA[wandb]]></category>
            <dc:creator><![CDATA[Ayush Thakur]]></dc:creator>
            <pubDate>Thu, 14 May 2020 14:18:36 GMT</pubDate>
            <atom:updated>2020-05-14T14:18:36.172Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/production-ml">Machine Learning in Production</a></h4><h4>Tips and tricks to debug your neural network</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EqL6EpTdqb81f4VN" /><figcaption>Photo by <a href="https://unsplash.com/@efekurnaz?utm_source=medium&amp;utm_medium=referral">Efe Kurnaz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>View interactive report <a href="https://app.wandb.ai/ayush-thakur/debug-neural-nets/reports/Visualizing-and-Debugging-Neural-Networks-with-PyTorch-and-W%26B--Vmlldzo2OTUzNA?utm_source=tds&amp;utm_medium=report&amp;utm_campaign=report_author">here</a>. All the code is available <a href="https://github.com/ayulockin/debugNNwithWandB">here</a>.</h4><p>In this post, we’ll see what makes a neural network under perform and ways we can debug this by visualizing the gradients and other parameters associated with model training. We’ll also discuss the problem of vanishing and exploding gradients and methods to overcome them.</p><p>Finally, we’ll see why proper weight initialization is useful, how to do it correctly, and dive into how regularization methods like dropout and batch normalization affect model performance.</p><h4>Where do neural network bugs come from?</h4><p>As shown in this <a href="https://medium.com/@keeper6928/how-to-unit-test-machine-learning-code-57cf6fd81765">piece</a>, neural network bugs are really hard to catch because:</p><p>1. The code never crashes, raises an exception, or even slows down.<br>2. The network still trains and the loss will still go down.<br>3. The values converge after a few hours, but to really poor results</p><p>I highly recommend reading <a href="http://karpathy.github.io/2019/04/25/recipe/">A Recipe for Training Neural Networks</a> by Andrej Karparthy if you’d like to dive deeper into this topic.</p><p>There is no decisive set of steps to be followed while debugging neural networks. But here is a list of concepts that, if implemented properly, can help debug your neural networks.</p><h4>So how can we debug our neural networks better?</h4><p>There is no decisive set of steps to be followed while debugging neural networks. But here is a list of concepts that, if implemented properly, can help debug your neural networks.</p><h4>Model Inputs</h4><p><strong><em>1. Decisions about data:</em></strong><em> </em>We must understand the nuances of data — the type of data, the way it is stored, class balances for targets and features, value scale consistency of data, etc.</p><p><strong><em>2. Data Preprocessing</em>:</strong> We must think about data preprocessing and try to incorporate domain knowledge into it. There are usually two occasions when data preprocessing is used:</p><ul><li><em>Data cleaning</em>: The objective task can be achieved easily if some parts of the data, known as artifacts, is removed.</li><li><em>Data augmentation</em>: When we have limited training data, we transform each data sample in numerous ways to be used for training the model (example scaling, shifting, rotating images).<br>This post is not focusing on the issues caused by bad data preprocessing.</li></ul><p><strong><em>3. Overfitting on a small dataset:</em></strong><em> </em>If we have a small dataset of 50–60 data samples, the model will overfit quickly i.e., the loss will be zero in 2–5 epochs. To overcome this, be sure to remove any regularization from the model. If your model is not overfitting, it might be because might be your model is not architected correctly or the choice of your loss is incorrect. Maybe your output layer is activated with sigmoid while you were trying to do multi-class classification. These errors can be easy to miss error. Check out my notebook demonstrating this <a href="https://github.com/ayulockin/debugNNwithWandB/blob/master/MNIST_pytorch_wandb_Overfit_Small.ipynb">here</a>.</p><p>So how can one avoid such errors? Keep reading.</p><h4>Model architecture</h4><p><strong><em>1. Start with a small architecture:</em></strong> Using fancy regularizers and schedulers may be overkill. In case of an error, it’s easier to debug a small network. Common errors include forgetting to pass tensors from one layer to another, have insane input to output neurons ratio, etc.</p><p><strong><em>2. Pretrained model(weights):</em></strong> If your model architecture is built on top of a standard backbone like VGG, Resnet, Inception, etc you can use pre-trained weights on a standard dataset — if you can, find one on the dataset that you are working with. One interesting recent paper, <a href="https://arxiv.org/abs/1902.07208">Transfusion: Understanding Transfer Learning for Medical Imaging</a> shows that using even a few early layers from a pre-trained ImageNet model can improve both the speed of training and final accuracy of medical imaging models. Therefore, you should use a general-purpose pre-trained model, even if it is not in the domain of the problem you’re solving. The amount of improvement from an ImageNet pre-trained model when applied to medical imaging is not that great. Thus there isn’t much guarantee on a head start either. For more, I recommend reading this amazing <a href="https://www.fast.ai/2020/01/13/self_supervised/">blog</a> post by Jeremy Howard.</p><h4>‍Loss</h4><p><strong><em>1. Choosing the right loss function</em>: </strong>First, make sure that you are using the right loss function for the given task. For a multi-class classifier, a binary loss function will not help improve the accuracy, so categorical cross-entropy is the right choice.</p><p><strong><em>2. Determine theoretical loss</em>: </strong>If your model started by guessing randomly (i.e. no pretrained model), check to see if the initial loss is close to your expected loss. If you’re using cross-entropy loss, check to see that your initial loss is approximately -log(1/num_classes. You can get some more suggestions <a href="http://cs231n.github.io/neural-networks-3/#loss">here</a>.</p><p><strong><em>3. Learning Rate</em>: </strong>This parameter determines the step size at each iteration while moving toward the minimum of a loss function. You can tweak the learning rate according to how steep or smooth your loss function is. But this can be a time and resource consuming step. Can you find the most optimal learning rate, automatically?</p><p>Leslie N. Smith presented a very smart and simple approach to systematically find a learning rate in a short amount of time and minimal resources. All you need is a model and a training set. The model is initialized with a small learning rate and trained on a batch of data. The associated loss and learning rate is saved. The learning rate is then increased, either linearly or exponentially, and the model is updated with this learning rate.</p><p>In <a href="https://github.com/ayulockin/debugNNwithWandB/blob/master/MNIST_pytorch_wandb_LRFinder.ipynb">this notebook</a>, you’ll find an implementation of this approach in PyTorch. I have implemented a class LRfinder. The method range_test holds the logic described above. Using wandb.log()I was able to log the learning rate and corresponding loss.</p><pre>if logwandb:<br>  wandb.log({&#39;lr&#39;: lr_schedule.get_lr()[0], &#39;loss&#39;: loss})</pre><p>Use this LRFinder to automatically find the optimal learning rate for your model.</p><pre>lr_finder = LRFinder(net, optimizer, device)<br><br>lr_finder.range_test(trainloader, end_lr=10, num_iter=100, logwandb=True)</pre><p>You can now head to your W&amp;B run page and find the minima of the LR curve. Use this as your learning rate and train on the entire batch of training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TviEWyjAv54YvfjQ.png" /><figcaption>Fig 1: Result of LRFinder. Captured from <a href="https://app.wandb.ai/ayush-thakur/debug-neural-nets?workspace=user-ayush-thakur">here</a>.</figcaption></figure><p>When the learning rate is too low the model is not able to learn anything and it remains plateaued. When the learning rate is just large enough it starts learning and you will find a sudden dip in the plot. The minima of the curve is what you are looking for as the optimal learning rate. When the learning rate is high the loss explodes i.e. sudden jump in loss.</p><p>If you are using Keras to build your model you can make use of the <strong>learning rate finder</strong> as demonstrated in this <a href="https://www.pyimagesearch.com/2019/08/05/keras-learning-rate-finder/">blog</a> by <a href="https://www.pyimagesearch.com/">PyImageSearch</a>. You can also refer this <a href="https://mc.ai/how-to-find-a-descent-learning-rate-using-tensorflow-2/">blog</a> for an implementation in TensorFlow 2.0.</p><h4>Activation Function</h4><p><strong>1. Problem of the vanishing gradients:</strong> There was a major problem 10 years ago in training a deep neural network due to the use of sigmoid/tanh activation functions. To understand this problem the reader is expected to have an understanding of feed forward and back propagation algorithms along with gradient-based optimization. I recommend that you watch this <a href="https://www.youtube.com/watch?v=JIWXbzRXk1I&amp;t=312s">video</a> or read this <a href="https://ayearofai.com/rohan-4-the-vanishing-gradient-problem-ec68f76ffb9b">blog </a>for a better understanding of this problem.</p><p>In a nutshell, when back propagation is performed, the gradient of the loss with respect to weights of each layer is calculated and it tends to get smaller as we keep on moving backwards in the network. The gradient for each layer can be computed using the chain rule of differentiation. Since the derivative of sigmoid ranges only from 0–0.25 numerically the gradient computed is really small and thus negligible weight updates take place. Due to this problem, the model could not converge or it would take a long time to do so.</p><p>Suppose you are building a not so traditional neural network architecture. The easiest way to debug such a network is to visualize the gradients. If you are building your network using PyTorch W&amp;B automatically plots gradients for each layer. Check out my notebook <a href="https://github.com/ayulockin/debugNNwithWandB/blob/master/MNIST_pytorch_wandb_Vanishing_Gradient.ipynb">here</a>.</p><p>You can find two models, NetwithIssueand Netin the notebook. The first model uses sigmoid as an activation function for each layer. The latter uses ReLU. The last layer in both the models uses a softmaxactivation function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89cfc5e8275da9069e19ccd881086735/href">https://medium.com/media/89cfc5e8275da9069e19ccd881086735/href</a></iframe><p>W&amp;B provides first class support for PyTorch. To automatically log gradients and store the network topology, you can call watch and pass in your PyTorch model. If you want to log histograms of parameter values as well, you can pass log=&#39;all&#39;argument to the watch method.</p><p>In the W&amp;B project page look for the gradient plot in Vanishing_Grad_1, VG_Converge and VG_solved_Relu the run page. To do so click on the run name and then click on the Gradient section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_bdsIrEeR_cdJ0nG.png" /><figcaption>Fig 2: VG_Converge gradient plot. captured from <a href="https://app.wandb.ai/ayush-thakur/debug-neural-nets/runs/neo43xm0">here</a>.</figcaption></figure><p>In this run the model was trained for 40 epochs on MNIST handwritten dataset. It eventually converged with a train-test accuracy of over 80%. You can notice a zero gradient for most of the epochs.</p><p>2. <strong>Dead ReLU: </strong>ReLUs aren’t a magic bullet since they can “die” when fed with values less than zero. A large chunk of the network might stop learning if most of the neurons die within a short period of training. In such a situation, take a closer look at your initial weights or add a small initial bias to your weights. If that doesn’t work, you can try to experiment with Maxout, Leaky ReLUs and ReLU6 as illustrated in the MobileNetV2 paper.</p><p>3. <strong>Problem of exploding gradients: </strong>This problem occurs when the later layers learn slower compared to the initial layers, unlike the vanishing gradient problem where earlier layers learn slower than the later layers. This problem occurs when the gradient grows exponentially as we move backwards through the layers. Practically, when gradients explode, the gradients could become NaN because of the numerical overflow or we might see irregular oscillations in the training loss curve. In the case of vanishing gradients, the weight updates are very small while in case of exploding gradients these updates are huge because of which the local minima is missed and models do not converge. You can watch this <a href="https://www.youtube.com/watch?v=IJ9atfxFjOQ&amp;t=12s">video</a> for a better understanding of this problem or go through this <a href="http://neuralnetworksanddeeplearning.com/chap5.html">blog</a>.</p><p>Let’s try to visualize the gradients in case of the exploding gradients. Check out this notebook <a href="https://github.com/ayulockin/debugNNwithWandB/blob/master/MNIST_pytorch_wandb_Exploding_Gradient.ipynb">here</a> where I intentionally initialized the weights with a big value of 100, such that they would explode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*5wG522ffHXlIy9fjh7JEdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BtiYGQGcvHsGnnRY.png" /><figcaption>Fig 3: Demonstrating Exploding gradient. Captured from <a href="https://app.wandb.ai/ayush-thakur/debug-neural-nets/runs/7gygoykn?workspace=user-ayush-thakur">here</a>.</figcaption></figure><p>Notice how the gradients are increasing exponentially going backward. The gradient value for conv1 is in the order of 10⁷ while for conv2 is 10⁵. Bad weight initialization can be one reason for this problem.</p><p>Exploding gradients are not usually encountered in the case of CNN based architectures. They’re more of a problem for Recurrent NNs. Check out this <a href="https://www.quora.com/Why-are-the-exploding-gradient-problems-mostly-encountered-in-recurrent-neural-networks">thread</a> for more insight. Due to numerical instability caused by exploding gradient you may get NaN as your loss. This notebook <a href="https://github.com/ayulockin/debugNNwithWandB/blob/master/Pytorch_wandb_Exploding_Gradient_NaN.ipynb">here</a> demonstrates this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/0*CRVYoG-fKANVc4QH.png" /><figcaption>Fig 4: NaN loss.</figcaption></figure><p>There are two simple ways around this problem. They are:</p><p>1. Gradient Scaling<br>2. Gradient Clipping</p><p>I used Gradient Clipping to overcome this problem in the <a href="https://github.com/ayulockin/debugNNwithWandB/blob/master/Pytorch_wandb_Exploding_Gradient_NaN.ipynb">linked notebook</a>. Gradient clipping will ‘clip’ the gradients or cap them to a threshold value to prevent the gradients from getting too large. In PyTorch you can do this with one line of code.</p><pre>torch.nn.utils.clip_grad_norm_(model.parameters(), 4.0)</pre><p>Here 4.0 is the threshold. This value worked for my demo use case. Check out the trainModified function in the notebook to see the implementation.</p><h4>Weights Initialization and other Regularizations</h4><p><strong>1. Weight Initialization: </strong>This is one of the most important aspects of training a neural network. Problems like image classification, sentiment analysis or playing Go can’t be solved using deterministic algorithms. You need a non deterministic algorithm to solve such problems. These algorithms use elements of randomness when making decisions during the execution of the algorithm. These algorithms make careful use of randomness. Artificial neural networks are trained using a stochastic optimization algorithm called stochastic gradient descent. Training a neural network is simply a non deterministic search for a ‘good’ solution.</p><p>As the search process (training) unfolds, there is a risk that we are stuck in an unfavorable area of the search space. The idea of getting stuck and returning a ‘less-good’ solution is called being getting stuck in a local optima. At times vanishing/exploding gradients prevent the network from learning. To counter this weight initialization is one method of introducing careful randomness into the searching problem. This randomness is introduced in the beginning. Using mini-batches for training with shuffle=True is another method of introducing randomness during progression of search. For more clarity of the underlying concept check out this <a href="https://machinelearningmastery.com/why-initialize-a-neural-network-with-random-weights/">blog</a>.</p><p>A good initialization has many benefits. It helps the network achieve global minima for gradient based optimization algorithms (just a piece of the puzzle). It prevents vanishing/exploding gradient problems. A good initialization can speed up training time as well. This blog <a href="https://towardsdatascience.com/weight-initialization-in-neural-networks-a-journey-from-the-basics-to-kaiming-954fb9b47c79">here</a> explains the basic idea behind weight initialization well.</p><p>The choice of your initialization method depends on your activation function. To learn more about initialization check out this <a href="https://www.deeplearning.ai/ai-notes/initialization/">article</a>.</p><ul><li>When using ReLU or leaky ReLU, use He initialization also called Kaiming initialization.</li><li>When using SELU or ELU, use LeCun initialization.</li><li>When using softmax or tanh, use Glorot initialization also called Xavier initialization.</li></ul><p>Most initialization methods come in uniform and normal distribution flavors. Check out this PyTorch <a href="https://pytorch.org/docs/stable/nn.init.html?highlight=nn%20init#torch.nn.init.zeros_">doc</a> for more info.</p><p>Check out my notebook <a href="https://github.com/ayulockin/debugNNwithWandB/blob/master/Cifar10_pytorch_wandb_Wt_Init.ipynb">here</a> to see how you can initialize weights in PyTorch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*9l_-jxoH-kH-bt7EXs5GyA.png" /></figure><p>Notice how the layers were initialized with kaiming_uniform. You’ll notice this model overfits. By simplifying the model you can easily overcome this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cgNT7_xNNhaIyi7p.png" /><figcaption>Fig 5: Model trained with better weight initialization. Captured from <a href="https://app.wandb.ai/ayush-thakur/debug-neural-nets/runs/2a5qddz3?workspace=user-ayush-thakur">here</a>.</figcaption></figure><p><strong>2. Dropout and Batch Normalization: </strong>Dropout is a regularization technique that “drops out” or “deactivates” a few neurons in the neural network randomly, in order to avoid the problem of overfitting. During training some neurons in the layer after which the dropout is applied are “turned off”. An ensemble of neural networks with fewer parameters (simpler model) reduces overfitting. Dropout simulates this phenomenon, contrary to snapshot ensembles of networks, without additional computational expense of training and maintaining multiple models. It introduces noise into a neural network to force it to learn to generalize well enough to deal with noise.</p><p>Batch Normalization is a technique to improve optimization. It’s a good practice to normalize the input data before training on it which prevents the learning algorithm from oscillating. We can say that the output of one layer is the input to the next layer. If this output can be normalized before being used as the input the learning process can be stabilized. This dramatically reduces the number of training epochs required to train deep networks. Batch Normalization makes normalization a part of the model architecture and is performed on mini-batches while training. Batch Normalization also allows the use of much higher learning rates and for us to be less careful about initialization.</p><p>Let’s implement the above discussed concepts and see the results. Check out my notebook <a href="https://github.com/ayulockin/debugNNwithWandB/blob/master/Cifar10_pytorch_wandb_Dropout_BN.ipynb">here</a> to see how one can use Batch Normalization and Dropout in Pytorch. I started with a base model to set the benchmark for this study. The implemented architecture is simple and results in overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*WfQ-RfvohwkfWjsrPW8vcw.png" /><figcaption>Fig 6: Notice how test loss increases eventually. Captured from <a href="https://app.wandb.ai/ayush-thakur/debug-neural-nets/runs/dxdz06vk">here</a>.</figcaption></figure><p>Notice how test loss increases eventually. I then applied Dropout layers with a drop rate of 0.5 after Conv blocks. To initialize this layer in PyTorch simply call the Dropout method of torch.nn.</p><pre>self.drop = torch.nn.Dropout()</pre><p>Dropout prevented overfitting but the model didn’t converge quickly as expected. This means that ensemble networks take longer to learn. In the context of dropout not every neuron is available while learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x-6VRXjYaNYG7Ax4.png" /><figcaption>Fig 7: Loss and Metric plot using dropout as regularizer. Captured from <a href="https://app.wandb.ai/ayush-thakur/debug-neural-nets/runs/tlf4e8fm">here</a>.</figcaption></figure><p>Next up is Batch Normalization. To initialize this layer in PyTorch simply call the BatchNorm2d method of torch.nn.</p><pre>self.bn = torch.nn.BatchNorm2d(32)</pre><p>Batch Normalization took fewer steps to converge the model. Since the model was simple, overfitting could not be avoided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KRyk_p0yAKlCcGg2.png" /><figcaption>Fig 8: Loss and Metric plot using Batch Normalization. Captured from <a href="https://app.wandb.ai/ayush-thakur/debug-neural-nets/runs/pntlvpic">here</a>.</figcaption></figure><p>Now let’s use both these layers together. If you are using BN and Dropout together follow this order (for more insight check out <a href="https://arxiv.org/abs/1801.05134">this</a> paper).</p><pre>CONV/FC -&gt; BatchNorm -&gt; ReLU(or other activation) -&gt; Dropout -&gt; CONV/FC</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1OhB7E2HSSL3wjXv.png" /><figcaption>Fig 9: Loss and Metric plot using Batch Normalization and Dropout. Captured from <a href="https://app.wandb.ai/ayush-thakur/debug-neural-nets/runs/1e5c7bk2">here</a>.</figcaption></figure><p>Notice that by using both Dropout and Batch Normalization overfitting was eliminated while the model converged quicker.</p><p>When you have a large dataset, it’s important to optimize well, and not as important to regularize well, so batch normalization is more important for large datasets. You can of course use both batch normalization and dropout at the same time, though Batch Normalization also acts as a regularizer, in some cases eliminating the need for Dropout.</p><h3>Notes</h3><ol><li>The article <a href="https://towardsdatascience.com/checklist-for-debugging-neural-networks-d8b2a9434f21">Checklist for debugging neural networks</a> would be a good next step.</li><li>Unit testing neural networks is not easy. This article discusses <a href="https://medium.com/@keeper6928/how-to-unit-test-machine-learning-code-57cf6fd81765">How to unit test machine learning code</a></li><li>I highly recommend reading <a href="http://neuralnetworksanddeeplearning.com/chap5.html">Why are deep neural networks hard to train?</a></li><li>For a more in depth explanation on gradient clipping check out <a href="https://machinelearningmastery.com/how-to-avoid-exploding-gradients-in-neural-networks-with-gradient-clipping/">how to avoid exploding gradients in neural networks with gradient clipping?</a></li><li><a href="https://www.wandb.com/articles/the-effects-of-weight-initialization-on-neural-nets">The effects of weight initialization on neural nets</a> by Sayak Paul, where he discusses in depth the different effects of weight initialization.</li></ol><p>I hope that this blog will be helpful for everyone in the Machine Learning community. I’ve tried to share some insights of my own and lots of good reading material for deeper understanding of the topics. The most important aspect of debugging neural network is to track your experiments so you can reproduce them later. Weight and Biases is really handy when it comes to tracking your experiments. With all the latest ways to visualize your experiments, it’s getting easier day by day.</p><p>I would like to thank Lavanya for the opportunity. I learned a lot in the process. Thank you <a href="https://sayak.dev/">Sayak Paul</a> for the constant mentoring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e20667baf72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/debugging-neural-networks-with-pytorch-and-w-b-2e20667baf72">Debugging Neural Networks with PyTorch and W&amp;B</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting FC Layers to Conv Layers]]></title>
            <link>https://mein2work.medium.com/converting-fc-layers-to-conv-layers-8a43880a44ed?source=rss-568907d77025------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a43880a44ed</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[semantic-segmentation]]></category>
            <dc:creator><![CDATA[Ayush Thakur]]></dc:creator>
            <pubDate>Thu, 04 Jul 2019 17:59:33 GMT</pubDate>
            <atom:updated>2019-07-04T17:59:33.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5QqP2nrC4J9GpRKK" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Motivation</h4><blockquote>Technology is remarkable when it inspires other technologies. The field of computer vision has done this time and again. The simple idea of convolving a 2D data like image with another 2D matrix called kernel with some stride and padding changed computer vision forever and opened so many new possibilities.</blockquote><p>One such possibility is for the computers to understand what’s there in an image or scene or frame. CNN revolutionized image classification task. But their power lies in the fact that they can sustain spatial information, unlike a dense neural network. The spatial information can thus be modified, manipulated and interpolated by computers to understand more from an image and not just classify.</p><p>Semantic Segmentation is one such aspect of computer vision and image processing in general whereby every pixel has a story to convey. We humans can judge and infer so many spatial information by looking at an image. The possibilities offered by semantic segmentation opened this door for computers too, thus advancements in technologies like autonomous vehicles.</p><h4>Image Classification Way to Semantic Segmentation</h4><p>One of the key ideas which you will come across when learning semantic segmentation is <strong>Fully Convolutional Network</strong>. In image classification task convolution blocks are usually flattened and then few layers of fully connected network end up to give classification results. But the retained spatial information got lost. In the case of classification, the convolution operation is done to reduce the numbers of features to be fed to a dense fully connected network. Another way to say this is Convolution operation downsamples a 2D data like image. But as mentioned above spatial information can be used to get more insights, which we are loosing by FC layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*spdVni4mHfVw_NakGrGUeQ.png" /><figcaption>CNN architecture for image classification task.</figcaption></figure><p>Convolution Neural Network for Image Classification is usually termed standard convolution or vanilla convolution or simply CNN. <a href="https://towardsdatascience.com/covolutional-neural-network-cb0883dd6529">Here’s a nice blog to understand the underlying principles of CNN</a>.</p><p>You can also find my implementation of Image Classification using CNN <a href="https://www.kaggle.com/ayuraj/asl-training">here</a>.</p><h4>Fully Connected to Fully Convolutional Network</h4><p>Thus Fully Connected network or FC layer has to be converted to an equivalent Conv layer. Let’s see what happens after one convolution operation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fi4NjAwytgIRDW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fblog-daniel-keypoints-i4NjAwytgIRDW&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeWFheHN2ZGNwZWpibTRkb2trNHh2dWs0bjA1bmZrbDlkaHgydTRyMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fi4NjAwytgIRDW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="318" frameborder="0" scrolling="no"><a href="https://medium.com/media/8074a1c07c881669b0b7278b6996ddd9/href">https://medium.com/media/8074a1c07c881669b0b7278b6996ddd9/href</a></iframe><p>Here, an input volume of shape (5x5x3) is convolved with a kernel of size (3x3) with zero padded input and stride of one. The resulting output volume is of shape (3x3x20), assuming 20 filters were used. Thus an image is downsampled while spatial information is retained.</p><p>The resulting output volume can be given by this formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*OfgHab16_jbjoFZoNSftQg.png" /></figure><blockquote>It is worth noting that the only difference between FC and CONV layers is that the neurons in the CONV layer are connected only to a local region in the input and that many of the neurons in a CONV volume share parameters. However, the neurons in both layers still compute dot products, so their functional form is identical.</blockquote><p>Thus to convert an FC layer Conv layer set the filter size(n) to be exactly the size of the input volume, and hence the output will be equivalent to a FC layer. To understand this let’s see a practical utility.</p><h4>Understand with Example</h4><p>Let’s take a sequential VGG16 network pretrained on images of shape (224x224x3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*sl_b_fu1TYtnSKdSBi00YA.png" /><figcaption>Import, Load Model, Model Summary</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*R7ehwPEY9101wzLpQuiudA.png" /><figcaption>CNN or standard CNN architecture</figcaption></figure><p>As we can see that the last three layers are fully connected (FC) layers, namely ‘fc1’, ‘fc2’, ‘predictions’. The input shape is (224,224,3) which got downsampled to (7,7,512) convolutional feature volume by a sequence of convolution, activation and pooling. They are flattened by a layer named ‘flattened’. The stored spatial information gets destroyed at this layer.</p><p>Let us take a convolutional layer which outputs a volume of size <em>7×7×512</em> and this is followed by a FC layer with 4096 neurons i.e. the output of the FC layers is 1x4096 for single image input. This can be equivalently expressed as a Conv layer with f=7, p=0, s=1 and nc=4096. You can do the maths. We end up with a volume of shape 1x1x4096. Likewise other two FC layers can be converted to equivalent Conv layers.</p><h4>Build Fully Convolution Network</h4><p>A fully convolution network can be built by simply replacing the FC layers with there equivalent Conv layers. In the example of VGG16 we can do so by first removing the last four layers. One way to do so is to pop layers from the model. In the model stack, each popping will remove the last layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*r2Hwik1jED1rOJpgAoLdwg.png" /><figcaption>Pop FC layers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*NYaFc6nBmWWcvRGpsAPSIQ.png" /><figcaption>CNN architecture without FC layers.</figcaption></figure><p>In order to add the equivalent layers we can use Keras functional model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dE5n4fRtsngC4xWnAt-KXA.png" /><figcaption>Fully convolutional network from VGG16.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*Mn2_biTqLqcCQx-mp0Q2Xw.png" /><figcaption>Model summary of FCN</figcaption></figure><p>We can observe that the total number of parameters still remain the same as in VGG16.</p><h4>Conclusion</h4><p>This blog talks about the essence of fully convolution network without going into many details. Also, the aim was to implement the same. Semantic Segmentation with FCN will be the followup blog. Thus having an understanding of FCN and how to actually implement it we can move forward to having a better understanding of semantic segmentation and it’s implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a43880a44ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using CNN to translate American Sign Language]]></title>
            <link>https://mein2work.medium.com/using-cnn-to-translate-american-sign-language-10d6443f7cd?source=rss-568907d77025------2</link>
            <guid isPermaLink="false">https://medium.com/p/10d6443f7cd</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ayush Thakur]]></dc:creator>
            <pubDate>Thu, 27 Jun 2019 06:44:56 GMT</pubDate>
            <atom:updated>2019-06-27T08:33:26.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>Translate American Sign Language Using CNN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mjwAO8IzSOnqKKbi" /><figcaption>Photo by <a href="https://unsplash.com/@andreilazarev?utm_source=medium&amp;utm_medium=referral">Andrei Lazarev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sign languages are languages that use the visual-manual modality to convey meaning. Sign languages are expressed through manual articulations in combination with non-manual elements. American Sign Language or ASL is one such sign language that serves as the predominant sign language of deaf communities in the United States and most of Anglophone Canada. Sign languages are full-fledged natural languages with their own grammar and lexicon. But since sign languages are not universal they are used in a limited population of trained professionals and users of the same.</p><h3>Defining The Problem</h3><p>Sign language can be understood by masses if an accurate translation of the same can be made possible. We can understand Chinese if translated into native languages like Hindi or English. The same is true for sign language. In order to do so following steps can be followed:</p><ol><li><strong>Capture the hand sign of the user</strong>: This can be done by recording the user and taking out each frame sequentially where the hand sign changed. This can be achieved by traditional image processing algorithms.</li><li><strong>Translate the hand sign to the corresponding character of the desired language</strong>: The translation here is actually an image classification task. Thus the frame(image) must be classified to its correct alphabet. This classification can be done by building a robust and accurate classifier.</li></ol><p>Convolution Neural Network is widely used for the image classification task.</p><h3>Data Preprocessing</h3><p>To build a classifier using deep learning approach we require a decent amount of data. The problem can be solved using a supervised learning approach for which labelled dataset is required. Labelled data typically takes a set of unlabeled data and augments each piece of that unlabeled data with some sort of meaningful “tag,” “label,” or “class” that is somehow informative or desirable to know. For our problem, the data is the image of a hand sign and the label is the English alphabet it belongs to.</p><p>The data that I used can be found <a href="https://www.kaggle.com/ayuraj/asl-dataset">here</a>. This particular dataset contains only 2,520 labelled images. But the kind of accuracy that I desired required more data. One way to do so is data augmentation. The traditional image processing algorithms that I used to get more data are:</p><ol><li><strong>Mirroring</strong>: The idea is to simply flip the image along a vertical axis passing through the center of the image.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwXxdEYhAvHGP2oedjGUuQ.jpeg" /><figcaption>ASL for ‘g’ and it’s mirrored image.</figcaption></figure><p>2. <strong>Rotating: </strong>This is one of the widely used data augmentation technique where the original image is rotated at some angle. Each generated image similar to us humans but are unique to the model to be trained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ue3KcldEHf-idQ8dgUFgPA.jpeg" /><figcaption>ASL for ‘d’ rotated at 0, 15, 30 and -15 degrees.</figcaption></figure><p>The final dataset can be found <a href="https://www.kaggle.com/ayuraj/american-sign-language-dataset#asl.zip">here</a>. After augmenting this dataset contains over 25,200 labelled data.</p><h3>The CNN architecture(Network Topology)</h3><p>After defining the problem and collecting the data(The data is clean, thus no further preprocessing is required) the task at hand is to actually build a multi class image classifier. I used Keras to do the job(Choose the framework of your liking).</p><h4>Data Loading, Reshaping and Splitting</h4><p>The first task at hand is to simply load data into memory. I applied a simple naive approach whereby I loaded complete data into memory. But it will suffice given that the data is not that huge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9YOTl3C4xHOhVyHpEK79w.png" /><figcaption>A simple approach to load data.</figcaption></figure><p>I used OpenCV to load and resize the image. Used keras.utils.to_categorical to one-hot encode labels. Using sklearn.utils.shuffle function to shuffle the dataset. This is especially required when the data-label is in order. Following the standard procedure of train-test split, I used sklearn.model_selection.train_test_split to perform the split giving 5% of dataset as a test set.</p><p>In case of a huge dataset, one can write a script to manually load batches of data or simply use ImageDataGenerator class provided by Keras followed by fit_generator, evaluate_generator and predict_generator. You can go through this awesome <a href="https://machinelearningmastery.com/how-to-load-large-datasets-from-directories-for-deep-learning-with-keras/">post</a> to learn more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*y7S0vHu2944JlIHIUOFMUw.png" /><figcaption>Image data along with their labels</figcaption></figure><h4>Model</h4><p>Now it’s time to define the CNN architecture to perform multi class classification. I used the standard CNN approach of Convolution Layer and Maxpooling followed by a few layers of Fully Connected Layers. A dropout layer was applied so that the model explores more possibilities and not rely on just a few nodes to perform classification. Every learn-able layer was relu activated except the output layer which has softmax activation. One can think of applying residual network or depth-wise separable convolution network but they will be an overkill for this simple dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynH5UXs-gxTYqzZ1pwA0Cw.png" /><figcaption>Standard CNN architecture</figcaption></figure><p>By using model.summary() we can get the summary report of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZDSnCtBGWGBlkN_TAfFQg.png" /><figcaption>Summary report</figcaption></figure><p>There are a total of 14 trainable layers. The report show layer names, the shape of the layers and the number of parameters to be learned.</p><h4>Training</h4><p>Using Keras API the standard procedure is to first compile the model and then fit the model to the input data. In the case of multi-class classification use categorical_crossentropy loss. I used adam optimizer and selected accuracy as the metric to be evaluated while training and testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzQbwUXaYURnAugw0hw8Xg.png" /><figcaption>Use this to set objective function, loss, metrics etc</figcaption></figure><p>The model was fit using the split dataset we created before. Mini-batch approach of training was considered for faster learning and better memory usage. I used the basic history callback which returns the metrics like accuracy and loss per epoch. This can be used to plot accuracy vs epoch and loss vs epoch graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_bKh1kou4UVVwZuRx2E-Q.png" /><figcaption>Use this to fit the training data to the model with various tune-able parameters.</figcaption></figure><p>Using this simple CNN based classifier I was able to achieve over 98% accuracy with just 15 epoch. Too many epochs can lead to overfitting of the training dataset, whereas too few may result in an underfit model. Using keras.callbacks.EarlyStopping you can specify an arbitrarily large number of training epochs. Using this method training stops once the model performance stops improving on a hold out validation dataset. I leave this up to your experimentation. I was satisfied with over 98% accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEAcZDo3sL5iHSHgOoasFw.png" /><figcaption>Training report</figcaption></figure><h4>Graphs and Prediction</h4><p>It’s best to visualize the metrics like accuracy and loss. The accuracy should increase with increasing epoch while the loss/cost must decrease. It’s always pleasing to look at a smooth downhill for loss and a smooth uphill for accuracy. In our case, there were slight jerks midway for validation set but this is part and parcel of training a deep learning model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*R159uDbLBWRfThJ-xTlkSg.png" /><figcaption>Accuracy and Loss plots</figcaption></figure><p>I predicted on the test dataset using the trained model and the results were satisfactory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*OT5UfC1wCP3gfC3OtpjTHQ.png" /><figcaption>Predict on test image.</figcaption></figure><h4>Conclusion</h4><p>The aim of this post was to share the methodology I used to tackle this particular dataset. I saved the model in .h5 format so that I can use this with the ASL translator application which I built using OpenCV. I will talk about the challenges and difficulties while building the application using traditional image processing techniques in my followup post. The complete implementation can be found <a href="https://github.com/ayulockin/ASL_Classifier">here</a>. I used kaggle kernel to train the model. The kernel can be found <a href="https://www.kaggle.com/ayuraj/asl-training/edit/run/13921221">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*RAncgIQxCnNXQkfGIYdScg.png" /><figcaption>Test images with true labels and predicted labels.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10d6443f7cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>