<?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 Arun Prakash on Medium]]></title>
        <description><![CDATA[Stories by Arun Prakash on Medium]]></description>
        <link>https://medium.com/@arunprakash_25500?source=rss-884e82e55b62------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UaTZeytawx0oWFNEHwxoRg.jpeg</url>
            <title>Stories by Arun Prakash on Medium</title>
            <link>https://medium.com/@arunprakash_25500?source=rss-884e82e55b62------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:31:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arunprakash_25500/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[Improve the performance of your object detection model]]></title>
            <link>https://blog.francium.tech/improve-the-performance-of-your-object-detection-model-af6a20319f56?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6a20319f56</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[image-augmentation]]></category>
            <category><![CDATA[test-time-agumentation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[psuedolabeling]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Wed, 02 Sep 2020 10:34:57 GMT</pubDate>
            <atom:updated>2020-09-02T10:34:57.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G8T77mFPMQ5n2fVU" /><figcaption>Photo by <a href="https://unsplash.com/@the_roaming_platypus?utm_source=medium&amp;utm_medium=referral">timJ</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We have seen how to build a custom object detector using Faster RCNN with PyTorch. That model performed pretty decently with the IOU of 71%, this can further be improved with little tweaks in training and inference.</p><ol><li>Image Augmentation</li><li>Pseudo labeling</li><li>Ensembling</li><li>Test Time Augmentation(TTA)</li></ol><h4>Image Augmentation</h4><p>This is a simple process to deal with complications associated with limited data. We will just duplicate the training data with little variations. Like we can flip the image, change the brightness of the image, change the image to grayscale, and many more. The key here is we need to preserve the key feature of the images and allow the model to learn from more data. This can backfire if we go too unrealistic and train the model with images that are nowhere near to the images we gonna use for testing. So use it wisely.</p><p>Implementing this is also pretty simple, In PyTorch, we can use inbuilt transforms or we can even build our own transformations. For the demo here I’m going to use an awesome library called <a href="https://github.com/albumentations-team/albumentations">albumentations</a>. I will use the code in this <a href="https://medium.com/p/bc2e4295bf49/edit">blog</a> to demonstrate how to add albumentations while loading data for the model. Here we will be generating the images on the fly during training. If needed we can generate images offline and have the dataset ready before we start the training too. Let’s import the library and define the transformation method get_transform().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/647cd87ff1839f4eced057e66443a6fa/href">https://medium.com/media/647cd87ff1839f4eced057e66443a6fa/href</a></iframe><p>Here we are applying 4 different types of transformation to the image and each transformation is defined with the probability that can be applied on the image and all 4 transformations are wrapped inside Compose and also every time we are converting the image to tensor. When we change the images for object detection task we should be changing the coordinates for bounding boxes/masks as well. BboxParams will exactly do that, in the format param, we should say which format of the bounding box we need as output. It can be coco/pascal_voc/Yolo/albumentations. I want the x_min, y_min, x_max, and y_max coordinates of the bounding box, so I have mentioned the format to be ‘pascal_voc’. Now that we have defined the transformation we can make the changes in TrainDataset class to apply this transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdY-PtLHRiRRkoCIldQnrQ.png" /></figure><p>Now the TrainDataset class is accepting transforms as a param we can initiate the class with the get_transform() method we have defined earlier.</p><pre># Initialize Dataset<br>train_dataset = TrainDataset(&#39;face/face_annotation.csv&#39;, get_transform())</pre><p>That’s it, now whenever the image is loaded it will have the transformations applied. Let’s have a look at a sample image after applying the transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*Q3J99Im2gAmc39zSmYR0gw.png" /></figure><p>It allows the model to learn from a variety of data and yields better performance.</p><h4>Pseudo labeling</h4><p>This is a semi-supervised learning technique that can help when we have a small amount of labeled data and lots of unlabelled data. When we train a model on a small set of data, it won&#39;t be robust. Also labeling the large set of data would take a lot of time and money. So what we can do is we can train the model on the available small labeled dataset and then use that model to predict the label on the unlabeled dataset(this label is called pseudo-label). Then again train the model with both labeled data and pseudo-labeled data. This will make the model more robust.</p><p>Let’s see how we can do this in the object detection task. Say we have already trained a model using steps in <a href="https://medium.com/p/bc2e4295bf49/edit">this blog</a> and have the model.pth file ready. And we have a set of unlabelled data in the faces_ul folder. Now we need to create a CSV file with image_id and bounding box coordinates using the trained model.pth.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c81bbb72ae50283bb0580b678ad14db/href">https://medium.com/media/6c81bbb72ae50283bb0580b678ad14db/href</a></iframe><p>While creating the bounding boxes with the trained model we use a higher threshold. We will add the bounding box to the image only of the model is at least 75% confident. If we go with a lower threshold then we might compromise the quality of the train data. But 75 is an arbitrary number and we can play around with this. Now let’s create a dataframe for face_annotation.csv consisting of labeled images.</p><pre>labeled_df = pd.read_csv(&#39;face/face_annotation.csv&#39;)<br># Concat two DFs<br>frames = [labeled_df, pseudo_lbl_df]<br>concat_df = pd.concat(frames)<br># Convert as csv<br>concat_df.to_csv(&#39;new_annotation.csv&#39;, index=False)</pre><p>Move all the unlabeled images to the “face/” folder and use a new_annotation.csv file to initiate the TranDataset as below.</p><pre>train_dataset = TrainDataset(&#39;new_annotation.csv&#39;)</pre><p>The rest of the training and inference will be exactly the same as <a href="https://medium.com/p/bc2e4295bf49/edit">this blog</a>. This simple technique improved IOU from 71% to 74%. The size of the unlabelled dataset is 1200 images. The performance of this technique fairly depends on the accuracy of the initial model. If that is bad and labeled images with incorrect bounding boxes then the second model will perform poorly.</p><h4>Ensembling</h4><p>This is a process in which we train multiple models and make inferences instead of doing it with one model. In object detection when we predict with multiple models, we will get multiple bounding boxes for a single object. Using these bounding boxes we then create a single bounding box for each object in the image. There are multiple libraries available for this such as torchvision.ops.nms(), soft NMS, NMW (Non-Maximum Weighted), and also an interesting library called <a href="https://github.com/ZFTurbo/Weighted-Boxes-Fusion">Weighted Boxes Fusion</a> which claims to have performed better than NMS and Soft NMS. I will demonstrate how to use the WBF ensemble for the object detector we build <a href="https://medium.com/p/bc2e4295bf49/edit">here</a> to identify faces in an image. Let&#39;s install the library first.</p><pre>pip install ensemble-boxes</pre><p>The Model weight “model.pth” was trained on plain images, let’s have this as model_1. Using the same training we can train another model, but this time we will be using image augmentation as explained above in this blog. This model would be model_2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1806b6c670341f9cf5aed89e31bf8bfe/href">https://medium.com/media/1806b6c670341f9cf5aed89e31bf8bfe/href</a></iframe><p>We have a method load_model to load the models from the weight file. And the make_predictions method will iterate over models and store the predictions in a variable and returns it. We can load any number of models and make predictions here. The ensemble method will then call the weighted_boxes_fusion method of the library, with multiple bounding boxes, scores, and labels for each detected object and return a single bounding box with the score and label. I have set the weight of the model_1 as 1 and model_2 as 2, we can play around with this. Now everything is set for the final predictions.</p><pre>images = next(iter(test_data_loader)):<br>predictions = make_predictions(images)<br>for i, image in enumerate(images):<br>    boxes, scores, labels = ensemble(predictions, image_index=i)</pre><p>The model_1 had an accuracy of 71% and model_2 had an accuracy of 73%. With ensembling both models the accuracy has been increased to 74.5%. The ensemble-boxes library implements NMS, soft NMS, NMW, and WBF ensembling methods. We can try out all the variations choose the best one suites our models. In my case, WBF performed better than the other three.</p><h4>Test Time Augmentation</h4><p>TTA is also an ensemble for me. This is a process of sending augmented variations of a test image several times to the model and average the predictions of each image and return the final prediction instead of sending a clean image once and return the prediction as final. This will really help boost the accuracy of the model.</p><p>For our object detection model, we can implement our own TTA with basic transformations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88809e93b56cb405fd3e8feed4e5d361/href">https://medium.com/media/88809e93b56cb405fd3e8feed4e5d361/href</a></iframe><p>We have our TTA classes ready and now we can create a method to predict with TTA. It will be more like how we did for the ensemble. Here also I’ll be using the weighted boxes fusion. The difference will be instead of sending the bounding boxes predicted by different models, we will now send the bounding boxes predicted by a single model but for the augmented variations of the single test image.</p><p>Let’s initiate the model and TTA transforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlTcZ1hcm5Fc-lOd46EnXw.png" /></figure><p>The combinations of the transforms applied here are random choices, we can play around with this combination and add as many transforms we like. But make sure not to overkill and degrade the model performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2baf17ed08d6a0cb9b49510d93e54c1b/href">https://medium.com/media/2baf17ed08d6a0cb9b49510d93e54c1b/href</a></iframe><p>The make_predictions method will iterate through the transforms and create predictions for them. During the final inference, we can call ensemble method with those predictions and get the final prediction of bounding boxes like below.</p><pre>images = next(iter(test_data_loader)):<br>predictions = make_predictions(images)<br>for i, image in enumerate(images):<br>    boxes, scores, labels = ensemble(predictions, image_index=i)</pre><p>TTA is very much effective and boosts the accuracy of the model up to 3 to 5%. It can be used with multiple model ensemble also. Overall using all these techniques we were able to achieve the IOU of 80% for our face detection model.</p><p>Thanks for the read!</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6a20319f56" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/improve-the-performance-of-your-object-detection-model-af6a20319f56">Improve the performance of your object detection model</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semi-Supervised Learning with Pseudo labeling]]></title>
            <link>https://blog.francium.tech/semi-supervised-learning-with-pseudo-labeling-de65988bb3b3?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/de65988bb3b3</guid>
            <category><![CDATA[labeled-data]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[psuedolabeling]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[semi-supervised-learning]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 09:15:43 GMT</pubDate>
            <atom:updated>2020-09-01T09:15:43.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TLVvFTADZXsXUgxC" /><figcaption>Photo by <a href="https://unsplash.com/@element5digital?utm_source=medium&amp;utm_medium=referral">Element5 Digital</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With so much advancement in technology and computing power, we are at ease in dealing with many of the supervised learning problems. This learning method requires tons of labeled data and we train our model on this data over and over to learn the pattern. This is effective and extremely performant. But we won’t be having the luxury of labeled data always. In many real-time cases, we will always have unlabeled data and need lots of time and effort to label this manually.</p><p>We have semi-supervised learning(SSL) methods to counter the unlabeled data. It is an approach that combines a small amount of labeled data and a large amount of unlabeled data during training. It improves the model&#39;s robustness as well.</p><p>Pseudo labeling is one such SSL approach that helps to deal with unlabeled data. At first, we can annotate a small batch of data and train a model with it and then use that model to detect objects on the unlabeled data, The labels annotated by the model is called pseudo labels. We can then combine both labeled and pseudo labeled data and train the model again. We can pseudo label all the unlabeled data at once or we can do it in batches too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKgu0zXy5Oh8wiWpqq8ULA.png" /></figure><p>In this blog, I will explain how to build an image classification model using pseudo labeling. For training, we can just reuse the code in <a href="https://blog.francium.tech/build-your-own-image-classifier-with-tensorflow-and-keras-dc147a15e38e">this blog</a>. I have 10000 images of cars and trucks and they are all unlabelled. Initially, we can label 500 images manually. we can rename them as &lt;&lt;class&gt;&gt;.&lt;&lt;seq_num&gt;&gt;.jpg, The class here is either car or truck. One important thing to note here is we need to have equal number samples in each class, if we miss that and label 400 cars and 100 trucks, our model will be more inclined to classify images as cars. And having such a bad model to do the pseudo labeling will end up with the worst possible final model. We can put all these 500 labeled images inside the train folder and call the helper functions to prepare the data for training. the helper methods <em>train_data_with_label </em>and<em> one_hot_label </em>will convert the raw image into n-dimensional pixel arrays with labels. The functionality of these two methods is explained in <a href="https://blog.francium.tech/build-your-own-image-classifier-with-tensorflow-and-keras-dc147a15e38e">this blog</a>.</p><p>Once we complete the training with these 500 images we will have the trained model ready to predict the label on the new unseen data. Now we can use this model to predict the class of the unlabeled data and create pseudo labels and then retrain the model with 9500 pseudo labeled data and 500 manually labeled data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49ce42052bac8728a89cc62d81bb1838/href">https://medium.com/media/49ce42052bac8728a89cc62d81bb1838/href</a></iframe><p>Here we have all the unlabeled data inside the <em>unlabeled</em> folder. We then iterate over each image and predict it’s class using model.predict. Once we predict the class we can then rename the file to its class name and copy/move it to the train folder. Once we complete this process we will have 9500 pseudo labeled data and 500 manually labeled data ready to be used for training. We can call the helper methods to prepare the data for training. Finally, we can call model.fit to initiate training for 50 epochs. In this approach, I have pseudo labeled all the unlabeled images at once and it gave a decent model, The key here is I had a great initial model and it was able to create pretty good pseudo labels and resulted in a good model. But this wouldn’t be the case in every scenario. So instead of pseudo labeling all the data at once we can iterate over the unlabeled data and for every new 500 pseudo-labeled data we can retrain the model, and repeat this process until we no longer have any unlabeled data. Below is the code to do that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8863abff40a73b1e575cb5e2bf2d76e/href">https://medium.com/media/e8863abff40a73b1e575cb5e2bf2d76e/href</a></iframe><p>Here we are training 10 epochs for every new addition of 500 pseudo-labeled data. This approach would be better for many scenarios and for me also it resulted in a better robust model.</p><p>These SSL methods are playing a huge role in speech recognition, web content classification, and many more tasks. Few things we should have in our mind before starting with SSL is, The size of the unlabeled data should be substantially higher than the size of the labeled data. otherwise, we could simply solve the problem with supervised learning methods itself. And the labeling task should not be a complex one, It would make pseudo labeling more challenging.</p><p>Thanks for the read!</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de65988bb3b3" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/semi-supervised-learning-with-pseudo-labeling-de65988bb3b3">Semi-Supervised Learning with Pseudo labeling</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Object Detection with YOLO v5]]></title>
            <link>https://blog.francium.tech/custom-object-detection-with-yolo-v5-7b7bc6d82e45?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b7bc6d82e45</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolov5]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 21:38:15 GMT</pubDate>
            <atom:updated>2021-07-22T05:40:06.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3__IbBhOG0-LWQGr" /><figcaption>Photo by <a href="https://unsplash.com/@taylorgsimpson?utm_source=medium&amp;utm_medium=referral">Taylor Simpson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are familiar with object detection then it’s quite certain that you know a bit about YOLO. It’s an efficient and faster object detection algorithm and the first choice for real-time object detection tasks.</p><p>Let’s have a look at its history a bit. Joseph Redmon invented and released the first version of YOLO in May 2016 and it was the biggest step forward in real-time object detection. He then worked on further enhancements and released two more versions YOLO v2 and v3. After the version 3 release Joseph Redmon has announced that he will be stopping any further research in computer vision to avoid the misuse of the technology. After two years of the v3 release, Alexey Bochkovskiy released the YOLO v4 version with the paper “<a href="https://arxiv.org/abs/2004.10934">YOLOv4: Optimal Speed and Accuracy of Object Detection</a>” and it performed much better than v3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aGHAXI9r9isdlJM5.png" /><figcaption>Source: <a href="https://github.com/AlexeyAB/darknet">Github</a></figcaption></figure><p>But just after a few days of its release, we have got a new version of YOLO from Glenn Jocher. It is built with PyTorch while all the other previous versions are based on the Darknet platform. There are a lot of <a href="https://github.com/AlexeyAB/darknet/issues/5920">controversies</a> going on with the selection of the name YOLOv5. But as per the performance matrics given by Glenn Jocher v5 is outperforming all the previous versions in terms of COCO AP.</p><p>Let’s train YOLOv5 on our custom dataset and see the performance ourselves. For this blog, we can use the flower dataset from <a href="https://storage.googleapis.com/openimages/web/visualizer/index.html?set=train&amp;type=detection&amp;c=%2Fm%2F0c9ph5">here</a>. Make sure the format of the annotation is in YOLO format. For all the images in the train directory, we should be having a &lt;&lt;image_name&gt;&gt;.txt file with YOLO annotation. Let’s have a look at a sample image with its annotation in the train directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*7s-cYcs7Bw4qaLnNtzikTw.png" /></figure><p>Once we have the dataset ready, we need to set up the environment. As I said earlier, this implementation is based on PyTorch, so we need PyTorch version ≥ 1.5, Python version 3.7, and CUDA version 10.2. Once we have this basic setup ready we can clone the YOLOv5 repo from <a href="https://github.com/ultralytics/yolov5">GitHub</a>.</p><pre>git clone <a href="https://github.com/ultralytics/yolov5">https://github.com/ultralytics/yolov5</a></pre><pre>cd yolov5</pre><p>Install all the dependencies in the requirement.txt file.</p><pre>pip install -r requirements.txt</pre><p>Now, we can start modifying the config file as per our dataset. As we are detecting the flowers, I have named the config file a flower.yaml. It should have the details of the training and validation data along with the classes we gonna detect. Here’s how my YAML file looks like.</p><p>YOLOv5 provides four different versions of the network to train our model. Small(<a href="https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J">YOLOv5s</a>), Medium(<a href="https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J">YOLOv5m</a>), Large(<a href="https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J">YOLOv5l</a>) and Extra-large(<a href="https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J">YOLOv5x</a>). We can use any of these networks based on our requirements. I have no limitations in computing power and also prefer the highest possible accuracy. so I chose YOLOv5x. Before actually using this, we need to make a small change in the yolov5x.yaml file by updating “nc” param to 1. If we need to train with pretrained weights, we can download that from <a href="https://drive.google.com/drive/folders/1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J">here</a>.</p><p>We are now done with all the configuration and initial setup that are needed to kick start the training. Let’s initiate training now.</p><pre>python train.py <br>--img 512 <br>--batch 4 <br>--epochs 45<br>--data ./yolov5config/flower.yaml <br>--cfg ./yolov5config/yolov5x.yaml<br>--weights ./yolov5config/yolov5x.pt</pre><p>We are training with an image size of 512*512 and a batch size of 4 for 45 epochs. These are arbitrary numbers and we can play around with this. If we want to train the network in multi-scale(size of the image will vary +/- 50%) mode, we can just add “ — multi-scale” at the end of the training command above. In some cases, the multi-scale mode improves model performance.</p><p>Once the training completes, we will have two weights in weights/ directory. best.pt and last.pt. best.pt is the one that gives better performance and last.pt is the model after the last epoch and it can be used to resume the training again if needed.</p><p>YOLOv5 has built-in augmentations to help build a robust model during the training, It also has inbuilt TTA to improve the inference performance. But the inbuilt TTA is just a flip and scale. So I have decided to write my own TTA to improve the model. Below is the complete code for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daa50f321c350b35c82f191a2af32309/href">https://medium.com/media/daa50f321c350b35c82f191a2af32309/href</a></iframe><p>Now if we run detect.py, we can see the output of the object detector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4slnsCHQFX9tmVXWfhBp9g.png" /></figure><p>For 45 epochs we have got pretty decent performance. So, keeping aside the controversy around the naming of the model and whatever the community decides to name it, It will definitely be one of the best object detection algorithms around.</p><p>Thanks for the read!</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b7bc6d82e45" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/custom-object-detection-with-yolo-v5-7b7bc6d82e45">Custom Object Detection with YOLO v5</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection with Faster RCNN]]></title>
            <link>https://blog.francium.tech/object-detection-with-faster-rcnn-bc2e4295bf49?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc2e4295bf49</guid>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[faster-r-cnn]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Sat, 29 Aug 2020 13:32:22 GMT</pubDate>
            <atom:updated>2020-08-29T13:32:22.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dcQR7yuUDmLobQta" /><figcaption>Photo by <a href="https://unsplash.com/@vitreous_macula?utm_source=medium&amp;utm_medium=referral">Julia Joppien</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Object Detection is always a hot topic in computer vision and is applied in many areas such as security, surveillance, autonomous vehicle systems, and machine inspection. Widely used object detector algorithms are either region-based detection algorithms (Faster R-CNN, R-FCN, FPN) or single-shot detection algorithms(SSD and YOLO).</p><p>The region-based detection or two-shot detection model has two stages:</p><ol><li>Region proposal</li><li>Classification of those regions and refinement of the location prediction.</li></ol><p>Single-shot detection skips the region proposal stage and yields final localisations and content prediction at once. Faster RCNN is more popular in region-based detectors. We will now see how to implement a custom object detector using Faster RCNN with PyTorch.</p><p>For the scope of this article, we will detect faces in an image. There can be multiple faces in a single image. I have got the images from Google and resized everything to 512 X 512. And for annotation, I have used the <a href="https://github.com/tzutalin/labelImg">labelImg</a> tool. The annotation file is a single CSV file, holding image_id and bounding box coordinates. Let’s import the required libraries.</p><pre>import pandas as pd<br>import numpy as np<br>import cv2<br>import torch<br>import torchvision<br>from torchvision.models.detection.faster_rcnn import FastRCNNPredictor<br>from torchvision.models.detection import FasterRCNN<br>from torch.utils.data import DataLoader, Dataset</pre><p>Next up, we can define the dataset for training. For that, we can inherit PyTorch’s Dataset class and create our own TrainDataset class. As per PyTorch documentation, our class should implement __len__ and __getitem__ methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiVSrCd2c6FjGKrn60N3mw.png" /></figure><p>For our Dataset class, we receive the annotation file as input. All our training images are inside the “face” folder. Inside the constructor, we convert the annotation file into the dataframe and get all the unique image_ids for further processing. In the __getitem__ method we can read the image using the image_id we have in the dataframe, and also we can get all the bounding boxes associated with that image.</p><p>We will then initialize a dict called target, which will be passed to model for training. This target will have metadata of the annotation like actual bounding box coordinates, it’s corresponding labels, image_id, area of the bounding boxes. The area param is used during evaluation with the COCO metric, to separate the metric scores between small, medium, and large boxes. If we set iscrowd as True, those instances will be ignored during evaluation. The __len__ method will give the size of the Dataset.</p><p>The next thing would be to set a data loader, which will load the training data in batches into the model for training. For this also we will be using PyTorch’s DataLoader utility.</p><pre># Initialize Dataset<br>train_dataset = TrainDataset(&#39;face/face_annotation.csv&#39;)</pre><pre>def collate_fn(batch):<br>    return tuple(zip(*batch))</pre><pre>train_data_loader = DataLoader(<br>    train_dataset,<br>    batch_size=2,<br>    shuffle=True,<br>    num_workers=2,<br>    collate_fn=collate_fn<br>)</pre><p>In the DataLoader we can pass the initialized train_dataset. batch_size and num_workers would be an arbitrary number, based on the memory available we can play around with this.</p><p>If we have GPU available we can set the device as cuda else as CPU.</p><pre>device = torch.device(&#39;cuda&#39;) if torch.cuda.is_available() else torch.device(&#39;cpu&#39;)</pre><p>Now let&#39;s load some training data and have a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEPl1QHvb4oGh2SrYZXpIQ.png" /></figure><p>we can run the above snippet and plot the images with its bounding boxes. Here are the few samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*XfbfDgg_RQstkjvIhQ1m0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L81gMr2VQ1MlNAqFc-OMvw.png" /></figure><p>Now let&#39;s initialize our model. I’m going to use torchvision’s FasterRCNN with a resnet50 backbone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AN39pwo8qSfvJQGqJ7jKyg.png" /></figure><p>We have set pretrained as true, so the function will return a model pre-trained on ImageNet. Here we set the num_classes as 2, considering background as one class.</p><p>Before we start the training we can declare the number of epochs we wanna train and also set the optimizer and learning rate scheduler.</p><pre>params = [p for p in model.parameters() if p.requires_grad]<br>optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005)<br>lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1)</pre><pre>num_epochs = 40</pre><p>The optimizer we are using here is SGD (Stochastic Gradient Descent), we have many other optimizers available in <a href="https://pytorch.org/docs/stable/optim.html">torch.optim</a>, we can play around with this. The learning rate scheduler helps to adjust the learning rate during the course of the training to achieve more accuracy and speed up convergence. We are StepLR scheduler which decays the learning rate of each parameter group by gamma every step_size epochs. The gamma and step_size hyperparameters will decide the lr decay, we can play around with those values. Finally, we gonna train this model for 40 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kgi1Enr1y-hjUvZHrfeS4Q.png" /></figure><p>The above code snippet will run the training for 40 epochs. optimizer.zero_grad() clears old gradients from the last step otherwise, we would just accumulate the gradients from all loss. backward<strong>()</strong> calls.</p><p><em>loss.backward() </em>call will compute the gradient of loss w.r.t all the parameters in loss that have <em>requires_grad = True</em> and store them in <em>parameter.grad </em>attribute for every parameter.</p><p><em>optimizer.step()</em> will update all the parameters based on <em>parameter.grad. lr_scheduler.step() </em>will adjust the learning rate. We should make sure that the lr.scheduler.step() was called after optimizer.step(), else the first value of the learning rate schedule will be skipped. We have saved the model for inference and checkpoint if in case we need to resume training for more epochs. Once the training is completed we will have the model.pth file.</p><p>For inference, we need to create test_dataset and test_data_loader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HM5_Um2OuBRqVVoRUVe8qA.png" /></figure><p>TestDataset is similar to TrainDataset, this will also implement __getitem__ and __len__ methods. But this will just return images instead of image and bounding box.</p><pre>test_dataset = TestDataset(&#39;test/&#39;)</pre><pre>test_data_loader = DataLoader(<br>    test_dataset,<br>    batch_size=2,<br>    shuffle=True,<br>    num_workers=2,<br>    collate_fn=collate_fn<br>)</pre><p>we can reuse the model initialization code we used for training with pretrained as Fase and then we can load our weight file as below.</p><pre>model.load_state_dict(torch.load(&#39;./model.pth&#39;))<br>model.to(device)</pre><p>Let’s plot our predictions now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IC1KsyTmsZn6jmoo7q-N3w.png" /></figure><p>We had 1500 images for training and it took around 5 hours on NVIDIA Tesla K80 GPU and the accuracy is pretty decent. We can still improve this model with various techniques like image augmentations, ensemble inference, and TTA. <a href="https://medium.com/p/af6a20319f56/edit">This blog</a> will explain these things in detail.</p><p>Thanks for the read!</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc2e4295bf49" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/object-detection-with-faster-rcnn-bc2e4295bf49">Object Detection with Faster RCNN</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgres Common Table Expressions]]></title>
            <link>https://blog.francium.tech/postgres-common-table-expressions-706f9470e8d7?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/706f9470e8d7</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[common-table-expressions]]></category>
            <category><![CDATA[recursive]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Thu, 07 May 2020 05:47:47 GMT</pubDate>
            <atom:updated>2020-05-07T05:47:47.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*doSeZJ8PbbadzDW4.png" /></figure><p>Common Table Expressions (CTE), also known as the WITH clause, is an awesome feature that helps in breaking down big queries into smaller queries which makes the whole query more readable and easier to maintain.</p><p>Let’s see a few examples of it and understand when to and when not to use it. First, let’s say we have a database of a college and we want to generate a report to get the list of departments having less than 50 as pass percentage. Without using CTE the query would be like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3be9278a803cfeed1716d13308197bcf/href">https://medium.com/media/3be9278a803cfeed1716d13308197bcf/href</a></iframe><p>Nothing is wrong here and it works perfectly fine. Now let’s try changing this query using CTE.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc5d8afdded4a5e823df28f1bf82770a/href">https://medium.com/media/fc5d8afdded4a5e823df28f1bf82770a/href</a></iframe><p>Now the subquery joins are replaced with the CTE joins. This is more readable. Especially when the query gets bigger and bigger it’s always hard to maintain it. The usage of CTE will be of great help in such cases. Not only that, in Postgres the CTE results will be materialized. It means even if we call the <strong><em>dept_results </em></strong>CTE in multiple places, the actual query definition will be run once and the result of it will be stored in memory. So if we have any complex logic that has to be used in multiple places in the same query then we can put that inside a CTE and call that any number of times.</p><h4>Recursive queries:</h4><p>The RECURSIVE keyword in CTE will change the simple nice to have feature into an awesome feature that helps us achieve interesting things like referring to its own output in CTE.</p><p>I will try to explain it with the employee-manager relationship in the <em>employees</em> table. Every manager is an employee himself and the employee table will have self-reference. The manager_id column of the <em>employees</em> table will refer to the id column of the same table.</p><p>Now if we are asked to get the manager name of a given employee, then it’s a simple select query like below.</p><pre>SELECT<br>  t1.id,<br>  t1.name,<br>  t2.name as manager_name<br>FROM<br>  employees t1<br>JOIN employees t2 ON t1.manager_id = t2.id<br>WHERE <br>  t1.id = 1;</pre><p>But if we were asked to list the whole reporting hierarchy then it’s not simple. Because we were given the id of an employee, using that we can get his manager, then from that result we have to find the manager’s manager and this will goes on until we reach a person who is not reporting to anyone. This can’t be achieved with the standard SQL query. Let’s write a query to achieve this using RECURSIVE CTE.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41203147a041faa5defa338a177d52ef/href">https://medium.com/media/41203147a041faa5defa338a177d52ef/href</a></iframe><p>Below is the result of the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*b6_iNrUjlHYr_ONL67672Q.png" /></figure><p>Now let’s break this and understand how we got the results. Within the CTE the first query <em>SELECT id, NAME, manager_id FROM employees WHERE id =4 </em>will generate the initial value and this is the working table now.</p><p>The second query <em>SELECT t.id, t.NAME, t.manager_id FROM employees t JOIN emp_hierarchy t1 ON t.id = t1.manager_id </em>will access the working table run until the termination condition is met. In our case, it will run until the manager_id of <em>emp_hierarchy </em>exists in the id column. The moment we have null as manager_id in <em>emp_hierarchy </em>the termination condition will be met.</p><p>The last select query is doing nothing, it just selects the data from the CTE and joins it with the <em>employees</em> table to get the desired result.</p><p>We can also use DML statements(Insert, Update, Delete) inside CTE. let’s take a look at a sample below.</p><pre>WITH <strong>deleted_students</strong> AS (<br>  DELETE FROM students WHERE id &lt; 100<br>  RETURNING *<br>)<br>INSERT INTO old_studs<br>SELECT * FROM <strong>deleted_students</strong>;</pre><p>There are many other such use cases where CTEs are handy. But we should be aware of the fact that the CTE execution is materialized and if not used correctly it can affect the performance badly.</p><p>Say we have CTEs that contain thousands of rows and when we try to query the CTEs the underlying index won’t be used. Because the CTE execution result is now stored in the memory and will not be an index scan. Let’s see an example of this.</p><p>I have a table <em>dummy</em> that has two columns ID and NAME and it has one million records. The ID column has an index, now we can fire a CTE query on it and check the execution plan.</p><pre>EXPLAIN ANALYZE <br>WITH <strong>recs</strong> AS(<br>SELECT * FROM dummy<br>) SELECT * FROM <strong>recs</strong> WHERE id = 500;</pre><pre>QUERY PLAN<br>--------------------------------------------------------------------<br> CTE Scan on recs  (cost=18334.00..40834.00 rows=5000 width=122) (actual time=0.203..398.096 rows=1 loops=1)<br>   Filter: (id = 500)<br>   Rows Removed by Filter: 999999<br>   CTE recs<br>     -&gt;  Seq Scan on dummy  (cost=0.00..18334.00 rows=1000000 width=37) (actual time=0.022..113.272 rows=1000000 loops=1)<br> Planning Time: 0.059 ms<br> Execution Time: 401.929 ms</pre><p>Clearly, no index was used. Now we can fire a query with a subquery.</p><pre>EXPLAIN ANALYSE<br>SELECT * FROM (SELECT * FROM dummy) t WHERE id=1000;</pre><pre>QUERY PLAN<br>--------------------------------------------------------------------<br> Index Scan using dummy_id_idx on dummy  (cost=0.42..8.44 rows=1 width=37) (actual time=1.571..1.573 rows=1 loops=1)<br>   Index Cond: (id = 1000)<br> Planning Time: 0.078 ms<br> Execution Time: 1.591 ms</pre><p>Now the optimizer applied the predicate <em>id</em> and used the <em>dummy_id_idx. </em>The difference in execution time says it all, it’s 1.5ms vs 401.9ms. In such cases, it’s always better to avoid CTE and use a simple subquery.</p><p>The same thing happens when we try to join two CTEs which has lots of records in it. Here the join operation will take place in the memory where the CTE execution is cached and there won’t be any index usage. In such cases, a safer option would be creating temp tables and creating an index on them before writing the join query.</p><p>Finally, CTEs are great and extremely useful. But we should always be aware of the data when we use it.</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=706f9470e8d7" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/postgres-common-table-expressions-706f9470e8d7">Postgres Common Table Expressions</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhance images with Autoencoders]]></title>
            <link>https://blog.francium.tech/enhance-images-with-autoencoders-58afa4fd638f?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/58afa4fd638f</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Tue, 05 May 2020 09:17:33 GMT</pubDate>
            <atom:updated>2020-05-05T09:22:03.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lBsum2JfVNSujKGG.jpg" /></figure><p>Autoencoders are a type of artificial neural network that can learn how to efficiently encode and compress the data and then learn to closely reconstruct the original input from the compressed representation.</p><p>It has two major components, the encoder network, and the decoder network. The encoder network will receive the input data and compress it by extracting only the important features from it.</p><p>The decoder network will then use this feature representation of the original image and reconstruct the original image. While training if the reconstructed input deviates from the original input then the loss will be high, so the model will learn to reconstruct the data as close to the original input data. Below is the representation of the autoencoder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6s21l06PAWfV_XoAVCj1A.png" /></figure><p>Now we can try to use this autoencoder to enhance the image quality, but if we understood the architecture correctly, It will try to reconstruct the original input we feed to the network. So if we send a low-resolution image then it will only reconstruct the noisy image.</p><p>To achieve the image enhancement trough encoders, we can do a minor change in the way we calculate the loss function. instead of calculating the loss using input(low-resolution image) and reconstructed image we can use the clear image and reconstructed image. So the model will learn to reconstruct the clear image instead of the low-resolution input image.</p><p>We can build our autoencoder using Keras. For the blog, I have used the images of human faces that I collected from google as explained in this <a href="https://blog.francium.tech/build-your-own-image-classifier-with-tensorflow-and-keras-dc147a15e38e">blog</a>. We can import all the necessary libraries we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TFidNZAxyPtHH2JPQGdWg.png" /></figure><p>I have around 500 images for training. I have all the images inside a folder “test_data”. Now we can start preparing the data for training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3LYN0GBGf-RCEBg6ek8iw.png" /></figure><p>we can use the image preprocessing tool from Keras. The images we have got from the internet might be different in size, we can load them and resize all into 64 X 64 color images and then convert them into image array. Then all these images are stored in a single “images” variable.</p><p>We can use the sklearn’s train_test_split helper to split the image data into train and test datasets.</p><pre>train_x, test_x = train_test_split(np.array(images), random_state=102, test_size=0.2)</pre><p>We are keeping 20% of the dataset as a test set. But this is not over yet. All we have now is the images of reasonably good quality and as mentioned above, these are useful for calculating the loss alone, we need low-resolution images as input for our task. So we will now reduce the resolution of all the images. Below is the function I will be using for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RD1BYQFVRIq_WP7B2VIlaw.png" /></figure><p>We are now reducing the resolution of the image to 25 X 25. It’s an arbitrary size we can choose anything we want, but make sure we are not losing a lot of features by reducing the resolution too much.</p><pre>train_lr = []<br>test_lr = []</pre><pre>for i in range(train_x.shape[0]):<br>    train_lr.append(reduce_res(train_x[i]))</pre><pre>train_lr = np.array(train_lr)</pre><pre>for i in range(test_x.shape[0]):<br>    test_lr.append(reduce_res(test_x[i]))</pre><pre>test_lr = np.array(test_lr)</pre><p>train_lr and test_lr are the variables hold the low-resolution images for our training. Now its time to build the neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDd2Rju2CQfPkkmgCduEsg.png" /></figure><p>We have initiated a Sequential model from Keras and adding the layers for the encoder. encoder network consists of three convolutional neural networks layer followed by the max pool layer and then a final CNN layer. All the CNN layers have relu as an activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kU-isY3LhZIHjLxQg60vJw.png" /></figure><p>The decoder network starts with a CNN layer followed by an upsampling layer and then 4 layers of CNN. Here also all the layers are having the relu activation with the same padding. We can see the model summary to understand better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_kOMm9kEOvJfyYOLy1MnA.png" /></figure><p>This clearly shows why we need 3 neurons in the last CNN layer, as the output of the network should be a color image. We are using the adam optimizer with 0.001 learning rate and mean square error as a loss function. We can play around with encoder and decoder network layers and other hyperparameters to achieve better results.</p><p>Now we can start training the model. I’m training the model for 100 epochs with a batch size of 50. we can play around with these based on your machine type. And after training, I’m saving the model.</p><pre>model.fit(train_lr, train_x, epochs=100, batch_size=50, shuffle=True, validation_data=(test_lr, test_x))<br>model.save(&#39;autoencoder_100.h5&#39;)</pre><p>Now its time to test our model.</p><pre>preds = model.predict(n_test_x)</pre><p>we can now plot the input and its corresponding model prediction to see the model performance.</p><pre>display_num = 4<br>plt.figure(figsize= (10,5))</pre><pre>for i in range(display_num):<br>    ax = plt.subplot(2, display_num, i+1)<br>    plt.imshow(n_test_x[i])<br>    ax.get_xaxis().set_visible(False)<br>    ax.get_yaxis().set_visible(False)</pre><pre>ax = plt.subplot(2, display_num, i+1+display_num)<br>    plt.imshow(preds[i])<br>    ax.get_xaxis().set_visible(False)<br>    ax.get_yaxis().set_visible(False)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkzl2ySH28xC8seg2w5eQQ.png" /></figure><p>If we see the output the model performed reasonably well even for the dataset of 500 images. The output image is of the same resolution but with the size 1/4th of the original image. This is useful in many areas like noise removal, dimensionality reduction, video quality improvement, image coloring, and many more. Hope this helped!</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58afa4fd638f" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/enhance-images-with-autoencoders-58afa4fd638f">Enhance images with Autoencoders</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time series prediction with Tensorflow and Keras]]></title>
            <link>https://blog.francium.tech/time-series-prediction-with-tensorflow-and-keras-c9510dda109d?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9510dda109d</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Wed, 01 Apr 2020 08:42:39 GMT</pubDate>
            <atom:updated>2020-04-01T08:42:39.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLHOS9XLxNhCbAtxQn_hFQ.png" /></figure><p>It’s always fascinating to see how the neural networks pull off amazing results, but even for them, it&#39;s not easy learning sequential/time-series data. The time component adds additional information which makes time series problems more difficult to handle compared to many other prediction tasks.</p><p>In this blog, we can see how to build a time series predictor with an artificial neural network. the dataset we are going to use is the historical exchange rate of USD to INR. The dataset can be downloaded from <a href="https://excelrates.com/historical-exchange-rates/USD-INR">here</a> as CSV.</p><p>For time series prediction we need to remember things learned from prior input while generating output. So we can use <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">RNN</a> for this. There might be a chance that we will face <a href="https://en.wikipedia.org/wiki/Vanishing_gradient_problem">vanishing gradient</a> problem and our model may not learn if the series is really long. To counter this issue we have improved RNNs <a href="https://en.wikipedia.org/wiki/Long_short-term_memory">LSTM</a> and <a href="https://en.wikipedia.org/wiki/Gated_recurrent_unit">GRU</a> that we can use. Our dataset is small with around 4000 data points and it might not cause the vanishing gradient problem at all. But in performance LSTM and GRU are better than simple RNNs because of their ability to learn long dependencies. Between LSTM and GRU, the performance is almost the same but GRU is easy to train because of simple nature compared to LSTM. So we will be using GRU here.</p><p>First, make sure python and TensorFlow are installed and then import all the necessary libraries to get the job done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*nWt1tYM8FnwemHNMUm082w.png" /></figure><p>The dataset is in CSV file, we can use pandas dataframe to load the data, visualize and finally prepare for training.</p><pre>df = pd.read_csv(&#39;exchange_rates_usd_inr.csv&#39;)</pre><p>The dataframe object “df” holds all the data points in the CSV file. we can see how this looks like in Jupyter notebook with <strong><em>df.head()</em></strong> command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*VnlF-QJtWNhBXyDngQ5Dpw.png" /></figure><p>The column USD is having all the values as 1 and it’s irrelevant for training, so we can safely remove it. Also, we don&#39;t really need Date column to train the model, so we can set that as dataframe index.</p><pre>df = df.drop(&#39;USD&#39;, axis=1)<br>df[&#39;Date&#39;] = pd.to_datetime(df[&quot;Date&quot;])<br>indexed_df = df.set_index([&quot;Date&quot;], drop=True)</pre><p>Now, we can plot the data points to have a better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*ibmtjgt6W53IPN2qg24VUw.png" /></figure><p>If we notice, all the data points after 2009 are having 0 as INR value. We can think of various solutions to impute these missing data points, but as we miss the whole series of data for about 10 years it doesn’t make any sense to replace the 0 with some algorithm derived value. This will affect our model performance. The best way to move forward here would be to drop them as we already have enough data points to train with almost 11 years of data.</p><pre>indexed_df = indexed_df[indexed_df.INR != 0.0]</pre><p>Now we can flip the dataframe to have the data sequence from the past to recent and then plot it.</p><pre>indexed_df = indexed_df.iloc[::-1]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BOMJpii_8EkO0mdzVkMLw.png" /></figure><p>This data looks good. We need to convert our dataset into data and labels in order to perform supervised learning on our model. This can be achieved by duplicating the INR field in the dataframe and then shifting the duplicated column by one period. This shift will make the first-row value for that column as NaN, we need to replace this NaN to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*aQ4WQg-nexwHP2sfE5D8QA.png" /></figure><p>Now we can see how the data looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*NEJNVWhH5_lhdG9AnQGQqg.png" /></figure><p>The next step would be splitting the train and test data. If we look at our data the INR value varies from 43 to 80, If left alone the features with high magnitudes will weigh in a lot more in the distance calculations than features with low magnitudes and thereby affect the performance of the model. To resolve this, we need to bring all features to the same level of magnitudes. We can achieve this by scaling the data, We will be using MinMaxScaler from sklearn.preprocessing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g4UEtS73hj-HQmPufaigrw.png" /></figure><p>Next, we can split the data and label separately and then reshape the data to be able to sent into the model.</p><pre># train data<br>y_train = train_scaled[:,-1]<br>X_train = train_scaled[:,0:-1]<br>X_train = X_train.reshape(len(X_train),1,1)</pre><pre># test data<br>y_test = test_scaled[:,-1]<br>X_test = test_scaled[:,0:-1]</pre><p>Now we are all set for the model building. We will be using Keras to build the neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rzSBD8niBe6ZjPRLbIlngA.png" /></figure><p>If you see the above code, we initialize the Sequential model and then adding a GRU layer with 75 neurons. This 75 is an arbitrary number, we can change this and see how the model behaves. Next would be a fully connected layer with just one neuron as our output is a single value. We can even try to stack the GRU layer by adding any number of GRU layers between the first GRU layer and the dense layer, in that case, we need to add the <strong>return_sequences=True </strong>parameter in all the GRU layers except the last one. Also, we can try adding the dropout the layer in between and see the difference in model performance. As the dataset is a less complex one, I have built a simple model possible. We are using Adam optimizer with “MSE” as a loss function and learning rate of 0.001.The model is now trained for 100 epochs and it’s time to start predict using the model.</p><pre>X_test = X_test.reshape(500,1,1)<br>y_pred = model.predict(X_test)</pre><p>We can plot the actual test values and predicted values to see how our model has performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*b2xfbkVfIVdWMEbC83dguw.png" /></figure><p>Looks like our model is performing very well and almost replicated the original data, we can zoom in a bit by plotting just 50 data points to see the difference in actual and predicted data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8yDKgbpWbLJh2Z5SnluocA.png" /></figure><p>We can see that the difference between the actual and predicted value is very small and the model performance is good. In the model, we can change the layers to LSTM or SimpleRNN instead of GRU and play around with the hyperparameters to see how the model is performing. Below is the complete code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb2297be8eb3bc1df597535bcc15e45a/href">https://medium.com/media/bb2297be8eb3bc1df597535bcc15e45a/href</a></iframe><p>Thanks for the read!</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focussed on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9510dda109d" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/time-series-prediction-with-tensorflow-and-keras-c9510dda109d">Time series prediction with Tensorflow and Keras</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face verification with Azure Face API]]></title>
            <link>https://blog.francium.tech/face-verification-with-azure-face-api-f38e154924ff?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/f38e154924ff</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[francium-tech]]></category>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 05:49:25 GMT</pubDate>
            <atom:updated>2020-03-25T05:49:25.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/998/0*fi9yhgfwh1mqaTni.jpg" /></figure><p>I have recently got a requirement to verify two images and see if both the images have the same person in it. This looks very interesting and there are few open source libraries doing this with decent accuracy. In order to get better accuracy I thought it can be dealt with <a href="https://blog.francium.tech/machine-learning-convolution-for-image-processing-42623c8dbec0">CNN</a> and started to think about implementing <a href="https://en.wikipedia.org/wiki/Siamese_neural_network">Siamese</a> CNN to solve this problem. Then I saw this Face API from Azure which is doing exactly this task with better accuracy and it comes in the free tier as well.</p><p>So I gave it a try and implemented a face verification app with azure face API. To start with we need to create an Azure account and subscribe to Face API to get the endpoint and key details. Once we have the credentials, we can start building the app. Open the VSCode terminal and run the following command to create the Project.</p><pre>dotnet new console -o &quot;FaceVerification&quot;</pre><p>This will create a new Project FaceVerification. If you open the project in VSCode the structure will be like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*t8Znznrm8j5O8CJ6NWeG8g.png" /></figure><p>If you open the Program.cs, it will have the namespace FaceVerification and class Program with default “Hello World!” code in it. We can start replacing this with our face verification code. Please note that I have followed the template given in the azure website for this implementation.</p><p>Open the FaceVerification.csproj file and add the Newtonsoft.json dependency as below to deal with JSON objects.</p><pre>&lt;ItemGroup&gt;</pre><pre>    &lt;PackageReference Include=&quot;Newtonsoft.Json&quot; Version=&quot;12.0.3&quot; /&gt;</pre><pre>&lt;/ItemGroup&gt;</pre><p>After adding this we need to run the restore command to resolve the newly added dependency. In the Program class, we can add subscription key and endpoint as constants as they will not change throughout. Here is how our Program class looks like now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLzva15haSJU_GgfiJLl6g.png" /></figure><p>Now we can start writing the actual methods which help verify the images. This process has two tasks, one is to identify the face in the given image(detection task) and then comparing detected faces (verification task).</p><p>For this task, I will be using the images in my local as input by specifying it’s path inside Program class. And these images have to be converted as byteArray in order to be sent in the HTTP request body. Here is the method to convert the image into byteArray.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNIZz3K2HWRbcVFzq8SreA.png" /></figure><p>Now that we have all the necessary items ready, the next step is the method to call the detection API to detect the face in the given image. This async method “MakeDetectRequest” will take image path as input and return detected faceId as output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmasL3APAHe7TBexySxD7Q.png" /></figure><p>If we see line number 77, we are assuming that the image will always contain one or no face. and If no face is detected we will return null.</p><p>Next step would be the method to call the verify API and check if the images have the same person in it. This “MakeVerifyRequest” method will receive an array of faceIds as input and return back an object with boolean “isIdentical” and “confidence” field contains the confidence score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e01n4wTxR9_bWpS5AHB-Ag.png" /></figure><p>That’s all for the helper methods, now we can jump back to Main method and call these helper methods to get the work done. We can loop through the image path array and call detect request to populate the faceIds array, and then using this faceIds array we can call the verify the request. we need to make sure that we will call the verify request only if we identify the face in both the images to avoid exception in verify API call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYRLdreDVNV1MPKBgOOLnw.png" /></figure><p>Now we are all set to test our code. Below are the images I chose to verify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*norVIp5I2iETmt3qQRvY8Q.png" /></figure><p>Image on the left is image_1 and the other one is image_2. Here is the output when we run the project.</p><pre>» dotnet run FaceVerification                                                                                   <br>{<br>  &quot;isIdentical&quot;: true,<br>  &quot;confidence&quot;: 0.89602<br>}</pre><p>It did Identify that both the images having the same person in it. Now we can keep the image_1 as it is and change image_2 with different person’s image as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FffWGEPWscWCDHWc4pOV_Q.png" /></figure><p>Now the isIdentical flag is false as expected.</p><pre>» dotnet run FaceVerification                                                                                   <br>{<br>  &quot;isIdentical&quot;: false,<br>  &quot;confidence&quot;: 0.18273<br>}</pre><p>Next will be sending an image with no one in it as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmJ_YQhUT7OXm8e1Rvu62g.png" /></figure><p>As expected our app responded with isIdentical flag as false with 0.0 confidence score.</p><pre>» dotnet run FaceVerification                                                                                   <br>{<br>  &quot;isIdentical&quot;: false,<br>  &quot;confidence&quot;: 0.0<br>}</pre><p>The amount of code we have written to get this done is very minimal and the accuracy is also pretty good. Hope this helps!</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focussed on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f38e154924ff" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/face-verification-with-azure-face-api-f38e154924ff">Face verification with Azure Face API</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Train a model in google colaboratory with google drive data]]></title>
            <link>https://blog.francium.tech/train-a-model-in-google-colaboratory-with-google-drive-data-8bdec222c0e3?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bdec222c0e3</guid>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[google-drive]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 14:47:23 GMT</pubDate>
            <atom:updated>2020-01-06T14:47:23.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*8N8ErDGntW1rqIW9.png" /></figure><p>As Deep Learning engineers, we always wanted access to powerful computers. And when it’s available for free, we would love to make full use of it. Google is providing colaboratory notebooks powered by GPUs and TPUs. But when we have huge dataset to train we will have a problem. We have ways to upload the data to the virtual machine in which colaboratory is running, but at the moment you get disconnected all the data associated to that VM is lost. So we can use our own google drive data to train and also store the trained models in drive itself.</p><p>Drive FUSE is a wrapper which can help link our colab virtual machine and google drive. We can start with installing the drive Fuse wrapper in our VM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLOH1sYL5yxdwh9QgiMrmw.png" /></figure><p>This will install fuse wrapper along with other dependencies. Next we need to get the auth tokens for the colab to access our drive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fIv6J_xwXPWmiXCON4rLg.png" /></figure><p>While executing this command we will be getting a link to authenticate our google account and grant some access permissions in order to get the token, we will be prompted in the notebook to enter the token we get after the authentication. Next, we need to generate the credentials for the fuse library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3GSC726b5P-053zcDeBJQ.png" /></figure><p>During this execution also we will have to authenticate again to generate the verification code to generate the credentials to access the files in google drive. Now we are all set to create a directory and mount our google drive using the fuse library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*7jppcRJwm9Bm7AG_WVJqqQ.png" /></figure><p>Now it’s all done and we can now access our google drive files from colab notebook. we can try the command “<strong><em>!ls drive/”</em></strong> and check if we can list all the files in the google drive directory. If we see all our files then we can start pointing the drive directory to train the model on colab.</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focussed on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to contact@francium.tech, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bdec222c0e3" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/train-a-model-in-google-colaboratory-with-google-drive-data-8bdec222c0e3">Train a model in google colaboratory with google drive data</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training Deep learning models with Google Cloud ML Engine]]></title>
            <link>https://blog.francium.tech/training-deep-learning-models-with-google-cloud-ml-engine-432ae46068d8?source=rss-884e82e55b62------2</link>
            <guid isPermaLink="false">https://medium.com/p/432ae46068d8</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ml-kit]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[cloud-ml-engine]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Arun Prakash]]></dc:creator>
            <pubDate>Sat, 29 Dec 2018 04:47:59 GMT</pubDate>
            <atom:updated>2018-12-29T04:47:59.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZ22S1W4qLYOw1Lai319VA.jpeg" /></figure><p>We often develop our DL models without many difficulties but training them with a huge amount of dataset is always a painful task when you have limited computing resources.</p><p>We can counter this problem with cloud services which allow us to train beyond our local machine and give us instant access to supercomputers. To train my <a href="https://blog.francium.tech/build-your-own-image-classifier-with-tensorflow-and-keras-dc147a15e38e">image classifier model</a>, I chose Google Cloud ML engine which is a cluster of supercomputers optimized for training ML models in google cloud platform and it will have most of our requirements preinstalled and we can get our model trained on the cloud without much additional setup. But it has limited documentation and it’s pretty hard to follow. So I have put together all the steps we need to follow in order get our model trained on cloud ML engine.</p><p>First things first, get a google cloud platform account and go to the <a href="https://console.cloud.google.com/home/dashboard?project=">console</a> to create your project. Follow google’s <a href="https://cloud.google.com/ml-engine/docs/tensorflow/getting-started-training-prediction">guide</a> to set up authentication and enable cloud ML and storage services. Then install the <a href="https://cloud.google.com/sdk/">Cloud SDK</a>. Once installed check the installation with the following command.</p><pre>gcloud init</pre><p>It will setup google cloud for your account and project. Now you can create a storage bucket either on the Google cloud console or using gsutil command. If you choose to use the console, click on Storage on the sidebar menu and then click on create bucket else run this command in terminal.</p><pre>gsutil mb -l us gs://ap-cloud-ml</pre><p>Once done our bucket will appear on the console as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_06qs4pRCFjL_H9pmGjZ5w.png" /></figure><p>Now we can start coding our model, As per Google, we have to follow the below folder structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*2pXKZi6EygypuadZbVJbaw.png" /></figure><p>trainer is the main folder holding the model code and cloudml config files.</p><p>setup.py is the file we use to mention the initial setup we need, In our case, the image classifier model uses Keras and h5py. so our setup.py will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spnltCzxegIeWmMEtmcdXA.png" /></figure><p>And for the cloudml config, I’m gonna use the basic GPU with Tensorflow 1.9, so my cloudml_gpu.yaml will be</p><pre>trainingInput:<br>  scaleTier: BASIC_GPU<br>  runtimeVersion: &quot;1.9&quot;</pre><p>Now change the image classifier code to run on the cloud, First up we gonna pickle our training and test dataset of 2500 images and put it into google cloud storage for easy access. while pickling the dataset make sure to use the protocol as 2 else we will get an error on cloud while unpickling the data. Below is the sample code to pickle the train dataset.</p><pre>def train_data_with_label():<br>    train_images = []<br>    for i in tqdm(os.listdir(train_data)):<br>        path = os.path.join(train_data, i)<br>        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)<br>        img = cv2.resize(img, (64, 64))<br>        train_images.append([np.array(img), one_hot_label(i)])<br>    shuffle(train_images)<br>    pickle.dump(train_images, open(&#39;./train_images.pickle&#39;, &#39;wb&#39;), protocol=2)<br>    return train_images</pre><p>Detailed implementation of train_data_with_label() and one_hot_label() methods and the whole image classifier can be seen <a href="https://blog.francium.tech/build-your-own-image-classifier-with-tensorflow-and-keras-dc147a15e38e">here</a>. Do the same for test images and get test_images.pickle.</p><p>Now put these files into google cloud storage through the console by clicking on the upload files option or gsutil command.</p><pre>gsutil cp *.pickle gs://ap-cloud-ml</pre><p>For our training code, import the necessary items.</p><pre>from keras.models import Sequential<br>from keras.layers import *<br>from keras.optimizers import *<br>import numpy as np<br>import pickle<br>import argparse<br>from tensorflow.python.lib.io import file_io<br>import tensorflow as tf</pre><p>argparse is to parse the input arguments for the train function, pickle to unpickle the training and test dataset for training, file_io is to access the data from storage and also to save the trained model to storage bucket. The main train function will be as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AX-nhX722IDL5ITynVVujQ.png" /></figure><p>This code will build the neural net and train it on the cloud and store the final model in cloud storage. Once this code is ready we can test this locally by running the below command.</p><pre>python -m trainer.google_cloud_ml_train --job-dir=./</pre><p>On successful run, we can check the same locally with the gcloud command to check everything is configured correctly.</p><pre>gcloud ml-engine local train \<br>  --module-name trainer.google_cloud_ml_train \<br>  --package-path ./trainer \<br>  -- \<br>  --job-dir ./</pre><p>Now it’s time for us to submit our training job to cloud ML and allow the supercomputers in GCP’s infra to do the rest.</p><pre>gcloud ml-engine jobs submit training img_classifier_on_cloud_ml \<br>  --staging-bucket gs://ap-cloud-ml \<br>  --module-name trainer.google_cloud_ml_train \<br>  --package-path ./trainer \<br>  --runtime-version 1.9 \<br>  --region us-east1 \<br>  --config=trainer/cloudml-gpu.yaml \<br>  -- \<br>  --job-dir gs://ap-cloud-ml</pre><p>module-name — training code python file in our trainer directory<br>package-path — path to the packaged application which is our trainer directory<br>runtime-version — tensorflow version we need<br>region-we can use any version, but with the other regions I kept getting the resource exhausted error, so better to stick with us-east1 as other regions always have high demand.<br>config — path to tour cloudml config file<br>job_dir — our local param to insist where to store the final model</p><p>On successful submission we should be able to see our job in the cloud ML console as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MI1XTI-iHijG41Z3HzfrQ.png" /></figure><p>we can also verify the logs to ensure our training is successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAQSPSZLzqd2fQzEK-s-2Q.png" /></figure><p>Now the trained model will be available in the location we passed in the job_dir argument, which is the ap-cloud-ml bucket in our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TG4SgzCqPug5P7LHDLAgiw.png" /></figure><p>We can download this model to local and make our predictions. Overall cloud ML engine enables us to train our models on the cloud with minimal code change easily.</p><p><a href="https://francium.tech/"><em>Francium Tech</em></a><em> is a technology company laser focussed on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don’t scare us. If you have any requirements or want a free health check of your systems or architecture, feel free to shoot an email to </em><a href="http://contact@francium.tech/"><em>contact@francium.tech</em></a><em>, we will get in touch with you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=432ae46068d8" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/training-deep-learning-models-with-google-cloud-ml-engine-432ae46068d8">Training Deep learning models with Google Cloud ML Engine</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>