<?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 Prabhnoor Singh on Medium]]></title>
        <description><![CDATA[Stories by Prabhnoor Singh on Medium]]></description>
        <link>https://medium.com/@prabhnoor0212?source=rss-1b6ee6ea1c95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VZlteghWvtX0p-Dr.jpg</url>
            <title>Stories by Prabhnoor Singh on Medium</title>
            <link>https://medium.com/@prabhnoor0212?source=rss-1b6ee6ea1c95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:05:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prabhnoor0212/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[What is Calibration of Models???]]></title>
            <link>https://medium.com/@prabhnoor0212/what-is-calibration-of-models-3aea5137705b?source=rss-1b6ee6ea1c95------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aea5137705b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[platts-scaling]]></category>
            <category><![CDATA[calibration]]></category>
            <category><![CDATA[calibration-plots]]></category>
            <category><![CDATA[isotonic-regression]]></category>
            <dc:creator><![CDATA[Prabhnoor Singh]]></dc:creator>
            <pubDate>Mon, 16 Sep 2019 03:08:28 GMT</pubDate>
            <atom:updated>2020-11-22T11:04:03.672Z</atom:updated>
            <content:encoded><![CDATA[<p>The structure of blog is given. Please, feel free to jump to any section of your choice.</p><ol><li>Introduction</li><li>Need for Calibration</li><li>Calibration Plots</li><li>Calibration Techniques- Platt’s Calibration &amp; Isotonic Regression</li><li>Calibration on imbalanced datasets</li><li>Resources</li></ol><h3><strong>1.Introduction</strong></h3><p>Before jumping into the terminology or the technical details of calibration, I would first like to discuss some cases and scenarios which will help us to smoothly transition into the details of calibration of models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*6zw5at5l08_zNsjK9-FTPg.jpeg" /></figure><p>To start, let’s consider a 2-class classification problem having binary outputs y←(1,0). Assume the training dataset: {xi, yi} where xi is the input for a model and yi is the true class label. We know that any Machine Learning (ML) model would be capable of predicting the output labels, but what if we need the probability value associated with a prediction instead of just a label? We also know that, many ML algorithms, like Naive Bayes, Logistic regression, etc., could easily learn a function f(xi) which would return the conditional probability P(yi=1/xi). But, many times those probability values are just estimates rather then the actual probability scores. For instance, consider the formulation of Naive Bayes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*6KIE5sJzXX3VYhmfJ2_15w.png" /><figcaption>Naive Bayes Algorithm-<a href="https://www.google.com/url?sa=i&amp;source=images&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjPjv2P99LkAhWb6nMBHeicDagQjRx6BAgBEAQ&amp;url=%2Furl%3Fsa%3Di%26source%3Dimages%26cd%3D%26ved%3D%26url%3Dhttps%253A%252F%252Fen.wikipedia.org%252Fwiki%252FNaive_Bayes_classifier%26psig%3DAOvVaw3uj8QZTZjRQ9vwBm--hQfm%26ust%3D1568640259218813&amp;psig=AOvVaw3uj8QZTZjRQ9vwBm--hQfm&amp;ust=1568640259218813">source</a></figcaption></figure><p>Here, we say that the P(Ck/x) is just proportional to and not equal to the RHS term. And, for predicting the actual label we only need these proportional values of P(y=1/x) and P(y=0/x), and we can then compare these values to assign the output label corresponding to the larger of the two values. So, this model did not need any exact probability value. However, in many real world applications we would need those exact probability values. Therefore, we would use calibration which would give the exact probability values of P(yi=1/xi) or P(yi=0/xi). So, calibration is a stage in Machine Learning where we have already trained a model and now we try to calibrate (improve the probability estimates) it to return the exact probability values.</p><h3><strong>2.Need for calibration</strong></h3><p>To understand the need for calibration, let me present a case where I have two already trained models: model A and model B. Now, I show 100 samples of query points to both the models. Model A predicts each input point to belong to class-1 with a probability value of 0.85 and it actually classify 86/100 points correctly to class-1. Model B predicts each input point to belong to class-1 with a probability value of 0.95 and it also classify 86/100 points correctly to class-1. Now, the question is which model is better? The answer is: Model A. Model A is better because it’s not over confident. It basically says that it has a confidence of 85% in its prediction and is actually correct 86% of the time. Thus, if you care about the exact probability values, then calibration is extremely important. Moreover, when we are using metrics such as <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html">log-loss</a>, which need probability values associated with the predicted label for computing the metric, using exact probability scores rather than estimates would give more reliable scores.</p><p>A practical example to substantiate this would be for a fraud detection system. Suppose, we are building a fraud detection system for a bank which needs to block malicious transactions whenever they are about to occur. So, for a given transaction if my models says that the transaction is malicious with a 0.95 probability score then for all the samples with 0.95 probability score, we should be able to see exactly 95% fraud cases in an ideal scenario. Thus, for sensitive tasks like this we would want to calibrate our model perfectly.</p><p>S<a href="https://scikit-learn.org/stable/modules/calibration.html">cikit-learn</a> defines the need for calibration as:</p><blockquote>When performing classification you often want not only to predict the class label, but also obtain a probability of the respective label. This probability gives you some kind of confidence on the prediction. Some models can give you poor estimates of the class probabilities and some even do not support probability prediction. The calibration module allows you to better calibrate the probabilities of a given model, or to add support for probability prediction.</blockquote><h3><strong>3. Calibration Plots</strong></h3><p>Before we look at some calibration plots, first we should understand the method by which the calibration plots are made. For calibration we would need one already trained model which could give us the probability estimate yi* when given a input xi as: f(xi) = yi*. As our model was trained on a training set, now we will would be using a validation set. For constructing a calibration plot we would need the following tuple: (xi, yi*, yi), where xi would be a point from the validation set, yi* would be computed from f(xi) and yi would be the actual class label ← (0,1). Now, the first step would be to compute this tuple for every row/instance in the validation set and then sort the table in increasing order of y*. After this, my table would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*c0wYmGU1ZDExiPg8jH1LWw.png" /></figure><p>The next step is to divide this whole dataset into chunks of say 100 points. So, if we have a total of 10,000 points in my validation set, we will end up with 100 chunks of 100 samples each like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*c2JD7OIms6z3xEdkJRumDA.png" /></figure><p>Now, we will compute average yi* and average yi for all the chunks. As we have 100 chunks, we will be getting 100 avg(yi*) values and 100 avg(yi) values. We can now plot the calibration plots. Calibration plots are nothing but the graph of avg(yi) vs avg(yi*). In an ideal scenario both should be equal and we would get a straight line. So, what is happening here actually? The answer is pretty simple. avg(yi) for a chunk is a cumulative representation of points that are actually labelled 1 in that chunk and avg(yi*) is the cumulative representation of the probabilities with which model predicted the values to be 1. For instance if avg(yi*) of chunk 1 is 0.3, then in an ideal scenario there must be 30 points out of 100 with actual class label 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nA4-9e4EGXlz00gJb9EvYg.png" /><figcaption>Calibration plot-<a href="https://www.google.com/url?sa=i&amp;source=images&amp;cd=&amp;ved=2ahUKEwi-9pnTqdPkAhWM6nMBHfWnAjwQjRx6BAgBEAQ&amp;url=https%3A%2F%2Fmachinelearningmastery.com%2Fcalibrated-classification-model-in-scikit-learn%2F&amp;psig=AOvVaw1va--4KTfstVDVYuVDWovM&amp;ust=1568653929819964">source</a></figcaption></figure><p>In above figure x-axis is avg(yi*) and y-axis is avg(yi). The blue dotted line shows the ideal scenario when predicted probabilities are actual representations of the actual labels. And, the yellow continuous line shows how we actually get the curve in a real life scenario where the probability value given by a model is just an estimate to be used for classifying the point rather than being a well calibrated exact probability representation. Having understood all this, we can now look at some calibration plots for some of the popular ML algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*SOyXLAq_Lai6ZiRYN8yBeg.png" /><figcaption>Calibration Plot Examples-<a href="https://jmetzen.github.io/2015-04-14/calibration.html">source</a></figcaption></figure><p>We can see that Logistic Regression actually is very close to being perfectly calibrated. The reason for that is Logistic Regression directly optimizes log-loss. The other techniques have biased results and thus, need calibration in order to get reliable probability scores.</p><h3><strong>4. Calibration Techniques</strong></h3><p>Until now, we have understood how to plot calibration plots and use them to check whether our models are well calibrated or not. Once we have identified that our model is not calibrated, our task is to calibrate it. When we say that our model is not calibrated, it means that the avg(yi*) or the average of predicted probabilities in a chunk is not equal to the avg(yi) or average of actual labels. So, we can pose this problem of calibrating the models as a regression problem in which we can say that our input is avg(yi*) and we have to predict(yi). Thus, we want to build a system where we will get yi* (un-calibrated probability estimate) as input and the output of the model would the actual calibrated probability. And, to this task, two most popular techniques are- Platt’s Calibration &amp; Isotonic Regression.</p><h4><strong>4.1 Platt’s Calibration/Sigmoid Calibration</strong></h4><p>The idea of Platt’s Calibration or Sigmoid Calibration is quite simple. If we look at the above figure-examples of calibration plots, we would notice that the green and the purple curves look so much like sigmoid plots. <a href="https://en.wikipedia.org/wiki/John_Platt_(computer_scientist)">John Platt</a> observed the same and proposed that as many of such curves are similar to sigmoid function, we can pose this calibration task of getting exact P(yi) from yi* by the simple modified sigmoid function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*jTtn9ZABrPnXgj_iN8MU7g.png" /><figcaption>Platt’s Scaling</figcaption></figure><p>In this formulation, we will have to learn A and B, which are constants, by solving an optimization problem. We can use avg(yi) of each chunk as P(y=1/x) and use avg(yi*) as f(x) to solve for A and B.</p><h4><strong>Downside of Platt’s Scaling:</strong></h4><p>However, there is a major downside to Platt’s Calibration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7n5RGboF-mnQYd5ChyPhBQ.png" /></figure><p>In this figure, the black line is the original function which we were required to learn in order to predict the actual probabilities from the probability estimates. But, by Platt’s scaling we learnt the blue sigmoid curve which is quite far away from the black curve and is not at all a good estimation. So, Platt’s scaling doesn’t work well when the functions are not of sigmoidal form. The fix for this is Isotonic regression which is shown as green curve in above figure.</p><p><strong>4.2 Isotonic Regression</strong></p><p>Isotonic regression can be used whenever the required function is not of the sigmoidal form. The idea of Isotonic regression is also quite simple. It says that we will fit multiple linear lines to explain the relationship between actual probabilities and predicted probability estimates. Thus, we are building piece-wise linear function which is nothing but sequence of linear lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0IjttjIzypcwDDNVLeTd6g.png" /><figcaption>Isotonic Regressin-<a href="https://scikit-learn.org/stable/auto_examples/plot_isotonic_regression.html">source</a></figcaption></figure><p>According to Scikit-learn Isotonic Regression works as follows:</p><blockquote>The isotonic regression finds a non-decreasing approximation of a function while minimizing the mean squared error on the training data. The benefit of such a model is that it does not assume any form for the target function such as linearity. For comparison a linear regression is also presented.</blockquote><p>For building this piece-wise linear system we would find the bunch of lines (slopes and intercepts) and the thresholds representing the start and end point of a line by solving an optimization problem.</p><p>The only problem with Isotonic Regression we need much more points as comapared to the Platt’s scaling because Platt’s scaling had only two parameters to learn-A and B. However, there is no upper bound on the number of parameters for Isotonic regression. We would need to learn n number of equations of lines and their thresholds.</p><h3><strong>5. Calibration on imbalanced datasets</strong></h3><p>In Machine Learning, when we get imbalanced dataset, we balance it by using up-sampling or down-sampling techniques, before training our model so as to ensure that our model doesn’t give unfair advantage to the minority class. However, the problem with this methodology is that now we have disturbed the original class distribution which was real representation of the actual population. In such scenarios it becomes even more important to calibrate our models. What we do is that we first split dataset into train, cv and test sets. We will balance only the train set and train our model on this balanced train set. Now, we will keep the cv data imbalanced only. We will learn the calibration function by using this cv data which is correct representation of the actual population. By balancing data we disturbed the original class probabilities, but now we are correcting them back by using cv data for calibration.</p><p><strong>6. Resources</strong></p><p>If you enjoyed this blog, you might also like the <a href="https://neptune.ai/blog/brier-score-and-model-calibration">blog</a> by neptune.ai on Brier score. And, this <a href="https://machinelearningmastery.com/calibrated-classification-model-in-scikit-learn/">blog</a> on clibration using scikit-learn by Jason Brownlee.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aea5137705b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essence of Machine Learning]]></title>
            <link>https://medium.com/analytics-vidhya/essence-of-machine-learning-ce687b517424?source=rss-1b6ee6ea1c95------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce687b517424</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prabhnoor Singh]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 13:01:37 GMT</pubDate>
            <atom:updated>2019-09-16T10:38:06.242Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I will try to express my take and my views on what Machine Learning essentially is. We will discuss with examples the intuition of Machine Learning and then gradually define the buzz word “Machine Learning”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*maqmu2RX4TqzAL55mgQUPA.jpeg" /></figure><p>Most of the people define Machine Learning(ML) as “ Ability to ‘learn’ with data, without being explicitly programmed”, and to be honest, I have never understood this definition at all. By reading just this, it seems like ML is some kind of sorcery. Also, there are many jokes around ML being just a bunch of IF-ELSE statements. So, what ML actually is. Is it putting a brain into a machine or is it just some convoluted IF-ELSE statements?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ixVE8gijbfoCOWFLCV5jgw.jpeg" /></figure><p>To really understand the meaning of Machine Learning and to grasp how a machine actually learns, we need to understand the terminologies associated with it. But, before going there, let’s take up an example to get an intuition on how a machine learns.</p><p>Let’s say a child, for the very first time in his life, sees a plane flying over his head. Now, the child out of curiosity asks his father “Dad, what just flew over my head?”The father tells him: “Hey, son it’s a plane”.</p><p>After a while, the child sees a bird flying over his head. But, due to his limited knowledge, he tells his dad: “Look! Dad, a plane” assuming that everything that flies over his head is a plane.</p><p>Now, the father corrects him and tells him: “It’s not a plane son. Carefully see that it has a beak, wings which could flap and also is much smaller in size, so it is a bird”.</p><p>The child has now learnt to differentiate between a plane and a bird. He could now correctly call out whenever he sees a bird or a plane but, what will happen if he sees a kite in the sky. He would certainly get confused and the father would now teach him to differentiate between a kite, plane and a bird by mentioning the striking or the differentiating features of these flying entities.</p><p>As long as the child is being fed with correct information, he is able to make the correct calls. Similarly, we try to feed a machine with data having distinguishing features so that it could learn for the data and make the correct calls just like the child. After understanding this example we are now ready to be introduced to the terminologies of machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*sMruXPtKWAZBFgi-1-firg.jpeg" /></figure><p>Coming this far, we have to define some terms to move forward to the actual meaning of Machine Learning. Learning begins with data. Data is nothing but the information we get. It consists of features. Features are nothing but the properties associated with each instance of data.</p><p>Comparing to the above example, data is all the information that the dad was supplying to his son and features are the way that information was supplied, example: flapping wings, size, presence of beak etc. In the real world we mostly get data in terms of rows and columns.</p><p>Each row of the table represents an instance of the data or in ML terms: a sample point/observation. Columns represents the properties of the data, which are called features in ML terminology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*hW-DT56qeBaYvPSTdC8pwg.png" /></figure><p>Let’s now understand how a machine learns from data. It is not true that machine would start learning from the data as soon as we feed it with these tables. We lay down certain rules, state some assumptions, formulate a hypothesis and prepare a cost function, based on which a machine can learn iteratively from it. The two most important terms here are: <strong>hypothesis function and cost function</strong>. To understand these terms first we need to know what is population and sample.</p><p>Population is the overall/complete form of data consisting of all the possible observations. A sample is a subset of that population which should be a true representation of data. Now, coming back to hypothesis function.</p><p>In Machine Learning we believe that a population is represented by some function. Our job is to make an assumption of that function so that the machine could learn the parameters of that function.</p><p>Parameters of the function are often learnt by iterating through the sample of data (It is very difficult to get the complete population, so we work on a sample of it.) and at each iteration computing the cost function. A cost function is basically a penalty function which would penalize the machine when it’s learning something wrong and would reward it when it’s learning something correct.</p><p>Comparing with the above example, the dad who was constantly teaching his son would be the cost function in that case. Hypothesis function would be the logic of the son which was making decisions based on the what he observed. The observations he was making were the sample of the original population. These are the basics of machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AutRhQETL8cwXlkUIgNgTA.png" /></figure><p>One of the major driving force towards making a machine learn rules is the correct assumption of the hypothesis function. One of the most simple assumption for a hypothesis function or the function which we believe is the most accurate representation of the population can be a Gaussian Distribution. If our assumption is correct, then the value from our cost function would be low. However, if the assumption is wrong then it means that we will get a very high value from the cost function. Then, we would need to make a complex assumption for the hypothesis.</p><p>One example of a complex assumption can be a Gaussian Mixture Models, which means that our population is coming from the aggregation/mixture of more than one distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*-ZqY-tHgGi7AL1RfF-Jupg.png" /><figcaption>Gaussian Mixture Model</figcaption></figure><p>Thus, we can say that the better our assumption of the function defining the population is, better would be the prediction from the model. Now, the logical question that arises is : “What is actually being learnt here?”. The answer to this question is: the parameters that define our assumed distribution.</p><p>For instance, if we have assumed our function to be coming from a Gaussian Distribution then, the model will learn the parameters of the Gaussian Distribution i.e. mean and standard-deviation. If we have assumed our function to be a line: y = m*x + c then, the model will learn the parameters m and c.</p><p>Having come this far, we can now also talk about the two classifications of the models in Machine Learning: Generative Models and Discriminative Models.</p><p>A Generative Model ‌learns the <strong>joint probability distribution p(x,y). </strong>This means that a generative model will try to directly estimate the original population function. Thus, it can actually generate data points belonging to the population.</p><p>However, A Discriminative model ‌learns the <strong>conditional probability distribution p(y|x). </strong>This means that, these models only learn to differentiate between classes and do not try to actually generate the data points. Finally, to end this blog I would leave you with what type of problems we solve in Machine Learning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOh7p7f0MYj-fkHSrrNdGg.png" /></figure><p>To summarise:</p><p>1 — Supervised learning has some input points (X) and some designated output labels (y). Our task is to map a function such that f(X) → y.</p><p>2 — In Unsupervised learning, we are only given input labels (X) and we have to observe patters/information from that only.</p><p>3 — In Reinforcement learning we work on the concept of continuous improvement by generating feedback from the environment/stimulus.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce687b517424" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/essence-of-machine-learning-ce687b517424">Essence of Machine Learning</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[Siamese Network Keras]]></title>
            <link>https://medium.com/@prabhnoor0212/siamese-network-keras-31a3a8f37d04?source=rss-1b6ee6ea1c95------2</link>
            <guid isPermaLink="false">https://medium.com/p/31a3a8f37d04</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[triplet-loss]]></category>
            <category><![CDATA[siamese-networks]]></category>
            <category><![CDATA[image-similarity]]></category>
            <category><![CDATA[text-similarity]]></category>
            <dc:creator><![CDATA[Prabhnoor Singh]]></dc:creator>
            <pubDate>Sat, 24 Aug 2019 19:45:58 GMT</pubDate>
            <atom:updated>2019-08-27T14:17:29.972Z</atom:updated>
            <content:encoded><![CDATA[<h3>Siamese Network Keras for Image and Text similarity.</h3><p><strong>TABLE OF CONTENTS</strong></p><ol><li>Introduction</li><li>Theory</li><li>Basic working</li><li>Siamese n/w for image similarity</li><li>Siamese n/w for text similarity</li><li>Siamese n/w with triplet loss</li><li>Scope</li><li>References</li></ol><h3><strong>1. Introduction</strong></h3><p>This blog is about a network, Siamese Network, which works extremely well for checking similarity between two systems . This network is widely used to solve the problems concerning image similarity and text similarity. For the scope of this blog I would demonstrate the application of this network in both the mentioned scenarios. For image similarity application of Siamese network, I would take the Kaggle problem — <a href="https://www.kaggle.com/c/recognizing-faces-in-the-wild">Recognizing faces in the wild</a> — that I participated in and secured 28th position on the leader-board using Siamese networks as baseline models . And, for the text similarity application of Saimese network, I would be using <a href="https://www.kaggle.com/c/quora-question-pairs">Quora Question Pair</a> similarity dataset. If you are only interested in using the code then jump to the references section and find the Github link.</p><h3><strong>2. Theory</strong></h3><p>According to Wikipedia, Siamese Neural Network is defined as —</p><blockquote><strong>Siamese neural network</strong> is an <a href="https://en.wikipedia.org/wiki/Artificial_neural_network">artificial neural network</a> that use the same weights while working in tandem on two different input vectors to compute comparable output vectors. Often one of the output vectors is precomputed, thus forming a baseline against which the other output vector is compared. This is similar to comparing <a href="https://en.wikipedia.org/wiki/Fingerprint">fingerprints</a> or more technical as a distance function for <a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing">Locality-sensitive hashing</a>.</blockquote><p>In the above mentioned datasets the very basic concept of Siamese Network will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQcJ7ik58aeTV0As2d9Jcw.png" /><figcaption>A basic Siamese network —<a href="https://www.mdpi.com/symmetry/symmetry-10-00385/article_deploy/html/images/symmetry-10-00385-g001.png"> Source</a></figcaption></figure><p>In Siamese network we keep the basic network for getting features of entities(images/text) same and pass the two entities we want to compare through the exact same network. By the exact same network it is meant that both the entities are passed through the same architecture having same weights as shown in the figure. At the end of common network we get a vectored representation of our input which can then be used for measuring or quantifying the similarity between them.</p><h3><strong>3. Basic Working</strong></h3><p>In the case of finding similarity between images we can first get the images in numpy array format and feed them through any architecture(should be same for both images) and get an n-dimensional representation at the end of the common network. These n-dimensional representations can then be used as input to some loss function or a similarity metric or a simple neural network architecture would work as well. One simple example of Siamese network is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*TjIZ52znavYCghYs0WBgLA.png" /><figcaption>A simple Siamese network-<a href="https://github.com/hlamba28/One-Shot-Learning-with-Siamese-Networks/blob/master/Siamese%20on%20Omniglot%20Dataset.ipynb">source</a></figcaption></figure><p>left_input and right_input shown in the above image represents the vectorized form of the two input images we wish to compare similarity. These image representation are then fed to a common network (a CNN in the above example). Same operations are performed on both the image vectors and the finally the distance between both of them is calculated by subtracted the vectors. The output of the difference of both the vectors is connected to a simple sigmoid output layer. Note that the input to this network is a list of two inputs — left_input and right_input.</p><h3><strong>4. Siamese network for image similarity</strong></h3><p>Siamese networks work very well for image similarity tasks. To show an example I am using the data set from Kaggle problem — <a href="https://www.kaggle.com/c/recognizing-faces-in-the-wild">Recognizing faces in the wild</a> which I participated in recently and secured 28th rank by just using and tweaking multiple Siamese networks shown below. For the sake of this blog I will be only discussing the Siamese network part of the solution. If you are interested in the other parts such as pre-processing, data generation, etc., kindly check out the project Github link in references.</p><p>Let me now explain the Siamese architecture which is being used for checking whether two people are related by blood or not judging by their facial features. To start, our overall model has two inputs. Here input_1 is the image of person 1 and input_2 is the image of person_2. The task is to identify whether these two persons are related by blood or not.</p><p>The base model or the common network in the Siamese network(as discussed above) used in this case study is VGGFACE pre-trained model (you can use any architecture of your choice here)in which trainable parameter for all the layers except the last three layers. The significance of doing this is that the top layers are just being used for feature engineering and the later layers responsible for decision making can be fine-tuned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*Mc3KoB1lMBlJQikl-w57Xw.png" /><figcaption><a href="https://github.com/prabhnoor0212/Kaggle-Recognizing-faces-in-the-wild">Siamese network for image similarity</a></figcaption></figure><p>x1 and x2 shown in the code are the features representing the two images. These two vectors are then sent through Global Max Pool and Global Avg Pool. x3 vector is the difference of of the vectors which then squared. Similarly x4 vector is the difference of the sqaure of x1 and x2 vectors. Further, x5 vector is the cosine similarity between x1 and x2 vectors. Finally, the x3, x4, x5 are concatenated and fed to a dense layer followed by a Dropout layer and then output sigmoid layer.</p><p>In simple words, the two images are featurized using a common network, then these two feature vectors can be directly used or sent through some decision making network to check for similarity between images.</p><h3>5. Siamese network for text similarity</h3><p>Just like we used Siamese network to check whether two images are similar or not, the same concept can also be used to check whether two pieces of texts are similar or not. For the example, we will consider <a href="https://www.kaggle.com/c/quora-question-pairs">Quora Question Pair</a> similarity dataset. The problem at hand is to check whether a pair of questions posted on Quora website are similar or not.</p><p>To solve this task, we can again use Siamese network for the classification of the text as similar or not. Here, the common network used for featurizing texts is a simple Embedding layer followed by LSTM unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*NFxcRiZJa7bo4WO1BDLXeg.png" /><figcaption><a href="https://github.com/prabhnoor0212/Siamese-Network-Text-Similarity">Siamese text similarity</a></figcaption></figure><p>In this network. input_1 and input_2 are pre-processed, Keras-tokenized text sequences which are to be compared for similar intent. These two text sequences are then fed through a common network of a basic embedding layer and an LSTM units. Once the feature vectors are obtained from this common network, a series of similarity measures are computed and are concatenated to be finally input into a Dense layer followed by sigmoid output unit which will finally help in classifying whether the given texts are similar or not.</p><h3><strong>6. Siamese in conjunction with triplet loss</strong></h3><p>Siamese network is often used in conjunction with triplet loss. Triplet loss synergies quite well with Siamese network because it accepts three different images or any input which is fed through a common Siamese network for getting features which can be used to later predict/classify accordingly.</p><p>According to Wikipedia:</p><blockquote><strong>Triplet loss</strong> is a <a href="https://en.wikipedia.org/wiki/Loss_function">loss function</a> for <a href="https://en.wikipedia.org/wiki/Artificial_neural_network">artificial neural networks</a> where a baseline (anchor) input is compared to a positive (truthy) input and a negative (falsy) input. The distance from the baseline (anchor) input to the positive (truthy) input is minimized, and the distance from the baseline (anchor) input to the negative (falsy) input is maximized.</blockquote><blockquote>It is often used for <a href="https://en.wikipedia.org/wiki/Similarity_learning">learning similarity</a> of for the purpose of learning embeddings, like <a href="https://en.wikipedia.org/wiki/Word_embedding">word embeddings</a> and even <a href="https://en.wikipedia.org/wiki/Thought_vector">thought vectors</a>, and <a href="https://en.wikipedia.org/wiki/Metric_learning">metric learning</a>.</blockquote><p>In triplet loss basically, we have three inputs- anchor, positive and negative. Anchor can be any image of the person, positive is some other image of the same person and negative is an image of different person. The loss function can be described as: L=max(d(a,p)−d(a,n)+margin,0) where d(a,p) is the distance between anchor image and positive image. Similarly, d(a,n) is the distance between anchor and negative image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*ESSKGKp-wKMaxU74lMCs1Q.png" /><figcaption><a href="https://www.google.com/url?sa=i&amp;source=images&amp;cd=&amp;ved=2ahUKEwjClIue2qLkAhVBQo8KHTFEDYMQjRx6BAgBEAQ&amp;url=%2Furl%3Fsa%3Di%26source%3Dimages%26cd%3D%26ved%3D%26url%3Dhttp%253A%252F%252Fcs231n.stanford.edu%252Freports%252F2017%252Fposters%252F108.pdf%26psig%3DAOvVaw1xC2y6bb6g7u8LUOUkAioq%26ust%3D1566983338901195&amp;psig=AOvVaw1xC2y6bb6g7u8LUOUkAioq&amp;ust=1566983338901195">Triplet loss learning</a></figcaption></figure><p>As it can be seen in the above image the triplet loss function tries to maximize the distance between anchor image and negative image while minimizing the distance between anchor image and positive image thereby learning to differentiate similar images to non similar ones. To learn about the theoretical aspects of triplet loss please have a look at this <a href="https://www.youtube.com/watch?v=d2XB5-tuCWU">video</a>. I will now focus on the practical aspects of using triplet function by considering the kaggle recognizing faces in wild dataset.</p><p>In practical scenarios the datasets we generally work with will have image pairs and output labels. So, we will have to first generate inputs such that instead of image pairs we have triplets of anchor, positive and negative image. We won’t require an output label so any dummy value will work as our triplet loss will try to work on the distances of the images rather than any labels. Here is the code for generating the dataset for the above mentioned dataset, please refer to the github code in the references to follow the precious steps as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*_LnWHm423hkVLqVBgezsgw.png" /><figcaption><a href="https://github.com/prabhnoor0212/Kaggle-Recognizing-faces-in-the-wild">Triplet data generation</a></figcaption></figure><p>In the above code you could see that this data generator is yielding three images X1(anchor image), X2(positive image), and X3(negative image) with dummy labels(these can be ignored). Now, we are ready to feed this data into our Siamese network with triplet loss. The code for triplet loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*09MbNkbyRBt7C3pHjaiFJQ.png" /><figcaption><a href="https://github.com/prabhnoor0212/Kaggle-Recognizing-faces-in-the-wild">Triplet loss code</a> — <a href="https://github.com/KinWaiCheuk/Triplet-net-keras/blob/master/Triplet%20NN%20Test%20on%20MNIST.ipynb">source</a></figcaption></figure><p>Further, this loss can be utilized in our custom networks(any network you want to work with) as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*_OrSpud5-9rFK9gYfRRR9A.png" /><figcaption><a href="https://github.com/prabhnoor0212/Kaggle-Recognizing-faces-in-the-wild">Siamese network with triplet loss</a></figcaption></figure><p>Here, our model accepts input_1(anchor), input_2(positive) and input_3(negative). These image vectors are then sent through a common Siamese network which in this case is VGGFace model. After, getting passed through Maxpool layers, these three vectors can be used by triplet loss function which will work according to the methodology discussed above. Finally, you can run model.fit_generator() method and start training your complete network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*gOCIxvNjHbQRrvHG0nH4IQ.png" /><figcaption><a href="https://github.com/prabhnoor0212/Kaggle-Recognizing-faces-in-the-wild">model training</a></figcaption></figure><p>Note: To get even better results with triplet loss, it is important to generate the dataset so that the negative sample taken is not any random image. Instead carefully construct a dataset by taking the negative image which looks similar to the anchor image but in reality it is not.</p><h3><strong>7. Scope</strong></h3><p>The scope of this blog was to introduce the applications of a very popular architecture- Siamese network and to provide quick and easy to understand reference code so that you can easily modify it and use it in your projects. The full code is given in the references section point [1] &amp; [2]. If working on the datasets used as examples for this blog, better results can easily be obtained with some hyperparameter tuning and also by playing around with the number of layers or using a different architecture all together. However, the underlying working of Siamese network remains same.</p><h3><strong>8. References</strong></h3><p>[1] <a href="https://github.com/prabhnoor0212/Kaggle-Recognizing-faces-in-the-wild">https://github.com/prabhnoor0212/Kaggle-Recognizing-faces-in-the-wild</a></p><p>[2] <a href="https://github.com/prabhnoor0212/Siamese-Network-Text-Similarity">https://github.com/prabhnoor0212/Siamese-Network-Text-Similarity</a></p><p>[3] <a href="https://www.kaggle.com/c/recognizing-faces-in-the-wild">https://www.kaggle.com/c/recognizing-faces-in-the-wild</a></p><p>[4] <a href="https://www.kaggle.com/c/quora-question-pairs">https://www.kaggle.com/c/quora-question-pairs</a></p><p>[5] <a href="https://en.wikipedia.org/wiki/Artificial_neural_network">https://en.wikipedia.org/wiki/Artificial_neural_network</a></p><p>[6] <a href="https://www.mdpi.com/symmetry/symmetry-10-00385/article_deploy/html/images/symmetry-10-00385-g001.png">https://www.mdpi.com/symmetry/symmetry-10-00385/article_deploy/html/images/symmetry-10-00385-g001.png</a></p><p>[7] <a href="https://github.com/hlamba28/One-Shot-Learning-with-Siamese-Networks/blob/master/Siamese%20on%20Omniglot%20Dataset.ipynb">https://github.com/hlamba28/One-Shot-Learning-with-Siamese-Networks/blob/master/Siamese%20on%20Omniglot%20Dataset.ipynb</a></p><p>[8] <a href="https://www.kaggle.com/hsinwenchang/vggface-baseline-197x197">https://www.kaggle.com/hsinwenchang/vggface-baseline-197x197</a></p><p>[9] <a href="https://www.youtube.com/watch?v=d2XB5-tuCWU">https://www.youtube.com/watch?v=d2XB5-tuCWU</a></p><p>[10] <a href="https://github.com/KinWaiCheuk/Triplet-net-keras/blob/master/Triplet%20NN%20Test%20on%20MNIST.ipynb">https://github.com/KinWaiCheuk/Triplet-net-keras/blob/master/Triplet%20NN%20Test%20on%20MNIST.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31a3a8f37d04" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>