<?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 Keshav G on Medium]]></title>
        <description><![CDATA[Stories by Keshav G on Medium]]></description>
        <link>https://medium.com/@kshavg?source=rss-64aef7a55f6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*rPZGPpLpvG-0ihBvGDp0zQ.jpeg</url>
            <title>Stories by Keshav G on Medium</title>
            <link>https://medium.com/@kshavg?source=rss-64aef7a55f6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:32:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kshavg/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[DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks]]></title>
            <link>https://medium.com/greendeck/deepar-probabilistic-forecasting-with-autoregressive-recurrent-networks-fa65dddae1f5?source=rss-64aef7a55f6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa65dddae1f5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <dc:creator><![CDATA[Keshav G]]></dc:creator>
            <pubDate>Wed, 25 Nov 2020 13:43:09 GMT</pubDate>
            <atom:updated>2022-03-16T09:54:15.378Z</atom:updated>
            <content:encoded><![CDATA[<h4>Amazon’s DeepAR is a forecasting method based on autoregressive recurrent networks, which learns a global model from historical data of all time series in the dataset.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9JGe_1BswJG-nah71Uitg.png" /><figcaption>Summary of the model</figcaption></figure><h3>ABOUT THE DATASET</h3><p>Here we use UCI’s Electricity Dataset that contains electricity consumption of 370 points/clients from a period of 2011 to 2014 at an interval of 15 minutes. Apart from electricity consumption data, we also generate some covariates series (for example Day of the Week, Month of the year, etc.) for individual time series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yR-KNz7yIbjaGsTz2GoDbg.png" /><figcaption>UCI’s Electricity Dataset (Link: <a href="https://archive.ics.uci.edu/ml/datasets/ElectricityLoadDiagrams20112014">https://archive.ics.uci.edu/ml/datasets/ElectricityLoadDiagrams20112014</a>)</figcaption></figure><p>DeepAr model learns seasonal behaviour pattern from these covariates which strengthens its forecasting capabilities. There are a total of 300 points/clients in the dataset. Each 300 points/clients is allotted a unique index called “Index of the series” which is passed along as covariate to the model. This “Index of the series” is further passed to an embedding layer which learns a unique embedding for individual points/clients.</p><h3>DEEP DIVE INTO THE MODEL ARCHITECTURE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwVG7rvAnS6I0KPfgYcMtQ.png" /><figcaption>DeepAR</figcaption></figure><h4>1. TRAINING</h4><p>DeepAR employs LSTM-based recurrent neural network architecture to the probabilistic forecasting. Some of the good resources for understanding LSTMs:</p><ol><li><a href="https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21">https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21</a></li><li><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">https://colah.github.io/posts/2015-08-Understanding-LSTMs/</a></li></ol><p>At each time step t, the inputs to the network are the covariates x(t), the target value at the previous time step z(t−1), as well as the previous network output h(t−1) (LSTM’s hidden state from previous time step). The network outputs h(t) = LSTM( h(t-1), z(t-1), x(t) ). This h(t) is then further used to calculate parameters (μ and σ in case of gaussian distribution or α and µ in case of binomial distribution) for the likelihood of z(t), which is used for training the LSTM parameters. LSTM initial cell state and hidden state are initialised with zeroes.</p><p>In this blog all calculation are made with respect to Gaussian Distribution. Therefore we will be only discussing Gaussian Likelihood.</p><p><strong>Gaussian Likelihood</strong></p><p>In <a href="https://en.wikipedia.org/wiki/Statistics">statistics</a>, the <strong>likelihood function</strong> (often simply called the <strong>likelihood</strong>) measures the <a href="https://en.wikipedia.org/wiki/Goodness_of_fit">goodness of fit</a> of a <a href="https://en.wikipedia.org/wiki/Statistical_model">statistical model</a> to a <a href="https://en.wikipedia.org/wiki/Sample_(statistics)">sample of data</a> for given values of the unknown <a href="https://en.wikipedia.org/wiki/Statistical_parameter">parameters</a>.</p><p>For Simplicity, likelihood is the probability of a point z(t) to lie in a gaussian distribution whose μ(mean) and σ(standard deviation) are known.</p><p>For example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*9A_Abm668EUEDbvx0TIPcA.png" /></figure><p>So, likelihood of target point z(t) is its probability of lying inside the gaussian distribution whose parameter are μ(mean) and σ(standard deviation) (predicted by the model). If z(t) is closer to mean it will have high likelihood.</p><p>Therefore negative of this Gaussian Likelihood can be used as a loss.</p><p>DeepAR uses this only as its loss function, to be specific they use negative of log of Gaussian Likelihood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*uBxViTv_EXWbDeYBZbE0JA.png" /><figcaption>to learn more about this equation: <a href="http://jrmeyer.github.io/machinelearning/2017/08/18/mle.html">http://jrmeyer.github.io/machinelearning/2017/08/18/mle.html</a></figcaption></figure><p>There are many likelihood algorithms, but their choice has to be made looking at the type of time series one has. Gaussian likelihood for real-valued data, and negative-binomial likelihood for positive count data. Other likelihood models can also readily be used, e.g. beta likelihood for data in the unit interval, Bernoulli likelihood for binary data, or mixtures in order to handle complex marginal distributions, as long as samples from the distribution can cheaply be obtained, and the log-likelihood and its gradients w.r.t. the parameters can be evaluated.</p><p><strong>Predicting μ(mean) and σ(standard deviation)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vx1B6poSLcvHrDd_4Mi_Q.png" /></figure><p>The LSTM output of this time step is further passed to two dense layer, output of first dense layer is the predicted <strong>μ(mean)</strong> and and output from the second dense layer is subjected to a Softplus activation , which results in predicted <strong>σ(standard deviation)</strong>.</p><h4>2. PREDICTION</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiLYaKRxmw7uR-hP2xiNKQ.png" /></figure><p>Upon training the model up to t time step, now it comes to predicting time steps &gt; t i.e. t+1,t+2… etc. For predicting z(t+1), first a gaussian distribution in created using the μ(t) and σ(t) , from this distribution n samples are drawn, median of these n samples is set to z`(t) . z`(t) along with current know covariates x(t+1) and previous hidden state h(t) are fed into the trained LSTM model which outputs h(t+1).</p><p>h(t+1) = LSTM(z`(t),x(t+1),h(t))</p><p>μ(t+1) and σ(t+1) are obtained using h(t+1), using the new μ(t+1) and σ(t+1) a gaussian distribution is created from which n samples are selected, whose median acts as the predicted value z`(t+1) and standard deviation as confidence interval, ci(t+1).</p><p>z`(t+1) = median(*samples)</p><p>ci(t+1) = standard deviation(*samples) x p</p><ul><li>*samples = n sample drawn from gaussian distribution with parameters μ(t+1) and σ(t+1)</li><li>p = confidence percentage</li></ul><p>For a 95% confidence interval set p = 2</p><p>Upper Confidence Interval = z`(t+1) + 2 * ci(t+1)</p><p>Lower Confidence Interval = z`(t+1) — 2*ci(t-1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*uNUq-JEcRJrlah3K_FuGZg.png" /></figure><h3>Resources:</h3><blockquote>Paper<em> : </em><a href="https://arxiv.org/pdf/1704.04110.pdf">https://arxiv.org/pdf/1704.04110.pdf</a></blockquote><blockquote>Pytorch Unofficial GitHub Implementations:</blockquote><blockquote><em>1) </em><a href="https://github.com/zhykoties/TimeSeries">https://github.com/zhykoties/TimeSeries</a> — closest to paper description</blockquote><blockquote>2) <a href="https://github.com/jingw2">https://github.com/jingw2</a> — implemented binomial likelihood as well</blockquote><blockquote>Amazon’s Official Implementation : <a href="https://github.com/awslabs/gluon-ts/tree/master/src/gluonts/model/deepar">https://github.com/awslabs/gluon-ts/tree/master/src/gluonts/model/deepar</a> — implemented in MxNet😔</blockquote><h3>About Me:</h3><p>ML Engineer in a fast-growing startup, Greendeck. We help retailers with pricing intelligence and business monitoring. We have offices both in London and Indore, India. If you are passionate about deep learning, or simply want to say hi, please drop me a line at keshav.gupta@greendeck.co. Any suggestion regarding the blog will be great as well. <a href="http://www.linkedin.com/in/kshavG">www.linkedin.com/in/kshavG</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa65dddae1f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/greendeck/deepar-probabilistic-forecasting-with-autoregressive-recurrent-networks-fa65dddae1f5">DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks</a> was originally published in <a href="https://medium.com/greendeck">Greendeck</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[N-BEATS: NEURAL BASIS EXPANSION ANALYSIS FOR INTERPRETABLE TIME SERIES FORECASTING]]></title>
            <link>https://kshavg.medium.com/n-beats-neural-basis-expansion-analysis-for-interpretable-time-series-forecasting-91e94c830393?source=rss-64aef7a55f6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/91e94c830393</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Keshav G]]></dc:creator>
            <pubDate>Sun, 17 May 2020 15:49:09 GMT</pubDate>
            <atom:updated>2020-05-17T15:49:09.239Z</atom:updated>
            <content:encoded><![CDATA[<p>N-beats is a deep neural architecture based on backward and forward residual links and a very deep stack of fully-connected layers. The architecture has a number of desirable properties, being interpretable, applicable without modification to a wide array of target domains, and fast to train. Two configurations of N-BEATS demonstrate state-of-the-art performance for M3, M4 and TOURISM competition datasets containing time series from diverse domains, improving forecast accuracy by 11% over a statistical benchmark and by 3% over last year’s winner of the M4 competition</p><h3>N-BEATS Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*1If8JU4JwFAta1kjMjkTQg.png" /><figcaption>Figure 1: N-BEATS Architecture</figcaption></figure><h4>1) Time Series Input</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*l5UU6We7Jq6murpFhS3V-w.png" /><figcaption>Figure 2:Time Series in consideration</figcaption></figure><p>The model takes time series data upto x ₜ (t=data points upto time t) as its input and predict future x ₜ₊ₕ (h = Forecast window length). The size of the input is n*H (n generally ranging from 2 to 7) also called the <strong>Lookback Period</strong>, model learn the behaviour of the time series over the lookback period and tries to predict the behaviour of data upto “H future points” also called <strong>Forecast Period.</strong></p><h4>2) Architecture Blocks:</h4><p>Time series data over the Lookback period serves as input to Stack 1, which in-turn is made up of multiple Blocks, which are arranged in a <strong>Doubly Residual Stacking</strong> manner. In order to understand working of the architecture we have to understand the Basic Block first.</p><p><strong>i) Basic Block</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*BkyblCw8UPIWZ_h3oqMXLg.png" /><figcaption>Figure 3: Generic Basic Block</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*Jznia_xjulaUbpNLATh_wg.png" /><figcaption>Figure 4: Internal structure of Generic Basic Block</figcaption></figure><p>Input to Stack 1 will pass through a Block which looks exactly as represented in Figure 3, Figure 4 is the internal layers configuration of Basic Block for clear understanding.</p><p>We have set length of Forecast period to 5 data points and Lookback Period to 15 data points.</p><p>15 dimensional input from the Lookback Period is first passed through a 4 layer [FC+Relu] stack and afterwards divided into two parts. Each of which is further passed through another FC and finally we get two outputs, a 15 dim vector in the form of Backcast and a 5 dim vector in the form of Forecast. This Basic Block learns to predict not only the future data points in the form of Forecast but also predicts the input data as well in the form of Backcast.</p><p><strong>ii) Doubly</strong> <strong>Residual Stacking Of Blocks:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*poRhmjNjCXPsv0Vb8ypwXg.png" /><figcaption>Figure 5: Internal Structure of a Stack</figcaption></figure><p>A single Stack consists of multiple Basic Blocks, arranged in a manner following Double Residual Stacking principal. There are two arithmetic operations going on with the output of the Basic Block (i.e Backcast and Forecast) hence the term Double Residual Stacking.</p><p>A 15 dim input of the Lookback Period (Lookback_inp) is passed through Block 1 which gives us two outputs Backcast_1 and Forecast_1. The 15 dim input to Block 2 will be element wise subtraction of Backcast_1 with Lookback_inp( Backcast_1-Lookback_inp ). By subtracting Lookback_inp from Backcast_1, a vector which incorporates only those learnings not learned enough by Block 1 will be passed as input to Block 2.</p><p>Following this logic, input to every Block would be a 15 dim vector which is made up of element wise subtraction of previous Block’s Backcast output and input. The Backcast output of the last Block in a Stack is called Stack Backcast output.</p><p>Whereas the Forecast output of all the blocks in the Stack will be added element wise to yield a 5 dim vector. This vector is going to serve as Stack Forecast Output.</p><p>iii) <strong>Combining the Stacks</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*Nd_A73ikjBQ-mjg6QJesKA.png" /><figcaption>Figure 6: Stacks arrangement</figcaption></figure><p>It is pretty evident from the above image that a 15 dim lookback_inp vector when passed through Stack 1 will yield two outputs, a 15 dim Stack Backcast Output and a 5 dim Stack Forecast Output. Stack Backcast Output will serve as input to Stack 2 (this vector represents learnings not learnt by Stack 1) and similarly Stack Backcast Output from individual Stack will act as input to next Stack down the line. Stack Forecast Output from all the Stacks will be summed element wise together to yield the final 5-dim Global Forecast Vector.</p><p>Loss using MSE(mean squared error) will be calculated on this predicted Global Forecast Vector and Ground Truth data.</p><p>All the Gradients in the architecture will be updated based on this Loss.</p><h3>Learning Trend:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*ERhjDwMuDkhktYisCsFoQQ.png" /><figcaption>Figure 7: Trend Block</figcaption></figure><p>In order to learn trend from the lookback period, we remove the last layer of the Basic Block and multiply outputs X and Y with two matrices as mentioned in Figure 7. This change is only incorporated in the Basic Block, author of the paper refers this new Block as Trend Block. These matrices are formed according to the logic mentioned in the N-beats paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEW6ipsLkWXkGwrEbzQyJg.png" /><figcaption>Figure 8: Equation for Trend Block</figcaption></figure><h3>Learning Seasonality</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*pqJxiTLGVSf_OZqTrHYT1A.png" /><figcaption>Figure 9: Seasonality Block</figcaption></figure><p>In order to learn seasonality from the lookback period, we remove the last layer of Basic Block and multiply outputs X and Y with two matrices as mentioned in Figure 9. This change is only incorporated in the Basic Block, author of the paper refer this new Block as Seasonality Block. These matrices are formed according to the logic mentioned in the N-beats paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xm3fbDONQPLZp8O3b_-RGw.png" /><figcaption>Figure 10: Equation for Seasonality Block</figcaption></figure><h3>Resources:</h3><blockquote><em>paper : </em><a href="https://arxiv.org/pdf/1905.10437.pdf">https://arxiv.org/pdf/1905.10437.pdf</a></blockquote><blockquote><em>github implementation: </em><a href="https://github.com/philipperemy/n-beats/blob/master/nbeats_pytorch/model.py">https://github.com/philipperemy/n-beats/blob/master/nbeats_pytorch/model.py</a></blockquote><h3>About Me:</h3><p>I work as a ML Engineer in a fast-growing startup, Greendeck. We, at Greendeck, help retailers with pricing intelligence. We have offices both in London and Indore,India. If you are passionate about deep learning, or simply want to say hi, please drop me a line at keshav.gupta@greendeck.co. Any suggestion regarding the blog will be great as well. <a href="http://www.linkedin.com/in/kshavG">www.linkedin.com/in/kshavG</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91e94c830393" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Similarity Loss for Deep Metric Learning]]></title>
            <link>https://kshavg.medium.com/multi-similarity-loss-for-deep-metric-learning-ad194691e2d3?source=rss-64aef7a55f6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad194691e2d3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Keshav G]]></dc:creator>
            <pubDate>Mon, 04 May 2020 09:31:01 GMT</pubDate>
            <atom:updated>2020-05-04T10:11:43.400Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multi-Similarity Loss</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*mJmbfPbJHioqOTKDsV4XAA.png" /></figure><p>Metric learning aims to learn an embedding space, where the embedded vectors of similar samples are encouraged to be closer, while dissimilar ones are pushed apart from each other. Multi Similarity Loss proposed intuitively better methods to achieve this and is backed up by its accuracies across public benchmark datasets. This paper main contribution are two fold: a) Introducing multiple similarities into the mix, b) hard pair mining.</p><h3>Multiple Similarities:</h3><p>This loss deals with 3 types of similarities that carry the information of pairs.</p><h4>1. Self Similarity:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*jpK1iR2vKDfPOo_CIK9Pjw.png" /><figcaption>x1 = anchor, x2 = positive, x3,x4 = negatives</figcaption></figure><p>Self similarity ensures that instances belonging to positive class remains closer to anchor than the instances associated with negative classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*qRPvSDxCOPCLZ8T_B95Udg.png" /><figcaption>Sᵢₖ= cosine similarity between pairs, λ = similarity margin, α,β = hyperparameters</figcaption></figure><p>Ms-Loss comprises of two parts:</p><p>i) Positive Part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*cRJGPsWoRjLovn3sS6TAag.png" /><figcaption>x1 = Anchor, x2,x3 = positives, λ = margin</figcaption></figure><p>This part deals exclusively with p-pairs (positive pairs). λ represents the similarity margin which controls the closeness of p-pairs by heavily penalizing those p-pairs whose cosine similarity &lt; λ. In the above diagram we can see two pairs x1-x2 and x1-x3, positive part of the loss for x1-x2 would be very low since e^(-α(Sᵢₖ — λ)) = e^(-α(0.7–0.5)) = e^(-0.2 * α), since α is hyperparameter and always greater than zero, value of this term will be very low when compared with positive part of the loss for x1-x3. For this pair, loss will be e^(-α(0.4–0.5)) = e^(0.1 α)). Cleⱼar distinction is there between the loss back propagated for x1-x2 and x1-x3.</p><p>ii) Negative Part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*YMrMumUqMmAM3uJqr33XHQ.png" /><figcaption>x1 = anchor, x2,x3 = negatives, λ = margin</figcaption></figure><p>This part deals exclusively with n-pairs (negative pairs). This part of the loss ensures negatives to have as low as possible similarity with the anchor. This means that negatives lying closer to x1 ( i.e having high similarity) should be penalized heavily than negatives lying further away from x1 ( i.e having low similarity). This is evident from the loss, for eg. loss for x1-x2 is e^(β(Sᵢₖ — λ)) = e^(β(0.3–0.5)) = e^(-0.2 * β), whereas loss for x1-x3 is e^(β(0.1– 0.5)) = e^(-0.4 * β), since e^(-0.2 * β) &gt; e^(-0.4 * β) for β &gt; 0,hence loss for n-pairs with high similarity will be more than n-pairs with low similarity.</p><h4>2. Negative relative similarity:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*ef08UMloGT-WXnZRy2TduQ.png" /><figcaption>Weight assigned to a negative pair in ms loss, this is derived by derivative of the MS Loss with respect to a single pair.</figcaption></figure><p>Maths for the above eq. will be shared in another Blog. <strong>Weight wᵢⱼ for a pair is defined as contribution of loss from that pair towards the total loss</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJMEcGqWUL9oZ24ZvV3ccA.png" /><figcaption>weight for x1-x2, Case 1 &gt; weight for x1-x2, Case 2&gt; weight for x1-x2, Case 3</figcaption></figure><p>Taking into consideration only one n-pair x1-x2, ms-loss not only assign weight to this pair only on the basis of self-similarity between x1-x2 but also on the basis of its relative similarity i.e all other negatives present in the batch with respect to x1.</p><p>In the above eq. Sᵢⱼ refers to self similarity between x1-x2 and Sᵢₖ refers to similarity between x1-x3,x1-x4,x1-x5,x1-x6,x1-x7. In the above image though x1-x2 has same similarity Sᵢⱼ across all cases, its w-ᵢⱼ varies across cases.</p><ul><li>Case 1: All other negatives (x3,x4,x5,x6,x7) are farther away from x1 with respect to x2.</li><li>Case 2: All negatives (x2,x3,x4,x5,x6,x7) lie at an equal distance from the anchor x1.</li><li>Case 3: All other negatives (x3,x4,x5,x6,x7) lie closer to x1 with respect to x2.</li></ul><p>The difference in the w-ᵢⱼ of the three case is the denominator term Σ[e^(β(Sᵢₖ- Sᵢⱼ))]. Where Sᵢₖ = cosine similarity between x1-x3,x1-x4,x1-x5,x1-x6,x1-x7 and Sᵢⱼ =cosine similarity between x1-x2.</p><ul><li>Case 1: w-ᵢⱼ is highest, since denominator term Σ[e^(β(Sᵢₖ- Sᵢⱼ))] is lowest as all Sᵢₖ&lt;Sᵢⱼ making this e^(negative term)</li><li>Case 2: w-ᵢⱼ is in middle, since in denominator term Σ[e^(β(Sᵢₖ- Sᵢⱼ))], Sᵢₖ≃ Sᵢⱼ making it e^(zero-ish term).</li><li>Case 3: w-ᵢⱼ is lowest, since denominator term Σ[e^(β(Sᵢₖ- Sᵢⱼ))] is largest as all Sᵢₖ&gt;Sᵢⱼ, therefore making this e^(positive term).</li></ul><p>Case 3: e^(positive term) &gt;Case 2: e^(zero-ish term) &gt;Case 1: e^(negative term)</p><p>Since w-ᵢⱼ is inversely proportional to denominator term;</p><p><em>Case 3: w-ᵢⱼ &gt;Case 2: w-ᵢⱼ&gt;Case 1: w-ᵢⱼ</em></p><h4>3. Positive relative similarity:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*VWL3Mx15BIMD4nP9Jr7XUQ.png" /><figcaption>Weight assigned to a positive pair in ms loss, this is derived by derivative of the MS Loss with respect to a single pair.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ci-u5fA9f0WMlfLOKftEJg.png" /><figcaption>weight for x1-x2, Case 1 &gt; weight for x1-x2, Case 2&gt; weight for x1-x2, Case 3</figcaption></figure><p>Negative relative similarity states the relationship of a single negative pair with all other negative pairs in the batch. Similarly positive relative similarity defines the relation between a single positive (x1-x2)and all other positives(x1-x3,x1-x4,x1-x5,x1-x6) in the batch. Following the procedure we did under Negative relative similarity heading, we can easily verify the results stated in the above image.</p><h3>Mining Hard Positives And Negatives</h3><p>Authors of Multi-Similarity loss paper used only hard negatives and positives for training and discarded all other pairs as they contribute little to no improvement and sometimes degraded the performance as well. Choosing only those pairs that carries the most information also make the algo computationally faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*OfnfAYo0csQ-LrHjvkLhBQ.png" /><figcaption>A = anchor, P = positives, N = negatives</figcaption></figure><h4>i) Hard Negative Mining:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*5S-jzgZpVLCfYafPzr8bKw.png" /></figure><p>The above eq. states that only those negatives should be included in training whose similarity with the anchor is greater than minimum similarity of a positive (positive which is lying furthest in embedding space). Therefore in the above diagram only negatives we have chosen are the red ones since they are all lying inside the positive with minimum similarity to anchor, rest all negative are discarded.</p><h4>ii) Hard Positive Mining:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*ZW0ojcBFLTUkg0api-fwPw.png" /></figure><p>The above eq. states that only those negatives should be included in training whose similarity with the anchor is less than maximum similarity of a negative (negative lying closest to anchor). Hard positives are coloured blue while rest are discarded.</p><h3>Understanding The Code:</h3><pre>class MultiSimilarityLoss(nn.Module):<br>    def __init__(self, cfg):<br>        super(MultiSimilarityLoss, self).__init__()<br>        self.thresh = 0.5<br>        self.margin = 0.1</pre><pre>        self.scale_pos = cfg.LOSSES.MULTI_SIMILARITY_LOSS.SCALE_POS<br>        self.scale_neg = cfg.LOSSES.MULTI_SIMILARITY_LOSS.SCALE_NEG</pre><pre>    def forward(self, feats, labels):<br>        # feats = features extracted from backbone model for images<br>        # labels = ground truth classes corresponding to images</pre><pre>        batch_size = feats.size(0)</pre><pre>        sim_mat = torch.matmul(feats, torch.t(feats))        <strong> <br>        # since feats are l2 normalized vectors, taking<br>its dot product with transpose of itself will yield a similarity matrix whose i,j (row and column) will correspond to similarity between i&#39;th embedding and j&#39;th embedding of the batch, dim of sim mat = batch_size * batch_size. zeroth row of this matrix correspond to similarity between zeroth embedding of the batch with all other embeddings in the batch.</strong></pre><pre>        epsilon = 1e-5<br>        loss = list()</pre><pre>        for i in range(batch_size): <br><strong>            # i&#39;th embedding is the anchor<br>  </strong><br>            pos_pair_ = sim_mat[i][labels == labels[i]] <br><strong>            # get all positive pair simply by matching ground truth labels of those embedding which share the same label with anchor</strong></pre><pre>            pos_pair_ = pos_pair_[pos_pair_ &lt; 1 - epsilon] <br><strong>            # remove the pair which calculates similarity of anchor with itself i.e the pair with similarity one.</strong></pre><pre>            neg_pair_ = sim_mat[i][labels != labels[i]] <br><strong>            # get all negative embeddings which doesn&#39;t share the same ground truth label with the anchor</strong></pre><pre>            neg_pair = neg_pair_[neg_pair_ + self.margin &gt; min(pos_pair_)]  <br><strong>            # mine hard negatives using the method described in the blog, a margin of 0.1 is added to the neg pair similarity to fetch negatives which are just lying on the brink of boundary for hard negative which would have been missed if this term was not present.</strong><br></pre><pre><br>            pos_pair = pos_pair_[pos_pair_ - self.margin &lt; max(neg_pair_)]<br>            <strong># mine hard positives using the method described in the blog with a margin of 0.1.</strong></pre><pre>            if len(neg_pair) &lt; 1 or len(pos_pair) &lt; 1:<br>                continue<br>            <strong># continue calculating the loss only if both hard pos and hard neg are present.</strong></pre><pre>            # weighting step</pre><pre>            pos_loss = 1.0 / self.scale_pos * torch.log(<br>                1 + torch.sum(torch.exp(-self.scale_pos * (pos_pair - self.thresh))))</pre><pre>            neg_loss = 1.0 / self.scale_neg * torch.log(<br>                1 + torch.sum(torch.exp(self.scale_neg * (neg_pair - self.thresh))))</pre><pre>            <strong># losses as described in the equation</strong></pre><pre>            loss.append(pos_loss + neg_loss)</pre><pre>        if len(loss) == 0:<br>            return torch.zeros([], requires_grad=True)</pre><pre>        loss = sum(loss) / batch_size<br>        return loss</pre><h3>Resources:</h3><blockquote>paper : <a href="http://openaccess.thecvf.com/content_CVPR_2019/papers/Wang_Multi-Similarity_Loss_With_General_Pair_Weighting_for_Deep_Metric_Learning_CVPR_2019_paper.pdf">http://openaccess.thecvf.com/content_CVPR_2019/papers/Wang_Multi-Similarity_Loss_With_General_Pair_Weighting_for_Deep_Metric_Learning_CVPR_2019_paper.pdf</a></blockquote><blockquote>official github implementation: <a href="https://github.com/MalongTech/research-ms-loss/blob/master/ret_benchmark/losses/multi_similarity_loss.py">https://github.com/MalongTech/research-ms-loss/blob/master/ret_benchmark/losses/multi_similarity_loss.py</a></blockquote><h3>About Me:</h3><p>I work as a ML Engineer in a fast-growing startup, Greendeck. We, at Greendeck, help retailers with pricing intelligence. We have offices both in London and Indore,India. If you are passionate about deep learning, or simply want to say hi, please drop me a line at keshav.gupta@greendeck.co. Any suggestion regarding the blog will be great as well. <a href="http://www.linkedin.com/in/kshavG">www.linkedin.com/in/kshavG</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad194691e2d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>