<?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 Utkarsh Dixit on Medium]]></title>
        <description><![CDATA[Stories by Utkarsh Dixit on Medium]]></description>
        <link>https://medium.com/@utkarshupd?source=rss-8261fb7609c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Utkarsh Dixit on Medium</title>
            <link>https://medium.com/@utkarshupd?source=rss-8261fb7609c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:41:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@utkarshupd/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[End to End solution of detecting kin-relationship from Faces.]]></title>
            <link>https://medium.com/data-science/end-to-end-solution-of-detecting-kin-relationship-from-faces-c70b9e9ecda6?source=rss-8261fb7609c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c70b9e9ecda6</guid>
            <category><![CDATA[deploy-model]]></category>
            <category><![CDATA[kinship]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Utkarsh Dixit]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 10:12:34 GMT</pubDate>
            <atom:updated>2021-06-08T16:08:41.074Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog will step by step guide you on how to build a <em>Deep Neural Network model with Keras </em>from scratch to finally deploying it to the web using Flask. This problem was a competition hosted by Kaggle and can be found <a href="https://www.kaggle.com/c/recognizing-faces-in-the-wild/overview">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8bN9fUUctBcymW-e" /><figcaption>Photo by <a href="https://unsplash.com/@priscilladupreez?utm_source=medium&amp;utm_medium=referral">Priscilla Du Preez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Table of contents:</h3><p>1- Defining our goal</p><p>2- Data and its Description</p><p>3- Building Model</p><p>4- Evaluation</p><p>5- Productionize the Model</p><p>6- The Video</p><p>7- To-Do Tasks</p><p>8- References</p><h3><strong>Defining our goal:</strong></h3><p>Do you have your father’s nose sitting on you?</p><p>Blood relatives often share facial features. Now researchers at Northeastern University want to improve their algorithm for facial image classification to bridge the gap between research and other familial markers like DNA results.</p><p>This technology remains largely unseen in practice for a couple of reasons:</p><p>1. Existing image databases for kinship recognition tasks aren’t large enough to capture and reflect the true data distributions of the families of the world.</p><p>2. Many hidden factors affect familial facial relationships, so a more discriminant model is needed than the computer vision algorithms used most often for higher-level categorizations (e.g. facial recognition or object classification).</p><p>So, we will be building a complex model by determining if two people are blood-related or not based solely on images of their faces.</p><h3>Data:</h3><p>We will be using data given by <a href="https://web.northeastern.edu/smilelab/fiw/">Families In the Wild (FIW)</a>, the largest and most comprehensive image database for automatic kinship recognition.</p><p>FIW’s dataset is obtained from publicly available images from celebrities. For more information about their labeling process, please visit their <a href="https://web.northeastern.edu/smilelab/fiw/database.html">database page</a>.</p><h4>File Description:</h4><p>The folder ‘train’ consists of subfolders of families with names (F0123), then these family folder contains subfolders for individuals (MIDx). Images in the same MIDx folder belong to the same person. Images in the same F0123 folder belong to the same family.</p><p>Train Folder is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*jBzlbiHPtv0NzBhJdihNig.jpeg" /><figcaption>Train Folder</figcaption></figure><p>Each subfolder of ‘train’ is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*3OpkZCUehDeE2pPEIVKQYw.jpeg" /></figure><p>Each folder of individuals contains faces of that person:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBvBuR-6WIgdjQ8b9FqFAQ.jpeg" /></figure><p>The folder ‘test’ contains images of faces that need to be tested with some another random image to be kin related or not.</p><p>The file ‘train_relationships.csv’ shown below contains training labels. Remember, not every individual in a family shares a kinship relationship. For example, a mother and father are kin to their children, but not to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*RZlhLBqTcvv5nWLIEPPRdQ.jpeg" /><figcaption>train_relationships.csv</figcaption></figure><h4>Setting up the required libraries to use when needed:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cd377fa69b8ef85ad08a9326007d030/href">https://medium.com/media/8cd377fa69b8ef85ad08a9326007d030/href</a></iframe><blockquote>Note: Importing the library ‘keras_vggface’ might give an error if it does not exist on your system. To download it you can refer/run/use below code:</blockquote><pre>!pip install git+https://github.com/rcmalli/keras-vggface.git</pre><p>Diving into the data folders and analyzing the <em>train_relationship.csv </em>file, I found some hiccups. Ex: In the <em>train_relationship.csv</em> file there is a relation between ‘F0039/MID1’ and ‘F0039/MID3’, but there is no such folder for ‘F0039/MID3’ in the train folder.</p><p>I can see some similar issues because of the absence of the following folders<br>F0039/MID4<br>F0041/MID5<br>F0041/MID7<br>F0051/MID5<br>… and more.</p><p>One of the simple solutions to the above problem is to ignore these empty directories and only consider the ones which are available to us.</p><p>Loading the data and splitting it into the train &amp; validation set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce4b1b211c3d80afe6a4e957599309fc/href">https://medium.com/media/ce4b1b211c3d80afe6a4e957599309fc/href</a></iframe><p>‘val_images’ contains folders of the families with folder names starting ‘F09’ while ‘train_images’ contains all other family folders.</p><p>Now, these two folders also contain the empty directories, the problem that we discussed above. Time to ignore them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39207cda7c1024c4bb886913c9025202/href">https://medium.com/media/39207cda7c1024c4bb886913c9025202/href</a></iframe><p>We have ‘train’ &amp; ‘val’ which contain the family folders for the training and validation process respectively.</p><p>After defining our goal for this problem we explored and understood the nature of data we have and we also overcome a simple problem we faced. Now is the time to do some modeling. Recall the goal we set for ourselves at the beginning:</p><blockquote>“Predict, given two faces are kin related or not.”</blockquote><p>So basically we have a classification problem at hand to be solved.</p><h3>Deep Learning Model:</h3><p>With the use of deep learning architecture, the task of face recognition showed highly improved accuracy as compared to previous classical methods. The state of the art models can now outperform even humans when trained with huge datasets.</p><p>For our problem, we will be using two different architectures that achieved state-of-the-art results on a range of face recognition benchmark datasets. Both these systems can be used to extract high-quality features from faces, called face embeddings, that can then be used to compare two faces that are similar or not.</p><p>1- <em>Facenet</em>: It is a face recognition system developed in 2015 by researchers at Google. It takes an image as input and predicts a 128-dimensional vector or face embedding. So in simple terms, this vector/face embedding now represents that input face in numbers.</p><p>2- <em>VGGFace</em>: It is developed by researchers of one of the most prominent groups when it comes to image processing, Visual Geometry Group at Oxford. It takes an image as input and predicts a 2048-dimensional vector or face embedding.</p><p>These two models will work as our base models i.e we will pass our pair of input images to both these models and get face embeddings representing input faces. It will be clear once we build the actual model below.</p><h4>Input:</h4><p>We have two face images, image_1 and image_2 and both our base models will take each of these images. Facenet will take image_1 and image_2 as input_1 and input_2. VGGFace will take image_1 and image_2 as input_3 and input_4.</p><blockquote>Note: Input sizes of images are different for both the different models.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5229fe1073ed720faf44087223461a3b/href">https://medium.com/media/5229fe1073ed720faf44087223461a3b/href</a></iframe><p>After passing the input images through both the base models we will get face embeddings for both the images. We have</p><p>x1- face embedding for image 1 from Facenet model</p><p>x2- face embedding for image 2 from Facenet model</p><p>x3- face embedding for image 1 from VGGFace model</p><p>x4- face embedding for image 2 from VGGFace model</p><p>We can directly use these embeddings for our classification task by passing them through Dense FC layers but instead of doing that it will be a good feature engineering trick to combine or merge these embeddings for better results.</p><p>Ex: Squaring the vector x1 may give more information about image_1.</p><p>Like this, we can use many different combinations like adding (x1,x2) multiplying (x3,x4), etc. The code for this is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15f85c1102927c7ca2300ee2e6418a8d/href">https://medium.com/media/15f85c1102927c7ca2300ee2e6418a8d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea0155894a8dc909eacd13130dd291c6/href">https://medium.com/media/ea0155894a8dc909eacd13130dd291c6/href</a></iframe><p>We have our model architecture ready. The next step is to start training it with some loss and optimizer. Before training the model, we need to define some helper functions which will help us in training and inference step.</p><p>‘read_img_fn’ will take the path of the input image and return the same image with a predefined size. Remember, we are using different input sizes of images for different base models. Like that, another function ‘read_img_vgg’ will do the same for the VGGFace model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edb4cda74a8d06dbf272eb6016b08715/href">https://medium.com/media/edb4cda74a8d06dbf272eb6016b08715/href</a></iframe><p>A special helper function which is ‘generate’ is used to generate batches of pair of images with some fixed bath_size. For every batch, it will return the combination of four images (each pair for input to both the models) and the labels.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c9b46daf0fead10dc588763173aab7/href">https://medium.com/media/d4c9b46daf0fead10dc588763173aab7/href</a></iframe><h3>Loss function and Model Configuration:</h3><p>As we discussed at the start, it is a binary classification problem. We’ll be using binary cross-entropy or logloss as the loss function for this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*2m6jXyz8afxwmz5r.png" /></figure><p>To configure the model, we will be using accuracy as the tool to keep track of performance while training and optimizer will be Adam with learning rate = 1e-5.</p><h3><strong>Training:</strong></h3><p>Finally, we are ready to train the model that we defined above. Using callbacks to store and use the trained model at various points, the final code of training looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b5f1ff8baf6cf11b83487d45bacaee7/href">https://medium.com/media/7b5f1ff8baf6cf11b83487d45bacaee7/href</a></iframe><p>You can see here we are using the ‘generate’ helper function to generate batches of images of size 16. After training for several epochs the model converged and the accuracy was not improving from there.</p><p>Finally, the trained model is saved with filename ‘<strong><em>facenet_vgg.h5&#39;.</em></strong></p><h3>Evaluation:</h3><p>Now we can use this trained model to predict the probabilities given two input images. We will be using the ‘sample_submission.csv’ file provided by Kaggle to do so. This file contains pairs of images and the model needs to predict the probability of kin relationship.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1544c26e9483e9dfca97fb5d177f743/href">https://medium.com/media/b1544c26e9483e9dfca97fb5d177f743/href</a></iframe><p>This file ‘face_vgg.csv’ is then submitted to the Kaggle to check the score. Our model performed well and gave the AUC score of ‘0.887’ on private lb and ‘0.881’ on public lb.</p><blockquote>From this, we can say that our complex deep learning model is performing well at this task and is ready to go into production.</blockquote><h3>Path to Production:</h3><p>We will be using Python-based micro web framework Flask to make a simple web server on the localhost which will act as an API and will help end-users to communicate to our trained model. So that now anyone can access our model.</p><p>First, let&#39;s build a simple web API using Flask to demonstrate how things work.</p><p>We will need two different files to make.</p><p>1- app.py — The Flask script for backend</p><pre>from flask import Flask, request, render_template<br>app = Flask(__name__)</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/&#39;)<br>def hello_world():<br>    return render_template(&#39;index.html&#39;)</pre><p>The above code will import the necessary files and initiate the Flask instance. Function hello_world() will render our home page to the user.</p><p>2- index.html — The home page html file which the user will see at the frontend.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Flask&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;p&gt;Hello world&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now we have both the two files which we need. After running the file app.py, the user will be able to see the page saying ‘Hello world’.</p><p>Before building let’s first visualize the whole structure of how things will work. The user will see a web-page requesting him/her to upload two image files that he/she needs to see if they are kin related or not. At the backend, our Flask script will access the two images and run the required operation on it. It will take the images, perform preprocessing and then it will pass them to our trained model. Finally, the model will predict the probability and will be projected at the frontend to the user.</p><p>Now we’ll go and build our kin-Prediction API.</p><p>This is how our project layout looks like —</p><pre><strong>/Kin-Prediction<br>   ├── templates<br>       └── index.html<br>       └── end.html</strong></pre><pre><strong>   ├── static<br>       └── Image1<br>       └── Image2<br>   ├── venv/<br>   ├── app.py<br>   ├── facenet_vgg.h5   </strong></pre><p>The project folder contains all the files that our Flask needs.</p><p>Folder templates will contain the HTML files for frontend which will be used by Flask to render when needed.</p><p>Folder static will contain the images that the user will upload for prediction.</p><p>‘ facenet_vgg.h5 ’ is our trained model which needs to be saved in the directory so that Flask can directly use it.</p><p>app.py file is the main Flask script that will be running and doing all the backend operations.</p><p>The below function from app.py will render the home page for the user.</p><pre>@app.route(&#39;/&#39;)<br>@app.route(&#39;/home&#39;)<br>def upload_image():<br>    return flask.render_template(&#39;index.html&#39;)</pre><p>The index.html file looks like this:</p><pre>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Kin Relationship&lt;/title&gt;<br>&lt;/head&gt;<br>   &lt;body  style=&quot;background-color:gray;&quot;  &gt;<br>      &lt;form action = &quot;http://localhost:5000/upload&quot; method = &quot;POST&quot;<br>         enctype = &quot;multipart/form-data&quot;  align=&quot;center&quot;&gt;<br>         First Image:&lt;label&gt;<br>         &lt;input type = &quot;file&quot; name = &quot;file1&quot; /&gt;&lt;/label&gt;<br>         Second Image&lt;label&gt;<br>         &lt;input type = &quot;file&quot; name = &quot;file2&quot; /&gt;&lt;/label&gt;<br><br>         &lt;label&gt;<br>         &lt;input type = &quot;submit&quot; value=&quot;Predict&quot;/&gt; &lt;/label&gt;<br><br>      &lt;/form&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The page will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNYOtHuz0lg33cbCr5pvHg.jpeg" /></figure><p>After choosing the images and clicking on the Predict button, both the images will be uploaded and saved to our local directory folder which is ‘static’. From there Flask will access the images and perform the required actions and finally predict the probability.</p><p>The code for this in app.py file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc95c13490e76e8475bb5b03133c0210/href">https://medium.com/media/dc95c13490e76e8475bb5b03133c0210/href</a></iframe><p>Finally, in the end, the flask will render the template ‘end.html’ with both the images and prediction.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Prediction&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body style=&quot;background-color:powderblue;&quot;&gt;<br>&lt;div&gt;<br>{% for i in image_name %}<br><br>&lt;img src=&quot; {{url_for(&#39;static&#39;, filename=i) }} &quot; style=&quot;width:250px;height:300px;&quot;  hspace=&quot;200&quot;&gt;<br><br>{% endfor %}<br><br>&lt;/div&gt;<br><br>&lt;h1 style=&quot;font-family:verdana;&quot;&gt; Probablity of two persons having kin relation is {{pred}} &lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>That&#39;s it. Our model is ready and running on the localhost. You can download and refer to the full code <a href="https://github.com/Utkarshupd/Kin_Relation_Prediction">here</a>.</p><blockquote>I tried this, first with images of me and my Dad and then with images of Mom and Dad. In both cases, the Model works perfectly fine and predicts high probability (kin-related) and low probability (Not kin-related) respectively.</blockquote><h3>The Video:</h3><p>Here is the video which showcases the above experiment.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fsd43B0oAHTI%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dsd43B0oAHTI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fsd43B0oAHTI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/81b316dc918eb42cc26884fbec90a8de/href">https://medium.com/media/81b316dc918eb42cc26884fbec90a8de/href</a></iframe><h3>To-Do tasks:</h3><p>1- Instead of just running it on a local server, we can deploy it on cloud-based web services like Heroku, so that anyone from anywhere can access your model.</p><p>2- Currently our model takes images of only faces of the people as it is trained on only faces. It will not work if given a full image of person. We can build a different solution which takes care of this problem.</p><p>3- Using advanced CSS and javascript, we can design our frontend to look good.</p><p>Thank you for getting this far in this blog. Hope you like it. You can connect with me over <a href="https://www.linkedin.com/in/iutkarshdixit/">Linkedin</a> for any suggestions.</p><h3>References:</h3><p>1- <a href="https://www.kaggle.com/c/recognizing-faces-in-the-wild/overview">https://www.kaggle.com/c/recognizing-faces-in-the-wild/overview</a></p><p>2- <a href="https://blog.keras.io/building-a-simple-keras-deep-learning-rest-api.html">https://blog.keras.io/building-a-simple-keras-deep-learning-rest-api.html</a></p><p>3- <a href="https://heartbeat.fritz.ai/brilliant-beginners-guide-to-model-deployment-133e158f6717">https://heartbeat.fritz.ai/brilliant-beginners-guide-to-model-deployment-133e158f6717</a></p><p>4- <a href="https://www.curiousily.com/posts/deploy-keras-deep-learning-project-to-production-with-flask/?fbclid=IwAR1t8EFUOZsh0s5tTN9b-EvBnWP1nwR89WAyzdg5e_TwaPwK1bGgvQZrC2U#build-rest-api">https://www.curiousily.com/posts/deploy-keras-deep-learning-project-to-production-with-flask/?fbclid=IwAR1t8EFUOZsh0s5tTN9b-EvBnWP1nwR89WAyzdg5e_TwaPwK1bGgvQZrC2U#build-rest-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c70b9e9ecda6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/end-to-end-solution-of-detecting-kin-relationship-from-faces-c70b9e9ecda6">End to End solution of detecting kin-relationship from Faces.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Machine translation and the need for Attention mechanism.]]></title>
            <link>https://medium.com/analytics-vidhya/neural-machine-translation-and-the-need-for-attention-mechanism-60f9a39da9a?source=rss-8261fb7609c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/60f9a39da9a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-translation]]></category>
            <dc:creator><![CDATA[Utkarsh Dixit]]></dc:creator>
            <pubDate>Thu, 10 Oct 2019 13:04:51 GMT</pubDate>
            <atom:updated>2019-11-10T16:57:33.845Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Neural Machine translation and the need for Attention Mechanism</strong></h3><h3><strong>Table of Contents:</strong></h3><p>1-Introduction</p><p>2-Encoder Architecture</p><p>3-Decoder Architecture</p><p>4-The Inference Stage</p><p>5-The Problem</p><p>6-What is Attention?</p><p>7-Implementing different types of Attention mechanisms</p><p>8-The drawback of attention</p><p>9-References</p><h4>1. Introduction:</h4><p>Sequence-to-sequence learning (Seq2Seq) is all about models that take a sequence as an input and outputs a sequence too. There are many examples and applications of this but today I will focus on one specific application which is a machine language translation. For eg English to Hindi.</p><p>There are many approaches you can follow to solve this particular task but the state of the art technique is the Encoder-Decoder approach(More on this later).</p><p>Technically, Encoder is a RNN unit that takes a sequence as an input and encodes it as a state vector which is then fed to a decoder with some input to predict the desired output.</p><p>Intuitively, Encoder summarizes the English sequence into a special vector which is given to decoder to translate them into equivalent Hindi outputs.</p><p><em>Point to be noted: Generally, this RNN unit is LSTM or GRU.</em></p><p>So our final architecture looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7DHZu5H9xkW-HXTTrDKCA.png" /></figure><p>Instead of describing everything here, Let&#39;s do it step by step:</p><h4>2. Encoder Architecture:</h4><p>I will go with a single LSTM unit to make life simpler but in real-world deep LSTM layers are used so that the model can learn in new possible and multiple ways.</p><p>Just for the context, LSTM unit takes three inputs and returns three outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDMde46xfjjrX-l40WnPZg.png" /></figure><p>Here X, h0 and c0 are the inputs.Y, ht and ct are the outputs. This figure above is the rolled version of a LSTM unit. Basically it takes one word/character at a time and gets unrolled over time. The below figure will make it clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJRo8Kr65WjcjrvJs0tgSQ.png" /></figure><p>The first input is the sequence that we want to translate and the other two inputs are two vectors, cell state and hidden state.</p><p>For example, lets take this sequence. <strong>“This is a good phone”. </strong>This sequence contains 5 words, so our encoder lstm will process each word at single time steps.</p><p>In the above diagram, x1 is the input word which is ‘This’, h0,c0 are the input state vectors that are initialized randomly at the start.It will output three vectors y1 (output vector), h1 and c1(state vectors).</p><p>Intuitively, h1 and c1 here contain the information of ‘This’ word which we inputted at timestep t0. Now LSTM at time step t1 will take h1 and c1 as input with next word in the sequence which is <strong>‘is’</strong>. Vector h3,c3 comprises information till word 3 which is<strong> ‘a’</strong>. So on till last time step 5, we will get h5 and c5 which contains information about the whole input sequence.</p><p>So now our input sequence <strong>“This is a good phone” </strong>gets converted to vector h5 and c5. We discard the output vectors (y1 to y5) because we don&#39;t need them here. We only need output state vectors as they will be containing the information about the given input sequence.</p><p>We will now initialize our decoder with these final encoder state vectors which are h5 and c5 rather than randomly which we did with encoder LSTM. Logically also it makes sense because we want our decoder to not just start randomly but to have a sense of what the input sequence is.</p><h4>3. Decoder Architecture:</h4><p>Decoder LSTM will also have the same architecture as encoder but with different inputs and outputs. Now there are two things, training phase, and the inference phase. We will touch on the inference phase later. First, finish the training phase.</p><p>We have the vectors encoded by our LSTM encoder. The h0 and c0 of the decoder are not initialized to random but with the h5 and c5 which we got from the encoder.</p><p>Also to make things work, we add _START_ symbol to the start and _END_ symbol at the end of the target sequence. Now the final sequence becomes <strong>‘_Start_ यह एक अच्छा फोन है _END_’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrMWze-_-5hhMo9UcJqTpA.png" /></figure><p>Here X1=_Start_ and Y1=यह with h0=h5 of encoder and c0=c5 of ecoder. This returns state vectors h1, c1 which is inputted to the decoder at the next time step and output Y1 which is inputted as ground truth to the decoder. This continues until the model encounters the _END_ symbol. At the last time step, we ignore the final state vectors of the decoder (h6,c6) because it is of no use to us, we only need output Y’s.</p><p>This technique is also called <strong>“Teacher Forcing”.</strong>More on this <a href="https://machinelearningmastery.com/teacher-forcing-for-recurrent-neural-networks/">here</a>.</p><p>The entire training architecture (Encoder + Decoder) can be summarized in the below diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUN57st-P36gAhLJuKIJrg.png" /></figure><p>Given the final architecture, We can now predict outputs from each time step and the errors are then back propagated through time in order to update the parameters of the whole network and then compute our training loss.</p><h4>4. The Inference Stage:</h4><p>The task of applying a trained model to generate a translation is called <strong>inference </strong>or more commonly decoding the sequence in machine translation.</p><p>We have a trained model, now we can generate predictions based on a given input sequence. This step is basically known as inference. You can refer it as a testing phase while the above steps were training phase. At this step, we only have the learned weights and input sequence which is to be decoded.</p><p>The model defined for training has learned weights for this operation, but the structure of the model is not designed to be called recursively to generate one word at a time. For this, we need to design new models for testing our trained model. There are many ways to perform decoding.</p><p>The inference stage contains two different encoder-decoder models which will act as stand-alone models for their respective purposes.</p><p>The encoder model is simple as it takes the input layer from the encoder in the trained model and outputs the hidden and cell state tensors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/0*-YR1AO_0V2Sbo2oF.png" /><figcaption><a href="https://machinelearningmastery.com/define-encoder-decoder-sequence-sequence-model-neural-machine-translation-keras/">https://machinelearningmastery.com/define-encoder-decoder-sequence-sequence-model-neural-machine-translation-keras/</a></figcaption></figure><p>The Decoder model is a more involved one. It requires three inputs, the hidden and cell states from the encoder as the initial state of the newly defined encoder model and the encoded translation output so far. For every word, it will be called i.e we have to make this inside a loop and the loop will end once it sees the _END_ symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kUq7DsyDizJeehpM.png" /><figcaption><a href="https://machinelearningmastery.com/define-encoder-decoder-sequence-sequence-model-neural-machine-translation-keras/">https://machinelearningmastery.com/define-encoder-decoder-sequence-sequence-model-neural-machine-translation-keras/</a></figcaption></figure><p>We’ll use this inference model to finally translate the sequence from one language to another.</p><h4>5. The Problem:</h4><p><strong>“Attention” </strong>is one of the recent trends in the Deep Learning Community. Ilya Sutskever, the man behind the above seq2seq architecture for machine translation mentioned that ‘Attention Mechanisms’ are one of the most exciting advancements in the above encoder-decoder approach, and that they are here to stay. But what is the problem behind that approach and what does attention solves?</p><p>To understand what attention can do for us, let’s go over the same machine translation problem above. We wanted to translate the sentence ‘This is a good phone’ to ‘यह एक अच्छा फोन है’. Remember we used an LSTM encoder to map the English sentence into final state vectors. Let&#39;s see that visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFvsfcyfEavBa3Iq5rL0nw.png" /><figcaption>Fig-8</figcaption></figure><p>We can see that vectors h5,c5 must encode everything we need to know about the source sentence. It must fully capture its meaning.</p><p><em>But there is a catch.</em></p><p>It basically captures the meaning of the whole sentence but this is when the sentence is not long. For example, the sentence that we took is only 5 words long and the normal encoder will do justice to it but when the sentence is 50 or 100 words long articles this single final vector will not be able to map the fully whole sequence. Look at it this way, If the sentence is 100 words long, the first word of the source sentence is probably highly correlated with the first word of the target sentence. But that means decoder has to consider information from 100 steps ago, and that information needs to be somehow encoded in the vector. RNN’s have this old problem of long term dependencies. In theory, architectures like LSTM should be able to deal with this, but in practice, long-term dependencies are still problematic. There are some hacks to make things better but they are not principled solutions.</p><p><em>And This is where ‘Attention’ comes in.</em></p><h4><strong>6. What is Attention:</strong></h4><p>Attention is a little modification of the previous approach. We no longer try to encode the full source sentence into a final fixed-length vector. Rather, we make use of all the middle or local vectors information collectively in order to decide the next sequence while decoding the target sentence.</p><p>For example, in the Fig-8 we will use all the h’s and c’s instead of only using h5,c5. So now if our decoder wants to decode ‘This’ into ‘यह’, it can directly access first state vectors h1,c1. This idea is known as giving more attention to the current word and hence the name Attention. Intuitively you can think that decoder will attend to the first English word when producing the first Hindi word and so on.</p><h4>Implementation of Custom Keras Layer:</h4><p>To implement our own attention mechanism we need to write the <a href="https://keras.io/layers/writing-your-own-keras-layers/">custom Keras layer</a>.</p><p>To implement it in Keras we need to write just three simple methods.</p><ul><li><strong><em>build(input_shape)</em></strong>: This is where you will define your weights. This method must set self.built = True at the end, which can be done by calling super([Layer], self).build().</li><li><strong><em>call(x)</em></strong>: This is where the layer&#39;s logic lives.</li><li><strong><em>compute_output_shape(input_shape)</em></strong>: In case your layer modifies the shape of its input, you should specify here the shape transformation logic.</li></ul><h4>7. Implementing different types of Attention mechanisms:</h4><p>The above explanation is a top-level view. We need to dig deep to fully understand it. Since 2015 Attention became quite a popular concept and tool to solve NLP problems. In recent years, many advancements and modifications happen on top of simple Attention mechanisms which leads to different types of models. While the underlying principles of Attention are the same in all different types, their differences lie mainly in their architectures and computations. Some of the popular ones I will discuss below with implementation in Keras. We can use the GRU unit instead of LSTM just for simplicity as GRU consists of a single hidden state as compared to LSTM which maintains two hidden states.</p><p><strong>7.1- Attention proposed by </strong><a href="https://arxiv.org/pdf/1409.0473.pdf"><strong>Bahdanau</strong></a><strong>:</strong></p><p>Right now we have all the encoded state vectors (h1) to (h5). The attention layer will take these encoded vectors and the internal state of the decoder at the previous time step as input. For predicting the first word itself, the decoder does not have any current internal state. For this reason, we will consider the last state of the encoder (i.e. h5) as the previous decoder state. Using these vectors alignment score will be calculated which will then be used to calculate attention weights. This is discussed in detail below:</p><p>The decoder is trained to predict the output y at time step t given the context vector c and previously predicted outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*1vyVxTXQOtJJ0bDDUaLTxQ.jpeg" /></figure><p>Here y is the previously predicted outputs and c is the context vector. In other words, we can say that the decoder is trying to find the conditional probability stated above. The conditional probability part can be modeled as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*-OCee9f3s8G-yBgdVLzQwA.jpeg" /></figure><p>where g is a nonlinear, potentially multi-layered, function that outputs the probability of ‘yt’, and ‘st’ is the decoder hidden state of the GRU/LSTM which is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*gipx2GTs6OBN7xP8nD5nhQ.jpeg" /></figure><p>Here you can see that probability is conditioned on distinct vector c which is context vector for every targeted word. The context vector ci depends on the encoder outputs sequence (h1, h2, …hTx ) to which the encoder maps the input sentence.</p><p>The context vector ci is, then, computed as a weighted sum of these state vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*ZIfwwcP7DZthx53wV2sgLg.jpeg" /></figure><p>If we unroll the above formula for our example of five words, we will get:</p><blockquote><em>context_vector = (</em>α<em>1 * h1 + </em>α<em>2 * h2 + </em>α<em>3 * h3 + </em>α<em>4 * h4 + </em>α<em>5 * h5)</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*N0EcRKVjkHsPQhbrfm-9QQ.jpeg" /></figure><p>is an alignment model that scores how well the inputs around position j and the output at position i match. The score is based on the decoder GRU/LSTM hidden state si−1 and the jth output hj of the input sentence. Here ‘a’ is a simple feedforward neural network which is jointly trained with all the other components of the proposed system. These alignment model eij are also called energy scores.</p><p>To calculate the energy_score/allignment_score t<a href="https://arxiv.org/pdf/1409.0473.pdf">he paper</a> introduces three weight matrices W_combined, W_decoder, W_encoder. The below formula will make it clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Xc3rFbbvFXfD13WfXA1wEw.jpeg" /></figure><p>Let’s define these weights in the build function of the class AttentionLayer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/005655ec5c866dcc52be43855cf19156/href">https://medium.com/media/005655ec5c866dcc52be43855cf19156/href</a></iframe><p>We have the weights defined required for the calculation of alignment_score. Now let’s go and define the call function of the class where the actual calculation and logic of the code will reside.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7df62618987b7d0d039dc880f81baad1/href">https://medium.com/media/7df62618987b7d0d039dc880f81baad1/href</a></iframe><p>The attention layer will finally return allignment_score and attention weights. The weights will be then used to calculate the final context vector.</p><pre>context_vector = attention_wts * enc_output_seq</pre><p>Our final Attention Layer class is defined below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cacdca07d7f68fb04b2b345b69744f7/href">https://medium.com/media/5cacdca07d7f68fb04b2b345b69744f7/href</a></iframe><p><strong>2 - Attention proposed by </strong><a href="https://arxiv.org/abs/1508.04025"><strong>Luong</strong></a><strong>:</strong></p><p>This mechanism was introduced by Thang Luong in 2015 after the Bahdanau’s mechanism. It was built on top of the previous mechanism and has some differences.</p><ol><li>The way that the alignment score is calculated.</li><li>The position at which the Attention mechanism is being introduced in the decoder.</li></ol><p>In the Bahdnau Attention, the attention layer takes encoded input vectors and decoder hidden vector at the previous time step as input. Then it calculates the context vector using that. Using that context vector output is predicted. But in Luong Attention, the context vector is utilized only after the RNN/LSTM produced the output for that time step. At the decoder level, The previous decoder hidden state and decoder output is passed through the <strong>Decoder RNN</strong> to generate a <strong>new hidden state</strong> for that time step. Using the new decoder hidden state and the encoder hidden states, <strong>alignment scores</strong> are calculated.</p><p>There is a total of three types of way the alignment scores are calculated as compared to Bahdanau’s which has only one type. These types are:</p><h4>Dot:</h4><p>In this function, we only need the hidden state of the decoder and hidden state of the encoder to calculate the alignment score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*eoTa2FQjwMnBfCIoeZ1Ppw.jpeg" /></figure><h4>General:</h4><p>This is similar to Dot function except it has a weight matrix after the dot function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*Y3GmBHlYJe9Q6i0hECACYg.jpeg" /></figure><h4>Concatenate:</h4><p>This function calculates the score in the following way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*tSFqwEhjpkDRXizJJwxKLQ.jpeg" /></figure><p>Here H_decoder is the new hidden state which is generated by passing previous hidden state and decoder output.</p><p>Below is the implementation of Luong Attention:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b7a61ede441c4bba60010acdbb9c231/href">https://medium.com/media/8b7a61ede441c4bba60010acdbb9c231/href</a></iframe><p><strong>8. The drawback of Attention:</strong></p><p>As stated in the above paragraph, it computes context_vector for every word which comes at a computation cost. Longer the sequences more will it take time to train. Also if you see Human attention is something that’s supposed to save computational resources. By focusing on one thing, we can neglect many other things. But that’s not really what we’re doing in the above model. We’re essentially looking at everything in detail before deciding what to focus on. Intuitively that’s equivalently outputting a translated word, and then going back through <em>all</em> of your internal memory of the text in order to decide which word to produce next. That seems like a waste, and not at all what humans are doing. In fact, it’s more akin to memory access, not attention, which in my opinion is somewhat of a misnomer. Still, that hasn’t stopped attention mechanisms from becoming quite popular and performing well on many tasks.</p><h4>9. References:</h4><p>1- <a href="https://machinelearningmastery.com/define-encoder-decoder-sequence-sequence-model-neural-machine-translation-keras/">https://machinelearningmastery.com/define-encoder-decoder-sequence-sequence-model-neural-machine-translation-keras/</a></p><p>2- <a href="https://github.com/tensorflow/nmt">https://github.com/tensorflow/nmt</a></p><p>3- <a href="https://www.tensorflow.org/tutorials/text/nmt_with_attention">https://www.tensorflow.org/tutorials/text/nmt_with_attention</a></p><p>4- <a href="https://machinelearningmastery.com/encoder-decoder-recurrent-neural-network-models-neural-machine-translation/">https://machinelearningmastery.com/encoder-decoder-recurrent-neural-network-models-neural-machine-translation/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60f9a39da9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/neural-machine-translation-and-the-need-for-attention-mechanism-60f9a39da9a">Neural Machine translation and the need for Attention mechanism.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Metrics: When to Use What]]></title>
            <link>https://medium.com/@utkarshupd/performance-metrics-when-to-use-what-375019dbec02?source=rss-8261fb7609c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/375019dbec02</guid>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[log-loss]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <dc:creator><![CDATA[Utkarsh Dixit]]></dc:creator>
            <pubDate>Mon, 22 Jul 2019 09:47:49 GMT</pubDate>
            <atom:updated>2019-07-22T09:47:49.015Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Guys!</p><p>There are lots of aspiring candidates who want to enter the field of Data Science/ML these days. One common problem among them is understanding the use of performance evaluation metrics (Regression/Classification) which we will tackle today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*YhwhkUWrThVhAou42okGEg.jpeg" /></figure><blockquote><strong>Note</strong>: This blog is not at all about, what are the different metrics in town and how they work. There are tons of blog out there which explains the same in a beautiful manner.</blockquote><p>This blog mainly focuses on the applied nature of different metrics. When to use a specific metric and when not to use it depending on different business problems. What are the merits/demerits of them.</p><blockquote><strong>Note</strong>: In this particular blog I am just going for Metrics which are used for Classification Problems.</blockquote><p>Before starting, here are some key points that are used a lot in the post.</p><h3>What is KPI ?</h3><p>Key performance indicators (KPIs) are business metrics used by corporate executives and other managers to track and analyze factors deemed crucial to the success of an organization.</p><h3>What is TN, FN, TP, FP, TNR, FPR?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*apvwJuqbT_nW6_Q-VsDHzw.png" /></figure><p>Let start with a business problem &amp; business objectives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*ksZT8X2slowDF3bONpmOdg.png" /><figcaption>Quora Case Study</figcaption></figure><p>You don&#39;t want your two questions to be classified wrongly as duplicates or non-duplicates because it will affect consumer satisfaction severely which will affect the business of Quora. Mis-classification cost is very high i.e FN &amp; FP should remain as close to 0 as possible which means TN &amp; TP will be close to 1. So the options we have are:</p><p><strong>Accuracy</strong>-It is not a good measure because data is imbalanced and accuracy doesn&#39;t care about class label proportions and can fail very easily.</p><p><strong>Confusion Matrix</strong>-It is highly interpretable even when the data is imbalanced. We can use CM to get a better understanding of model performance. What are FN &amp; FP which we care the most in this problem.The problem with CM is that it is not a single metric but a combination of 4 metrics. So we have to use a single metric along with CM.</p><p><strong>ROC-AUC: </strong>It can be used when the data is imbalance.AUC is maximized when the True negatives(TN) are maximum for a given threshold. But here we are concerned with FN &amp; FP rather than TN.So this is not the thing we want.</p><p><strong>F1-Score-</strong>It is a collective measure of Precision &amp; Recall. Higher the Pre. &amp; Rec. higher the F1 score. Recall is high when FN is low. Precision is high when FP is low. So this is the one which can be used as KPI.</p><p>Heres another Business problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*riKEbr2-C4JSoQXSvBLPJw.png" /></figure><p>We need to detect probabilities of each datapoint (patient) whether it has cancer or not. In medical fields false positive classifications are more tolerable than false negatives i.e we cant describe a patient as non-cancer when he is actually having cancer. This would be a blunder. So our FN has to be minimized to 0.</p><p><strong>Confusion Matrix</strong> again will come handy to us as it will tell us how our model is doing with FN &amp; FP.</p><p><strong>F1 score</strong> will tell us about both FN &amp; FP but we are more concerned about FN because even if there are few FP, we can send the patient’s data for further screening but this is not the case with FN.</p><p><strong>ROC-AUC: </strong>Generally, there is a probability threshold of 0.5 for a problem i.e if P(y)&gt;0.5 it is marked positive else negative. But threshold probabilities can vary in problems like Cancer Detection depending upon a business domain expert. For eg, A doctor may think that even if the probability of having cancer is 0.3, declare it positive. There are a number of approaches for selecting thresholds, and ROC analysis is quite a powerful option. ROC analysis can easily let you do cost-sensitive threshold selection that will let you select your threshold optimally. But there&#39;s a catch here, ROC does not deal with actual probability score, it cares about the ranking order of your probabilities. Thus you may not be able to compare two different models. For eg. In this problem two different Models, Model A &amp; Model B can have the same AUC Score because of the same ranking order.</p><p><strong>LogLoss </strong>could also be one metric we are looking for. The best thing about log loss is that it penalizes the error because it is more like a cost function rather than an evaluation metric. It incorporates the idea of probabilistic confidence. It will not have the same <strong>logloss </strong>for models A &amp; B as above because it considers the actual probability score &amp; not the ranking order. One drawback of this metric is that the majority class can dominate the loss.</p><p>Another Business Problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*_TcOUevOEcfBqGXGs3kcPQ.png" /></figure><p>Here there are no such high-end constraints like penalizing misclassified points or non-tolerable errors. So using <strong>logloss, precision Recall, F1-Score</strong> can be used but will be an overkill.</p><p><em>The business objective is just to test a model that how well it is differentiating between class labels. For that </em><strong><em>ROC-AUC </em></strong><em>will work like a charm</em>.</p><p>There is also an interesting interpretation of <strong>AUC </strong>score which tells us about the classification capability of a model which goes as follows:</p><p>If AUC of our model is 0.80, then we can say that-</p><blockquote>Given one positive &amp; one negative label data point, the probability that our model will classify those two points correctly is 80%.</blockquote><p><strong>In a nutshell:</strong></p><p><strong>Logloss </strong>is one of the most used classification metric in the industry. Higher the confidence in probability lower will be the loss. But it should not be used for every problem as we have seen in Donors Choose dataset.</p><p><strong>ROC-AUC</strong> considers TPR &amp; FPR in its curve. High TPR Low FPR maximizes AUC score which can also be interpreted as ‘lower the FP points higher the TN points’. It can be used where TN points matter.Drawback is that it ignores the exact probability score.</p><p><strong>F1-Score</strong> takes care of both Precision &amp; Recall and hence is a good metric when both Pre &amp; Rec needs to be high. It can be used as a ‘KPI’ to compare different models.</p><p><strong>Confusion Matrix</strong> works well with both balanced &amp; imbalanced datasets and is often used to get richer understanding of the model performance. But sometimes it may be misleading so instead of CM we can also use classification report provided by sklearn. It cannot be used to compare two models. Also when a problem is a multiclass problem of say N different classes then you have to look at NxN matrix which could be daunting and hence don&#39;t give much help. Classification report will work here.</p><h3><strong>Conclusion:</strong></h3><p>So after analyzing the above real-world business problems, we can say that there is no perfect single classification evaluation metric. Everyone has there own sets of merits &amp; demerits. The metric should be chosen depending on business needs and the context of the problem you are trying to solve.</p><p>Some of the references are given below to dive deep further.</p><p>That&#39;s it. If you liked this article, please leave a 👏 ! Thank you for your time.</p><h3>References:</h3><ul><li><a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/">How to Use ROC Curves and Precision-Recall Curves for Classification in Python - Machine Learning Mastery</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html">classification_report</a></li><li><a href="https://www.kaggle.com/lct14558/imbalanced-data-why-you-should-not-use-roc-curve">Imbalanced data &amp; why you should NOT use ROC curve</a></li><li><a href="https://link.springer.com/article/10.1007/s00330-014-3487-0">Disadvantages of using the area under the receiver operating characteristic curve to assess imaging tests: A discussion and proposal for an alternative approach</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=375019dbec02" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>