<?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 Shanya Sharma on Medium]]></title>
        <description><![CDATA[Stories by Shanya Sharma on Medium]]></description>
        <link>https://medium.com/@the_change?source=rss-9f3577f85a30------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BXH7bjGSJ661PbP6.</url>
            <title>Stories by Shanya Sharma on Medium</title>
            <link>https://medium.com/@the_change?source=rss-9f3577f85a30------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:09:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@the_change/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[Linear Algebra is fun, trust me! (Part 1)]]></title>
            <link>https://medium.com/analytics-vidhya/linear-algebra-is-fun-trust-me-part-1-dfab83c2453e?source=rss-9f3577f85a30------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfab83c2453e</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Shanya Sharma]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 14:10:12 GMT</pubDate>
            <atom:updated>2020-01-07T12:51:29.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*vE6x6pNrcb33BJxxUJx3wQ.png" /><figcaption>Source: <a href="https://www.amazon.in/Manga-Guide-Linear-Algebra-Guides/dp/1593274130">The Manga Guide to Linear Algebra</a></figcaption></figure><p>Linear Algebra is one area of Mathematics that is extensively used throughout machine learning especially in the field of deep learning. A good understanding of this area is required for understanding various machine learning and deep learning algorithms.</p><p>There are numerous resources that help build a solid foundation of Linear Algebra and explain the concepts thoroughly. My personal recommendation being <a href="https://ocw.mit.edu/faculty/gilbert-strang/">MIT’s Linear Algebra course by Prof. Gilbert Strang</a> and <a href="https://www.deeplearningbook.org/contents/linear_algebra.html">Chapter 2 of the Deep Learning book</a> by Goodfellow, Bengio and Courville ( I have <strong>summarised the chapter</strong> <a href="https://github.com/thechange/Book-Summaries/blob/master/DeepLearningBook/2.%20Linear%20Algebra..ipynb">here</a>, to make the content more accessible for the reader). <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab">3 blues 1 Brown</a> does an amazing job of explaining the mathematical concepts through visualizations.</p><p>However, even after one is done understanding all the math, it gets difficult to figure out <strong>where and</strong> <strong>how exactly does Linear Algebra fit in implementing real-life applications</strong>? Through this series, I attempt to provide you with enough details to understand some key concepts of Linear Algebra by explaining a bit of (not so rigorous) math along with their use in various applications that we come across very often.</p><p><em>Please note that the implementations I show here are pretty naive and are probably never used in production but will give you an idea of how Linear Algebra is used in real life.</em></p><p>Let’s get started off by covering the following topics:</p><ul><li>Scalars, Vectors, and Matrices</li><li>____ Transpose</li><li>____ Scalar Multiplication</li><li>____ Dot products</li><li>____ Convolution</li></ul><h3>[TL;DR]: Applications covered in the post:</h3><ul><li><strong>Intensity Scaling</strong></li><li><strong>Document Similarity</strong></li><li><strong>Image Blurring/Smoothing</strong></li><li><strong>Detecting blur in images</strong></li></ul><h3>Scalars, Vectors, and Matrices</h3><p>This section covers the basics of scalars, vectors, and matrices, as well as concepts like transpose, dot product, scalar multiplication, etc. If you are already familiar with these, feel free to skip directly to the <strong>applications.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*mYhU4DPggDbLfjsal5bO6w.png" /><figcaption>Visualization of vectors in space</figcaption></figure><p>A <strong>scalar </strong><em>s </em>(usually denoted using lowercase italics) is just a single number in contrast to a <strong>vector</strong> <strong>x </strong>(typically denoted by lowercase names in bold typeface) which is an array of numbers of the same type. We can think of vectors as identifying points in space, with each element giving the coordinate along a diﬀerent axis as shown in the figure(left).</p><p>A <strong>matrix</strong> <strong>A</strong> (denoted by uppercase in bold typeface), on the other hand, is a 2-D array of numbers written as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*gJ-lDgfj4Uqdqp9ijTRF9g.png" /><figcaption>Aᵢⱼ denotes element in the ith row and jth column of the matrix</figcaption></figure><p>An <strong>image</strong>, for example, is a <strong>matrix</strong>, of square <strong>pixels</strong> arranged in columns and rows. Sometimes we might need an array with more than two dimensions. Such objects, in Linear Algebra, are known as <strong>tensors.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*WbLIc4-xIOfHiO2oWzimyA.png" /><figcaption>Source: <a href="https://dev.to/mmithrakumar/scalars-vectors-matrices-and-tensors-with-tensorflow-2-0-1f66">https://dev.to/mmithrakumar/scalars-vectors-matrices-and-tensors-with-tensorflow-2-0-1f66</a></figcaption></figure><p>Let’s now take a look at the operations performed on these objects.</p><h4>Transpose</h4><p>Transposition is one of the most important operations performed on matrices. The transpose <strong>Aᵀ</strong> of a matrix <strong>A </strong>is the matrix obtained when it is flipped across its diagonal (called the <strong>main diagonal</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*GE3R2GRIZuc7wDQZUpCumA.png" /><figcaption>Transpose: (Aᵀ)ᵢⱼ = Aⱼᵢ</figcaption></figure><p>If you consider a vector as a matrix with only one column (or row), its transpose would result in a row vector (or column vector) with one row (or column).</p><h4><strong>Scalar and Matrix Multiplication</strong></h4><p>We can multiply a matrix with a scalar, vector or by another matrix. Each of these operations has its own peculiarities and usage. Let’s look at them one by one.</p><p><strong>Scalar Multiplication:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*BFJ_auCZL_CyU2wPI-lvDw.png" /><figcaption>Scalar multiplication | Source: Khan Academy</figcaption></figure><p>A matrix can be multiplied by a scalar just by multiplying every entry of the matrix with it.</p><p>Now, you must be wondering what good would such a simple operation possibly achieve. Well, one very popular usage of scalar multiplication is <strong>intensity scaling</strong> in images(not to be confused with geometric scaling).</p><p>Given a scaling factor greater than one, intensity scaling will brighten an image and will darken the image if the scalar is less than 1. For instance, the image below has been taken under low lighting conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*ocQTu3T4Y1aCWBg2aBk3mQ.png" /><figcaption>Original Image</figcaption></figure><p>The image is so dark, we can barely see anything. Let’s try multiplying it with a scalar and see how it changes.</p><pre>image = cv2.imread(&#39;image.jpg&#39;)<br>cv2.imshow(&#39;Bright Image&#39;, image*4)  #Scalar multiplication by 4</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*HjTfFiNYyIKvv3nI_rdrsA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*VLYSzTkPUA5nQ-1kG3859g.jpeg" /><figcaption>Image after intensity scaling</figcaption></figure><p>Simply scaling every pixel by a factor of 4, we obtain an image that is much clearer (left). However, we should make sure that the calculated pixel doesn’t exceed the maximum value. For e.g., if we multiply the above image with a factor of 6, we obtain the image on right. If you notice, the top right area is distorted. All the pixels in the original image, which on multiplication by 6 exceed the maximum value ( 255 in this case ), are <strong>wrapped around</strong> from 255 back to 0.</p><p><em>So the next time you use a photo editing app to change the intensity of an image, you know what goes behind the curtains.</em></p><p><strong>Matrix Multiplication</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*-ErFIkI2LKJQk2_yHqyebw.png" /><figcaption>Dot Product | Source: Khan Academy</figcaption></figure><p>One of the most important operations involving matrices is the multiplication of two matrices. For a <strong>matrix product</strong> of matrices <strong>A</strong> and <strong>B, </strong>the number of columns (n) in <strong>A</strong> should be equal to the number of rows (p) in <strong>B</strong>. If <strong>A</strong> is of shape <em>m </em>x<em> n</em> and <strong>B</strong> is of shape <em>p </em>x<em> q</em>, the resulting matrix <strong>C</strong> is of shape <em>m </em>x<em> q.</em></p><p>The product operation can be visualized by the fig. above and is defined by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*p2wnkcN2JvD8FgbkAmL6qQ.png" /></figure><p>The dot product of two vectors <strong><em>x</em></strong><em> </em>and <strong><em>y</em></strong><em> </em>can be written as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*UJicDfLq9Cv4VZLLCxRL7A.png" /><figcaption>Dot Product of two vectors in terms of norms</figcaption></figure><p>where ||<strong><em>x</em></strong> ||₂ and ||<strong><em>y</em></strong>||₂ represent the distance of the vector coordinates from the origin of the vector space (<a href="https://en.wikipedia.org/wiki/Norm_(mathematics)">L₂ norm</a>) and θ represents the angle between them.</p><p>One very famous application of dot products is in calculating <strong>document similarity. </strong>In practice, <strong>cosine similarity</strong> is a similarity metric used to determine how similar two texts/documents are. Say we have two vectors, each representing a sentence. The angle between them (obtained from the dot vector) gives us an idea of their similarity where orthogonality (θ=90<strong>) </strong>means dissimilarity and θ=0 (parallel) indicates that the documents are similar.</p><p>For example, consider the following three sentences:<br>a = “This article is really interesting”<br>b = “The other article is really interesting”<br>c = “This is boring”</p><p>Now we’ll represent each of these sentences as vectors where each element of the vector will indicate the presence of the words across all the three sentences. (This approach is known as <strong>Bag of Words</strong> approach. You can read about some other text-vectorization techniques <a href="https://monkeylearn.com/blog/beginners-guide-text-vectorization/">here</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*fA6xAHzoJQguwZkB0TzYAQ.png" /></figure><p>Let’s see what the similarity comes out to be:</p><pre>def cosine_sim(a, b):<br>    dot_product = np.dot(a, b)<br>    norm_a = np.linalg.norm(a)<br>    norm_b = np.linalg.norm(b)<br>    return dot_product / (norm_a * norm_b)</pre><pre>#Representing sentences as vectors<br>a = np.array([1, 0, 0, 1, 1, 1, 0, 1]) <br>b = np.array([0, 1, 1, 1, 1, 1,  0, 1])<br>c = np.array([1, 0, 0, 1, 0, 0,  1, 0])</pre><pre>#Sentence a and b should be more similar<br>print(cosine_sim(a, b)) # 0.73<br>print(cosine_sim(b, c)) # 0.23<br>print(cosine_sim(a, c)) # 0.23</pre><p>We see that sentences a and b come out to be more similar in comparison to b and c (or a and c) since they have more words in common. No matter how naive this might seem, with some preprocessing, cosine similarity has shown to give great results.</p><p><strong>Convolution</strong></p><p>Convolution is a modification of multiplication operation wherein the elementwise multiplication of two matrices (of the same dimensions) is followed by a sum.</p><p>Convolutions are one of the most critical and fundamental building-blocks in the field of computer vision. In simple words, there is a small matrix (known as a <strong>kernel</strong>) that sits on a big matrix (say, original image) and slides from left-to-right and top-to-bottom while applying convolution at each coordinate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*wvwT9LlHcDfexIiv7fWWxA.gif" /><figcaption>Convolution: Yellow matrix represents the kernel while the green matrix can be considered to be a part of the original image</figcaption></figure><p>While convolution forms the base of the most complex computer vision applications, some basic applications involve blurring, sharpening, edge detection in an image, etc.</p><p>Following is an example of using a <strong>7x7 average blurring kernel</strong> to smooth/blur an image</p><pre>image = cv2.imread(&#39;original.jpg&#39;)<br>blur_filter = np.ones((7, 7), np.float)/(49.0) #kernel</pre><pre><em>#filter2D performs the convolution operation for us<br></em>image_blur = cv2.filter2D(image, -1, blur_filter)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*nO_adlhhjXdX9R8h_zQTkg.png" /><figcaption>Original Image vs Blurred Image</figcaption></figure><p>Have you noticed how photo management apps these days can classify blurred images from non- blurred ones? Interesting isn’t it. As you must have guessed, convolution does the trick for them.</p><p>One of the methods that works quite well is by calculating the <strong>variation of laplacian</strong> (proposed by Pech-Pacheco et al. in their paper <a href="http://optica.csic.es/papers/icpr2k.pdf">Diatom autofocusing in brightfield microscopy: a comparative study</a>). The method can be <strong>implemented in two steps.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*kg6RIJdqdLDlfH_MgOljqg.png" /><figcaption>Laplacian filter</figcaption></figure><ul><li>Convolve the image using a <strong>Laplacian filter</strong></li><li>Take the variance of the response and compare it with a threshold</li></ul><p>OpenCV helps us do this in a <strong>single line of code</strong>. Let’s apply that on the image we used for blurring.</p><pre>             cv2.Laplacian(image, cv2.CV_64F).var()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*4LGPYNoQplvezHweReDOVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*koh08sPS0-HUQr9i3gxcVQ.png" /><figcaption>Images classified according to the blur. <a href="https://github.com/thechange/Blogs/blob/master/Linear%20Algebra%20is%20fun%20Part%201.ipynb">Code</a></figcaption></figure><p>I strongly recommend that you go through <a href="https://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/">this</a> tutorial by <a href="https://www.pyimagesearch.com/">PyImageSearch</a> to understand Blur Detection in detail.</p><h3>Conclusion</h3><p>That’s all for this post. I hope these applications will make Linear Algebra more intriguing to you. I’ll be covering some more concepts like <strong>Basis, SVD </strong>and<strong> Eigen Decomposition</strong> in the posts to come. You can find the <strong>complete</strong> <strong>code</strong> covering all these applications <a href="https://github.com/thechange/Blogs/blob/master/Linear%20Algebra%20is%20fun%20Part%201.ipynb">here</a>.</p><p>Stay tuned for the posts to come!!</p><p>Please feel free to provide feedback and suggestions (and clap if you like it). You can connect with me on <a href="https://www.linkedin.com/in/shanya-sharma-thechange/">Linkedin</a> and <a href="https://twitter.com/evolvedeve">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfab83c2453e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/linear-algebra-is-fun-trust-me-part-1-dfab83c2453e">Linear Algebra is fun, trust me! (Part 1)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principal Component Analysis Explained]]></title>
            <link>https://medium.com/@the_change/principal-component-analysis-explained-560df8832b93?source=rss-9f3577f85a30------2</link>
            <guid isPermaLink="false">https://medium.com/p/560df8832b93</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[apc]]></category>
            <dc:creator><![CDATA[Shanya Sharma]]></dc:creator>
            <pubDate>Wed, 05 Jun 2019 12:44:49 GMT</pubDate>
            <atom:updated>2020-01-01T14:05:38.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dp-3I3tTZoung0yPW0_J7g.png" /></figure><p>This post aims at providing a detailed explanation of <strong>Principal Component Analysis (PCA) </strong>especially to answer how it works. I, basically, am trying to put together What, Why, When and How of the concept.</p><p>While I try to make the explanation as lucid as possible, there are a few concepts, the knowledge of which will help you understand it better: Matrix operation, Linear Algebra (eigenvectors/eigenvalues) and a bit of statistics(standardization, variance, covariance, independence). Note that you don’t need to go through these as a prerequisite for this article. I’d be discussing them in brief whenever required, however, you can go through the links provided for a detailed understanding.</p><h4>But what is the need for PCA?</h4><p>Before delving deep into the details of PCA and how it works, I guess it was better if we knew why we needed it in the first place. So let’s understand this using an example. Say you want to predict the number of slums in a city for 2019 and you have various features to analyze such as population, density, urbanization rate, working population, literacy rate, marginal workers and so on. <strong>To keep it short, let’s imagine that you have too many features to train your model.</strong></p><p>Now, though you have a lot of information to train your model, do you really need all of it? Because many of them will measure related properties and so will be redundant. To say it the other way, how do you figure out which features to keep? Or do you keep all of them and hope that it doesn’t affect the strength of your model? If you’re familiar with the term <strong>curse of dimensionality</strong>, you’d know that a lot of problems arise with a high dimension of data, overfitting being one of them.</p><p>So how do you ensure that you somehow reduce the dimension without losing the important information? Now one way of doing this is keeping only a few important features (say top 5) and eliminate the rest. While this <strong>feature elimination</strong> method does reduce the dimensionality, it doesn’t guarantee to prevent the loss of information.</p><p>This is where Principal Component Analysis comes to save the day. Our superhero for this post, PCA is basically a dimensionality-reduction method which is used to reduce the dimensionality of large data sets. So let’s suppose you’ve 100 features to train your model on. Now not only are you skeptical about using them all because you don’t know how relevant each of them is, but you also have trouble exploring the data and visualizing it because of such a large dimension. Now what PCA will do is create 100 new features. But what’s different this time is that each of the new features is orthogonal to each other, i.e. they’ll be independent of each other and not correlated. They’ll then be arranged in the order of their contribution towards prediction and we’ll keep only the ones that are important and drop the rest.</p><p><strong>But we were following the dropping technique with feature elimination too, weren’t we?</strong> Right, but the new features that PCA created hold the information from the old ones. So unlike the feature elimination method, where we were straight away dropping the features that we found less important, with PCA, we’ll have the most important information from these old features even if we drop the less important “new” features. Don’t worry, you’ll understand it better as we go ahead in the post. For now, let’s just move forward knowing that <strong>PCA helps us transform our old features into new ones in a way that it extracts the most valuable information in the top few features so that we can drop the rest and reduce our dimension as required.</strong></p><h4><strong>Superpower explained</strong></h4><p>We’ve been glorifying PCA for a long time now. So it’s time we understand what goes underneath the hood and how does PCA actually work (basically, the math).</p><p>As the name suggests, Principal Component Analysis helps us calculate the principal components in the data. These components are basically the “new” features that we discussed in the previous section. They are ordered such that the retention of variation present in the original variables decreases as we move down in the order. So, in this way, the 1st principal component retains maximum variation that was present in the original components.</p><p>Now, let’s step by step understand the math behind it. But before that, I’ll quickly go through some mathematical concepts that’ll help you understand the upcoming explanation better.</p><ol><li><strong>Variance: </strong>Variance helps us understand how spread the data set is. The variance (symbolized by <strong>S</strong>²) and standard deviation (the square root of the variance, symbolized by <strong>S</strong>) are the most commonly used measures of spread. Mathematically, it is the average squared deviation from the mean score.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*jeevl0u8GZJBvid1kqxENg.png" /><figcaption>Formula to calculate variance : [ squaring deviation from the mean ÷ number of observations]</figcaption></figure><p>For example, for the numbers 1, 2, and 3 the mean is 2 and the variance is 0.667.</p><pre>              [(1–2)² + (2–2)² + (3–2)²] ÷ 3 = 0.667</pre><p>2<strong>. Covariance: </strong>Covariance helps us understand how much — to what extent — the variables change together. In PCA, it helps us measure how each variable is associated with one another. The formula for calculating covariance is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*QFpzwjcfORAe-Kw_InxIGw.png" /><figcaption>Formula for calculating covariance: [product of deviation from mean ÷ total observations]</figcaption></figure><pre>x: 2.1, 2.4, 3.6(mean = 2.7)<br>y: 8, 10, 12(mean = 10)</pre><pre>[(2.1-2.7)(8-10)+(2.4-2.7)(10-10)+(3.6-2.7)(12-10)]÷(4)= 0.75</pre><p>A positive covariance means X and Y are positively related i.e. as Y increases with an increase in X. Negative covariance depicts the exact opposite relation. zero covariance means X and Y are not related.</p><p>3. <strong>Covariance Matrix: </strong>Covariance matrix Σ, is a d×d matrix where each element represents the covariance between two features. Below is how a covariance matrix is calculated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*2RuhOQyK7pMukPbA.png" /></figure><p>The diagonal elements of this matrix are the variances of the variables, and the off-diagonal elements are the covariances between the variables.</p><p>4. <strong>Eigen Decomposition- Eigen Vectors and Eigen Values: </strong>The eigenvectors and eigenvalues of a covariance (or correlation) matrix represent the “core” of a PCA. Eigenvectors and values exist in pairs: every eigenvector has a corresponding eigenvalue. An eigenvector is basically a direction with eigenvalue as a number, telling us how much variance there is in the data in that direction.</p><blockquote><em>Let </em><strong>A</strong><em> be a square matrix, </em><strong><em>ν</em></strong><em> a vector and </em><strong><em>λ</em></strong><em> a scalar that satisfies </em><strong>A</strong><em>ν</em><strong><em> = λ</em></strong><em>ν, then </em><strong><em>λ</em></strong><em> is called eigenvalue associated with eigenvector </em><strong><em>ν</em></strong><em> of </em><strong>A</strong><em>.</em></blockquote><p>The eigenvector with the highest eigenvalue is therefore considered the principal component. I highly recommend that you go through <a href="http://setosa.io/ev/eigenvectors-and-eigenvalues/">this visualization</a> to have a better understanding. And though numpy has inbuilt functions for eigen-decomposition (that we’ll use for implementation), I recommend you to go through <a href="https://math.mit.edu/~gs/linearalgebra/ila0601.pdf/">this</a>, to understand the mathematical calculation.</p><p>Okay, so now that we’re a bit familiar with the mathematical terms let’s go through the process of obtaining principle components from a raw dataset.</p><ol><li>Before starting, you should have your data organized with m rows and likely n<em>+1</em> columns, where one column corresponds to your target variable (<strong><em>Y</em></strong>) and the rest of the columns denote various independent features(<strong><em>X</em></strong>).</li><li>For each column of matrix <strong><em>X</em></strong> and, subtract the mean of that column from each entry to ensure that each column has a mean of zero.</li><li>Standardize: Since PCA chooses components on the basis of variance, it is important that we standardize the data before doing the analysis. However, you don’t always need to standardize the data. If the scale of all the variables is the same (e.g. all of them give percentage) then applying standardization will not have much effect on data, however, if the scales are different, we need to standardize the data into a matrix <strong><em>Z.</em></strong></li><li>Obtain the covariance matrix. Since we already ensured that each column has a mean of zero (in step 2), we now can calculate the covariance matrix by multiplying the matrix <strong><em>Z</em></strong> with its transpose. (As an exercise, compare this with the formula under the covariance matrix section to validate.)</li><li>Calculate the eigenvectors and their corresponding eigenvalues of the covariance matrix(<strong><em>Z</em></strong>ᵀ<strong><em>Z</em></strong>).</li><li>Sort the eigenvectors by decreasing eigenvalues obtained from the decomposition. For eg. if λ₄ has the highest eigenvalue, 4th eigen vector needs to be placed first (indicating that the 4th eigenvector is the most important of all). We’ll now have a matrix of sorted eigenvectors.</li><li>Multiply the resulting matrix with the standardized matrix <strong><em>Z. </em></strong>This way, our data will be transformed to a new subspace.</li><li>Finally, select the number of features to keep. For visualization, 2–3 features are chosen. Similarly, if you want to maintain 99% of the variance across your data, you can calculate the cumulative variance and keep only the ones that contribute to that 99%.</li></ol><p>And we’re done!</p><p><strong>[TL;DR]: What our superhero PCA does is:</strong></p><p>a. Calculates the association of features to each other (Covariance Matrix)</p><p>b. Once we know the relations between the features, it gives us the directions (eigen vectors) along which the data is spread. Along with that, it also gives the importance of each direction (eigen values)</p><p>We can then transform our data to a subspace by keeping only the vectors that are important and dropping the rest.</p><h4>Just give me the code…</h4><p>Various computing packages provide functions for PCA. However, I have implemented the <a href="https://github.com/thechange/Blogs/blob/master/Principal%20Component%20Analysis.ipynb"><strong>code from scratch</strong></a> if that helps you understand the steps better.</p><p>Hope this made PCA simpler and easier to understand for you. If you find anything wrong or have any other suggestion/feedback, please mention it in the comments. (And clap if you like it!)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=560df8832b93" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>