<?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 Maria on Medium]]></title>
        <description><![CDATA[Stories by Maria on Medium]]></description>
        <link>https://medium.com/@marialavrovskaya?source=rss-761c41053653------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hxDdxt53q2hYUuSAzpbvnQ.png</url>
            <title>Stories by Maria on Medium</title>
            <link>https://medium.com/@marialavrovskaya?source=rss-761c41053653------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:14:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marialavrovskaya/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[SVM Talking algos: Using Interior Point Methods for SVM Training]]></title>
            <link>https://medium.com/data-science/svm-talking-algos-using-interior-point-methods-for-svm-training-d705cdf78c94?source=rss-761c41053653------2</link>
            <guid isPermaLink="false">https://medium.com/p/d705cdf78c94</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <dc:creator><![CDATA[Maria]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 13:03:38 GMT</pubDate>
            <atom:updated>2021-10-18T20:49:27.899Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>Training Support Vector Classifier from scratch using optimisation methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*WRt7jEmSZr7i5vM2copzLg.png" /></figure><p>Alright, folks! We have already discussed the <a href="https://medium.com/@marialavrovskaya/svm-talking-maths-quadratic-programming-and-cholesky-factorisation-968a493db10b">preliminaries of constrained optimisation</a> and <a href="https://towardsdatascience.com/svm-talking-maths-formulating-support-vector-machine-as-a-quadratic-programming-problem-ab5d30a8d73e">formulated the Support Vector Machine classification problem as quadratic program</a> (QP). Today we learn how to train Support Vector Classifier <strong>numerically.</strong></p><p>This article can be split into two parts: theory and practice! If you have come across Interior Point methods before, you can just skip the theoretical part and scroll down to our practical example!</p><p>First, we try to provide some intuition to Interior Point Methods starting from Barrier Methods. Second, we formulate the Primal-dual method that comes directly from modified KKT conditions. This might not make sense right now but it will as you read! Finally, we code our classifier from scratch — that’s where all the building blocks learnt before will come together.</p><h3>Theory! Support Vector Classifier as QP</h3><p>We start off by <a href="https://towardsdatascience.com/svm-talking-maths-formulating-support-vector-machine-as-a-quadratic-programming-problem-ab5d30a8d73e">recalling</a> that Support Vector Classifier can be expressed as quadratic program through its dual</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*qoJEuXv0bIlPem2b" /><figcaption>SVM as QP</figcaption></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*IaZ_zYEo2lywTkag" /></figure><p>This is our optimisation problem! Let’s now learn how to tackle it numerically.</p><h3>Build your intuition: Interior Point Methods</h3><p>The important idea behind interior-point methods is that they try to solve the problem (written above) or the KKT conditions (formulated for the problem above) by applying Newton’s method to a sequence of <strong>equality </strong>constrained problems or to a sequence of <strong>modified</strong> versions of KKT conditions. Two natural questions are: where do inequality constraints disappear and what are modified versions of KKT conditions?</p><p>The former can be easily viewed through Barrier methods helping to build intuition for the latter. Let’s jump straight into it 🚀</p><h4>Where do inequality constraints disappear?</h4><p>We attempt to approximately formulate the inequality constrained problem (written above) as an equality constrained problem to which Newton’s method can be applied. Our first step is to rewrite the problem (let’s take the general form discussed <a href="https://medium.com/@marialavrovskaya/svm-talking-maths-quadratic-programming-and-cholesky-factorisation-968a493db10b">here</a>) by making the inequality constraints implicit in the objective. This is done by introducing the indicator function. Hence we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*b5MWDkSrHUvfDira" /></figure><p>So far so good. The only problem here is that this objective cannot be twice differentiable, which means that our assumptions are violated and we cannot apply Newton’s method to it. So what can we do?</p><p>We approximate it one more time! Now we want to approximate the indicator function with something that can be differentiable. Likely we have one! We approximate the indicator function by another function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/0*_-kL71vi0zA_GyeZ" /></figure><p>where <em>t</em>&gt;0 is a parameter that sets the accuracy of the approximation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aA-ofHQ0OxbM97MGViVJ9A.png" /><figcaption>Image created by Author. Inspired by [1]</figcaption></figure><p>The graph shows the accuracy of approximation for different values of <em>t=0.5, 2, 4, 5. </em>The blue line (<em>t=5</em>) demonstrates that as <em>t</em> parameter grows, we have a better approximation.</p><p>This gives us a new optimisation problem. By multiplying the objective by <em>t, </em>we get the equivalent minimisation problem that has the same minimisers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*Es-4DPh1NKqfjWSt" /></figure><p>The new function <em>phi </em>is called the logarithmic barrier which accounts for inequality constraints<em>.</em></p><h4>What are the modified KKT conditions?</h4><p>We now consider the problem written above. For every <em>t&gt;0 </em>we<em> </em>define <em>x*(t)</em> as the solution. As we apply the<a href="https://en.wikipedia.org/wiki/Newton%27s_method_in_optimization"> Newton method</a>, we have central points which are <em>x*(t). </em>This <strong>central path is </strong>strictly feasible which means that equality conditions are satisfied for these central points as well. We recall that the minimisers are found where the gradient is zero. We write the Lagrangian</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*rcVO-E448iCjaZ7L" /></figure><p>Wonder where nu is coming from? As before, we write our minimisation problem <em>all in one expression</em> in the form of Lagrangian (which means augmenting the objective function with Lagrangian multiplier for equality constraints). Then we take the derivative and make it equal to zero, we recall that this is where minimisers are. We state that there exists optimal <em>nu </em>such that the expression written blow holds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*Rlc0OA6Bgh-QjUv_" /></figure><p>From the expression above we can derive an important property of the central path: every central point <em>x*(t) </em>yields a dual feasible point and hence, the lower bound on the optimal solution <em>p*</em>. Recalling reading about it <a href="https://medium.com/@marialavrovskaya/svm-talking-maths-quadratic-programming-and-cholesky-factorisation-968a493db10b">here</a>?</p><p>If we define the lambda as following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/0*3AO9osA6YPPhDrz-" /></figure><p>This gives us a dual function and by plugging our lambda inside, we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*E3dWhYn6ale6QX9W" /></figure><p>Whereas before we said that the duality gap is practically zero, practically we showed that it’s not quite like that. We have our duality gap that equals <em>-m/t.</em></p><p>This deforms the form of our <a href="https://medium.com/me/stats/post/ab5d30a8d73e">stated</a> KKT conditions. The <strong>new</strong> KKT conditions are simply called <strong>modified</strong> KKT conditions. Thus our last condition is replaced by taking into account the duality gap we discussed!</p><p>Thus are new modified KKT conditions, a.k.a centrality conditions, are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/0*CEcrSp8_PrxAeP0Z" /><figcaption>Modified KKT conditions</figcaption></figure><p>So far so good! We provided intuition where the modified KKT conditions are coming from, which hopefully helped you grasp the idea behind interior point algorithms better. From this moment onwards, all you should remember is the modified KKT conditions and that we are trying to solve the system using the <a href="https://en.wikipedia.org/wiki/Newton%27s_method_in_optimization">Newton method</a>! :)</p><h3>Solving numerically: Primal-dual method</h3><p>Essentially, we express the modified conditions as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/0*bJxr-bJOt3h2QToZ" /><figcaption>Nonlinear equations r_t</figcaption></figure><p>where we define</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*MEhQMRHKQel_8qNm" /></figure><p>and <em>f(x) </em>is a vector of inequality constraints and and <em>Df</em> is its derivative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*ThC0lnlU_urSQitf" /></figure><p>Once we find <em>x, lambda, nu</em> that satisfy the first equation, that means that we found our minimisers! Do you see where these matrix of equations is coming from? This is indeed our modified KKT conditions with all the terms on the left-hand side!</p><p>Now what should we do to solve it? We consider the Newton step for solving nonlinear equations <em>r_t </em>for fixed <em>t</em>. We will denote the current point and Newton step as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/0*uKEOEYd_7fpn2UX1" /></figure><p>respectively. The Newton step is characterized by the nonlinear equations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/0*G6HujJ4T_e-x19NU" /></figure><p>So in terms of <em>x, lambda </em>and<em> nu</em> we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*sajg4CRKKpygMIx7" /><figcaption>Final system</figcaption></figure><h3>Practice! Translating into the code</h3><p>Finally, here we are! We have our final nonlinear equations that we want to solve numerically using the Newton method. How do we code it up? In this tutorial we use Matlab</p><h4>Note about our data</h4><p>We use the synthetically generated data set that contains two classes and cannot be easily separated by the straight line. This data set was generated using Python code and can be accessed <a href="https://github.com/MariaLavrovskaya/Nowearetalking/tree/main/svm/data">here</a>.</p><h4>Step 1. Read the data from the CSV file</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e52a48020b6b9d0f4b9aa064b3b8f2c/href">https://medium.com/media/1e52a48020b6b9d0f4b9aa064b3b8f2c/href</a></iframe><h4>Step 2. Translate the problem into the code</h4><p>Remember, in the beginning of this article we discussed our QP for Support Vector Machine? Translating it into the code is very straightforward as we 1) know the objective and 2) know our inequality and equality constraints. Let’s put it together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39940879fa9f7c719c50a31ca2bc13a9/href">https://medium.com/media/39940879fa9f7c719c50a31ca2bc13a9/href</a></iframe><p>We first need to create our D matrix. Recall, it contains the product of x and y, hence we write for loop to find it. Once D is found, we write its first-order and second-order derivatives. Then we put together inequality and equality constraints and their derivatives.</p><p>Lines from 33–38 show the problem setup. Recall we are trying to optimise <em>x, lambda and nu</em>, so we should start from somewhere! How do we pick a starting point? You can really start with whatever, the only requirement: the choice should be feasible, meaning that at this point the constraints of the problem are not violated!</p><h4>Step 3. Picking default parameters</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8539d07f9469126406595792d84fb59e/href">https://medium.com/media/8539d07f9469126406595792d84fb59e/href</a></iframe><p>Before we only discussed parameter <em>t, </em>however there are other parameters that we should choose by default. The primal dual algorithm assumes that at each iteration <em>t </em>is getting bigger, so we introduce <em>m </em>constant that we multiply <em>t</em> by at every iteration (we will see that further in the code). <em>tol and maxIter </em>are two parameters that are stopping criteria.</p><p><em>tol </em>controls surrogate duality gap, so we only stop when the surrogate duality gap is very very small. Surrogate duality gap is introduced due to the fact that Primal-dual method does not necessarily produce points at every iteration that are necessarily feasible, this means that at each iteration we cannot necessarily compute the duality gap and stop when its very very small — hence, we introduce the surrogate duality gap.</p><p><em>maxIter </em>just ensures that we go on for a certain number of iterations so we won’t be solving forever.</p><p>Backtracking options allow to determine the length of the step. We will see how it is used inside of the algorithm.</p><h4>Step 4. Code the algorithm up</h4><p>Firstly, I am deeply thankful to Dr. Marta Betcke who introduced me to Numerical Optimisation while I was studying in UCL. The algorithm presented in this section was inspired by Dr. Marta Betcke who is a lecturer in Numerical Optimisation in University College London.</p><p>We create a separate function that would take all our parameters defined above as input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/540e3c151be0ed7ac389bbad32546f49/href">https://medium.com/media/540e3c151be0ed7ac389bbad32546f49/href</a></iframe><p>We found our <em>deltaY</em> by inverting <em>r_t</em> for <em>deltaY </em>[1]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/0*DzKP1LH9yxQDDMDA" /></figure><h4>Step 5. Determine step length</h4><p>We found the direction we need to go, but we have not done a step in this direction yet. How should we determine the length of our step? We use <a href="https://en.wikipedia.org/wiki/Line_search">line search</a> but adapt it to work for the Primal-dual algorithm.</p><p>The basic line search should be modified by accounting for the norm of the residual and by ensuring that two constraints hold. The first constrain is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*BwXGNI2EZO3Wn5lZ" /><figcaption>The first constraint for backtracking</figcaption></figure><p>For the sake of simplicity, here we assume that this first constraint is never violated. Thus we set <em>s_max=1.</em></p><p>The second constraint ensures that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/0*0jr54lbLcUxiy0TN" /><figcaption>The second constraint for backtracking</figcaption></figure><p>To ensure the second constraint, we need to start backtracking reducing s until the constraints are met. That’s where the <em>optsBT</em> options we introduced before kick in! As we don’t want to backtrack forever if the constraints are not met, we want to ensure that we stop when a certain number of iterations is met.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b492e6c05b3311b30db8c80728abd01/href">https://medium.com/media/3b492e6c05b3311b30db8c80728abd01/href</a></iframe><p>We keep doing this exercise until either our surrogate duality gap is smaller than the tolerance level or the maximum number of iterations is reached! The final trio <em>x_k, lambda_k and nu_k </em>will be our solution!</p><h4>Step 6. Call to action</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2ece8e783899e22266d40fa4cc10109/href">https://medium.com/media/e2ece8e783899e22266d40fa4cc10109/href</a></iframe><p>We call the created function that we named PrimalDual to work!</p><h4>Step 7. Plot the decision boundary</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dd0c2079054d1bacc26a43d8f0a353b/href">https://medium.com/media/3dd0c2079054d1bacc26a43d8f0a353b/href</a></iframe><p>Here we are! As we have been recording the iterations, we now can find the supporting vectors that are bigger than some threshold (we use 0.001)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHMrVZzDQfobV-_7Z5Kmvw.png" /><figcaption>Image by Author</figcaption></figure><figure><img alt="Image by Author." src="https://cdn-images-1.medium.com/max/1024/1*qiTvEtoP0x4cTUQGHyMZEQ.png" /><figcaption>Image by Author</figcaption></figure><p>Recall that our <em>infoPD </em>struct also contains information on the surrogate duality gap at every iteration. By plotting it as a function of a number of iteration, we can see that it’s rapidly decreasing. It does not go to zero exactly, but it’s smaller than the <em>tol=1e-12 </em>we set in the very beginning.</p><p><strong>References:</strong></p><p>[1] V. L. Boyd Stephen, <em>Convex Optimization</em>. 2004.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d705cdf78c94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/svm-talking-algos-using-interior-point-methods-for-svm-training-d705cdf78c94">SVM Talking algos: Using Interior Point Methods for SVM Training</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SVM Talking maths: Formulating Support Vector Machine as a Quadratic Programming problem]]></title>
            <link>https://medium.com/data-science/svm-talking-maths-formulating-support-vector-machine-as-a-quadratic-programming-problem-ab5d30a8d73e?source=rss-761c41053653------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab5d30a8d73e</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Maria]]></dc:creator>
            <pubDate>Thu, 07 Oct 2021 16:40:18 GMT</pubDate>
            <atom:updated>2021-10-08T13:09:43.439Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>From the idea of separating hyperplane to the final quadratic program in 4 steps</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zU5XcxCMLm81mwkN660V9A.gif" /><figcaption>GIF by Author</figcaption></figure><p>Last week we <a href="https://medium.com/@marialavrovskaya/svm-talking-maths-quadratic-programming-and-cholesky-factorisation-968a493db10b">introduced</a> constrained optimisation and left you with no hint how this might be helpful to tackle the Support Vector Machine problem numerically. This time we will put everything into context by formulating Support Vector Machine as QP problem!</p><p>In this article, we introduce Karuch-Kuhn-Tucket (KKT) conditions, formulate the Support Vector Machine problem as a convex optimisation problem and introduce several transformations to make it more convenient to solve numerically!</p><p><em>Let’s jump straight into it.</em></p><h3>What are these KKT conditions and why do we care?</h3><p>To put it plainly, KKT conditions are the first derivate <strong>tests </strong>that allow us to check whether we have<strong> indeed </strong>reached the optimal solution<strong>. </strong>We recall that assuming the objective function, inequality and equality constraints are differentiable, our Lagrangian has the following form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*Re5ARW1HkGbYbQqB" /></figure><p>where x* is the optimal solution. Thus we have the following KKT conditions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*E-fN2An__I4rWxIH" /><figcaption>KKT conditions</figcaption></figure><p><em>Do all these symbols make sense for you? If not, let me know I’ll provide more explanations!</em></p><p><strong>Here is good news! 😃</strong> If we assume that the objective is convex, these conditions become necessary and sufficient. In other words, we are guaranteed that <em>x*, lambda* </em>and<em> nu*</em> are primal and dual optimal <strong>with zero duality gap</strong>. Remember what it <a href="https://medium.com/@marialavrovskaya/svm-talking-maths-quadratic-programming-and-cholesky-factorisation-968a493db10b">means</a>?</p><p>So now, we are fully set! We have our Lagrangian and KKT conditions, how should we formulate SVM as a constrained optimisation problem?</p><h3>Support vector machines as Quadratic Programming problem</h3><p>We recall that Support Vector Machine essentially finds an optimal hyperplane, where “support vectors” are the ones that position of hyperplane and the width of margins.¹</p><h4>The idea of separating hyperplane</h4><p>If we have vector <em>x </em>in a<em> p-</em>dimensional space, a hyperplane or affine set <em>L </em>is defined by the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/0*pV31Uk8wAEVjJyJ5" /><figcaption>Separating hyperplane</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Amy_BnbY4AQ7sYIDBpVKQ.png" /><figcaption>Image by Author. Inspired by [1]</figcaption></figure><p>That’s the picture you should have in your mind (<em>Sorry for the messy drawing</em>). <strong>Big idea!</strong> 🙂These <em>betas </em>are the ones that control the orientation of the line — thus, we want to find the optimal separation by minimising our <em>betas</em>!</p><p>We now list some important properties:</p><ol><li>For any two points x_1 and x_2 lying in <em>L, </em>we have</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/0*6-0F5JeVXhV6y1vQ" /></figure><p>Thus we can construct vector normal <em>B* </em>to the surface L. As we are in 2D here, we have a line instead of the surface. <em>We recall that vector normal is a vector that is perpendicular to the surface at a given point.</em></p><p>2. For any given point <em>x_0 </em>in<em> L, </em>we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/0*Xzy0hAJg71J7_r1J" /><figcaption>Directly from the definition of separating hyperplane above</figcaption></figure><p>3. The <strong>signed</strong> distance of any point of<em> x </em>to<em> L </em>is given by. <em>I note that we have a derivative in the denominator in the final expression because taking the first-order derivative of the objective, we will be left with beta’s only.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*53yP-zwKflMUbY2j" /></figure><h4>Step 1 — Formulate an optimisation problem.</h4><p>The objective is to find the hyperplane that separates the data points by <strong>maximising the distance to the closest point from either class.</strong> If M is a signed distance,<strong> </strong>then we have the following optimisation problem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*44f5AuXU0F1q_uYy" /></figure><p>The following inequality condition ensures that all the points are at least a signed distance <em>M</em> from the decision boundary defined by <em>betas</em>.</p><h4>Step 2 — Think again! Reformulate for convenience.</h4><p>Now follow carefully, there are three important adjustments we should do to the aforementioned optimisation formulation<strong> to account for misclassification</strong> and <strong>to make it slightly easier to solve numerically</strong>. We introduce the following changes:</p><ol><li>Arbitrarily set</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/0*8akisre68ec8-UJ_" /></figure><p>This allows us to rewrite the initial problem in such a way that in the future we will be minimising the squared norm, which is done purely for convenience.</p><p>2. The real-world problem is usually <strong>non-separable</strong> as it always includes some observations that overlap in the future space. This is called <strong>soft margin</strong>. We thus need to allow some points to be on the wrong side of the margin. Mathematically, we introduce <strong>slack variables </strong><em>(</em>letter <em>xi)</em><strong>, </strong>the sum of which should not exceed the value <em>C</em> specified</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*MemkV-UXw8yiazng" /></figure><p>This constraint is formulated in such a way to express the proportional amount by which the prediction <em>f(x_i) is </em>on the wrong side of its margin.</p><p>We now have the following optimisation problem. <em>We note that 1/2 is introduced before the squared norm is done purely for convenience — recall that once we take the first-order derivative, the power of 2 will go down so 1/2 will cancel it out. Furthermore, we rewrite the bounding constraint as “regularisation” term, which is essentially the same thing as we are penalising for the misclassification mistakes!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*lMKmyCbx0cuNWNqe" /><figcaption>Rewritten optimisation problem</figcaption></figure><h4>Step 3 — Write Lagrangian (we are almost there).</h4><p>The aforementioned gives us the constrained optimisation problem, now we put everything together to get Lagrangian!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*HAFtRII07aDUYm6t" /></figure><p>So our new goal is to minimise the <em>vector of beta</em>, <em>beta_0</em>, <em>alphas</em> and <em>the vector of xi</em>. Can you see where all these terms come from? If not, let me know and I will break it down.</p><p>What else are we missing here? Right! We still need to apply our first-derivative tests (KKT conditions) to see whether the optimal solution we are attempted to find is truly optimal. Let’s write these down now.</p><p>We first introduce <strong>Stationarity Conditions</strong>. This is the same as if we were trying to determine a stationary point where the derivative of the function is zero. As we are optimising with respect to the <em>vector of beta</em>, <em>beta_0</em>, <em>alphas</em> and <em>the vector of xi. </em>We need to ensure that all three pass these stationary tests! Thus, we write</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/0*_34pxf-hLfRDH_i5" /><figcaption>Stationarity conditions</figcaption></figure><p>From the primal form of the problem, we have so-called Primal Feasibility conditions. <em>Feasibility simply means that our optimal point lies in the possible region that satisfies the constraints!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/0*TGiwH9DE77uOOP8T" /><figcaption>Primal Feasibility Constraints</figcaption></figure><p>Going further, we have Multipliers conditions! Well, since these two are directly coming from KKT conditions. We have one multiplier for equality constraints and another for inequality constraints. Hence, we write</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*PzHU0dQHaJeN3ybH" /><figcaption>Lagrangian multipliers conditions</figcaption></figure><p>Last but not least, we have Complementary Slackness conditions. These constraints are introduced since we have <strong>zero duality gap</strong> and thus they guarantee that the values of primal and dual are the same! You can read more about how these conditions are obtained <a href="http://www.gatsby.ucl.ac.uk/~gretton/coursefiles/Slides5A.pdf">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*qjwUuI529gF3SihF" /><figcaption>Complementary slackness conditions</figcaption></figure><h4>Step 4 — Lagrangian looks a bit scary. Let’s write the dual form!</h4><p>Our Lagrangian looks very scary and we also have 9(!) constraints to account for. We already know that we have a convex problem, thus we can find the global optimum even if we approach the problem by writing the dual form.</p><p>Let’s try reformulating our primal problem into dual form. We use the first three Stationarity conditions and plug them into the Lagrangian. We write</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AJxTHfmlNhCKZ20H" /></figure><p>To summarise, we have the following problem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*teAMhopLohZzb1zq" /><figcaption>Final quadratic programming problem!</figcaption></figure><p>This is much simpler than the Lagrangian we have seen before. It is also much more flexible as we have introduced slack variables that allow for misclassifications!</p><p>Look at this expression carefully. What does it remind you of? Exactly, it has the form of a quadratic program!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*wXO9CFghnp6wqbD4" /><figcaption>Standard form of quadratic problem</figcaption></figure><p>This means that now we can apply QP methods to solve this problem numerically 🚀</p><h4>The nicest thing — here comes a kernel function!</h4><p>One of the nicest things about the dual form is that the data (our <em>x</em>) comes in the form of a dot product. This means that we can apply any kind of transformations to our data beforehand! This is very handy as hardly any real datasets can be separated linearly!</p><p><strong>References:</strong></p><p>[1] T. et. all. Hastie, “Springer Series in Statistics The Elements of Statistical Learning,” <em>Math. Intell.</em>, vol. 27, no. 2, pp. 83–85, 2009, [Online]. Available: <a href="http://www.springerlink.com/index/D7X7KX6772HQ2135.pdf.">http://www.springerlink.com/index/D7X7KX6772HQ2135.pdf.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab5d30a8d73e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/svm-talking-maths-formulating-support-vector-machine-as-a-quadratic-programming-problem-ab5d30a8d73e">SVM Talking maths: Formulating Support Vector Machine as a Quadratic Programming problem</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SVM Talking maths: Quadratic Programming and Cholesky factorisation]]></title>
            <link>https://medium.com/@marialavrovskaya/svm-talking-maths-quadratic-programming-and-cholesky-factorisation-968a493db10b?source=rss-761c41053653------2</link>
            <guid isPermaLink="false">https://medium.com/p/968a493db10b</guid>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Maria]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 10:08:25 GMT</pubDate>
            <atom:updated>2021-10-09T10:53:12.582Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Here we talk about maths behind SVM numerical algorithms.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOJmxX8EHwPB--7ih0BeHA.png" /></figure><p><em>Setting the scene. </em>Have you ever wondered why one algorithm works and the other does not? This story opens up a new series of articles that is designed as complete guide with the objective not only to teach you how to write a few lines of function calls, but also to make mathematics more comprehensible for those who’d like to take informed decisions while choosing an algorithm. Furthermore, this also allows to brush up on your skills before taking any ML-related interviews.</p><p>Our very first series is designed to familiarise you with Support Vector Machines (SVM), one of the well-known supervised learning algorithms. The focus of this series is not on linear algebra that is behind <em>separating hyperplanes</em>. This has been discussed over and over and over again in numerous articles and ML books — good one can be found <a href="https://ankitnitjsr13.medium.com/math-behind-support-vector-machine-svm-5e7376d0ee4d">here</a>. Thus, we decided to look at SVM as on optimisation problem and introduce two very different algorithms that help us to tackle it. We start off from the basics of constrained optimisation and then move to problem formulations under two effective optimisation techniques.</p><p><strong>Here’s our plan — so you will not need to spend extra time reading something that you have already known before.</strong></p><ol><li><strong>Talking maths</strong>: Quadratic Programming and Cholesky Decomposition</li><li><strong>Talking maths: </strong>Support Vector Machine as constrained optimisation problem</li><li><strong>Talking algorithms</strong>: Using Interior Point Methods for SVM training</li><li><strong>Talking algorithms</strong>: Using Sequential Optimisation for SVM training</li></ol><p>In this article we break down the general form of constrained optimisation problem, talk about Lagrangian, its dual form and finally discuss Cholesky factorisation.</p><h3>What is convexity?</h3><p>We begin with some mathematical ideas that will come in handy as we go forward. Let’s talk about convexity first. We can have <strong>convex set</strong> and <strong>convex function</strong>. Let’s imagine that we have a collection of elements S (set) . Essentially, it is when you can draw a line joining any two points that belong to our newly created set S and the line segment will lie entirely below. Concavity is just the same thing but flipped over — now you have a line segment that lies above. This is informal definition that helps to picture things in your head. Like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBv3MuvgUJq2fgbaOXS5Gw.jpeg" /></figure><p>Let’s now talk about the convex function. Things become slightly more complicated — we need to provide <strong>one property of convex functions</strong>. This is — the function is defined to be convex if its domain S is a convex set (as we have just seen) and if for those two points x and y that belong to our set S the following property holds.</p><p>This is also called <strong>Jensen’s inequality </strong>and it’s a common interview question<strong>. </strong>Intuitively, you can think of expected value — this will help not to forget!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*Y60K8TX96weqZCWR" /><figcaption>Jensen’s inequality</figcaption></figure><h3>What are affine functions?</h3><p>We have now discussed a very first tool that is needed to fully grasp the idea behind constrained optimisation. The second building block is <strong>affine functions</strong>. The easiest way to think about them is to start with system of linear equations. Remember this <a href="https://www.khanacademy.org/test-prep/sat/new-sat-tips-planning/sat-math-test-lessons/a/gtp--sat-math--article--solving-system-of-linear-equations--lesson#:~:text=A%20system%20of%20linear%20equations,linear%20equations%20with%20two%20variables.">concept</a> from linear algebra?</p><p>A function is affine if it is a sum of a linear function and a constant, i.e. if it has a form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*CyQzBR_dsYO0yOBU" /><figcaption>Definition of affine functions</figcaption></figure><p>There is an interesting feature related to numerical optimisation and convexity. If we suppose that we have f(S) where <strong>f is affine and S is a convex set , </strong>then the image under f is convex.<em> Just to save your time recalling what the image is — it is a set of all outputs.</em></p><p>The natural question is now: <strong>why are we bothered?</strong></p><h3><strong>Constrained optimisation: Lagrangian and duality come together</strong></h3><p>To find an <em>optimal hyperplane</em> for SVM problem, we need to formulate it as <strong>constrained optimisation problem</strong>. This is when everything we have discussed so far will come together into one picture. Let’s go 🚀</p><p>The convex optimisation problem is one of the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/0*eVD9Vrm_HR3fgp2H" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*_4X8tGSjqn6Y8R--" /><figcaption>Constrained optimisation problem with equality and inequality constraints</figcaption></figure><p>and it requires</p><ul><li>The objective function to be <strong>convex</strong></li><li>The <strong>inequality</strong> constraint functions to be<strong> convex</strong></li><li>The <strong>equality</strong> constraint functions to be <strong>affine</strong></li></ul><p>In this form we have everything separated, but what should we do if we want to put everything together?<strong> We call it Lagrangian!</strong></p><p>The general idea of the Lagrangian <em>(L) </em>duality is to take constraint into account by augmenting the objective function with a weighted sum of the constraint functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*IhwsLKR_GmFkZrH4" /><figcaption>Lagrangian mapping</figcaption></figure><p>And according to the description above, we have the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*0cqd3TIK-xtO48Xo" /><figcaption>Lagrangian form</figcaption></figure><p><em>Lambda</em> and <em>nu</em> are Lagrangian multiplier. The first on is associated with inequality constraint and the second is associated with equality constraints. This problem can be flipped into <strong>dual form </strong>in hope that it will be easier to solve it. Then we have Lagrangian dual form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/0*0kmovZ6800VpDu09" /><figcaption>Lagrangian dual form mapping</figcaption></figure><p>It is defined as the minimum value of the Lagrangian over all <em>x</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/0*WmINQWTjxcDUD8IV" /><figcaption>Lagrangian dual form</figcaption></figure><p>There is one property of this function that makes it <strong>extremely useful</strong>. The dual function a pointwise infimum (inf) of a family of affine functions and by construction (you can read more about it here and here) it is concave, even when the problem is not convex. Thus, the dual function gives lower bound on the optimal value <em>p*.</em></p><p>Confused by the last few sentences? I know we have been there too. Before we show one example that will clarify that, we need to note that for certain constrained optimisation problems this we have <strong>zero duality gap</strong>. This essentially means that the optimal minima can be achieved by considering either primal or dual problem. This property is exhibited (1) if we have a convex quadratic objective function and affine constraint functions and (2) if the Hessian matrix with respect to (wrt) <em>x</em> is<em> </em><strong>semidefinite</strong> or <strong>definite</strong>. Good news! SVM is exactly this kind of problem 😄</p><p>Just one more thing that is <strong>very important</strong> to discuss — at the optimal minima Karush-Kuhn-Tucker (KKT) conditions must be satisfied! Don’t be bothered by that too much right now, we will explain how to incorporate them into the problem in the future!</p><h3>Showing zero duality gap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7RmYiVusmAlmUvOjS-oow.png" /><figcaption>Zero duality gap showed</figcaption></figure><p>Now we go back to zero duality gap and show visually what it really means. For representational purposes, we pick a very known function and one linear constraint. We want to find the pointwise infimum if we keep lambdas fixed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b27bad12fcab45b07cf51710f81bd289/href">https://medium.com/media/b27bad12fcab45b07cf51710f81bd289/href</a></iframe><p>Along the x-axis if we fix lambda, we can see parabola-looking surface, the nice thing about this plot is that we can clearly see here that on the other hand if we fix <em>x</em>, Lagrangian is the linear function of lambda. If the constraint is violated so we have x-axis which are infeasible gives us the positive slope, whereas for feasible x’s the slope would be negative. We have constructed a Lagrangian and the way it looks is going to be generic. To look at the dual function, because this Lagrangian is the quadratic function, we know how to take the inf of it, in this case the minimum (the vertex) and then we find the maximum. How does it corresponds to the Lagrangian? We sliced parallel to the <em>x</em> and taken inf every time wrt <em>x</em> and assigned it to the dual function. We plot on our surface the points that corresponds to the inf function for each individual lambda. <strong>That’s where the dual function lives on the Lagrangian.</strong></p><h3>Cholesky Factorisation</h3><p>Now we are all set to formulate SVM as quadratic programming problem. We will do this in two upcoming articles! Now we need to discuss the very last mathematical tool that is required to fully grasp the idea behind Interior Point Methods — <strong>we now talk about Cholesky Decomposition</strong>!</p><p>Every positive definite matrix can be factored as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*VGHViK5f4Dxw1DEm" /></figure><p>R is upper triangular with positive diagonal elements. We also recall that positive definite matrix is symmetric matrix when</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/0*0shqexso_0HiwssY" /></figure><p>These are mathematical formulations of definite matrix and Cholesky factorisation.</p><p>Now, the natural questions are: why do we need these all maths for SVM and how should we tackle this numerically? We will answer all these questions in the upcoming articles 😜 🚀</p><h3>Test yourself</h3><ol><li>What is Jensen’s inequality?</li><li>How affine functions are defined?</li><li>Define the constrained optimisation problem, Lagrangian and its dual form</li><li>What kind of matrix can be decomposed as Cholesky Factorisation?</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=968a493db10b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes a movie hit a “jackpot”? Learning from data with Multiple Linear Regression]]></title>
            <link>https://medium.com/data-science/what-makes-a-movie-hit-a-jackpot-learning-from-data-with-multiple-linear-regression-339f6c1a7022?source=rss-761c41053653------2</link>
            <guid isPermaLink="false">https://medium.com/p/339f6c1a7022</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[regression-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Maria]]></dc:creator>
            <pubDate>Thu, 20 Jun 2019 13:23:05 GMT</pubDate>
            <atom:updated>2021-06-11T15:21:10.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1ljOmO4Dd9-_TUMl" /><figcaption>Photo by <a href="https://unsplash.com/@dmjdenise?utm_source=medium&amp;utm_medium=referral">Denise Jans</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The first and foremost thing that I have to mention — this post is for complete beginners who are willing to step on the road of data analysis and wonder why ultimate guides don’t work the proper way. With the small tweaks, I will show how to create multiple linear model with numerous independent variables, pointing on a roster of errors that you might face on your way.</p><p><strong>Here’s our plan — you may skip if something seems familiar to you:</strong></p><ul><li>Some background about Multiple Linear Regression;</li><li>Reading the .RData file and converting it to DataFrame;</li><li>A quick Explanatory Data Analysis;</li><li>Hunting for missing values;</li><li>Dealing with categorical variables;</li><li>Building Regression Model;</li><li>Factors that might influence the prediction of your model;</li><li>R codes that might be useful.</li></ul><h3><strong>Some background</strong></h3><p>Before diving in, I would like to review important details about the concept of Multiple Linear Regression. We use multiple independent predictors ( denoted x1, x2, x3, …) to predict the value of dependent variable y. Through the analysis, MLR find a line that best “fits” the data. The residual is the difference between observed value and the predicted value — therefore, the less the sum of square residuals is, the more accurate model we have.</p><p>Why do we consider the sum of squared residuals? The answer is pretty simple: by <strong>squaring the residual values</strong>, we treat positive and negative discrepancies in the same way.</p><h4><strong>There are two important things that you have to learn by heart</strong>:</h4><ol><li><strong>Collinearity</strong>: two predictor variables are said to be collinear when they are correlated with each other. Remember, predictors are also called independent variables, so they should be independent of each other. Inclusion of collinear predictors complicates model estimation. <strong>Remember: independence matters!</strong></li><li><strong>Parsimony</strong>: Avoid adding predictors associated with each other because often times the addition of such variables brings nothing new to the table. Simply remember the <strong>Occam Razor’s principle</strong>: among models that are equally good we want to select the one that has the <strong>fewer</strong> variables.</li></ol><h3><strong>About the dataset</strong></h3><p>For this MLR, I will be using the dataset that includes information about the 651 randomly sampled movies produced and released before 2016, taken from <a href="http://www.rottentomatoes.com/">Rotten Tomatoes</a> and <a href="http://www.imdb.com/">IMDB</a>. My dataset comes in .RData file format — to open the data, we first need to convert it into the Pandas DataFrame. To that end, the “pyreadr” library comes in handy.</p><p><strong><em>Hint</em></strong>: While “importing stats models.api as sm” you can be stuck with the “<em>ImportError: cannot import name ‘factorial’ with pip installed packages</em>”. It has to do something with the latest version of stats models — to overcome this issue you need to downgrade your current version of scipy.</p><p><strong>It can be done with typing : <em>python3.6 -m pip install scipy==1.2 — upgrade</em> </strong>in your Terminal or if you are using Jupiter notebook, put<strong> <em>“conda” instead of pip.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86bb44ef9b145d4e706056affde8e31d/href">https://medium.com/media/86bb44ef9b145d4e706056affde8e31d/href</a></iframe><h3><strong>Explanatory Data Analysis : Feature selection</strong></h3><p>Obviously, we don’t have to consider every variable out of 32 for your model — it doesn’t make any sense to include them in statistical analysis as they were given for informational purposes. The right question is: <strong>What variables should I consider in my model?</strong></p><p>First, let’s look at our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVyP5EGyjB0r80UBnTnH-g.png" /><figcaption>Codebook for Movies dataset</figcaption></figure><p>At the first glance, it seems that the data contains a number of dependent variables that are highly correlated. If we see that variables are highly correlated with each other, we select one and drop others. To find the dependence, we use Pearson’s correlation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5d15670e04e54d3f2651dad72285e1b/href">https://medium.com/media/b5d15670e04e54d3f2651dad72285e1b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_e0YMGT3rZbQu4PIJT1Ekg.png" /></figure><p>From the heatmap above, we see that there are two “groups” of variables that are highly correlated with each other:</p><ol><li>[‘imdb_rating’], [‘critics_score’], [‘audience_score’]</li><li>[‘dvd_rel_year’], [’thtr_rel_year’]</li></ol><p>Remember, that MLR states that we <em>do need to have independent variables, hence we need to stay with the one from each group and drop the others.</em></p><p>From my personal view, I will stay with [‘imdb_rating’]. What would we drop more?</p><p><strong>Note</strong>, that I have to drop all three TimeSeries variables ([‘thtr_rel_year’, ‘thtr_rel_month’, ‘thtr_rel_day’]), as it is a violation of the classical assumption that the errors are independent of each other. In other words, year, months and days are highly collinear — that will result in a bad effect. Remember, we need to take care that all of our variables are independent and not highly correlated! Those are the continuous variables and for this matter we should treat them with more advanced statistical methods. You can learn about this in minute detail in the <a href="https://stats.stackexchange.com/questions/411128/how-time-series-structure-can-affect-the-independence-of-residuals-condition-for">ticket</a> that I have created on StackExchange.</p><p>In light of this assumptions, I will come up with few variables and drop the other. For my future model, I’ve chosen:</p><p>Feature matrix:</p><ol><li>title_type —( as the id of the film);</li><li>genre;</li><li>runtime;</li><li>best_pic_nom (as the outstanding source it can be bring new viewers);</li><li>top200_box;</li><li>director;</li><li>actor1;</li></ol><p>Dependent variable: [‘imdb_rating’].</p><p>For this step, I create <strong>one DataFrame</strong> for both — feature matrix and dependent variable unless I deal with missing values. The reason is that while dealing with missing values we have to delete all rows in <strong>EVERY </strong>column to keep both of our future DataFrames (for feature matrix and dependent variable) in the same shape.</p><p>So we’ve come to the point when we start working with the DataFrame and dropping those variables, that we won’t consider in our model.</p><p><strong>There are two methods that can be used for feature selection from Pandas library</strong>:</p><ol><li>Data.iloc[&lt;row selection&gt;, &lt;column selection&gt;] — works if you know the index of your variables (Note that .iloc returns a Pandas Series when one row is selected, and a Pandas DataFrame when multiple rows are selected, or if any column in full is selected.)</li><li>Data.loc[&lt;row selection&gt;, &lt;column selection&gt;] — works with labeled data by the name of rows/ columns</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b07aea1818771fa2f1d1252df6079b9/href">https://medium.com/media/9b07aea1818771fa2f1d1252df6079b9/href</a></iframe><h3><strong>Hunting for missing values</strong></h3><p>As the regression function will simply raise MissingValueError if we ask to build regression model based on data that contains NaNs, we have to take care about them in advance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aeddd27cee52b816be6ad53b3380d97/href">https://medium.com/media/6aeddd27cee52b816be6ad53b3380d97/href</a></iframe><p>From the given result we see, that (in sum) we have 5 missing values with the following distribution: one in [‘runtime’] , two in [‘director’] and [‘actor’], respectively.</p><p>As the algorithm suggest, we simply drop them with the following function shown below. The point is: since we have more than enough observations, the missing values don’t influence the whole scope that much, therefore we can drop them.</p><p><strong>Note</strong>, that it’s really important to specify <strong>‘ inplace=True’ argument</strong>, as if not doing so, nothing will happen and you will end up with the same number of missing values as before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9b26b16bc9800e1a0126c8b910bcc9f/href">https://medium.com/media/e9b26b16bc9800e1a0126c8b910bcc9f/href</a></iframe><h3><strong>Treating categorical variables as dummy</strong></h3><p>Now it’s time to split our dataset for two: the feature matrix and dependent variable. The feature matrix simply contains the variables that are used for modelling and dependent variable is the one that we try to predict.</p><p>There are two ways how we can perform the conversion from categorical variables to dummy. One is using the pandas.get_dummies() function — however, it adds more variability in data and perform purely with scikit-learn (Note, I am not saying that I doesn’t work, you just get the higher Mean Square Error in the end). To that end, I use two other methods provided in scikit-learn library.</p><h4>Step 1. Label Encoding</h4><p>The first step is to label all the levels of 1 categorical variable — LabelEncoder() encodes labels with value between 0 and n_classes-1. This simply means : categorical variables with 10 levels (“Drama”, “Comedy” etc.) will be labeled from 0 to 9.</p><p><strong>Hint,</strong> you can use this method to iterate over every column <strong>once at a time</strong>!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f1d331f0993652570c94c56ab00cba1/href">https://medium.com/media/8f1d331f0993652570c94c56ab00cba1/href</a></iframe><p>Here we go, we don’t have any words anymore, just <strong>numbers</strong>. You might ask :” Why don’t we just stay with label encoded variables?”</p><p>The answer is that for any statistical measurements those variables having a higher label (say 9 for Tragedy) will have a higher result — it would turn out to be a disaster for your regression analysis.</p><h4>Step 2. One-hot Encoding</h4><p>As a corollary, <strong>the next step</strong> is to use one hot encoder to perform “binarization” of the category and include it as a feature to train the model. With this code, you end up with a roster of columns with 0 and 1 values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa867bdc66c104d2daf3b99cd4abce8e/href">https://medium.com/media/fa867bdc66c104d2daf3b99cd4abce8e/href</a></iframe><h4>Step 3. Standardisation</h4><p>Finally, we are done with categorical features. Now there is a last step before we plug everything into a model. To deal with one continuous variable ( [‘runtime’]). To standardise it, we will use the StandardScaler() method.</p><p><strong>In other words, standardisation tells how far each of our values is from the mean in terms of standard deviation.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b1a8c782e0aab0bfc8be7387e9fe61e/href">https://medium.com/media/3b1a8c782e0aab0bfc8be7387e9fe61e/href</a></iframe><p><strong>Here is the important note: </strong>If you end up your last line of code with <em>.fit_transform(nothing in here)</em>. You get an error — all of the values turn out to be zeroes now! Intuitively, there is nothing wrong, but one problem behind — for every number of array you subtract from it mean of this number, which equal to number and divide by the standard deviation of this number. To overcome this, you need to transform it from (1,n) to (n,1).</p><p>After all, you need to concatenate all the features together (just like in SQL):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ce8e8d59b0de082e0fadc4124a847ef/href">https://medium.com/media/1ce8e8d59b0de082e0fadc4124a847ef/href</a></iframe><h4>Finally, here comes your regression model:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2975d77b7e1be3572129da8de73d67e0/href">https://medium.com/media/2975d77b7e1be3572129da8de73d67e0/href</a></iframe><p><strong>Hint</strong>: when working with pandas encoding, there is <strong>a rule of thumb</strong> to drop one variable — simply, because one of your variables becomes a reference level. While following along, you might notice we haven’t done it, therefore we set our fit_intercept too False. In case of pandas encoding, you should change it to “True”. More details are <a href="https://datascience.stackexchange.com/questions/27957/why-do-we-need-to-discard-one-dummy-variable">here</a>.</p><p>To test how our model performs, we check the predicted values in comparison with the observed ones:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eabd9050b42332a13cd69d1646be8ca/href">https://medium.com/media/4eabd9050b42332a13cd69d1646be8ca/href</a></iframe><p><strong>In our case MSE = 1.20</strong>. One possible interpretation would be that I estimate the imdb rating for a movie with ≈±1 error. Mhh, interesting! How might we interpret that? In other words, as we know from the basis STAT-101 course, mean is too sensitive to outliers. Meaning in our case, that the films that have less scores from the audience have more variability in data, resulting in purely predicted values. To that end, we compute median square error. As you might check, it’s less than 0.4 in our case. Meaning that our model performs pretty well and can be improved with more data coming into the model.</p><h3>Factors that may have contributed to this inaccuracy in the model</h3><p><strong>More data is needed</strong>: We need to include more variables just to get the best possible prediction (for example, we could include the time series variables, but — as we see know that the correlation is pretty low — it wouldn’t influence our model that much).</p><p><strong>Bad assumptions</strong>: to check whether all of our variables are not collinear, we could perform MLR diagnostics (there is a highly recommended <a href="https://www.coursera.org/lecture/linear-regression-model/diagnostics-for-mlr-quxtC">video</a> that will guide your through) &amp; drop those that bring nothing new to the model</p><p><strong>Lack of features</strong>: The features we used don’t have the highest correlation with the dependent variable. There are two possible solutions: we could surf the net for a more comprehensive dataset or we might build a web scraper :)</p><p>For those, who are more familiar with R coding, I’ve made the more detailed analysis using R studio. You can check it out clicking the <a href="https://www.dropbox.com/s/inls77pasi0ut6f/Reg_Model_project.html?dl=0">link</a>.</p><p>The dataset can be found <a href="https://www.dropbox.com/s/pwda4qbm2cm6u5x/Movies.RData?dl=0">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=339f6c1a7022" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-makes-a-movie-hit-a-jackpot-learning-from-data-with-multiple-linear-regression-339f6c1a7022">What makes a movie hit a “jackpot”? Learning from data with Multiple Linear Regression</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The emerging landscape of DLT in FinTech]]></title>
            <link>https://medium.com/@marialavrovskaya/the-emerging-landscape-of-dlt-in-fintech-6ad570be8f1c?source=rss-761c41053653------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ad570be8f1c</guid>
            <category><![CDATA[regulatory-compliance]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[dlt]]></category>
            <dc:creator><![CDATA[Maria]]></dc:creator>
            <pubDate>Fri, 08 Mar 2019 08:32:40 GMT</pubDate>
            <atom:updated>2019-03-08T08:32:40.917Z</atom:updated>
            <content:encoded><![CDATA[<p>In case if you’ve been wondering why there is that much blockchain news in your feed</p><p>Before we dive in, I share my article’s plan with you to make it easy to skip topics that are familiar to you.</p><p><strong>Navigate through the article</strong>:</p><ul><li><strong>DLT &amp; Blockchain</strong> are not the same thing</li><li><strong>Crossing the Chasm</strong>: towards product / market fit</li><li><strong>Challenges</strong>: and how they are likely to be addressed</li><li><strong>Privacy</strong>: Making transactions private to only the parties within the transaction</li><li><strong>Performance &amp; Scalability</strong>: Directed Acyclic Graph DLTs as a disruptive alternative</li><li><strong>Security: </strong>hardware protection in consideration of potential fraud</li><li><strong>Interoperability: </strong>addressing the dissimilarity of siloed payment systems</li></ul><h3><strong>Once again: DLT &amp; Blockchain are not the same thing</strong></h3><p>To put it plainly, there is a dichotomy in both headings — as DLT &amp; blockchain are not the same thing.</p><p>“What’s the actual difference between these two?”, you might ask. Let’s get into it.</p><p><em>Just a quick peek on both approaches</em>. For short, distributed ledger technology, as the name suggests, is the database of records that isn’t stored in any one central body — in fact, it’s quite the opposite, all the transactions are spread across several nodes computing devices. Sounds quite familiar to blockchain, doesn’t it? Nonetheless, it’s not.</p><p>While in the DLT the implementer has a greater control as he can set the parameters, ergo it turns out to contradict with the ideological point of view on decentralization as it is.</p><p>On the other hand, we have blockchain — <strong>one of the forms </strong>of distributed ledger with the very particular technological basis. What sets blockchain apart from DLT? The answer is <strong>how the chains are formed</strong>. All the records are linked in groups — so-called blocks, — and form a chain, encrypted by a specific type of cryptographic signature. Going further, each of the transactions (for example) is approved by consensus. In contrary to blockchain, DLT won’t necessarily construct a chain of blocks.</p><h3><strong>Crossing the Chasm: </strong>towards product / market fit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*mOLQyogdiwfe2DDt7LDwWA.png" /></figure><p>All the hype around ICOs failures &amp; bitcoin volatility over the last, the whole idea of decentralization has received a lot of attention — starting from bitcoin fanatics &amp; spreading into banking sector. Let’s embrace classy Geoffrey A. Moore’s strategy on breaking into the market.</p><p>What we saw was in the nature of these innovators, coupled with emerging blockchain technologies. As Geoffrey A. Moore describes, “Innovators pursue new technology products aggressively. They sometimes seek them out even before a formal marketing program has been launched. This is because technology is a central interest in their life, regardless of what function it is performing”. Sounds pretty familiar, right? Clearly, in the spotlight of a tremendous number of ICOs failure, at that time blockchain was just in the very beginning of the crossing the chasm curve. With the lack of ready-to-use algorithms, existed projects were stumbling along the way &amp; had shown their inadequacy breeding mistrust from incumbents. On one hand, issues with complexity, increased expenses &amp; limited speed have prevented its way to the mainstream. On the other, at that time there was no an actual path to pave regarding a lack of existed regulations &amp; global uncertainty.</p><p>As the years passed by, the technology matures &amp; is worth taking a look at once again. Obviously, that’s the time when <strong>early adopters</strong> step in. Despite the fact that the paragraph above was likely telling more about blockchain &amp; its adoption curve, large corporations &amp; banks themselves have headed towards other existing forms of DLT. Likely, to bolster adoption, Distributed Ledger Technology starts finding its way into legal frameworks:</p><ul><li><strong>Luxembourg</strong>: On 27 Sep. 2018, the Chambre des Députés published the Draft Law 7363, which states that securities may be registered and transferred using secure electronic registration mechanisms based on DLT. The holding and circulation in DLT can be organised via security tokens.</li><li><strong>UK</strong>: In terms of investigating existing legal frameworks, it varies from a specific case study, falling in a regulatory perimeter (see the spreadsheet below)</li><li><strong>EU</strong>: Prospectus Regulations, coming into force in the middle of summer 2019, will suggest how “security tokens” will be treated among EU countries</li><li><strong>Switzerland</strong>: In the end of December 2018, Swiss leaders approved a technology-friendly legal framework outlining the substantial benefits that DLT could bring</li></ul><p>While we’ve seen how countries’ authorities are paving the way mapping both benefits &amp; risks to existing regulations, it’s not clear how several cryptoassets will be regulated under MiFID II or how miners would be treated under the CSDR in terms of governance and technical requirements.</p><p>In a nutshell, regulators have to react quickly on fast-changing environment ushering in the new era where DLT implementation across several industries is the new reality. There are no concerns about the beneficial impact that it can bring. Best-of-breed solutions may enhance system resilience, improve the efficiency of end-to-end settlement processes and reporting, auditing and oversight enabling greater automation. As a corollary, now is the perfect time achieving product / market fit — for those innovators who stayed afloat &amp; fine-tuned its products according to the market needs.</p><h3><strong>Challenges — and how they are likely to be addressed</strong></h3><p>However, there are still a number of questions remaining unanswered. Being more concrete let’s define the most major ones as the key challenges that are faced by DLT design:</p><p><strong>Privacy: Making transactions private to only the parties within the transaction</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*xIt9mZOXWptUVFGDSwbW6g.jpeg" /><figcaption>Pic taken from <a href="https://docs.corda.net/">https://docs.corda.net/</a></figcaption></figure><p>Transparency — as the key benefit of DLT — raises concerns about privacy in financial services. As it’s quite rare that every party should have access to every piece of data recorded on the platform. Thereby one of the main approaches to consider is where data is not fully distributed amongst all participants in the network.</p><p>Diving into ideological basis, one of the main blockchain attractions is being trustless, meaning that I don’t need to trust you personally to valid the transaction across the network. However, for financial services it can’t be a case in terms of data privacy. To address this issue, Corda (powered by R3 consortium) have made the distributed ledger where transactions are visible only for those entries within the group. <strong>You have to be a known identity</strong>! While being not fully distributed, Corda enables business to make transactions without central authority.</p><p>In the end of 2018, R3 has launched Corda Settler — the universal application to facilitate global payments. It uses XRP (Ripple) as a cryptographic conformation for settlement &amp; it allows participants to issue payment requests and settle them on the Corda network.</p><p>In the end of the January, SWIFT, the global banking payment network, has announced the integration with R3 working collaboratively on DLT Trial.</p><p>With the eye towards success, it helps increasing traceability of its cross-border payments through its GPI service in comparison with what we have today — where typical international payments take three to five working days to complete.</p><p><strong>Performance &amp; Scalability</strong>: <strong>Directed Acyclic Graph DLTs as a disruptive alternative</strong></p><p>This issue stands for the need to scale the time it takes to proceed individual transactions with the computational power added to the network. Another aspect of scalability is that, with the system becoming more popular, it shouldn’t dramatically increase the storage load placed on users of the system.</p><p>In this case, nodes form a chain of transaction — a “branch”. Compared to blockchain, any new transaction must approve two previous transactions. The longer the transaction history of the branch, the more “trusted” it is. If you like to dive more deeply into word “directed”, you should consider reading this article where the technology <a href="https://medium.com/fantomfoundation/an-introduction-to-dags-and-how-they-differ-from-blockchains-a6f703462090">is explained</a> in simple english.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*kauIEO1j2UY5v2SuruqVxA.png" /></figure><p>Emerge as the twin pillars, DAG-based solutions have started entering the fintech market. For example, COTI has launched the world’s first blockchain protocol optimized for payments and stable coins addressing the main issue of scalability &amp; transaction costs. Where throughput is massively increased, enthusiasts claim to be able to surpass the 10,000 transactions per second (TPS) benchmark, suggesting that one day they could even reach Visa’s 25,000TPS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NB4Pfms10aAXXj9Svo3xtw.png" /></figure><p><strong>Security: hardware protection in consideration of potential fraud</strong></p><p>As most of you know, DLTs wallets are protected with public / private keys cryptography — this raises a bunch of concerns, whether it’s that reliable for use in daily life. What’s more, in the analytical report of BIS, they put on the table the question, if with time passing by future technological advancements may render cryptographic tools less effective &amp; secure. As a corollary, while speaking about “security concerns” we bear in mind both:</p><ul><li><strong>Unreliability of private keys</strong> as if the key is either stolen or accidentally, the cybercroop may get a full access to your finance</li><li><strong>Repercussion for the security</strong> of system itself &amp; assets that it manages</li></ul><p>The most obvious risk that consumers can face — <strong>theft</strong> right from the device. As it’s almost impossible to keep in mind #050357%95379398 cryptographic keys, vulnerability lies in the human habits — how keys are stored &amp; used across the network. To guard against these bias, there are some initial advices like not storing keys in .doc files on laptop or install any anti-viruses across all the devices. However, from my point of view, they are not that applicable &amp; leave opportunities for hacking.</p><p>On the contrary, I would like to point out more on a <strong>hardware protection</strong> that has been recently released. Yeah, you got it right — Samsung <a href="https://www.theverge.com/2019/2/25/18233131/samsung-galaxy-s10-bitcoin-cryptocurrency-wallet-features">has just announced Samsung Galaxy S10</a> with crypto wallet supporting built-in options for digital assets protection. How does it work? It’s said that the new built-in chip is added with PUF technology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*dBUT9w2QUPvJoBN1g49i7g.jpeg" /><figcaption>Pic is taken from topnews.one/ release</figcaption></figure><p>The key idea behind PUFs is the variations that occurs naturally during the manufacturing process. Therefore every chip can have a unique number based on hardware circuits. Therefore while making consensus using PUF-enabled network, you don’t need to make any verification using third parties’ nodes from the network. As you may guess, these unique keys &amp; elimination the need of the transaction being sent to the blockchain deliver truly safe p2p experience.</p><p>Let’s say you want to send money to your friend, who doesn’t own the smartphone with PUF-based chip yet. In essence, this would be done like any normal blockchain transactions happen today: the transaction would be sent to the network and would be recorded on a public ledger available for anyone to see.</p><p><strong>Interoperability: addressing the dissimilarity of siloed payment systems</strong></p><p>Imagine, you meet a guy — at first glance, you really like him, thereby you would like to know him better. Apparently, both of you speak different languages, so there is no way to get to each other without the involvement of third party. The first thing that comes to mind — let’s ask google to do it for us. It helps, but not for long. Indeed, there should be a seamless communication between you two.</p><p>Metaphorically speaking, this is the whole idea behind the “interoperability” issue — any attempts to directly transfer money from your bank to digital wallet will turn out to be that hard (in many cases, impossible) that you will soon give it up.</p><p>Thereby it’s important to develop an approach that sits between DLT systems enabling them to communicate effectively. To overcome this issue, <a href="https://www.accenture.com/t20181022T205253Z__w__/cz-en/_acnmedia/PDF-88/Accenture-20180514-Blockchain-Interoperability-POV.pdf">Accenture has come with the “connecting node”</a> eliminating back-and-forth messaging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIrDW3JCOSusArd5LGLJMQ.png" /><figcaption>Pic taken from Accenture’s “Connecting ecosystems: blockchain integration”</figcaption></figure><p>To cooperate effectively, DLT ecosystems have to come up with the integration protocol, wherein they agree upon business rules, policies &amp; standards.</p><p><em>If something appears unclear to you, just lmk so I’ll shed more light on it in the future posts :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ad570be8f1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>