I Can Compress 1000 Dimensions Into 2 — Here’s What PCA Taught Me
From the publisher’s feed, collected in the ZeroLabs newsroom.
Understand what PCA is, how it works, and how to implement it in Python with a real world example“If you can’t explain it to a six year old, you don’t understand it yourself.”― Albert EinsteinI want to apply the logic of that quote to this article (but six? nah.. let’s say you are sixteen). Principal Component Analysis (PCA) is an important technique in the fields of Machine Learning and statistics. But while learning this topic in my ML journey I found most resources too technical for us beginners.As a result, I wanted to write my own blog combining the best intuitions I could get to explain anyone easily from all these resources. While the intuition using examples and analogies is easy to understand but the algorithm we’ll cover is pretty technical. A basic understanding of linear algebra (matrix multiplication, matrix transposition, matrix inverses, matrix decomposition, eigenvectors, and eigenvalues) along with statistics and machine learning concepts (standardization, variance, covariance, independence, linear regression, and feature selection) will make this article and PCA much easier to follow.WHAT is PCA and WHY we use it?Before understanding PCA, we first must understand what is so called fancy ‘Curse of Dimensionality’ (CoD) in ML and statistics.Different feature spaces via LivebookLet’s take a real world analogy to understand it. Assume, you lost your wallet in three different places or scenarios — on a road, in a playground and in a building. Where do you think you can find your wallet most easily? Yes! on a road. Why? — Because it’s a single dimension and searching is easier when we have to focus in 1D (Which in technical jargon called — less sparsity of data) as we increase the dimensions — to a 2D (Playground) or a 3D (Building) the sparsity increases and the performance of the searching algorithms (for finding relationships) deteriorates due to the exponential increase in the volume of the space and fewer observations per region (called Input/Feature space in ML).Now that you understand the problem with more dimensions, let’s discuss the solution “Dimensionality reduction”. Which unsurprisingly, just a technical word for saying we want to reduce the number of input columns or features without losing the essence of these data which can be achieved by mostly these two classes:Feature SelectionFeature Extraction.As the name suggests, Feature selection is a way of selecting the most important columns or features that is of most importance and dropping the rest. But what if all the columns are of same importance or we don’t have enough domain knowledge to remove a feature directly? Here comes Feature Extraction (which includes PCA). Finally PCA!…PCA stands for Principal Component Analysis. It is a feature extraction technique used for reducing CoD by transforming higher dimensional data to lower dimensional data. The tradeoff is that the resulting features are often “difficult to interpret”.For Feature Extraction using PCA, let’s say we have 10 variables (input columns), we create 10 new variables by combining the original 10 variables. These new variables are then ranked by how much information (variance) they capture from the original dataset, and we keep only the most informative ones. Somewhat unsurprisingly, these new independent variables are combinations of our old ones, we’re still keeping the most valuable parts of our old variables, even when we drop one or more of these “new” variables!AI image generated by Author using ChatGPTOkay… this might be tricky for someone learning about PCA for the first time. So, let’s take an example of a cricket stadium and a camera man who wants to take picture of the game going on, he would need tons of cameras to cover all the angles and every player on the ground. But, what if we could just use single virtual camera set at such a place that covers most informations in a straight line to understand the pitch almost perfectly. If I had to explain in a layman language, this is what PCA does. It takes snapshot of the data in n-dimensions and bring it to a fewer dimensions.In simple terms, PCA is a feature extraction technique that compresses the original features into a new set of “independent features” called principal components. These components are designed to capture most of the important information present in the data. By keeping only the “most informative” components and discarding the “less significant” ones, we can reduce the dimensionality of the dataset without losing much useful information. As an added benefit, each of the “new” variables after PCA are all independent of one another. This is a BONUS, because most ML models work better when input features don’t overlap with each other.Geometric Intuition of PCA and HOW it works?I was repeatedly talking about the “Most Informative data” or “Variance”. Roughly, by variance I meant how much data is spread. For the sake of understanding the importance of spread, we are taking an example of 2D data or two columns containing informationg of different houses — Number_of_Rooms, Number_of_Washrooms and its Price as target/output column. We’ll try to convert this 2D data to 1D:Data visualized by Author using Python MatplotlibWider spread explains more about the data, it is same as taking the image of the cricket game at such an angle that will cover all the players rather than taking from an angle which covers fewer players in the image.We do not have to drop the shadow only onto the X or Y axis. Since we are taking an easy example we got the best shadow on the X axis but, we can drop it at any angle — tilt the axis 30°, 45°, whatever. And some of those tilted angles will give a much longer shadow than the original axes.This is the actual trick PCA plays. It does not touch your data at all. It just rotates the axes like rotating the grid underneath the dots until it finds the angle where the shadow is the longest.Think of it like this: imagine you have a bunch of ants walking diagonally across a table. If you shine a light straight down onto the X-axis, their shadow looks short and bunched up. But if you tilt the light to match the diagonal direction the ants are walking, suddenly the shadow stretches out long and you can see all of them clearly. The ants didn’t move. You just found a better angle to look from.And here’s the cool part, using something called Linear Transformation from Linear Algebra, you can rotate a coordinate system to literally any angle you want. That means there are infinite possible rotated axes, called Principal Components. Each one is at a right angle (orthogonal) to the others, meaning they are completely independent i.e one doesn’t contain any information that the other already has.But we don’t need all of them. Since the whole point is to reduce dimensions, we just pick the one axis that gives the longest shadow — the direction where the data is most spread out.How do we actually find that best direction?We don’t just try every angle randomly. There’s a smart way to find it directly, and that’s where eigenvectors and eigenvalues come in.Here’s the easiest way to think about it:When you rotate or stretch a coordinate system, most arrows (vectors) change both their direction and their length. But there are a few special arrows that are so perfectly aligned with the transformation that they don’t rotate at all, they only get longer or shorter. Those special arrows are called eigenvectors.The amount by which an eigenvector gets stretched is called its eigenvalue.Eigenvector = the directionEigenvalue = how important that direction is (how much spread it captures)A big eigenvalue means the data is very spread out along that direction. A small eigenvalue means not much is happening there. So PCA simply picks the eigenvector with the biggest eigenvalue, that’s the Principal Component we keep.But where do we get these eigenvectors from?Covariance Matrix by Sergen CansizFrom something called the covariance matrix.Don’t let the name scare you. For our house example with 2 features (Number_of_Rooms, Number_of_Washrooms), the covariance matrix is just a 2×2 table that looks like this: Rooms WashroomsRooms [ Var(Rooms) Cov(R, W) ]Washrooms [ Cov(W, R) Var(Washrooms) ]Notice the pattern:The diagonal (top-left, bottom-right) contains the variance of each feature on its own. How much Rooms varies across houses, and how much Washrooms varies across houses. This is exactly the spread we kept talking about.The off-diagonal contains the covariance between the two features. A single number that answers: when a house has more rooms, does it usually also have more washrooms? If yes, covariance is positive. If they go opposite, it’s negative. If they don’t care about each other at all, it’s zero.So the covariance matrix is basically a compact summary containing diagonal that tells you how each feature behaves alone, and off-diagonal tells you how they behave together.Now here’s why this matters for PCA: since the diagonal holds all the variance (spread) information, and PCA wants the direction of maximum spread, the covariance matrix becomes the perfect place to look. We find the eigenvectors of this matrix — and the eigenvector that belongs to the largest eigenvalue points exactly in the direction where the data is spread the most. That becomes your (first) Principal Component. Still confused about how this works mathematically? It involves some higher level maths specially Rayleigh quotient theorem, matrix decomposition, etc. Which is beyond the scope of this article. We don’t need to dive deep into the maths of it for now.The final step — projectionNow that we have this “best direction”, we take every single data point, every house and ask: “if I drop this house’s shadow onto that best direction, where does it land?”That landing spot is one single number. So a house that used to be described by 2 values (Number_of_Rooms, Number_of_Washrooms) now gets just 1 value — its position along the Principal Component.Mathematically it looks like this:Houses (1000 × 2) × Eigenvector (2 × 1) = Transformed Houses (1000 × 1)Read it as: 1000 houses, each described by 2 numbers (rooms and washrooms), multiplied by the best direction, gives you 1000 houses each described by just 1 number.We went from 2D to 1D and we didn’t throw away random stuff. We specifically kept the direction where the shadow was widest — the Number_of_Rooms axis because that’s where the data was most spread out, which means that's where most of the information about Price is hiding. The Number_of_Washrooms axis had a tiny shadow, so dropping it didn't hurt much.That is exactly what PCA does!How to implement it?For the code demo we are taking a new dataset. It contains three features (feature1, feature2 and feature3) for which we’ll try to make this 3D to 2D using PCA.To implement PCA, we follow 4 simple steps:Step 1: Center the data Subtract the mean of each feature from all its values — this shifts the entire data so it’s centered around zero. We do this because PCA measures spread from the center, and if the data is sitting off to one side, the math gets confused about where the actual center of spread is.Step 2: Build the Covariance Matrix Take that centered data and compute the covariance matrix — the 3×3 table (as we have 3 features now) we just discussed that holds variance on the diagonal and covariance off it.Step 3: Find Eigenvectors and Eigenvalues Decompose the covariance matrix to get its eigenvectors (directions) and eigenvalues (how much spread each direction captures). Sort them — biggest eigenvalue first.Step 4: Pick the top Principal Component(s) Take only the eigenvector(s) with the largest eigenvalue(s) — these are your Principal Components. Project your original data onto them and you’re done. 3D becomes 2D.Code Democreate the dataset:import numpy as npimport pandas as pdnp.random.seed(23)mu_vec1 = np.array([0,0,0])cov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])class1_sample = np.random.multivariate_normal( mu_vec1, cov_mat1, 20)df = pd.DataFrame( class1_sample, columns=['feature1', 'feature2', 'feature3'])df['target'] = 1mu_vec2 = np.array([1,1,1])cov_mat2 = np.array([[1,0,0],[0,1,0],[0,0,1]])class2_sample = np.random.multivariate_normal( mu_vec2, cov_mat2, 20)df1 = pd.DataFrame( class2_sample, columns=['feature1', 'feature2', 'feature3'])df1['target'] = 0df = pd.concat([df, df1], ignore_index=True)df = df.sample(40)df.head()| Index | feature1 | feature2 | feature3 | target ||------:|----------:|----------:|----------:|-------:|| 2 | -0.367548 | -1.137460 | -1.322148 | 1 || 34 | 0.177061 | -0.598109 | 1.226512 | 0 || 14 | 0.420623 | 0.411620 | -0.071324 | 1 || 11 | 1.968435 | -0.547788 | -0.679418 | 1 || 12 | -2.506230 | 0.146960 | 0.606195 | 1 |Plot the using plotly in 3D space:import plotly.express as px#y_train_trf = y_train.astype(str)fig = px.scatter_3d(df, x=df['feature1'], y=df['feature2'], z=df[ 'feature3'],color=df['target'].astype('str'))fig.update_traces(marker=dict(size=12, line=dict(width=2, color='DarkSlateGrey')), selector=dict(mode='markers'))fig.show()3D visualization of 3 features using plotly by AuthorFollow the steps:# Step 1 - Apply standard scalingfrom sklearn. preprocessing import StandardScalerscaler = StandardScaler()df.iloc[:,0:3] = scaler.fit_transform(df.iloc[:,0:3])# Step 2 - Find Covariance Matrixcovariance_matrix = np.cov([df.iloc[:,0],df.iloc[:,1],df.iloc[:,2]])print('Covariance Matrix: \n', covariance_matrix)Covariance Matrix: [[1.02564103 0.20478114 0.080118 ] [0.20478114 1.02564103 0.19838882] [0.080118 0.19838882 1.02564103]]# Step 3 - eigenvalues and eigenvectorseigen_values, eigen_vectors = np.linalg.eig(covariance_matrix)eigen_valuesarray([1.3536065 , 0.94557084, 0.77774573])eigen_vectorsarray([[-0.53875915, -0.69363291, 0.47813384], [-0.65608325, -0.01057596, -0.75461442], [-0.52848211, 0.72025103, 0.44938304]])Visualize the Principal Components%pylab inlineimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfrom mpl_toolkits.mplot3d import proj3dfrom matplotlib.patches import FancyArrowPatchclass Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): super().__init__((0,0), (0,0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform( xs3d, ys3d, zs3d, self.axes.get_proj() ) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) super().draw(renderer) def do_3d_projection(self, renderer=None): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform( xs3d, ys3d, zs3d, self.axes.get_proj() ) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) return np.min(zs)fig = plt.figure(figsize=(7,7))ax = fig.add_subplot(111, projection='3d')ax.plot( df['feature1'], df['feature2'], df['feature3'], 'o', markersize=8, color='blue', alpha=0.2)ax.plot( [df['feature1'].mean()], [df['feature2'].mean()], [df['feature3'].mean()], 'o', markersize=10, color='red', alpha=0.5)for v in eigen_vectors.T: a = Arrow3D( [df['feature1'].mean(), v[0]], [df['feature2'].mean(), v[1]], [df['feature3'].mean(), v[2]], mutation_scale=20, lw=3, arrowstyle='-|>', color='black' ) ax.add_artist(a)ax.set_xlabel('x_values')ax.set_ylabel('y_values')ax.set_zlabel('z_values')plt.title('Eigenvectors')plt.show()Visualization of Principal Components by AuthorChoose the top 2 Principal Components — to perform dimensionality reduction from 3D to 2D:pc = eigen_vectors[0:2]pcarray([[-0.53875915, -0.69363291, 0.47813384], [-0.65608325, -0.01057596, -0.75461442]])Transform the data to these Principal Components:transformed_df = np.dot (df.iloc[:,0:3],pc.T)# 10,3 - 3,2new_df = pd.DataFrame(transformed_df, columns=['PC1', 'PC2' ])new_df['target'] = df['target'].valuesnew_df.head()Visualize the new features in 2D:new_df['target'] = new_df['target'].astype('str')fig = px.scatter( x=new_df['PC1'], y=new_df['PC2'], color=new_df['target'], color_discrete_sequence=px.colors.qualitative.G10)fig.update_traces( marker=dict( size=12, line=dict( width=2, color='DarkSlateGrey' ) ), selector=dict(mode='markers'))fig.show()Reduced 3D to 2D visualizationNoticed something? Yesss!… This is the same data we visualized in 3D earlier we just have taken the best image of it that covers the most information and hence reduced the dimensions using PCA.What are SVDs?Hopefully, you understood the intuition and the geometric idea behind PCA. What I did not cover was the computational steps.I said “Compute covariance matrix, find eigenvectors/eigenvalues and somehow we will get the Principal Components using some maths between these things which is beyond this article’s scope!”Here, I must mention that Scikit-learn’s PCA use Singular Value Decompisition (SVD) under the hood but produces the “same result”.Why libraries uses SVDs?Imagine:1 million rows10,000 featuresOur method first creates a covariance matrix:10000×10000SVD works directly on the original matrix without creating covariance matrix and is:fastermore memory efficientnumerically more stableTask: Work on MNIST datasetMNIST images are 28×28 pixels, and each pixel is a feature. So each image is actually nearly 1000 features (or 28 × 28 = 784). PCA can compress that down to 2 dimensions so you can actually plot it on a 2D graph and see the clusters of digits.Obviously those 2 components don’t capture everything, you lose a lot but it’s the classic demo one can use to visualize high-dimensional data. The point isn’t accuracy, it’s showing that PCA can take something insanely large and squish it into something human-readable.I Can Compress 1000 Dimensions Into 2 — Here’s What PCA Taught Me was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.