<?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 Balasaravanan on Medium]]></title>
        <description><![CDATA[Stories by Balasaravanan on Medium]]></description>
        <link>https://medium.com/@bassv33?source=rss-c00c5e58051e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RqND1Oyx3tE5qB1F8vfa9g.jpeg</url>
            <title>Stories by Balasaravanan on Medium</title>
            <link>https://medium.com/@bassv33?source=rss-c00c5e58051e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:01:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bassv33/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[why cossim not sinsim or tansim]]></title>
            <link>https://medium.com/@bassv33/why-cossim-not-sinsim-or-tansim-194eb1a3c175?source=rss-c00c5e58051e------2</link>
            <guid isPermaLink="false">https://medium.com/p/194eb1a3c175</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[trigonometry]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cosine-similarity]]></category>
            <category><![CDATA[law-of-cosines]]></category>
            <dc:creator><![CDATA[Balasaravanan]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 18:37:23 GMT</pubDate>
            <atom:updated>2026-01-20T18:13:29.069Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I want to discuss how cossim is derived</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*awWkdInwtSV3eZ6AnwUxaA.png" /></figure><p>Let’s move back to the <strong>Law of Cosines</strong> and try to get some grasp on it.<br>Let’s consider an <strong>equilateral triangle</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*As3ski_JZMOb6C5FM3yzxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*DOsjvHLSehqXwPCNi1wSuw.png" /></figure><p>Now we will move to the Dot Product</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*j0mQ_HkiSvcqrtCKCkduOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*e58s5Wk36saO5UFnOGCVsg.png" /></figure><p>applying law of cosines</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*Q7jqZVwU7S-2JPcpnHh4gA.png" /></figure><p>Now equating both expressions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*bKRzfFqmdHT4nOXsZucUMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*G69HJjiBMfYKRMGwNtVW8w.png" /></figure><h3>Why the cosine appears in the dot product</h3><p>Suppose we want a scalar quantity that measures the <strong>alignment</strong> between two vectors <strong>A</strong> and <strong>B</strong>.</p><p>A natural requirement is:</p><ul><li>The alignment should be <strong>maximum</strong> when the vectors point in the same direction.</li><li>The alignment should be <strong>zero</strong> when the vectors are perpendicular.</li><li>The alignment should be <strong>negative</strong> when the vectors point in opposite directions.</li></ul><p>Now observe the key fact:</p><blockquote><em>The maximum possible alignment occurs </em><strong><em>only when the angle between the vectors is zero</em></strong><em>.</em></blockquote><p>So we want a function f(θ) such that:</p><p>A⋅B=∥A∥ ∥B∥ f(θ)</p><p>with the constraints:</p><p>f(0)=1,f ⁣(π/2)=0,f(π)=−1</p><p>Among all trigonometric functions, <strong>only cosine satisfies these conditions</strong>.</p><p>Therefore, the dot product is defined as:</p><p>A⋅B=∥A∥ ∥B∥cos⁡θ</p><p>Thanks For Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=194eb1a3c175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Gradient Boosting Uses Gradients Internally — Regression]]></title>
            <link>https://medium.com/@bassv33/how-gradient-boosting-uses-gradients-internally-35e5290d8d88?source=rss-c00c5e58051e------2</link>
            <guid isPermaLink="false">https://medium.com/p/35e5290d8d88</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[ensemble-method]]></category>
            <dc:creator><![CDATA[Balasaravanan]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 19:00:12 GMT</pubDate>
            <atom:updated>2025-08-06T19:50:59.998Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Hi everyone,</strong></p><p>It’s been a while since I last shared anything, and over the past few weeks, I’ve been exploring topics I felt were worth diving deeper into.</p><p>This time, I’ve decided to focus on <strong>ensemble methods</strong> — particularly <strong>Gradient Boosting</strong> and <strong>XGBoost</strong>. Most of you are probably familiar with terms like the <strong>output score</strong>, <strong>similarity score</strong>, and <strong>initial prediction</strong> used in boosting algorithms. But in this post, let’s go one step further — and actually <strong>derive</strong> these formulas to understand <strong>how and why</strong> they’re constructed the way they are.</p><p>We’ll explore how the algorithms iteratively improve by minimizing a loss function using <strong>gradient-based updates</strong>, much like how gradient descent works in regression.</p><blockquote><em>⚠️ </em><strong><em>Note:</em></strong><em> To get the most out of this post, it helps to already be familiar with the </em><strong><em>workflow of gradient boosting</em></strong><em> — this write-up focuses on the math behind each step rather than the basic flow.</em></blockquote><p>Let’s get started.</p><p>We can break down the computation logic into four main steps:</p><ol><li>Initial prediction</li><li>Computing residuals for each data point</li><li>Creating terminal regions</li><li>Computing the output value for each terminal region</li><li><strong>Initial Prediction</strong></li></ol><p>To begin, we need a dataset (x,y) and a differentiable loss function. We’ll use the Mean Squared Error (MSE) as the cost function for regression tasks and Log Loss for classification, as these are commonly used and well-understood.</p><p>Loss function: L(y, γ)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*UUWKZUW1ZVAiNw6cPfilxA.png" /></figure><p>The above equation indicates that we need to choose the value of γ that minimizes the overall loss function. This aligns with the fundamental goal behind many optimization and convergence-based algorithms — to reduce the loss as much as possible at each step.</p><p>To find the minimizing γ, we take the derivative of the loss with respect to γ and set it to zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*xssyvru3kmJ68nlimLLVlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*6wAm5CaBzlVPeemWZLSHnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*nEBn1-bStr6xbSIjeAO7_Q.png" /></figure><p>This is precisely why we compute the average of the target values as the initial prediction in gradient boosting models</p><p><strong>2. Computing Residuals</strong></p><p>For each tree t=1 to T, compute the residuals for each data point i=1 to n as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUz-RzX8PndoeBZaEHJipQ.png" /></figure><p>This means we compute the negative gradient of the loss function evaluated at the current prediction Ft−1(x), which becomes the “residual” for the next tree to fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Mfx9UlTQDeKTGeyFoqm3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNIZWFEYHf0hB8dxrkqfdg.png" /></figure><p>3. Create Terminal Regions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*U4fbDTVa1kgm8vy1FaXVvQ.png" /></figure><p><strong>4. Compute output score</strong></p><p>For each leaf j=1,2,…,Jm​ of the mth tree:</p><p>We want to find the best constant γjm​ to assign to all points in that leaf, by minimizing the loss when added to the current model prediction Fm−1(x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*RYfgWK14TjzMojBks2w7UA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*LKx2Cp28GyqfIBBjzpDH2g.png" /></figure><p>Take derivative w.r.t. γ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*ds63QiN0uCjunj4iNflOkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*ms27awCMLkcA78nrfOj5gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*mukXY71pOASICKhexW4jBA.png" /></figure><p>This is the average residual in that leaf.</p><p><strong>Model Prediction Update in Gradient Boosting</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jA-3l3LJBNxWHxcWvS18vg.png" /></figure><p>We will be repeating this process for mmm trees, and with each tree added, there will be a reduction in residuals, which gradually improves the model’s predictions.</p><blockquote>To simplify the derivative, we often use a 1/2 ​ factor in the MSE loss:</blockquote><blockquote>This leads to a cleaner derivative:</blockquote><blockquote>The negative of this gradient, is called the pseudo-residual, which guides how the next tree should fit the remaining error.</blockquote><p>I believe this explanation will be especially helpful for those who are already familiar with how gradient boosting works at a high level, and now want to understand the underlying math behind each step.</p><p>In my next blog, I’ll cover the classification version of this algorithm. After that, I’ll also extend this series to include how XGBoost works internally.</p><p>Follow for more updates on related topics!</p><p>Have a nice day, and thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35e5290d8d88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dual Formulation in SVM]]></title>
            <link>https://medium.com/@bassv33/dual-formulation-in-svm-96d291ba2808?source=rss-c00c5e58051e------2</link>
            <guid isPermaLink="false">https://medium.com/p/96d291ba2808</guid>
            <category><![CDATA[dual-formulation]]></category>
            <category><![CDATA[lagrange-multiplier]]></category>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[svm-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Balasaravanan]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 17:58:32 GMT</pubDate>
            <atom:updated>2025-06-21T18:07:24.202Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we’ll dive into the <strong>mathematics behind SVM optimization</strong> — focusing on how the optimal hyperplane is derived using constrained optimization techniques. We assume you already have a theoretical understanding of <strong>Support Vector Machines (SVMs)</strong> and how they work conceptually — including ideas like hyperplanes, margins, and support vectors.</p><p>Here, our goal is to go one step deeper and explore how these concepts are formalized mathematically, leading to the formulation of the <strong>primal and dual optimization problems</strong>,</p><p>support vector machines are formulated as constrained optimization problems.</p><blockquote><strong>objective</strong>: Maximize the margin between the separating hyperplanes and the closest data points (support vectors).</blockquote><blockquote><strong>constraints</strong>: All training points must be correctly classified. This ensure that the hyperplane separates the classes without errors.</blockquote><p>SVM aims to find the hyperplane that not only separates the classes but also maximizes the distance between the support vectors and the hyperplane providing a robust and generalizable model. This constrained problem is typically solved using quadratic programming techniques.</p><p>Now lets derive our objective and constraints</p><p>As we know, the decision boundary is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*jyEzPXWqEWbNnALJbm2PIA.png" /></figure><p>Marginal hyperplane for positive class is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*2pfxQlyHNyv43iINkDQVvg.png" /></figure><p>Marginal hyperplane for negative class is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*J85cVpzXUWImg1SMiPEXqg.png" /></figure><p>Basically, our objective is to maximize the distance between the marginal hyperplanes. Here, it’s important to note that the value 1 is not the actual distance between the hyperplanes. We have two hyperplanes, and given the X and Y vectors, our goal is to choose a W vector such that the distance between the hyperplanes is as large as possible.</p><blockquote>Can you think of a point X where the marginal hyperplane equation is satisfied? Yes, you’re right — this will hold true for <strong>support vectors</strong>.</blockquote><blockquote><strong>Note:</strong> While the hyperplane is influenced by all training data points, only a few points actually lie <em>on</em> the margin. These specific points are called <strong>support vectors</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*WbnUxDyq6tFKvJmf9uYxCg.png" /></figure><p>So, now the difference between the above 2 equation will give the distance between both the marginal hyperplanes .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*njGlXp3ZRankBrvn4rjcgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*d3TopIFQbewihl1HS1b7AQ.png" /></figure><p>So, the idea behind optimization in SVM is to <strong>maximize the margin</strong>, which is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*0FjQZZOHDogfhX7HOYkjJg.png" /></figure><p>However, since optimization problems are usually formulated as <strong>minimization</strong>, we take the inverse approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*vWaSV-AECg1uqXqRC6B6Ww.png" /></figure><p>W.R.T</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*zQt-VOep7a41-ZVcVhvbRw.png" /></figure><p>The above constraints can be converted into a single inequality constraints</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*LW2rxo4cqjIt7s7ZowUuHA.png" /></figure><p>This constrained optimization problem is solved using the <strong>Lagrangian dual formulation</strong>, by applying the <strong>Karush-Kuhn-Tucker (KKT) conditions</strong>, and finally using a <strong>quadratic programming (QP) solver</strong> to solve the resulting dual problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*WWJSJbTnnO-7xcMvv-7ulw.png" /></figure><p>Here, αi​ is the <strong>Lagrange multiplier.</strong></p><p>According to KKT, we took derivative with respect to primal variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*5jmVoFMcGokvvEWIc55Lxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*14Y7anZ9lFfUF9-T5smA5Q.png" /></figure><p>To satisfy optimality (KKT stationarity condition), we set this derivative to 0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*ygvN6wvHK6lBTHE1kTOluw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*7ufiiB4oGeo0HwWG0loxyw.png" /></figure><p>Now, we will substitute the above values in the primal optimization equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*_3woHNVVBICV6fxRG8qUbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*Vx9Va3FdD0k2j4AL-prUCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*4h44VRMx9w8nvKx3zQiYcQ.png" /></figure><p>These equations together form the <strong>dual objective function</strong>. Now, this equation will act as the <strong>objective</strong> in a constrained optimization problem.</p><p>The associated <strong>constraints</strong> are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*d2Fx9e8lbA29CgRGt_gplw.png" /></figure><p>The <strong>first constraint</strong> (αi≥0) comes directly from the <strong>KKT conditions</strong>, which state that Lagrange multipliers must be non-negative. This also connects with SVM’s geometric interpretation:<br> if αi&gt;0, then the corresponding data point lies <strong>on the margin hyperplane</strong> and is thus a <strong>support vector</strong>.</p><p>The<strong> second constrain</strong>t (∑αiyi=0) appears because the dual function is<strong> not explicitly expressed in terms of b</strong>. Since we didn’t substitute a value for b (unlike W, which we replaced in the dual), this constraint ensures that the Lagrangian remains independent of b and satisfies the optimality conditions.</p><p>From the dual optimization, we compute the alpha vectors. Using those, we can determine W, then compute b using the support vector values, and finally derive f(x), which serves as the prediction function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*Rf0lQ2yjByPPHl7DFaW4tA.png" /></figure><p>Let’s walk through a simple example using a small dataset and derive the <strong>quadratic optimization problem (dual form)</strong> for SVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*oVClLS6F8f0UGbStxfZYmg.png" /></figure><p>The <strong>Gram matrix</strong> K=Xi.Xj</p><ul><li>X1⋅X1 = 2 × 2 + 2 × 2 = 4+4 = 8</li><li>X1⋅X2 = 2 × 1 + 2 ×(−1) = 2−2 = 0</li><li>X1⋅X3 = 2 ×(−2) + 2 ×(−2) = −4−4 = −8</li><li>X2⋅X2 = 1 × 1 + (−1)×(−1) = 1+1 = 2</li><li>X2⋅X3 = 1 ×(−2) + (−1)×(−2) = −2+2 = 0</li><li>X3⋅X3 = (−2) 2 + (−2) 2 = 4+4 = 8</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*nfUBvGNMGClRAgt4kZ_1UQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*ZcKdBzeM5xoHP3VQSJGE1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*hzkzn-6oLqpcly_k0QHaYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*sGC7SFxhPOx8W2DDLVyxBg.png" /></figure><p>W.R.T αi ​≥ 0 and α1​−α2​−α3 ​= 0</p><p>we can say like α1​ = α2​+α3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*zKxSaM_mTK24ECbFBPmDcA.png" /></figure><p>In this way, we can construct a quadratic equation for any dataset and solve it to find the optimal <strong>alpha vector</strong> values. It’s important to note that <strong>alpha is not associated with the feature dimension</strong>, but rather <strong>with each data point</strong> in the training set.</p><p>The data points for which α&gt;0 are known as <strong>support vectors</strong> — they lie on the margin and influence the decision boundary.</p><p>There are several Python libraries available to solve such quadratic programming problems, and one of the most commonly used is qpsolver.</p><p>Here, we <strong>do not apply the constraints using Lagrange multipliers again</strong> in the dual formulation. If we did, the dual would transform into another level of dual optimization, introducing <strong>new Lagrange multipliers</strong> for the constraints αi≥0 and ∑αiyi=0.</p><p>Everything we’ve derived so far applies to the <strong>hard-margin SVM classifier</strong>. In the case of <strong>soft-margin SVM</strong>, we introduce an additional term in the objective function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*665ptM2z1aUe7xgHhcMprw.png" /></figure><p>where C is a <strong>hyperparameter</strong>, and ξi represents the <strong>slack variables</strong> that allow for misclassification.</p><p>For <strong>SVM regression</strong>, we introduce an additional parameter ϵ, along with two slack variables ξi and ξi*​ for each data point. These primal variables can grow based on the error margin.</p><p>However, in both soft-margin classification and regression, we still apply the <strong>Karush-Kuhn-Tucker (KKT) conditions</strong> to derive the optimal solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96d291ba2808" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Not MSE for the Loss Function -Logistic Regression?]]></title>
            <link>https://medium.com/@bassv33/why-not-use-same-mse-as-loss-function-for-logistic-regression-72e065870e60?source=rss-c00c5e58051e------2</link>
            <guid isPermaLink="false">https://medium.com/p/72e065870e60</guid>
            <category><![CDATA[log-loss]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mean-squared-error]]></category>
            <dc:creator><![CDATA[Balasaravanan]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 17:57:35 GMT</pubDate>
            <atom:updated>2025-06-10T17:59:56.148Z</atom:updated>
            <content:encoded><![CDATA[<p>As we all know, logistic regression is a probabilistic approach that uses the sigmoid activation function on the output. You might have heard that using Mean Squared Error (MSE) as the cost function can lead to issues like getting stuck in local minima. In this blog, I’m going to explain the log loss function, why we don’t use MSE or similar cost functions, and the reasoning behind choosing log loss instead.</p><p>In probability, <strong>likelihood</strong> refers to the probability that a model assigns to the actual observed outcome. For a binary classification task, if the true label is y∈{0,1} and the predicted probability of the positive class is p, the likelihood is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*XQtKKyh3tKTx0bWSyhfD5Q.png" /></figure><p>This means the model gives a high likelihood when it assigns a high probability to the correct class.</p><p>To make computations easier and more stable, especially when dealing with many data points, we take the logarithm of the likelihood. This is called the <strong>log-likelihood</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*qPBA9cn8n08kfuTdjxkPjQ.png" /></figure><p>We aim to increase the log-likelihood, which means increasing the probability of the predicted output belonging to the true class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*DFptZGDgMEEHvMguh1B_Kw.png" /></figure><p>But, in gradient descent, our goal is to minimize the cost function. So, instead of using the log-likelihood directly, we use the <strong>negative log-likelihood</strong>, which we then aim to minimize.</p><p>The <strong>final log loss function</strong>, widely used in binary classification tasks is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ue1gu5Cjbj6SDQfgRJPxsw.png" /></figure><p>Okay. Now we have seen how the log loss function works is a classification cost function. Initially, logistic regression is quite similar to linear regression — it doesn’t even explicitly construct a decision boundary like an SVM classifier. Its equation is also:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*jNuTRqwxZVfVWLhT7F6K8A.png" /></figure><p>Here, we simply try to find the best fit line and apply an activation function on top of it to restrict the output between 0 and 1, so that we can classify into two classes. But then, why don’t we use Mean Squared Error (MSE)? We often hear that using MSE introduces local minima. However, if we try to visualize this through gradient descent using a convergence algorithm, we may not immediately see the difference — though we might observe differences in the slope values. To truly understand the behavior, we need to iterate over a range of values to see where local minima occur and where the model gets stuck.</p><p>I’ve created a code snippet that performs gradient calculation, computes the loss, and adjusts the slope accordingly. Importantly, the process doesn’t stop just because the slope becomes zero — there could be multiple points where the gradient vanishes. With this, I compared the behavior of the log loss function and the MSE function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*ArVpV0Cnpjbk5E4nQgvunA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*OzJpghYqoBQOW5JvfmH7UQ.png" /></figure><p>Now, why does this happen? Because the introduction of the sigmoid not only restricts the output range — it also makes the surface non-linear. The plane is no longer flat; it bends into an S-shaped curve. That’s how the sigmoid both restricts the output and introduces non-linearity into the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*4VfcEt4bBeF0YMjennBvpw.png" /></figure><p>Now this is <strong>no longer a simple quadratic (convex)</strong> — it’s a <strong>quadratic of a sigmoid.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72e065870e60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Squared Gradients Amplify Overfitting — And Why Absolute Gradients Can Help Feature Selection]]></title>
            <link>https://medium.com/@bassv33/how-squared-gradients-amplify-overfitting-and-why-absolute-gradients-can-help-feature-selection-89bfa861145a?source=rss-c00c5e58051e------2</link>
            <guid isPermaLink="false">https://medium.com/p/89bfa861145a</guid>
            <category><![CDATA[l2-regularization]]></category>
            <category><![CDATA[ridge-regression]]></category>
            <category><![CDATA[lasso-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[l1-regularization]]></category>
            <dc:creator><![CDATA[Balasaravanan]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 09:21:44 GMT</pubDate>
            <atom:updated>2025-06-01T09:58:03.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Squared Gradients Amplify Overfitting — And Why Absolute Gradients Can Help Feature Selection</h3><p>In this blog, let’s walk through why we say Ridge Regression helps in avoiding overfitting, while LASSO Regression helps in eliminating independent features that are weakly correlated with the output. At first glance, the math seems quite similar — in Ridge, we add the sum of squared weights as a regularization term, whereas in LASSO, we add the sum of the absolute values of the weights. So how does this one change — from squares to absolutes — drastically alter the behavior of the algorithm?</p><p>Let’s explore that by diving into the derivation.</p><p>Ridge regression cost function is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*XmrqGD2Qopb3367tTVI04A.png" /></figure><p>Now, when we <strong>take the derivative</strong> of this cost with respect to θ, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*pqOBWp_vaLu3ctUxZj0hIA.png" /></figure><p>Now, in <strong>gradient descent</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*OUYgrPUHjMgCCO9TIFYl8g.png" /></figure><p>Let’s rewrite this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*wocl9VCG2zPvAn2VEyyxHw.png" /></figure><p>In <strong>Ridge Regression</strong>, the regularization term is proportional to the square of the slope (i.e., λθ²). When we compute the derivative of this term with respect to the parameter θ, we get 2λ. This derivative <strong>depends on the current value of θ</strong>, meaning:</p><ul><li>As θ becomes smaller, the regularization term itself becomes smaller.</li><li>As a result, the gradient update becomes smaller too — the “pull” toward zero gets weaker the closer you get.</li><li>This means <strong>Ridge regression shrinks</strong> parameters but <strong>rarely drives them exactly to zero</strong>.</li><li>It reduces the <strong>magnitude</strong> of the weights, helping to <strong>prevent overfitting</strong>, but usually retains <strong>all features</strong>.</li></ul><p>In <strong>LASSO Regression</strong>, the regularization term is based on the <strong>absolute value</strong> of the slope (i.e., λ∣θ∣). The derivative of this term is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2DL6gfXRQHZWYXlRpIBOA.png" /></figure><p>So the update becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*QchdzrKn6n8urqPyhscklQ.png" /></figure><p>This derivative is <strong>constant</strong>, the regularization term still applies a <strong>constant force</strong> to reduce it. Eventually, if the force from the data’s gradient is weaker than λ, the <strong>sign of the total gradient flips. </strong>When that happens, the optimizer <strong>drives θ exactly to 0</strong>, and <strong>stops updating it</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LP95CZ85awCdOQON5WgX4g.png" /></figure><blockquote><strong>Note</strong>: λ acts like a scaling factor — it determines what proportion of the slope to subtract. But the actual update to θ at each step depends on the current value of θ itself, not just λ. In most gradient graphs, λ is shown as the main driver, which can be misleading. Yes, increasing λ reduces the slope, but that’s because it increases the proportion of the slope being subtracted. So the slope reduction is determined by both λ and θ — not by λ alone.</blockquote><p>This is why <strong>LASSO leads to sparse solutions</strong>, effectively performing <strong>feature selection</strong> by eliminating some coefficients.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89bfa861145a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why MAE Leads to Slower Optimization: A Mathematical Perspective]]></title>
            <link>https://medium.com/@bassv33/why-mae-leads-to-slower-optimization-a-mathematical-perspective-c210c92c6639?source=rss-c00c5e58051e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c210c92c6639</guid>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[derivatives]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cost-function]]></category>
            <dc:creator><![CDATA[Balasaravanan]]></dc:creator>
            <pubDate>Wed, 21 May 2025 19:14:21 GMT</pubDate>
            <atom:updated>2025-05-21T19:14:21.523Z</atom:updated>
            <content:encoded><![CDATA[<p>When training machine learning models, the choice of loss function plays a critical role in determining how quickly and effectively the model learns. One commonly used loss function is the <strong>Mean Absolute Error (MAE)</strong>. However, it’s often observed that models trained with MAE converge more slowly compared to those using alternatives like Mean Squared Error (MSE).</p><p>In this explanation, we’ll explore <strong>why MAE leads to slower convergence</strong>, and <strong>why it’s not differentiable at zero</strong> — both of which are key reasons behind its optimization behavior. To do this, we’ll walk through the underlying mathematics and develop an intuition for how MAE behaves during gradient-based learning.</p><p>We’ll break this down into two main questions:</p><ol><li><strong>Why does MAE take a longer time to converge?</strong></li><li><strong>Why is MAE not differentiable at zero?</strong></li></ol><p>To begin, let’s define the MAE cost function mathematically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*dYFkLaE6qYJb-CFpmt0srQ.png" /></figure><p>To understand how optimization progresses, let’s visualize the cost function and how the gradient (slope) at a point helps guide the updates toward the conteur</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*JaCfNW9OgNv2IRZLUfSFRw.png" /></figure><p>First, we take the slope of the best fit line and use it to calculate the corresponding cost value, which together form an instantaneous point on the cost curve. Using the derivative of the MAE function, we find the gradient — the slope of the tangent line — at that point. This tangent line then guides the update step toward the minimum of the cost function</p><p>The derivative of MAE :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*WO21vOie4m5_6MJPpMm2mw.png" /></figure><p>This means we are only considering the sign — either +1 or -1 — during each gradient computation. As a result, the updates do not depend on the magnitude of the error, only on its direction. This causes the optimizer to take uniform steps regardless of how far the prediction is from the target, leading to slower and less precise convergence.</p><p>Ultimately, <strong>this results in a longer time to reach the optimal point.</strong></p><p><strong>Why Not Differentiable at 0</strong></p><p>Before diving into why the MAE function isn’t differentiable at zero, let’s first review what a derivative represents and how it relates to the behavior of functions at specific points.</p><p>For a function f(x), the derivative at a point x=a gives the slope of the curve at that point.</p><p>The derivative of f(x) at x=a is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*FG7H3RuPaoqn0XkoEcJSsQ.png" /></figure><p>Lets visualize the above derivation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*dk-c-GD9fT6TkHtpHalZ1A.png" /></figure><p>Now, lets derive the derivative equation using basic slope equation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*dVI5mdhSCxtLYcPqIMHVfQ.png" /></figure><p>This equation gives the rate of change in y with respect to x, which represents the slope. Since we are working with two distinct points, we are dealing with a secant line. The goal of the derivative is to find the instantaneous rate of change — that is, the slope of the curve at a single point, which corresponds to the tangent line.</p><p>The derivative equation is used to find the instantaneous rate of change at the point (a+h,f(a+h)). To do this, we examine what happens as h approaches 0 — meaning the distance between two points becomes smaller and smaller. As h→0, the secant line between the points (a,f(a)) and (a+h,f(a+h)) becomes a tangent line. At this point, we can determine the instantaneous rate of change, which is the slope of the tangent.. This is represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*FG7H3RuPaoqn0XkoEcJSsQ.png" /></figure><p>Now, let’s discuss why the function is not differentiable at 0.<br> To check differentiability at a point, we usually compare the left-hand limit (LHL) and right-hand limit (RHL) of the derivative.</p><p>Let’s take f(x)=∣x∣, and check the derivative at x=0.</p><p>We use the definition of the derivative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*OtTns_kPGfaJDT8Nbrkm7Q.png" /></figure><p>Now we evaluate the limits from both sides:</p><p><strong>Right-hand limit (as h→0+)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*pL_hNGCwT5wIeRlZiWhCNw.png" /></figure><p><strong>Left-hand limit (as h→0−)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*CAtZhgPUvlNJT199ZgCuZw.png" /></figure><p>Since the left-hand and right-hand limits are not equal, the derivative at x=0 does not exist.<br><strong>Hence, f(x)=∣x∣ is not differentiable at 0.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c210c92c6639" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tangent Line Working in Gradient Descent]]></title>
            <link>https://medium.com/@bassv33/tangent-line-working-in-gradient-descent-ea6ab0c6e331?source=rss-c00c5e58051e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea6ab0c6e331</guid>
            <category><![CDATA[cost-function]]></category>
            <category><![CDATA[tangent-line]]></category>
            <category><![CDATA[convergence-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Balasaravanan]]></dc:creator>
            <pubDate>Thu, 15 May 2025 17:33:42 GMT</pubDate>
            <atom:updated>2025-05-15T17:33:42.629Z</atom:updated>
            <content:encoded><![CDATA[<p>As we all know, convergence algorithms rely on tangent lines to move in the direction of the steepest descent, ultimately aiming to find the optimal minima. In this blog, I’ll walk you through how tangent lines are formed and how they function in the context of gradient descent.</p><p><strong>P.S.</strong>: Don’t confuse the slope of the <strong>best-fit line</strong> with the slope of a <strong>tangent line</strong> .</p><h3>Let’s begin by understanding what a tangent line is.</h3><p>The definition of a tangent line has evolved over time.</p><p>Initially, it was defined as a line that touches a circle at exactly one point.</p><p>Later, it was generalized as a line that touches any curve at a single point without crossing it.</p><p>Eventually, the definition became more mathematical: a tangent line is one that, when slightly altered, becomes a secant line (a line that intersects the curve at two or more points). In calculus terms, the derivative at a point exists if the left-hand limit is equal to the right-hand limit.</p><p>To draw a tangent line, the equation is simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*Wn3inW8jg6brU_KGBtBTgQ.png" /></figure><p>where m is the slope of the tangent at point (x1,y1).</p><p>Now, let’s understand the <strong>purpose</strong> of a tangent line. A tangent line gives the <strong>rate of change</strong> of a curve at a specific point. In other words, it tells us how steep the curve is at that point.</p><p>Let’s take a real-world example. Consider a graph that shows the relationship between <strong>year</strong> and <strong>world population</strong>. If we want to find the rate of change of the world population at a particular year, we draw a tangent line at that point on the curve. The <strong>slope of that tangent line</strong> will represent the <strong>instantaneous rate of population change</strong> in that specific year.</p><h3>Tangent Line in Gradient Descent</h3><p>Now, let’s say we have a best-fit line with a slope θ1=0.2. For simplicity, let’s assume θ0=0 (i.e., the intercept is zero). So the equation of our line becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*zh9Uy99rZDMEkgA5dqbaog.png" /></figure><p>Next, we need to compute the <strong>cost function</strong>, which in our case is the <strong>Mean Squared Error (MSE)</strong>. The cost function is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*XcyTg2AyrDFwbgbtLT4Lbw.png" /></figure><p>Usually, when we visualize gradient descent, we plot the <strong>cost function</strong> J(θ1) against θ1​. This curve represents how the cost changes for different values of θ1​.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*FG_xbsR9Gs-17mVu09kJZw.gif" /></figure><p>Lets take a single training point and update the equation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*UwQVGTgHmleDMMI4t7375w.png" /></figure><p>Lets perform derivation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*NPKvcr1UctIvT5zHzGimGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*cQyKKy3xW9poFuuRaKHRxg.png" /></figure><p>If we substitute the respective θ1​ value, we will get the slope of the tangent line. Now we have the slope of the tangent line, and we also have the point (θ1,J(θ1)),</p><p>where ,</p><p>θ1 is the slope of the best-fit line and</p><p>J(θ1) is the corresponding cost.</p><p>Now we can compute the equation of the tangent line at that point on the gradient descent curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*Wn3inW8jg6brU_KGBtBTgQ.png" /></figure><p>This forms the basis of the convergence algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*qx_k5yi5AEedz9Bq3kIqBg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea6ab0c6e331" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about positional encoding and linear transformation in transformers]]></title>
            <link>https://medium.com/@bassv33/all-you-need-to-know-about-positional-encoding-and-linear-transformation-in-transformers-34d4b6768d47?source=rss-c00c5e58051e------2</link>
            <guid isPermaLink="false">https://medium.com/p/34d4b6768d47</guid>
            <category><![CDATA[linear-transformation]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[positional-encoding]]></category>
            <dc:creator><![CDATA[Balasaravanan]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 17:08:44 GMT</pubDate>
            <atom:updated>2025-03-11T06:16:15.473Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In the previous sequence-to-sequence architecture, positional information was derived from timestamp processing. However, in Transformers, the main goal is to process all tokens in parallel. This results in the loss of positional information. To overcome this, a separate positional encoding is created and combined with the initial word embedding to form the input to the attention mechanism.</p><p><strong>The intuition behind taking sin-cos positional encoding equation</strong></p><p>The simple idea that comes to mind when incorporating positional value is to extend the vector size by one and add sequence numbers such as 1, 2, and so on to the extended vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8_W4ExwI8c6LsK3Ar2Jig.png" /><figcaption>fig 1</figcaption></figure><p>However, this is not an ideal solution since we have millions of tokens while training a Transformer model. Assigning this huge number would cause exploding gradient problems.</p><h3>What do we need?</h3><ol><li>We need to assign a unique value to each position</li><li>And it should be restricted within a range of values.</li></ol><p>So, the researchers decided to use a sinusoidal function, which meets one of our expectations: it remains within a fixed range. For an amplitude of 1, the sine function oscillates between -1 and +1 with respect to frequency and time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*TMBui8zi5UjvwaD_hhn5ug.png" /><figcaption>fig 2</figcaption></figure><p>Now, for the next question, we need unique values. Instead of using just a 1D vector and computing sin(x) for the position value, can we use a 2D vector and compute cos(x) for that position?</p><p>eg: cat sat on my mat</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*dzoIpuPIYAiUbexbckJjAw.png" /><figcaption>fig 3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2fscu4k0hnlM8U7UjQvhA.png" /><figcaption>fig 4</figcaption></figure><p>Let’s talk about the X value later by comparing the positional encoding with signal processing. For now, let’s focus on obtaining unique values.</p><p>Even though the chances of getting the same value are reduced, there is still a possibility of duplication. Instead of using a 2D vector, can we extend the positional vector dimension to match the word embedding dimension? As we move to higher dimensions, we can use lower frequencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGfrQbX8NxDn6zJeNPoPFA.png" /><figcaption>fig 5</figcaption></figure><p>Now, we are able to obtain a unique vector for positional encoding.</p><p>Okay, now that we have the positional encoding values, before diving into how the sine and cosine functions capture relative positions, let’s first discuss the positional encoding equation.</p><p>As mentioned earlier, we will use sine and cosine functions interchangeably at different index positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SGLYx4E_L3Tp1FsD3sFtA.png" /><figcaption>fig 6</figcaption></figure><p>where,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*CQUMENeOXd1b8a4mnTiPng.png" /></figure><p>Lets compare the sine function of signal processing and sine function of positional encoding to understand the frequency change</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*tb0LQZQI37x5eDTY7GD2UQ.png" /></figure><p>In signal processing, a sine wave oscillates faster or slower depending on its frequency and time. If we specify that we need 5 wave cycles to be completed in 5 seconds, the wavelength will be determined accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WuCjtOO-p6hWqBQf2nigw.png" /><figcaption>fig 7</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*UZZq9m8PGu2L34cvAaEoLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*jGhyIzZZ0fySJiN0jG0wkg.png" /></figure><p><strong>Now, we will learn how our model captures the relative positions between words using these sine and cosine values.</strong></p><p>Let’s discuss this using a heatmap visualization. I have created this heatmap to illustrate the positional encoding for a 128-dimensional space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_1EaEnGOipCR83CaolYOA.png" /><figcaption>fig 8</figcaption></figure><p>We can observe a predictable pattern across positions. In the lower dimensions, we see high-frequency oscillations, whereas in the higher dimensions, the frequency decreases, resulting in low-frequency oscillations due to the larger wavelength.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_0LtML1iAnGVGAE0EI-BQ.png" /><figcaption>fig 9</figcaption></figure><p>So, now that we have computed the positional encoding values, we will add them to the initial word embeddings. The resulting 512-dimensional vector will then be used as input to the self-attention layer.</p><p>Now, we all have this big question: <strong>Won’t adding these values affect the positional encoding pattern?</strong></p><p>Let me walk through an important statement mentioned in the paper <em>Attention Is All You Need</em>,</p><p>‘We chose this function because we hypothesized that it would allow the model to easily learn to attend to relative positions. This is because, for any fixed offset k, PEpos+k​ can be represented as a linear function of PEpos’</p><ol><li>Now, we know that positional encoding follows a structured pattern</li><li>And we add it to word embeddings before passing them into the self-attention mechanism.</li><li>How does this positional pattern remains intanct in self attention ?</li></ol><p>for any token at position t, the input to self-attention is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*FzI34BTnNrJkiw-2ICzt3A.png" /></figure><p>Lets calculate query vector of pos t and key vector of pos s and try to get the attention score</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*Pv_NVzD90teCub_tAhf7yA.png" /></figure><p>The term</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*jBpFo0Od-x6vV49NxMlSfQ.png" /></figure><p>is completely dependent on positional encoding values. It proves that while computing self-attention, we can extract positional information separately. This means the model learns the positional pattern without any disturbance. Even though we are adding positional encoding to word embeddings, the positional information remains intact and unaffected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*1igtVFVW52D3GV7Y58Kx_Q.png" /></figure><p>Based on this predictable pattern, if we know e(T) and e(S), we can easily determine that a shifted version of e(S) appears after a certain number of positions.</p><p>The key idea is that we <strong>cannot compute the absolute positions</strong> of two words directly. However, using the pattern in positional encoding, we can determine their <strong>relative position</strong> within the sequence.</p><p>Now, we will derive the proof for the linear transformation in positional encoding. This linear transformation in sine-cosine positional encoding enables us to obtain a predictable pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*eySY1RVt-PKc22RlCq9TtQ.png" /><figcaption>fig 10</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*L4ITOogsglopYzx6WyB_Qw.png" /><figcaption>fig 10</figcaption></figure><p>We have to <strong>prove</strong> that the shift in position from T to T+k is linearly transformed, which in turn demonstrates the existence of a predictable pattern for the shift from T to T+k.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*qFbLCbm4oDRawmDFXOTxUw.png" /></figure><p>shifting position T to T+k</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*dJog08GlFlIITZ-sazAzfQ.png" /></figure><p>let us consider</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*oRq-iDPhJj3clNxn6oW7NQ.png" /></figure><p>applying sin(a+b)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*BhRfTU8kr9Xrkcmdfy9Tew.png" /></figure><p>In the same way computing for (4)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*QyWs94IgYrF6M-kPxvZW7w.png" /></figure><p>Now, there exists a linear combination</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*mItYv15Dh8H62ivL9KKH8A.png" /></figure><p>representing this in a matrix form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*_mA499t_OkiAjbdSeFlCEQ.png" /></figure><p>This transformation can be represented as a 2D rotation matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*K0sbQvA11JaFOvz-ASSJUg.png" /></figure><p>This matrix shows that shifting the position by k applies a linear rotation in the sinusoidal embedding space, preserving the relative positional pattern</p><p><strong>why this matter for positional encoding</strong></p><p>In Transformer positional encoding, the sine and cosine functions define a 2D space for each dimension. When we shift a token’s position from T to T+k, the new positional encoding can be expressed as a rotated version of the previous one.</p><p>This concludes our proof that the position T+K is a linear transformation of the position T.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d4b6768d47" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>