<?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 Monk AI on Medium]]></title>
        <description><![CDATA[Stories by Monk AI on Medium]]></description>
        <link>https://medium.com/@monkai?source=rss-349a772c539b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yPCdeXU9bTj8vd-_rFC7iA.png</url>
            <title>Stories by Monk AI on Medium</title>
            <link>https://medium.com/@monkai?source=rss-349a772c539b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:22:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@monkai/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[Logo Detection in Videos]]></title>
            <link>https://medium.com/@monkai/logo-detection-in-videos-cfcd0319cfe?source=rss-349a772c539b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfcd0319cfe</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[logo-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[inside-ai]]></category>
            <dc:creator><![CDATA[Monk AI]]></dc:creator>
            <pubDate>Fri, 24 Jan 2020 18:08:55 GMT</pubDate>
            <atom:updated>2020-01-24T19:14:31.386Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/inside-ai/home">InsideAI</a></h4><h4>Using <a href="https://github.com/Tessellate-Imaging/Monk_Object_Detection">MonkAI detection</a> workflow to locate overall brand presence in videos</h4><h3>TLDR</h3><p><a href="https://colab.research.google.com/drive/1LRTu3Zbh5Hy84CY5W9vJqTAER589jHx7">Google Colaboratory</a></p><h3>Contents</h3><ul><li>Introduction to MonkAI Object Detection workflows</li><li>Creating a custom object detector using MXRCNN</li><li>Processing images with a trained logo detector</li></ul><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*xF4nzkGhsJaWIp0HOyr8LA.jpeg" /></figure><p>One of the integral parts of a brand’s identity is it’s Logo. A Logo is a symbolic representation of a brand and the companies that get it right, often are remembered by their logo instead of their name. The intriguing thing is that human brains can recall a brand identity captured in a partial glance, or even with mild occlusions.</p><p>With TV ads being charged at per second rates, and brands looking to get more eyeballs for their products, detecting on screen presence could help marketing teams quantify their ROI.</p><p>In today’s blog we create a Logo Detector using MonkAI’s Object Detection workflows.</p><h3>MonkAI</h3><p>MonkAI is a computer vision toolkit which acts as a unified syntax invariant wrapper for Pytorch, Mxnet and Keras.</p><p>The workflows help entry level programmers by giving them simple to use workflows for setting up and prototyping Deep Learning algorithms for Computer Vision. That being said, the library is also packed with features for expert deep learning engineers.</p><p>For more information about MonkAI checkout the Github repos at : <a href="https://github.com/Tessellate-Imaging/Monk_Object_Detection">https://github.com/Tessellate-Imaging/Monk_Object_Detection</a></p><p>Do give us a star if you like what you see!</p><p>Alright enough said… Let’s begin!</p><h3>Prepare the Data</h3><p>The credit for the dataset goes to :</p><pre><em>Open Logo Detection Challenge.</em><br>Hang Su, Xiatian Zhu and Shaogang Gong.<br>In Proc. British Machine Vision Conference (BMVC), Newcastle, UK, September 2018.</pre><p>MonkAI takes ground truth in either COCO format OR in the format below. We’ll name the latter as Monk format:</p><pre>| Id         | Labels                                 |<br>| img1.jpg   | x1 y1 x2 y2 label1 x1 y1 x2 y2 label2  |</pre><ul><li>Labels: xmin ymin xmax ymax label</li><li>xmin, ymin - top left corner of bounding box</li><li>xmax, ymax - bottom right corner of bounding box</li></ul><p>We start by downloading and extracting the dataset. The original data labels are in VOC format. We can choose to either convert these labels to COCO or Monk.</p><p>Check out the <a href="https://github.com/Tessellate-Imaging/Monk_Object_Detection/blob/master/example_notebooks/3_mxrcnn/VOC%20Type%20to%20Coco%20-%20Via%20Monk%20Type%20Annotation.ipynb">demo ipynb notebook</a> for code on Data format conversion.</p><h3>Setup Monk</h3><p>Using Monk object detection workflows you can orchestrate a Computer Vision project in lesser L.O.C. For more Object Detection pipelines checkout <a href="https://github.com/Tessellate-Imaging/Monk_Object_Detection/tree/master/example_notebooks">the example notebooks</a> on Github.</p><p>Object Detection requires heavy compute power. Incase you don’t have access to a GPU machine locally you can tryout Kaggle kernels OR Google Colab for training your models.</p><p>For this exercise we use Google’s Colab, a free ipynb environment that comes packed with free GPU access.</p><pre>!git clone <a href="https://github.com/Tessellate-Imaging/Monk_Object_Detection">https://github.com/Tessellate-Imaging/Monk_Object_Detection</a></pre><pre>cd Monk_Object_Detection/3_mxrcnn/installation<br>cat requirements_cuda10.0.txt | xargs -n 1 -L 1 pip install<br>cd ../../../</pre><p>Each object detection workflow has its own set of dependencies, which can be found within requirements file in the respective directories.</p><h3>Model Training</h3><p>Before we begin training, we calculate the dataset’s mean and standard deviation values using the following <a href="https://gist.github.com/jdhao/9a86d4b9e4f79c5330d54de991461fd6">code snippet</a>. You can utilise the same script for any Object Detection workflow.</p><p>We begin by importing the library :</p><pre>import os<br>import sys<br>sys.path.append(&quot;Monk_Object_Detection/3_mxrcnn/lib/&quot;)<br>sys.path.append(&quot;Monk_Object_Detection/3_mxrcnn/lib/mx-rcnn&quot;)</pre><pre>from train_base import *</pre><p>Next we setup the parameters for training our model :</p><pre># Dataset Parameters<br>root_dir = &quot;./&quot;;<br>coco_dir = &quot;openlogo&quot;;<br>img_dir = &quot;JPEGImages&quot;;</pre><pre>set_dataset_params(root_dir=root_dir,coco_dir=coco_dir, imageset=img_dir);</pre><pre># Model Params -- Choose from vgg16, resnet50 OR resnet101<br>set_model_params(model_name=&quot;vgg16&quot;);</pre><pre># Setup Hyperparameters<br>set_hyper_params(gpus=&quot;0&quot;, lr=0.001, lr_decay_epoch=&quot;1&quot;, epochs=5, batch_size=4);</pre><p>Following are the hyper-parameters that can be set :</p><ul><li>Starting learning rate ‘lr’ == 0.001</li><li>Learning rate decay after ’n’ epochs. n == 1</li><li>Number of ‘epochs’ == 5</li><li>‘batch_size’ == 4</li></ul><p>To use multiple GPUs while training pass the GPU indexes as a list :</p><ul><li>gpus = [0,1,2,3]</li></ul><p>Now we can load the parameters and begin training :</p><pre>set_output_params(log_interval=5, save_prefix=&quot;model_vgg16&quot;);</pre><pre>set_img_preproc_params(img_short_side=600, img_long_side=1000,<br>mean=mean, std=std);</pre><pre>initialize_rpn_params();<br>initialize_rcnn_params();</pre><pre>roidb = set_dataset();</pre><pre>sym = set_network();<br>train(sym, roidb);</pre><p>Once the training begins you should receive output messages as follows:</p><pre>INFO:root:Epoch[0] Batch [0-100] Speed: 4.90 samples/sec RPNAcc=0.952806 RPNLogLoss=0.216140 RPNL1Loss=1.289626 RCNNAcc=0.831915 RCNNLogLoss=1.527982 RCNNL1Loss=1.836704 </pre><pre>INFO:root:Epoch[0] Batch [0-200] Speed: 4.68 samples/sec RPNAcc=0.961399 RPNLogLoss=0.167928 RPNL1Loss=1.038006 RCNNAcc=0.840485 RCNNLogLoss=1.402681 RCNNL1Loss=1.873249 </pre><pre>INFO:root:Epoch[0] Batch [0-300] Speed: 4.55 samples/sec RPNAcc=0.964584 RPNLogLoss=0.147237 RPNL1Loss=0.950124 RCNNAcc=0.842322 RCNNLogLoss=1.338426 RCNNL1Loss=1.890560 </pre><pre>INFO:root:Epoch[0] Batch [0-400] Speed: 4.77 samples/sec RPNAcc=0.965913 RPNLogLoss=0.135502 RPNL1Loss=0.889152 RCNNAcc=0.842581 RCNNLogLoss=1.291315 RCNNL1Loss=1.933994</pre><p>Finally after training for 5 epochs we arrive at the following accuracy and loss values :</p><pre>INFO:root:Epoch[4] Train-RPNAcc=0.992778<br>INFO:root:Epoch[4] Train-RPNLogLoss=0.019948<br>INFO:root:Epoch[4] Train-RPNL1Loss=0.197941<br>INFO:root:Epoch[4] Train-RCNNAcc=0.973778<br>INFO:root:Epoch[4] Train-RCNNLogLoss=0.090478<br>INFO:root:Epoch[4] Train-RCNNL1Loss=0.512981<br>INFO:root:Saved checkpoint to &quot;trained_model/model_resnet101-0005.params&quot;</pre><p>Now that we have trained our model, it’s time to test it on some images:</p><h3>Inference</h3><p>Before you can begin testing your new model on images make sure you have stored the model at an accessible location. We start by loading the model and class labels.</p><pre>import os<br>import sys<br>sys.path.append(&quot;Monk_Object_Detection/3_mxrcnn/lib/&quot;)<br>sys.path.append(&quot;Monk_Object_Detection/3_mxrcnn/lib/mx-rcnn&quot;)</pre><pre>from infer_base import *</pre><pre>class_file = set_class_list(&quot;./openlogo/annotations/classes.txt&quot;);</pre><pre>set_model_params(model_name=&quot;vgg16&quot;,model_path=&quot;trained_model/model_vgg16-0001.params&quot;);</pre><pre>set_hyper_params(gpus=&quot;0&quot;, batch_size=1);</pre><pre>set_img_preproc_params(img_short_side=600, img_long_side=1000,mean=(123.68, 116.779, 103.939), std=(1.0, 1.0, 1.0));</pre><pre>initialize_rpn_params();<br>initialize_rcnn_params();<br>sym = set_network();<br>mod = load_model(sym);<br>set_output_params(vis_thresh=0.9, vis=True)</pre><p>Lo and behold, our logo detector can hunt popular brand logos within images and videos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*EEsBN_yoNvwHzppF42xFVA.png" /></figure><pre>Infer(image_path, mod);</pre><p>Incase you feel stuck we have prepared an Evaluation notebook along with the trained models :</p><p><a href="https://colab.research.google.com/drive/1alL8bpjXq4m3RyedeeoRI5qOW83Siotr">Google Colaboratory</a></p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfcd0319cfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Food Classification with Monk]]></title>
            <link>https://medium.com/@monkai/food-classification-with-monk-ccc215b283ff?source=rss-349a772c539b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccc215b283ff</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[food]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[food-technology]]></category>
            <dc:creator><![CDATA[Monk AI]]></dc:creator>
            <pubDate>Mon, 02 Dec 2019 13:17:48 GMT</pubDate>
            <atom:updated>2019-12-02T13:30:09.038Z</atom:updated>
            <content:encoded><![CDATA[<h3>What will you build!</h3><p>In this post we will make 3 levels of Food Classification models :</p><ul><li>Classify input image as Food vs Non Food</li><li>Classify an input image of Food into 11 super categories</li><li>Classify an input image of Food as one of 101 dishes</li></ul><p>And finally combine the 3 projects into one Food Classification application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ykiHyGErizGRhBGxileQKA.gif" /><figcaption>Final Food classification app</figcaption></figure><h3>TLDR</h3><p><a href="https://drive.google.com/file/d/1ELNkFaMqEU_xOYG1V80vqc0WQJeSaGQO/view?usp=sharing">Food101_Classification.ipynb</a></p><p>Let’s begin!</p><h3>Setup</h3><p>We start our exercise by setting up Monk Computer Vision toolkit. To know more about Monk checkout the <a href="https://monkai-42.firebaseapp.com/">WEBSITE</a> and <a href="https://clever-noyce-f9d43f.netlify.com/">DOCS</a>.</p><pre>$ git clone <a href="https://github.com/Tessellate-Imaging/monk_v1">https://github.com/Tessellate-Imaging/monk_v1</a></pre><p>Setup the dependencies based on the platform you are working with. Monk is compatible with Ubuntu, MacOS, Windows and online Jupyter environments like Kaggle and Colab.</p><p>Check out the <a href="https://clever-noyce-f9d43f.netlify.com/#/setup/setup">setup docs</a> for setting up dependencies on respective environments.</p><h3>Project 1 : Food vs Non Food Classification</h3><p>Let’s create our first project for classifying an input image into food or non food categories. The goal of this project is solely to determine if a food item is present in the input image and can be further classified into a super and sub category.</p><h4>Start Experiment 1</h4><p>Import monk library</p><pre>import os<br>import sys<br>sys.path.append(&quot;./monk_v1/monk/&quot;);<br>import psutil<br>from pytorch_prototype import prototype</pre><p>and create a new experiment</p><pre>ptf = prototype(verbose=1);<br>ptf.Prototype(“food_nonfood”, “exp1”);</pre><h4>Dataset</h4><p>For this project we are using the <a href="https://mmspg.epfl.ch/downloads/food-image-datasets/">Food-5k</a> dataset.</p><p>“This dataset contains 2500 food and 2500 non-food images, for the task of food/non-food classification from the paper “Food/Non-food Image Classification and Food Categorisation using Pre-Trained GoogLeNet Model”. The whole dataset is divided in three parts: training, validation and evaluation. The naming convention is as follows:</p><p>{ClassID}_{ImageID}.jpg</p><p>ClassID: 0 or 1; 0 means non-food and 1 means food.”</p><p>For our project we will combine the training, validation and evaluation sets into one.</p><pre>from glob import glob<br>import os<br>import shutil<br>from tqdm import tqdm</pre><pre>folders = glob(&quot;./food-5k/*&quot;)</pre><pre>food_dir = &#39;./food-5k/food&#39;<br>non_food_dir = &#39;./food-5k/non-food&#39;<br>if not os.path.exists(food_dir):<br>    os.makedirs(food_dir)<br>if not os.path.exists(non_food_dir):<br>    os.makedirs(non_food_dir)</pre><pre>c = 1<br>n_c = 1<br>for i in folders:<br>    imageList = glob(i + &#39;/*.jpg&#39;)<br>    print(len(imageList))<br>    for j in tqdm(imageList):<br>        imgName = j.split(&#39;/&#39;)[-1]<br>        label = imgName.split(&#39;_&#39;)[0]<br>        if label == &#39;0&#39;:<br>            outPath = non_food_dir + &#39;/&#39; + str(n_c) + &#39;.jpg&#39;<br>            n_c += 1<br>        elif label == &#39;1&#39;:<br>            outPath = food_dir + &#39;/&#39; + str(c) + &#39;.jpg&#39;<br>            c += 1<br>        shutil.move(j,outPath)</pre><p>Now we can load our dataset, select our CNN architecture to train and set the number of epochs.</p><pre>ptf.Default(dataset_path=&quot;./food-5k/&quot;, model_name=&quot;resnet18&quot;, freeze_base_network=True, num_epochs=5)</pre><p>And begin training :</p><pre>ptf.Train()</pre><p>After training is finished we can observe the loss and accuracy plots stored inside <strong>workspace&gt;”project_name”&gt;”exp_name”&gt;output&gt;logs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*kwa1nfPzgCGvat85YhLk5g.png" /><figcaption>accuracy plot for food_nonfood experiment 1</figcaption></figure><p>Let’s create a new experiment with a different CNN architecture and see if we can achieve better performance.</p><h4>Experiment 2</h4><pre>ptf = prototype(verbose=1);<br>ptf.Prototype(“food_nonfood”, “exp2”);</pre><p>We can check the available models using :</p><pre>ptf.List_Models()</pre><p>Our experiment 1 was created using <strong>‘resnet18’</strong>. For experiment 2 we will select <strong>‘resnet101’</strong>.</p><p>By using residual networks, many problems can be solved such as:</p><ul><li>ResNets are easy to optimize, but the “plain” networks (that simply stack layers) shows higher training error when the depth increases.</li><li>ResNets can easily gain accuracy from greatly increased depth, producing results which are better than previous networks.</li></ul><p>To know more about ResNet architectures check out this <a href="https://neurohive.io/en/popular-networks/resnet/">post</a>.</p><pre>ptf.Default(dataset_path=”./food-5k/”, model_name=”resnet101&quot;, freeze_base_network=True, num_epochs=5)</pre><p>For experiment 2 we will unfreeze a few more layers from our pre-trained model to make them available for training. We also increase the number of epochs and reload the experiment.</p><pre>ptf.update_freeze_layers(100);<br>ptf.update_num_epochs(30);<br>ptf.Reload()</pre><p>And finally train the model:</p><pre>ptf.Train()</pre><p>Once again we can observe the loss and accuracy plots for this experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*5taQKqeZKCNwKPNlD-aoYw.png" /><figcaption>accuracy plot for food_nonfood classifier experiment 2</figcaption></figure><h4>Comparison</h4><p>We can compare the two experiments for training and validation accuracies and losses. (Check out <a href="https://clever-noyce-f9d43f.netlify.com/#/compare_experiment">DOCS</a>)</p><pre>from compare_prototype import compare</pre><pre>ctf = compare(verbose=1);<br>ctf.Comparison(&quot;food_nonfood&quot;);</pre><pre>ctf.Add_Experiment(&quot;food_nonfood&quot;, &quot;exp1&quot;);<br>ctf.Add_Experiment(&quot;food_nonfood&quot;, &quot;exp2&quot;);</pre><pre>ctf.Generate_Statistics()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvuIbfkg-xL1nn8EiyFogg.png" /></figure><p>Let’s test our model on food and non_food images.</p><h4>Inference</h4><p>First we load the experiment in evaluation mode:</p><pre>ptf.Prototype(“food_nonfood”, “exp2”, eval_infer=True);</pre><pre>img_name = “./test.jpg”;<br>predictions = ptf.Infer(img_name=img_name, return_raw=False);<br>print(predictions)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kd7pJ9qzH48zZ3F9Vr6WMg.jpeg" /></figure><pre>Prediction<br>    Image name:         ./test.jpg<br>    Predicted class:      food<br>    Predicted score:      4.16873025894165<br><br>{&#39;img_name&#39;: &#39;./test.jpg&#39;, &#39;predicted_class&#39;: &#39;food&#39;, &#39;score&#39;: 4.1687303}</pre><h3>Project 2 : Food-11 Classification</h3><p>Now that we can classify input image as food or nonfood, we shall begin with classifying food images into different categories of dishes.</p><h4>Dataset</h4><p>For this project we will utilise <a href="https://mmspg.epfl.ch/downloads/food-image-datasets/">Food-11</a> dataset.</p><p>“This dataset contains 16643 food images grouped in 11 major food categories. The 11 categories are Bread, Dairy product, Dessert, Egg, Fried food, Meat, Noodles/Pasta, Rice, Seafood, Soup, and Vegetable/Fruit. Similar as Food-5K dataset, the whole dataset is divided in three parts: training, validation and evaluation. The same naming convention is used, where ID 0–10 refers to the 11 food categories respectively.”</p><p>We will combine the training, evaluation and validation folders into one set of images and split them into respective class folders.</p><pre>classes = {&#39;0&#39;:&#39;Bread&#39;,&#39;1&#39;:&#39;Dairy_Product&#39;,&#39;2&#39;:&#39;Dessert&#39;,&#39;3&#39;:&#39;Egg&#39;,&#39;4&#39;:&#39;Fried_Food&#39;,&#39;5&#39;:&#39;Meat&#39;,&#39;6&#39;:&#39;Noodles_Pasta&#39;,&#39;7&#39;:&#39;Rice&#39;,&#39;8&#39;:&#39;Seafood&#39;,&#39;9&#39;:&#39;Soup&#39;,&#39;10&#39;:&#39;Vegetable_Fruit&#39;}</pre><pre>from glob import glob</pre><pre>folders = glob(&quot;./food-11/*&quot;)<br>print(folders)</pre><pre>import os</pre><pre>for k,item in classes.items():<br>    directory = &#39;./food-11/&#39; + item<br>    if not os.path.exists(directory):<br>        os.makedirs(directory)</pre><pre>import shutil<br>from tqdm import tqdm</pre><pre>c = 1<br>for i in folders:<br>    imageList = glob(i + &#39;/*.jpg&#39;)<br>    #print(len(imageList))<br>    for j in tqdm(imageList):<br>        imgName = j.split(&#39;/&#39;)[-1]<br>        label = imgName.split(&#39;_&#39;)[0]<br>        outPath = &#39;./food-11/&#39; + classes[label] + &#39;/&#39; + str(c) + &#39;.jpg&#39;<br>        c += 1<br>        shutil.move(j,outPath)</pre><h4>Start Experiment 1</h4><p>We can now create a new project, start with our experiment and load our dataset.</p><pre>ptf = prototype(verbose=1);<br>ptf.Prototype(&quot;food-11&quot;, &quot;exp1&quot;);</pre><pre>ptf.Default(dataset_path=&quot;./food-11/&quot;, model_name=&quot;resnet101&quot;, freeze_base_network=True, num_epochs=10)</pre><p>For this experiment we are using Resnet101 as our pre-trained model. Finally we can begin training :</p><pre>ptf.Train()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*37s-DSnnEHGo0wbTs3CBTw.png" /></figure><p>We can observe that after 10 epochs the model achieves an accuracy of ~ 75%. The validation loss was still going down and we can achieve better accuracy if we train for more epochs. Let’s try that out using <a href="https://clever-noyce-f9d43f.netlify.com/#/copy_experiment">Copy_Experiment</a></p><h4>Experiment 2</h4><p>We create the new experiment using the previous experiment 1 as a template and make a few updates.</p><pre>ptf = prototype(verbose=1)<br>ptf.Prototype(&quot;food-11&quot;, &quot;exp2&quot;, copy_from=[&quot;food-11&quot;, &quot;exp1&quot;]);</pre><pre>ptf.update_freeze_layers(100);<br>ptf.update_num_epochs(30);</pre><pre>ptf.Reload()</pre><p>Note : Don’t forget to reload the experiment with ‘ptf.Reload()’ after making <a href="https://clever-noyce-f9d43f.netlify.com/#/update_mode/update_dataset">updates to your experiment</a></p><p>And now we can begin our training. Once training is complete we will compare the both the experiments and choose one to inference with.</p><h4>Compare</h4><pre>ctf = compare(verbose=1);<br>ctf.Comparison(&quot;food-11&quot;);</pre><pre>ctf.Add_Experiment(&quot;food-11&quot;, &quot;exp1&quot;);<br>ctf.Add_Experiment(&quot;food-11&quot;, &quot;exp2&quot;);</pre><pre>ctf.Generate_Statistics()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Voabo64c5AL6j6uzTLB_kA.png" /></figure><p>Since we used Copy_Experiment the accuracy for experiment 2 for epoch 1 starts from a better value that experiment 1. We can also observe that we quickly reach saturation around 10 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5Qw8F_c2oerulQA4B4qUw.png" /></figure><p>We can also observe the validation accuracy keeps fluctuating. We can definitely choose to go ahead with experiment 2 model with considerably better training and validation performance.</p><h4>Inference</h4><p>Our food-11 project model can classify an input food image into one of 11 top level food categories.</p><p>Let’s test it on our waffles image!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kd7pJ9qzH48zZ3F9Vr6WMg.jpeg" /></figure><pre>{&#39;img_name&#39;: &#39;./test.jpg&#39;, &#39;predicted_class&#39;: &#39;Dessert&#39;, &#39;score&#39;: 27.722319}</pre><p>The prediction comes out to ‘Dessert’!</p><h3>Project 3 : Food-101 Classification</h3><p>Finally we move on to classifying the input image into exactly what we are looking at. In this project we will classify the image from out of 101 classes of food items.</p><h4>Dataset</h4><p>For this experiment we will be utilising dataset gathered by these awesome researchers : <a href="https://www.vision.ee.ethz.ch/datasets_extra/food-101/">LINK</a></p><p>Citations at the bottom of the post.</p><p>“This dataset contains 101 food categories, with 101&#39;000 images. For each class, 250 manually reviewed test images are provided as well as 750 training images. On purpose, the training images were not cleaned, and thus still contain some amount of noise. This comes mostly in the form of intense colors and sometimes wrong labels. All images were rescaled to have a maximum side length of 512 pixels.”</p><h4>Experiment 1</h4><p>For this experiment we will utilise a denset201 pretrained model.</p><p>We can create the experiment, load the dataset, select the pretrained architecture, set the number of epochs and begin training all in just 4 lines of code.</p><pre>ptf = prototype(verbose=1)<br>ptf.Prototype(&quot;food-101&quot;, &quot;exp1&quot;)</pre><pre>ptf.Default(dataset_path=&quot;./food-101/images/&quot;, model_name=&quot;densenet169&quot;, freeze_base_network=False, num_epochs=10)</pre><pre>ptf.Train()</pre><p>After 10 epochs the training accuracy comes out to ~87% which is not bad to start out with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*krPnXfmWmq5c6cPSf40WWw.png" /></figure><p>Let’s finally test our waffles input image and see the results.</p><h4>Inference</h4><p>Let’s load up the experiment in evaluation mode and test on single image. Check out our <a href="https://clever-noyce-f9d43f.netlify.com/#/quick_mode/quickmode_pytorch">Docs</a> for running test on a batch of images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kd7pJ9qzH48zZ3F9Vr6WMg.jpeg" /></figure><pre>{&#39;img_name&#39;: &#39;./test.jpg&#39;, &#39;predicted_class&#39;: &#39;waffles&#39;, &#39;score&#39;: 74.87055}</pre><p>And guess what! The model predicts that the input image is of “Waffles”.</p><h3>Food Classification Application</h3><p>Finally we will combine the 3 projects to create a Food Classification application, which can detect if an input image is of a food item and if yes then predict the super (out of 11) and sub (out of 101) category of the food.</p><pre>import requests<br>import os<br>import sys<br>sys.path.append(&quot;./monk_v1/monk/&quot;);<br>import psutil<br>from pytorch_prototype import prototype</pre><pre>def saveImg(img_url):<br>    # URL of the image to be downloaded is defined as image_url <br>    r = requests.get(img_url) # create HTTP response object <br>    with open(&#39;test.jpg&#39;,&#39;wb&#39;) as f: <br>        f.write(r.content)</pre><pre>def classify(img_url):<br>    saveImg(img_url)<br>    img_name = &#39;./test.jpg&#39;<br>    ptf1 = prototype(verbose=0)<br>    ptf1.Prototype(&quot;food_nonfood&quot;, &quot;exp2&quot;, eval_infer=True);</pre><pre>    predictions = ptf1.Infer(img_name=img_name, return_raw=False);</pre><pre>    if predictions[&#39;predicted_class&#39;] == &quot;non_food&quot;:<br>        return &quot;Input image does not contain food&quot;<br>    else:<br>        ptf2 = prototype(verbose=0)<br>        ptf2.Prototype(&quot;food-11&quot;, &quot;exp2&quot;, eval_infer=True);<br>        predictions = ptf2.Infer(img_name=img_name,  return_raw=False);</pre><pre>    superLabel = predictions[&#39;predicted_class&#39;]</pre><pre>    ptf3 = prototype(verbose=0)<br>        ptf3.Prototype(&quot;food-101&quot;, &quot;exp1&quot;, eval_infer=True);<br>        predictions = ptf3.Infer(img_name=img_name, return_raw=False);</pre><pre>    subLabel = predictions[&#39;predicted_class&#39;]</pre><pre>    return &quot;Input image is of category {}, and is actually {}.&quot;.format(superLabel,subLabel)</pre><p>Finally to test the classification app run:</p><pre>test_url = &quot;<a href="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/delish-keto-waffle-horizontal-034-1543784709.jpg">https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/delish-keto-waffle-horizontal-034-1543784709.jpg</a>&quot;</pre><pre>output = classify(test_url)<br>print(output)</pre><p>To test with a new image, update the test_url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*6piu-HjpGlponFwrjVHLtA.jpeg" /></figure><pre>Input image is of category Bread, and is actually pizza.</pre><p>That’s all for this post folks. Hope you enjoyed going through this.</p><p>The trained models are available to download here as a workspace directory <a href="https://docs.google.com/uc?export=download&amp;id=1Bn3rAY5MmRiXCeY-qJnAxs_b7h-qAdfY">HERE</a>.</p><p>The workspace folder is cross platform compatible. All you need to do is setup monk and paste the workspace in your working directory to be able to run inference.</p><p>Do give us a star on <a href="https://github.com/Tessellate-Imaging/monk_v1/">Github</a> if you like what you see (All the haters of food get out!)</p><p>Happy Coding!</p><h3>References</h3><ul><li><a href="https://neurohive.io/en/popular-networks/resnet/">https://neurohive.io/en/popular-networks/resnet/</a></li><li><a href="https://www.vision.ee.ethz.ch/datasets_extra/food-101/">https://www.vision.ee.ethz.ch/datasets_extra/food-101/</a></li><li><a href="https://mmspg.epfl.ch/downloads/food-image-datasets/">https://mmspg.epfl.ch/downloads/food-image-datasets/</a></li></ul><pre>@inproceedings{bossard14,<br>  title = {Food-101 -- Mining Discriminative Components with Random Forests},<br>  author = {Bossard, Lukas and Guillaumin, Matthieu and Van Gool, Luc},<br>  booktitle = {European Conference on Computer Vision},<br>  year = {2014}<br>}</pre><p>Regards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccc215b283ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sign Language Classification with Monk]]></title>
            <link>https://medium.com/@monkai/sign-language-classification-with-monk-6850bc6fc4ea?source=rss-349a772c539b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6850bc6fc4ea</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[sign-language]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-classification]]></category>
            <dc:creator><![CDATA[Monk AI]]></dc:creator>
            <pubDate>Thu, 28 Nov 2019 07:45:19 GMT</pubDate>
            <atom:updated>2019-11-28T07:45:19.607Z</atom:updated>
            <content:encoded><![CDATA[<h3>TLDR</h3><p><a href="https://colab.research.google.com/drive/1FWiathcbPx_DbBiWhH9WSC92WAylrhAG">Google Colaboratory</a></p><h3>Introduction</h3><p>Communication is an essence of human life. From ancient hieroglyphics to the 6500 languages spoken currently across the world, they all signify the importance of our ability to reach out to our fellow human beings.</p><p>Even though the global literacy rate for all people aged 15 and above is <strong>86.3%, </strong>there are only about 250 certified sign language interpreters in India, translating for a deaf population of between 1.8 million and 7 million. The wide disparity in population estimates exists because the Indian census doesn’t track the number of deaf people — instead, it documents an aggregate number of people with disabilities. <br>(Source : <a href="https://www.pri.org/stories/2017-01-04/deaf-community-millions-hearing-india-only-just-beginning-sign">https://www.pri.org/stories/2017-01-04/deaf-community-millions-hearing-india-only-just-beginning-sign</a>)</p><h3>What will you build!</h3><p>In this blog post we build an American Sign Language classifier and try to automate the process of sign language translation.</p><h3>Setup</h3><p>We start by setting up Monk and it’s dependencies on colab. For further setup instructions on different platforms check out the <a href="https://clever-noyce-f9d43f.netlify.com/#/setup/setup">DOCS</a>.</p><pre>$ git clone <a href="https://github.com/Tessellate-Imaging/monk_v1">https://github.com/Tessellate-Imaging/monk_v1</a><br>$ cd monk_v1/installation &amp;&amp; pip install -r requirements_cu10.txt<br>$ cd ../..</pre><h3>Dataset</h3><p>We will utilise the ASL image dataset from Kaggle — <a href="https://www.kaggle.com/grassknoted/asl-alphabet">LINK</a>.</p><h3>Training</h3><p>Next we will use Pytorch as our backend to create a new Project and use Resnet50 as our pre-trained model.</p><pre>ptf = prototype(verbose=1);</pre><pre>ptf.Prototype(&quot;asl&quot;, &quot;exp1&quot;);</pre><pre>ptf.Default(dataset_path=&quot;./dataset/train&quot;, model_name=&quot;resnet50&quot;, freeze_base_network=True, num_epochs=10);</pre><p>We train our model for 10 epochs and check the training and validation accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*2Cmj4404cRadG_ut3Wj6lg.png" /></figure><p>The plot shows that even though our training accuracy is lower, the model performs quite well on the validation set.</p><p>The dataset is not diverse enough to create a generalised model.</p><p>However further improvement can be achieved by using image augmentation strategies.</p><p>Let’s put the model to test with a realtime video classification.</p><p><strong>Note</strong> : A process automation pipeline for image or video processing requires much more than just a classification model. In our case we would require a hand detector to localise the position of hands within the frame, a hand tracker to reduce jitter from the hand detector and finally the sign language classifier. Even after setting up all the modules, the heuristics and dataset requirements would differ based on the application and deployment scenario. To give an example, the current classifier is built with a webcam dataset and will surely not work with AR headsets which have a different point of view.</p><p>For this exercise we will set a region of interest within the frame where our hand must be placed for the model to determine the gestures.</p><h3>Realtime Gesture Classification</h3><p>We begin by loading our experiment in evaluation mode.</p><pre>import os<br>import sys<br>sys.path.append(“./monk_v1/monk/”);<br>import psutil<br>from pytorch_prototype import prototype<br>from imutils.video import VideoStream<br>import cv2</pre><pre>ptf = prototype(verbose=1)<br>ptf.Prototype(“asl”, “exp1”, eval_infer=True);</pre><p>We capture a video stream from our webcam, set a region of interest within the frame and store it in a file.</p><pre>if __name__ == ‘__main__’:<br>  vs = VideoStream().start()<br>  im_height, im_width = (None, None)<br>  while True:<br>    # Read Frame and process<br>    frame = vs.read()<br>    frame = cv2.resize(frame, (640, 480))<br>    frame = cv2.flip( frame, 1 )</pre><pre>    #Set ROI<br>    cv2.rectangle(frame, (350,50), (600,300), (255,0,0) , 3, 1)</pre><pre>    roi = frame[50:300,350:600]</pre><pre>    roi = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)<br>    cv2.imwrite(“roi.jpg”,roi)</pre><p>Next we load the ROI image and infer using our classification model generated with Monk and display the predicted class:</p><pre>    predictions = ptf.Infer(img_name=”roi.jpg”, return_raw=False);<br>    <br>    cv2.putText(frame, predictions[‘predicted_class’],(350,40),cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2)<br>    <br>    cv2.imshow(‘ASL’, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))<br> <br>    if cv2.waitKey(25) &amp; 0xFF == ord(‘q’):<br>      cv2.destroyAllWindows()<br>      vs.stop()<br>      break</pre><p>The model performs fairly well in proper lighting conditions. In the following video I try to write the word “MONK” using hand gestures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*RGW1izoL0tAwEW0JQTzotA.gif" /></figure><h3>Coming Soon!</h3><p>We are constantly striving to improve the features available in Monk. Following are some developments that we will be releasing soon:</p><ul><li>Adding custom layers and creating custom Deep Neural architectures</li><li>More optimisers, regularisers and loss functions</li><li>Multi-label classification for image tagging</li></ul><p>We are creating a community of collaborators for Monk.</p><p>Signup here to become a beta tester : <a href="https://monkai-42.firebaseapp.com/">LINK</a></p><p><strong>Mention in comments which features and applications you would like us to build next.</strong></p><p>Do give us a star on <a href="https://github.com/Tessellate-Imaging/monk_v1/">Github</a> if you like what you see!</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6850bc6fc4ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plant Disease Classification with Monk]]></title>
            <link>https://medium.com/@monkai/plant-disease-classification-with-monk-3a4d7ba419b9?source=rss-349a772c539b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a4d7ba419b9</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[plant-disease]]></category>
            <category><![CDATA[inside-ai]]></category>
            <dc:creator><![CDATA[Monk AI]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 12:52:06 GMT</pubDate>
            <atom:updated>2020-01-17T10:35:12.735Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/inside-ai/">Inside AI</a></h4><h4>Using model finder to automate detecting the right hyper-parameters</h4><h3>TLDR</h3><p><a href="https://drive.google.com/file/d/1BrWdjgXREy6VWYlyn9wF4iaqSGf8yvEa/view?usp=sharing">Plant_Disease_Classification.ipynb</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bnXj3CixhKv7upOTrY3Thw.png" /><figcaption>Leaf Diseases</figcaption></figure><p>In agriculture, leaf diseases cause a major decrease in both quality and quantity of yields. Automating plant disease detection using Computer Vision could play a role in early detection and prevention of diseases.</p><h3>What will you build!</h3><p>In this exercise we will explore how to build a plant leaf disease classifier using Monk’s quick <a href="https://clever-noyce-f9d43f.netlify.com/#/hp_finder/model_finder">Hyper-Parameter finding feature</a>.</p><p>Monk provides a syntax invariant transfer learning framework that supports Keras, Pytorch and Mxnet in the backend. (Read — <a href="https://clever-noyce-f9d43f.netlify.com/">Documentation</a>).</p><p>Computer Vision developers have to explore strategies while selecting the correct learning rates, a fitting CNN architecture, use the right optimisers and fine-tune many more parameters to get the best performing models.</p><p>The Hyper-Parameter finding features assists in analysing multiple options for a selected hyper-parameter before proceeding with the actual experiment. This not just saves a lot of time spent in prototyping but also assists in quickly exploring the how well a selected set of parameters perform on the dataset in use and the final application.</p><p>Let’s begin!</p><h3>Setup</h3><p>We start by setting up Monk and it’s dependencies on colab. For further setup instructions on different platforms check out the <a href="https://clever-noyce-f9d43f.netlify.com/#/setup/setup">DOCS</a>.</p><pre>$ git clone <a href="https://github.com/Tessellate-Imaging/monk_v1">https://github.com/Tessellate-Imaging/monk_v1</a><br>$ cd monk_v1/installation &amp;&amp; pip install -r requirements_cu10.txt<br>$ cd ../..</pre><h3>Dataset</h3><p>For this exercise we will use dataset gathered by the awesome folks at <a href="https://plantvillage.psu.edu/">PlantVillage</a>.</p><h3>Experimentation</h3><p>Before setting up our analysis, we have to start by creating a new project and experiment</p><pre># Step 1 - Create experiment</pre><pre>ptf = prototype(verbose=1);</pre><pre>ptf.Prototype(&quot;plant_disease&quot;, &quot;exp1&quot;);</pre><p>and setup the ‘Default’ dataset paths</p><pre>ptf.Default(dataset_path=[&quot;./dataset/train&quot;, &quot;./dataset/val&quot;], model_name=&quot;resnet18&quot;, freeze_base_network=True, num_epochs=5);</pre><p>Now we are ready to run some analysis and find the best Hyper-Parameters.</p><p>Currently we can analyse the following parameters :</p><ol><li>Find the best CNN architecture — [<a href="https://clever-noyce-f9d43f.netlify.com/#/hp_finder/model_finder">DOCS</a>]</li><li>Find the right batch size — [<a href="https://clever-noyce-f9d43f.netlify.com/#/hp_finder/batch_size_finder">DOCS</a>]</li><li>Find the a good input shape — [<a href="https://clever-noyce-f9d43f.netlify.com/#/hp_finder/input_dimension_finder">DOCS</a>]</li><li>Select a good starting learning rate — [<a href="https://clever-noyce-f9d43f.netlify.com/#/hp_finder/LR_finder">DOCS</a>]</li><li>Select the best performing Optimiser — [<a href="https://clever-noyce-f9d43f.netlify.com/#/hp_finder/optimiser_finder">DOCS</a>]</li></ol><p>We will analyse each of the above parameters to select the best and finally train our model to build the application of Plant Leaf disease classification.</p><h3>Model Finder</h3><p>Start by giving a name to the analysis. For every analysis a new project is created with multiple experiments inside.</p><pre>analysis_name = “Model_Finder”;</pre><p>Now we pass on the list of Models from which to analyse</p><ul><li>First element in the list — Model Name</li><li>Second element in the list — Boolean value to freeze base network or not</li><li>Third element in the list — Boolean value to use pretrained model as the starting point or not</li></ul><pre>models = [[“resnet34”, True, True], [“resnet50”, False, True],[“densenet121”, False, True], [“densenet169”, True, True], [“densenet201”, True, True]];</pre><p>Set the Number of epochs for each experiment to run</p><pre>epochs=5;</pre><p>Select the Percentage of original dataset to take in for experimentation</p><pre>percent_data=10;</pre><p>Finally we run the analysis function to search for best performing models:</p><ul><li>“keep_all” — Keeps all the experiments created</li><li>“keep_none” — Deletes all experiments created</li></ul><pre>ptf.Analyse_Models(analysis_name, models, percent_data, num_epochs=epochs, state=”keep_none”);</pre><p>When the analysis is running, the estimated time is displayed for every experiment</p><pre>Running Model analysis<br>Analysis Name : Model_Finder </pre><pre>Running experiment : 1/5 <br>Experiment name : Model_resnet34_freeze_base_pretrained <br>Estimated time : 2 min</pre><p>Finally after the experiment is completed we receive the following output on training and validation accuracies and losses :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*VPXPpgLOyhSvlFVgZq8WwA.png" /></figure><p>Select the best performing CNN architecture, update your experiment and continue with further analysis. Don’t forget to reload the experiment after updating.</p><pre>## Update Model Architecture<br>ptf.update_model_name(“densenet121”);<br>ptf.update_freeze_base_network(False);<br>ptf.update_use_pretrained(True);<br>ptf.Reload();</pre><p>For further instructions on updating experiment parameters, check out the <a href="https://clever-noyce-f9d43f.netlify.com/#/update_mode/update_dataset">documentation</a>.</p><p>The other four analysis follow a similar syntax. We’ll quickly go through each of these:</p><h3>Batch Size Finder</h3><pre># Analysis Project Name<br>analysis_name = “Batch_Size_Finder”;</pre><pre># Batch sizes to explore<br>batch_sizes = [4, 8, 16, 32];</pre><pre># Num epochs for each experiment to run<br>epochs = 10;</pre><pre># Percentage of original dataset to take in for experimentation<br>percent_data = 10;</pre><pre>ptf.Analyse_Batch_Sizes(analysis_name, batch_sizes, percent_data, num_epochs=epochs, state=”keep_none”);</pre><p>Generated output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*M3_aakYsou85v9FGjr_xfQ.png" /></figure><p>Update the experiment :</p><pre>## Update Batch Size</pre><pre>ptf.update_batch_size(8);<br>ptf.Reload();</pre><h3>Input Shape Finder</h3><pre># Analysis Project Name<br>analysis_name = “Input_Size_Finder”;</pre><pre># Input sizes to explore<br>input_sizes = [224, 256, 512];</pre><pre># Num epochs for each experiment to run<br>epochs=5;</pre><pre># Percentage of original dataset to take in for experimentation<br>percent_data=10;</pre><pre>ptf.Analyse_Input_Sizes(analysis_name, input_sizes, percent_data, num_epochs=epochs, state=”keep_none”);</pre><p>Generated output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*FhEz5PoB9WxaBZ2SUzO33w.png" /></figure><p>Update the experiment :</p><pre>## Update Input Size</pre><pre>ptf.update_input_size(224);<br>ptf.Reload();</pre><h3>Learning Rate Analysis</h3><pre># Analysis Project Name<br>analysis_name = “Learning_Rate_Finder”</pre><pre># Learning rates to explore<br>lrs = [0.01, 0.005, 0.001, 0.0001];</pre><pre># Num epochs for each experiment to run<br>epochs=5</pre><pre># Percentage of original dataset to take in for experimentation<br>percent_data=10</pre><pre>ptf.Analyse_Learning_Rates(analysis_name, lrs, percent_data, num_epochs=epochs, state=”keep_none”);</pre><p>Generated output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*Ht6x1pf1giaFnXaO7ipjhA.png" /></figure><p>Update the experiment :</p><pre>## Update Learning Rate</pre><pre>ptf.update_learning_rate(0.01);<br>ptf.Reload();</pre><h3>Optimiser Analysis</h3><pre># Analysis Project Name<br>analysis_name = “Optimiser_Finder”;</pre><pre># Optimizers to explore<br>optimizers = [“sgd”, “adam”, “adamax”, “rmsprop”]; #Model name, learning rate</pre><pre># Num epochs for each experiment to run<br>epochs = 5;</pre><pre># Percentage of original dataset to take in for experimentation<br>percent_data = 10;</pre><pre>ptf.Analyse_Optimizers(analysis_name, optimizers, percent_data, num_epochs=epochs, state=”keep_none”);</pre><p>Generated output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*RIZhPczLnDrvMcnmgJepbQ.png" /></figure><p>Update the experiment :</p><pre>## Update Optimiser</pre><pre>ptf.optimizer_adamax(0.001);<br>ptf.Reload();</pre><h3>Training</h3><p>Finally after setting the correct hyper-parameters, we can begin training the model.</p><pre>ptf.Train();</pre><h3>Copy Experiment</h3><p>We can visualise the accuracy and loss plots, located inside the workspace directory. From the plots we observe that the losses can go further down:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*E8ofVh7_ZxaIKIMNNNDLDQ.png" /></figure><p>To continue training, we copy our previous experiment and resume from that state — [<a href="https://clever-noyce-f9d43f.netlify.com/#/copy_experiment">DOCS</a>]</p><h3>Compare Experiments</h3><p>After finishing our training we can compare both these experiments to check if we actually improved performance using <a href="https://clever-noyce-f9d43f.netlify.com/#/compare_experiment">Compare Experiment</a> feature in Monk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neuU89tS7bCUCglWdGs97A.png" /><figcaption>Validation accuracy comparison</figcaption></figure><p>Our ‘experiment 1’ ran for 5 epochs and ‘experiment 2’ ran for 10 epochs. Even though a minor improvement in validation accuracy, an increase from 96% to 97% could help achieve leader board positions for competitions hosted on Kaggle and EvalAi.</p><p>Hope you have fun building niche solutions with our tools.</p><p>To signup as a beta tester for our tools visit our <a href="https://monkai-42.firebaseapp.com/">website</a>.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a4d7ba419b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning with Monk]]></title>
            <link>https://medium.com/@monkai/fine-tuning-with-monk-6cec33fd6252?source=rss-349a772c539b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cec33fd6252</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Monk AI]]></dc:creator>
            <pubDate>Tue, 19 Nov 2019 08:09:15 GMT</pubDate>
            <atom:updated>2019-11-19T08:09:15.348Z</atom:updated>
            <content:encoded><![CDATA[<h3>TLDR</h3><p><a href="https://drive.google.com/file/d/1Qd6XRWIsIfge5nbl0jT_RM8_a-iacEuH/view?usp=sharing">Indoor_Scene_Classification.ipynb</a></p><h3>What will you build?</h3><p>In this exercise we will create and fine-tune an ‘indoor scene classifier’ using <a href="https://monkai-42.firebaseapp.com/">Monk</a>.</p><p>We will use Transfer Learning, wherein we pick a ‘Model’ which has already been trained to answer a similar problem and retrain it for our case.</p><p>Transfer Learning is a faster workaround than training a model from scratch.</p><p>Monk provides a syntax invariant transfer learning framework that supports Keras, Pytorch and Mxnet in the backend. (Read — <a href="https://clever-noyce-f9d43f.netlify.com/">Documentation</a>).</p><h3>Setup</h3><p>We start by setting up Monk and it’s dependencies on colab. For further setup instructions on different platforms check out the <a href="https://clever-noyce-f9d43f.netlify.com/#/setup/setup">DOCS</a>.</p><pre>$ git clone <a href="https://github.com/Tessellate-Imaging/monk_v1">https://github.com/Tessellate-Imaging/monk_v1</a><br>$ cd monk_v1/installation &amp;&amp; pip install -r requirements_cu10.txt<br>$ cd ../..</pre><h3>Dataset</h3><p>We will utilise the image dataset gathered by these awesome researchers —<a href="https://omidpoursaeed.github.io/publication/vision-based-real-estate-price-estimation/"> LINK</a>.</p><p>Optional : <a href="https://medium.com/@paudelanjanchandra/download-google-drive-files-using-wget-3c2c025a8b99">How to download large files from Google drive</a></p><h3>Training</h3><p>Next we will use Pytorch as our backend to create a new Project and use Resnet101 as our pre-trained model.</p><pre>ptf = prototype(verbose=1);</pre><pre>ptf.Prototype(&quot;indoor_scene&quot;, &quot;exp1&quot;);</pre><pre>ptf.Default(dataset_path=&quot;./Train/&quot;, model_name=&quot;resnet101&quot;, freeze_base_network=True, num_epochs=10);</pre><p>With Monk you can download or upload your workspace onto different machines and resume your work from where you left.</p><p>To demo this we will run inference by downloading the workspace to our local machine. To keep the download size small, we will disable saving intermediate models.</p><pre>ptf.update_save_intermediate_models(False);</pre><pre>ptf.Reload()</pre><h3>Inference</h3><p>Let’s zip our workspace and download it locally for inferencing. Before we can begin doing this we have to setup Monk on our local system. Check the documentation for further instructions on this — <a href="https://clever-noyce-f9d43f.netlify.com/#/setup/setup">SETUP</a></p><pre>$ zip -r workspace.zip workspace</pre><p>After importing ‘Monk’ in our local workspace, we can test our model on a single image and check the predicted label. (<a href="https://clever-noyce-f9d43f.netlify.com/#/quick_mode/quickmode_pytorch">DOCS</a>)</p><pre>ptf.Prototype(&quot;indoor_scene&quot;, &quot;exp1&quot;, eval_infer=True);</pre><pre>img_name = &quot;test.jpg&quot;;</pre><pre>predictions = ptf.Infer(img_name=img_name, return_raw=False);</pre><pre>print(predictions)</pre><h3>Hyper-Parameter Tuning</h3><p>Now that we have achieved a baseline validation accuracy of ‘INSERT VALUE’, we can resume fine-tuning the generated model from previous exercise. To do this we use the ‘<a href="https://clever-noyce-f9d43f.netlify.com/#/copy_experiment">copy_from</a>’ feature in Monk.</p><pre>ptf.Prototype(&quot;indoor_scene&quot;, &quot;exp2&quot;, copy_from=[&quot;indoor_scene&quot;, &quot;exp1&quot;]);</pre><p>We can now update our hyper-parameters,</p><pre>##########Update hyperparameters################</pre><pre>ptf.optimizer_asgd(0.001, weight_decay=0.00001);</pre><pre>ptf.update_num_epochs(10);</pre><pre>################################################</pre><p>Add randomised cropping</p><pre>########Update Transforms#####################</pre><pre>ptf.apply_random_resized_crop(224, train=True, val=True);</pre><pre>###############################################</pre><p>and freeze more layers from our pre-trained model to tune the weights and biases in the last few layers.</p><pre>###########For freeze layers#####################</pre><pre>ptf.update_freeze_layers(100);</pre><pre>################################################</pre><p>We can now retrain our model to see if we can churn a better validation accuracy.</p><p>NOTE : Don’t forget to reload the experiment after adding updates.</p><pre>ptf.Reload()</pre><pre>ptf.Train()</pre><p>Ohh and don’t forget to take a break, stretch your legs. You can always resume training from the last break point using Monk’s resume training feature.</p><p>All you have to do is load the experiment with resume state and begin. Read the docs for more information — <a href="https://clever-noyce-f9d43f.netlify.com/">DOCS</a></p><h3>Compare</h3><p>Finally to check if we the second experiment was fruitful and if we can do further improvement, we can <a href="https://clever-noyce-f9d43f.netlify.com/#/compare_experiment">compare our experiments</a> and visualise losses.</p><pre>from compare_prototype import compare</pre><pre>ctf = compare(verbose=1);</pre><pre>ctf.Comparison(&quot;indoor_scene&quot;);</pre><pre>ctf.Add_Experiment(&quot;indoor_scene&quot;, &quot;exp1&quot;);</pre><pre>ctf.Add_Experiment(&quot;indoor_scene&quot;, &quot;exp2&quot;);</pre><pre>ctf.Generate_Statistics()</pre><p>The final training accuracy plots show that we definitely improved from our baseline model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2RwUD8pzu6cq81AdqeZCw.png" /><figcaption>Training accuracy</figcaption></figure><p>We don’t have to stop here. We can utilise augmentation strategies on our dataset and further improve the model performance on newer data.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cec33fd6252" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fashion Classification with Monk]]></title>
            <link>https://medium.com/@monkai/fashion-classification-with-monk-66f601117e61?source=rss-349a772c539b------2</link>
            <guid isPermaLink="false">https://medium.com/p/66f601117e61</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clothes-classification]]></category>
            <dc:creator><![CDATA[Monk AI]]></dc:creator>
            <pubDate>Thu, 14 Nov 2019 21:11:03 GMT</pubDate>
            <atom:updated>2019-11-14T21:11:03.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>TLDR;</h3><p><a href="https://colab.research.google.com/gist/li8bot/73cd78dd420588cae7bcd597ca0521a5/fashion_myntra.ipynb">Google Colaboratory</a></p><h3>Creating a fashion classifier with Monk and Densenets</h3><p>In this exercise we will take a look some of MONK’s auxiliary functions while switching our backend framework between Pytorch, Keras and Mxnet.</p><p>We will use Densenets as our CNN architecture. To get a deeper understanding of Dense blocks and Densenets do checkout this awesome blog post — <a href="https://towardsdatascience.com/review-densenet-image-classification-b6631a8ef803">LINK</a></p><p>As our dataset source we will be using Myntra Fashion dataset kindly shared by Param Aggarwal — <a href="https://www.kaggle.com/paramaggarwal/fashion-product-images-small">LINK</a></p><p>Let’s begin.</p><h3>The Setup</h3><p>We start by setting up Monk and its dependencies on colab. For further setup instructions on different platforms check out the <a href="https://clever-noyce-f9d43f.netlify.com/#/setup/setup">DOCS</a>.</p><pre>$ git clone <a href="https://github.com/Tessellate-Imaging/monk_v1">https://github.com/Tessellate-Imaging/monk_v1</a><br>$ cd monk_v1/installation &amp;&amp; pip install -r requirements_cu10.txt<br>$ cd ../..</pre><p>Next we grab the data. You can either download the dataset using kaggle. To skip setting up kaggle API on colab, we’ve created a dropbox link to the dataset.</p><pre>$ wget <a href="https://www.dropbox.com/s/wzgyr1dx4sejo5u/dataset.zip">https://www.dropbox.com/s/wzgyr1dx4sejo5u/dataset.zip</a><br>$ unzip dataset.zip</pre><p>Checking out the ground truth csv file we find different feature columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*-ZlQkP5wSY5aHT2sU1iNAw.png" /><figcaption>style.csv</figcaption></figure><p>For this exercise we will classify fashion items into their sub category labels. To do this we extract the image ‘id’ column along with ‘subCategory’ to create a new labels file.</p><pre>import pandas as pd<br>gt = pd.read_csv(&quot;./dataset/styles.csv&quot;,error_bad_lines=False)<br>label_gt = gt[[&#39;id&#39;,&#39;subCategory&#39;]]<br>label_gt[&#39;id&#39;] = label_gt[&#39;id&#39;].astype(str) + &#39;.jpg&#39;<br>label_gt.to_csv(&#39;./dataset/subCategory.csv&#39;,index=False)</pre><p>Now that we have the images and label files ready, we can begin with creating experiments.</p><h3>Monk with Pytorch</h3><p>After importing MONK creating an experiment is simple. We can load Pytorch backend and create a new project and experiment.</p><pre>import os<br>import sys<br>sys.path.append(&quot;./monk_v1/monk/&quot;);<br>import psutil</pre><pre>from pytorch_prototype import prototype</pre><pre>ptf = prototype(verbose=1);<br>ptf.Prototype(&quot;fashion&quot;, &quot;exp1&quot;);</pre><p>Next we create the ‘Dataset’ object and setup the dataset and label path along with CNN architecture and number of epochs.(<a href="https://clever-noyce-f9d43f.netlify.com/#/dataset_format/image_classification">DOCS</a>)</p><pre>ptf.Default(dataset_path=&quot;./mod_dataset/images&quot;, path_to_csv=&quot;./mod_dataset/subCategory.csv&quot;, model_name=&quot;densenet121&quot;, freeze_base_network=True, num_epochs=5);</pre><p>We can check for missing or corrupt images and take a look at class imbalances using Monk’s EDA function (<a href="https://clever-noyce-f9d43f.netlify.com/#/aux_functions">DOCS</a>)</p><pre>ptf.EDA(check_missing=True, check_corrupt=True);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*YDRNyjdi7fjLfN6sNvZYVg.png" /><figcaption>Find missing images in your dataset</figcaption></figure><p>We have to update our labels file and remove rows containing missing or corrupt images. The notebook has a function ‘cleanCSV’ for this purpose.</p><p>After cleaning our labels file if we generated a new CSV, we have to update our ‘Dataset’ object to the location. This can be done by using the update functions (<a href="https://clever-noyce-f9d43f.netlify.com/#/update_mode/update_dataset">DOCS</a>). Remember to run ‘Reload()’ after any making an update.</p><pre>ptf.update_dataset(dataset_path=&quot;./dataset/images&quot;,path_to_csv=&quot;./dataset/subCategory_cleaned.csv&quot;);</pre><pre>ptf.Reload()</pre><p>And now we can start our training with :</p><pre>ptf.Train()</pre><p>For this experiment we are using densenet121 architecture. In the next experiments we will be using densenet169 and densenet201 architectures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*H3HjgnC-iqS2TTbFpp4iLw.png" /><figcaption>Different Densenet architectures</figcaption></figure><p>After training is complete we get our final model accuracies and losses saved in our workspace folder. Now we can continue with the experiment and test our the other 2 densenet architectures.</p><pre>ptf = prototype(verbose=1);</pre><pre>ptf.Prototype(&quot;fashion&quot;, &quot;exp2&quot;);</pre><pre>ptf.Default(dataset_path=&quot;./dataset/images&quot;, path_to_csv=&quot;./dataset/subCategory_cleaned.csv&quot;, model_name=&quot;densenet169&quot;, freeze_base_network=True, num_epochs=5);</pre><pre>ptf.Train()</pre><p>AND</p><pre>ptf = prototype(verbose=1);</pre><pre>ptf.Prototype(&quot;fashion&quot;, &quot;exp3&quot;);</pre><pre>ptf.Default(dataset_path=&quot;./dataset/images&quot;, path_to_csv=&quot;./dataset/subCategory_cleaned.csv&quot;, model_name=&quot;densenet201&quot;, freeze_base_network=True, num_epochs=5);</pre><pre>ptf.Train()</pre><p>After training is complete for the 3 experiments we can quickly compare these and find out differences in losses(both training and validation), compare training time and resource utilisation and select the best model.</p><p>Since we have trained only for 5 epochs, it still will not be clear which architecture to choose from the 3, however you can test out with either more epochs or even with a different CNN architecture. To update the model check out our <a href="https://clever-noyce-f9d43f.netlify.com/#/update_mode/update_model">DOCUMENTATION</a></p><h3>Compare experiments</h3><p>To run comparison we have to import the ‘compare’ module and add the 3 experiments.</p><pre>from compare_prototype import compare<br>ctf = compare(verbose=1);<br>ctf.Comparison(&quot;Fashion_Pytorch_Densenet&quot;);<br>ctf.Add_Experiment(&quot;fashion&quot;, &quot;exp1&quot;);<br>ctf.Add_Experiment(&quot;fashion&quot;, &quot;exp2&quot;);<br>ctf.Add_Experiment(&quot;fashion&quot;, &quot;exp3&quot;);</pre><p>After adding the experiments to compare, we can generate the statistics. To find out more about the compare module check out (<a href="https://clever-noyce-f9d43f.netlify.com/#/compare_experiment">DOCS</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9zxlxRvfYCXNi8A0_PkKQ.png" /></figure><p>The training accuracy performance shows that ‘densenet169’ performs marginally better than the other 2. However looking at the validation accuracy shows us a different picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqYtRoeYYCM4t92UpyfxeA.png" /></figure><p>Experiment 3 with ‘densenet201’ performs better that the others. If we compare the best validation accuracies for the 3 models, they are pretty close:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNyBLhbXd4i4s907uR66Cw.png" /></figure><p>However one more metric to checkout before going ahead is the training times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4UcK7UHVlXtsNND6BusMQ.png" /></figure><p>This shows that the more complex our CNN architecture the more time is takes to train per epoch. Next we’ll create similar experiments but with Keras and Mxnet.</p><h3>Monk with Mxnet</h3><p>Monk is a syntax invariant library. So working with either of the available backend Deep Learning framework does not change the program you have to write.</p><p>The only change will be in import :</p><pre>from gluon_prototype import prototype</pre><p>Next we create experiments the same way with different densenet architectures and carry out training.</p><p>Gluon experiments —</p><pre>gtf = prototype(verbose=1);</pre><pre>gtf.Prototype(&quot;fashion&quot;, &quot;exp4&quot;);</pre><pre>gtf.Default(dataset_path=&quot;./dataset/images&quot;, path_to_csv=&quot;./dataset/subCategory_cleaned.csv&quot;, model_name=&quot;densenet121&quot;, freeze_base_network=True, num_epochs=5);</pre><pre>gtf.Train()</pre><p>And so on…</p><h3>Monk with Keras</h3><p>As mentioned in the previous section, the only thing that changes is the import. So to utilise keras in the backend we import:</p><pre>from keras_prototype import prototype</pre><p>And then create some more experiments:</p><pre>ktf = prototype(verbose=1);</pre><pre>ktf.Prototype(&quot;fashion&quot;, &quot;exp7&quot;);</pre><pre>ktf.Default(dataset_path=&quot;./dataset/images&quot;, path_to_csv=&quot;./dataset/subCategory_cleaned.csv&quot;, model_name=&quot;densenet121&quot;, freeze_base_network=True, num_epochs=5);</pre><pre>ktf.Train()</pre><p>And so on…</p><p>Finally when we have trained the 9 experiments we can compare which framework and which architecture performed the best by using the compare utility in Monk(<a href="https://clever-noyce-f9d43f.netlify.com/#/compare_experiment">DOCS</a>) and fine-tune the ones performing better.</p><p>Comparison plot for training accuracy generated from our exercise :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UVlliOGzirXOaUIeH7m0A.png" /></figure><p>To achieve better results, try changing the learning rate schedulers and train for more epochs. You can easily copy an experiment and modify the hyper parameters, to generate better results. Check out our <a href="https://clever-noyce-f9d43f.netlify.com/#/copy_experiment">documentation</a> for further instructions on this.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66f601117e61" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>