Lesson 7 · PCA & friends
⏱ 57 min read
Why reduce the dimensionality of the data at all, if you can simply use every feature?
Imagine you need to teach a computer to estimate a person's physical characteristics. There is height, weight, chest circumference, waist circumference, leg length and several dozen more measurements.
It would seem that the more data you give the model, the better: every extra feature may carry useful information.
But there is a nuance. Some features tell you almost the same thing. For example, height and leg length are related, and the circumferences of different body parts can together reflect the general build of a person. Perhaps you do not need all the original measurements separately in order to describe the main differences between people.
What if you replace several similar features with a small number of new ones that preserve most of the structure of the data? That is exactly the problem PCA (Principal Component Analysis) helps to solve.
PCA looks for directions in the data along which the spread is greatest, and lets you represent objects by their coordinates along the chosen directions. If a few such coordinates are enough, you can move to a lower-dimensional representation.
But one thing is worth agreeing on right away: PCA cannot determine which information is truly important for any possible task. In the standard formulation it preserves the directions with the greatest variance — that is, the greatest spread of the data. And spread does not always coincide with usefulness for prediction.
In this lecture we will go step by step through why the method works exactly this way, where matrices and eigenvectors come from, how PCA and SVD are related, and how to check the result with numbers.
1. Why dimensionality reduction is needed
1.1. What an object and a feature are
Let us start with the table you already know from machine learning. Suppose we collect data about people:
| Object | Height, cm | Weight, kg | Chest circumference, cm |
|---|---|---|---|
| A | 160 | 52 | 84 |
| B | 170 | 65 | 92 |
| C | 180 | 78 | 100 |
| D | 190 | 90 | 108 |
Here:
- Object (sample) — one row of the table, for example a particular person.
- Feature — a characteristic that describes an object, for example height.
- Dataset — the whole table.
This table has four objects and three features.
These are different things: the number of objects shows how many observations we collected, while the number of features shows how many characteristics we measure for each observation.
If we measure every person by 100 characteristics, we have 100 features regardless of whether we collected data about four people or about a million.
1.2. What dimensionality means
In machine learning, the dimensionality of data often means the number of features that describe an object. A single object can be written as a set of numbers:
This is a vector of three coordinates. Each coordinate corresponds to one feature.
In our example the dimensionality of the feature space is three. Mathematically, the object is represented by a point in three-dimensional space.
If every object has 100 features, we speak of a 100-dimensional feature space. If it has 768, of a 768-dimensional one. Such spaces are hard to picture with your eyes, but mathematically you can work with them.
There is a small terminological subtlety: in linear algebra the dimension of a space is a more general concept. In this lecture, when we talk about the dimensionality of data, we will mean the number of features unless stated otherwise.
1.3. Why many features can be a problem
A large number of features is not a drawback in itself. For example, a detailed description of an image may indeed require thousands of values.
Problems appear in several situations.
The first is redundancy. Two or more features may contain similar information. Height and leg length are not identical, but they can be related. If features are strongly correlated, part of the structure of the data can be described more compactly.
The second is the complexity of analysis. Plotting an ordinary graph of the relationship between two features is easy. Seeing the structure of data with 500 features on a single graph is much harder.
The third is computational cost. Some algorithms have to perform more operations as the number of features grows. For example, the distance between two objects is computed over all coordinates, so, all else being equal, increasing their number raises the cost of the computation.
The fourth is the difficulty of training. Depending on the algorithm, the amount of data and the nature of the features, high dimensionality can make it harder to estimate patterns and can increase the risk of overfitting.
This does not mean that a large number of features is always bad or that reducing it always helps. It all depends on the task.
1.4. What dimensionality reduction is
Dimensionality reduction is a transformation of the data in which objects are represented by fewer coordinates than before. For example:
The objects do not disappear: we still describe the same observations, but we use a more compact representation. There are two fundamentally different approaches.
- Feature selection: we keep some of the original columns and delete the rest.
- Feature extraction: we create new characteristics out of the original ones. PCA belongs to this approach.
For example, instead of separate measurements of height, leg length and arm length, PCA can construct a new direction that is a combination of these characteristics. The value of the new feature will depend on several original measurements at once.
That is why PCA is not just a way to delete unnecessary columns. It changes the coordinate system in which we describe objects.
2. What it means to preserve information
Suppose every object is described by two numbers: \(x_1\) and \(x_2\).
We want to replace these two numbers with one. This is possible if we project the object onto a chosen direction. But a single number in the general case does not allow us to reconstruct the two original numbers uniquely.
For example, the points \((2,0)\), \((0,2)\) and \((1,1)\) may give the same projection onto certain directions, even though they differ in the original space.
So when we reduce dimensionality, we usually lose part of the information about the exact position of the objects.
2.1. What exactly PCA tries to preserve
PCA chooses directions so that the first components preserve as large a share of the variance of the data as possible. Here variance is a numerical measure of the spread of values. We will look at it in detail a little later.
For now the following intuition is enough: if the points differ strongly along some direction, the coordinate along it helps to distinguish objects. If all the points are almost the same in some direction, the coordinate along it may add little information about the differences between observations.
PCA gives preference to the first direction.
There is, however, an important limitation. Imagine we have medical data and the target variable is the presence of a rare disease. A feature that hardly changes for most people but helps to detect this disease may have a small variance. PCA does not know that we want to predict the disease, and it does not guarantee that this feature will be preserved as a separate useful signal.
So we need to distinguish between:
- preserving variance — the main goal of standard PCA;
- preserving information for a specific prediction — a different task, which requires taking into account the target variable or the quality of the subsequent model.
2.2. The trade-off between dimensionality and accuracy
Suppose the original data has 100 features.
- If you keep 100 components, you can preserve the entire linear representation of the original centred data.
- If you keep 50 components, the representation becomes more compact, but part of the information is lost.
- If you keep only 2 components, the data is convenient to visualise, but the losses may turn out to be significant.
So we are looking for a trade-off between compactness and accuracy of the representation.
An important question for this lecture: how do you choose the directions and understand how many of them are enough? To answer it, we first need to look at the geometry of the data, variance and projections.
3. The geometry of data and feature space
To understand PCA we need a geometric picture of the data. The good news is that we already know almost everything we need from school geometry; we will simply use it in machine learning.
3.1. Features as the coordinates of a point
Let us take two features: height and weight. Every person can be represented by a point on a plane:
- the horizontal axis is height;
- the vertical axis is weight.
A person 170 cm tall and weighing 65 kg corresponds to the point \((170,65)\). If there are many objects, a cloud of points (point cloud) appears on the plane.
The cloud can look different:
- almost round — the spread is roughly the same in all directions;
- elongated along the diagonal — one type of change is often accompanied by another;
- elongated vertically — the spread along the vertical axis is much greater;
- lying almost on a line — the points are strongly related to each other.
The last case is especially interesting for PCA.
3.2. Two features, but almost one line
Consider the data:
| Object | \(x_1\) | \(x_2\) |
|---|---|---|
| A | 1 | 2 |
| B | 2 | 4 |
| C | 3 | 6 |
| D | 4 | 8 |
Here the second feature is always twice the first:
The points lie on one straight line. Although every object is described by two numbers, knowing the first number is enough to distinguish these objects: the second can be recovered by the formula.
This is an idealised case of complete linear dependence.
In real data the equality is usually not so exact. For example, weight and height are related, but two people of the same height can have different weights. Then the cloud of points will not be a line but an elongated strip.
The main idea: if the points are concentrated around some line, perhaps their essential differences can be described by a single coordinate along that line.
That is exactly the question PCA asks: which direction describes the spread of the data best? But before looking for a direction, we need to learn to measure spread with a number.
4. Variance — the basis of PCA intuition
4.1. What spread is
Suppose we measured the grades of two groups of students. The first group:
The second group:
Both groups have a mean grade of 5. But the data differs: in the first group the grades are close to the mean, in the second they are noticeably further from it.
So the mean alone is not enough to describe the data. We need a measure that shows how far the values are spread around the mean.
This measure is called variance.
4.2. The mean
The arithmetic mean is the sum of the values divided by their number. If the values are denoted \(x_1,x_2,\ldots,x_n\), then:
Let us go through the symbols:
- \(x_i\) — an individual value with the index \(i\);
- \(n\) — the number of values;
- \(\sum\) — the summation sign;
- \(\bar{x}\) — the mean value.
For example, for the set \((2,4,6)\):
4.3. Deviation from the mean
A deviation shows how much an individual value differs from the mean:
For the set \((2,4,6)\) with mean 4:
| Value \(x_i\) | Mean \(\bar{x}\) | Deviation |
|---|---|---|
| 2 | 4 | −2 |
| 4 | 4 | 0 |
| 6 | 4 | +2 |
Why can we not simply average the deviations? Because negative and positive numbers cancel each other out:
This would happen for almost any set if we count deviations from its mean. That is why deviations are squared.
4.4. Why deviations are squared
Squaring makes negative values positive:
Besides that, squaring gives more weight to large deviations: the square of a deviation of 4 is 16, while the square of a deviation of 2 is only 4.
Now we can average the squared deviations.
4.5. The variance formula
For a complete set of observations (a population), variance is computed like this:
Here:
- \(\sigma^2\) — the variance;
- \(n\) — the number of observations;
- \(x_i\) — an individual value;
- \(\mu\) — the population mean;
- \(x_i-\mu\) — the deviation from the mean;
- the square of the deviation — its non-negative magnitude;
- the sum of squares is divided by the number of observations.
For a sample, the following estimate of variance is often used:
Here the denominator is \(n-1\) rather than \(n\). This correction is used for an unbiased estimate of the population variance under the standard assumptions about a random sample.
In PCA you may encounter both conventions for normalising the covariance. If the factor is the same for all components, the directions of the principal components do not change, although the numerical values of the variances do.
4.6. Computing variance by hand
Take the set:
Step 1. Find the mean:
Step 2. Find the deviations:
Step 3. Square the deviations:
Step 4. Add up the squares:
Step 5. Divide by the number of observations:
This is the variance if we treat the three numbers as the complete set of observations. If we were computing the sample variance, we would get:
Both quantities describe the spread, but they use different normalisation rules.
4.7. Why PCA looks for maximum variance
Let us go back to the cloud of points.
Imagine we drew several straight lines through its centre and projected all the points onto each line. For every line we can compute the variance of the resulting coordinates.
- If the projections are close to each other, the variance is small.
- If the projections are spread widely along the line, the variance is large.
PCA chooses the direction on which the variance of the projections is maximal. This direction is called the first principal component.
But a large variance does not mean that a feature is causally important, and it does not guarantee that the feature is more useful for predicting the target variable. PCA assesses the geometry of the spread, not cause-and-effect relationships.
5. What a principal component is
5.1. A direction in space
In two-dimensional space you can specify a direction with a vector. For example:
This vector points horizontally: the first coordinate is 1, the second is 0. Another example:
It points in the vertical direction. And the vector
defines a diagonal direction.
A vector is an ordered set of numbers that can be interpreted as the coordinates of a point or, in a suitable context, as a direction and a length.
For PCA, directions are usually given by unit vectors — vectors of length 1. This lets you compare directions without mixing the direction with the length of the vector.
5.2. The first principal component
The first principal component (First Principal Component, PC1) is the direction along which the projections of the centred data have the maximum possible variance among all unit directions.
An important formulation: it is a direction, and not necessarily an original feature. For example, if the original features were height \(x_1\) and weight \(x_2\), the first component can look like this:
This means that the new direction combines both features. The coefficients show how much each original feature contributes to the construction of the direction.
For a unit vector the following holds:
So the length of the vector is indeed 1.
5.3. A direction and a coordinate are not the same thing
Two concepts need to be distinguished. The first is the direction of the component. It is a vector shared by the whole dataset, for example \(v_1=(0.8,0.6)\).
The second is the value of the component for an object. It is a number showing the position of a particular object along that direction.
For example, one person's PC1 coordinate may be −2 and another's +3. The direction itself stays the same. In other words, PCA first finds a system of new axes and then expresses every object in the coordinates of that system.
5.4. The second and subsequent components
After the first component, PCA can find the second one:
- it is perpendicular to the first;
- among the directions satisfying this condition, it maximises the variance of the projections.
Perpendicularity in linear algebra is called orthogonality.
In two-dimensional space the second component will be perpendicular to the first. In a higher-dimensional space the following mutually orthogonal directions are constructed in the same way.
The components are ordered by decreasing explained variance:
Here \(\lambda_i\) is an eigenvalue, which we will examine in detail later. It shows the variance along the corresponding component under the standard formulation of PCA with a consistent normalisation.
The first component explains no less variance than the second, the second no less than the third, and so on.
6. Projecting the data onto a new direction
6.1. What a projection means
Imagine a point on a sheet of paper and a straight line drawn across the sheet. If you drop a perpendicular from the point onto the line, you get its orthogonal projection.
When projecting onto a line, a two-dimensional point is replaced by a single number — the coordinate along that line. That is exactly how PCA turns two original features into one new coordinate.
6.2. The dot product
To compute a projection you need the dot product. For two vectors of the same dimensionality we multiply the corresponding coordinates and add up the results.
For example:
Their dot product:
The symbol \(v^\top\) means transposition: a column turns into a row. So the multiplication \(x^\top v\), in the standard notation of the dot product, can be read as the sum of the products of the coordinates. In the PCA formulas we use the equivalent notation \(x^\top v\), where \(x\) and \(v\) are columns.
6.3. The projection formula in PCA
For a centred object \(x\) and a unit direction vector \(v\), the projection coordinate is:
Here:
- \(x\) — the vector of the original object after centering;
- \(v\) — the unit vector of the component's direction;
- \(x^\top v\) — the dot product;
- \(z\) — a single number, the coordinate of the object along the chosen direction.
Why does it produce one number? Because the dot product of two vectors of the same length returns a scalar — an ordinary number, not a new vector.
Why is it a coordinate along the direction? Because for a unit \(v\) the dot product measures the signed length of the projection onto that axis: the sign shows the side relative to the centre, and the absolute value shows the distance along the axis.
6.4. A numerical example
Let a centred object have the coordinates:
And let the chosen direction be:
We have already computed:
So the original object was described by two coordinates, 3 and 4. After projection onto the chosen direction it is described by a single coordinate, 4.8.
That is dimensionality reduction from two to one.
At the same time we lose the information about the position of the object in the direction perpendicular to the chosen axis. If two objects differ only in the coordinate along the lost direction, their values after projection may coincide.
That is why PCA with one component gives a compressed representation but usually does not allow you to reconstruct all the original coordinates exactly.
7. How PCA reduces dimensionality: the general algorithm
Now let us assemble the geometric ideas into a sequence of actions.
Step 1. Prepare the table
Let \(X\) be the data matrix in which the rows correspond to objects and the columns to features. If we have 100 objects and 5 features, the size of the matrix is:
The symbol \(\mathbb{R}\) denotes the set of real numbers. The notation says that the matrix has 100 rows and 5 columns.
Step 2. Centre the features
For each column we compute the mean and subtract it from all the values of that column. In this way we move the origin to the centre of the data. We will look at this in detail in the next section.
Step 3. Scale the features if necessary
If the features are measured in substantially different units or have very different scales, we decide whether they need to be standardised. This is not a mandatory step for absolutely every task.
Step 4. Find the principal directions
PCA determines the directions along which the projections of the data have the greatest variance. For this you can use the covariance matrix and its eigenvectors, or the singular value decomposition of the original centred matrix.
These computational approaches are related mathematically. We will examine them further.
Step 5. Order the components
The components are arranged by decreasing variance: first the most variable direction, then the next one, and so on.
Step 6. Choose the number of components
If there are 100 original features, you can keep, for example, 10 components. The choice depends on what share of the variance we want to preserve and on the task for which we are preparing the data.
Step 7. Project the objects
Every object is transformed into the coordinates of the chosen components. Instead of 100 original values we get 10 new ones. If we denote the matrix of the chosen directions by \(V_k\), the transformation can be written as:
Here \(X_{\text{centered}}\) is the centred data matrix, \(V_k\) is the matrix of the \(k\) chosen directions, and \(Z\) is the new feature matrix.
If the original matrix has size \(100\times100\) and \(V_k\) has size \(100\times10\), then the result \(Z\) has size \(100\times10\).
So we keep the same number of objects, but each object is described by fewer coordinates.
PCA and feature removal — what is the difference?
With ordinary column removal we, for example, keep height and weight and delete chest circumference. No new features appear.
With PCA the new features are linear combinations of the original ones. A component may include all 100 original features, even though the final representation will contain only one number.
This makes it possible to describe directions of joint change compactly, but it can make interpretation harder: the value of the new component no longer has such a simple unit of measurement as kilograms or centimetres.
8. Centering the data
8.1. What centering is
Centering is subtracting the mean value of a feature from every value of that feature. The formula:
Here:
- \(x_i\) — the original value;
- \(\bar{x}\) — the mean value of the feature;
- \(x_i^{\text{centered}}\) — the value after centering.
Suppose we measured the height of three people:
The mean is:
Subtract 170 from every value:
| Original height | After centering |
|---|---|
| 160 | −10 |
| 170 | 0 |
| 180 | +10 |
The mean of the centred values:
After centering, the mean of every feature is zero up to possible computational error.
8.2. Why it matters for PCA
Classical PCA analyses the spread relative to the centre of the data.
Imagine that all the points lie near the coordinates \((1000,1000)\), but the distances between them are very small. If the data is not centred, an analysis based on ordinary dot products and matrix decomposition may mix the information about the offset of the cloud from the origin with its internal structure.
Centering lets you study exactly the variation around the mean.
For classical PCA via the covariance matrix, centering is a standard part of the procedure.
8.3. Centering is not the same as normalization
Centering changes the position of the data relative to the origin, but it does not change the scale of the spread. For example:
The distances between the values stay the same: 10 units between neighbouring values.
With standardization we not only subtract the mean but also divide by the standard deviation. That changes the scale.
So let us remember:
- Centering: subtract the mean.
- Scaling: change the scale of the values.
- Standardization: subtract the mean and divide by the standard deviation.
9. Feature scaling
This topic is related to Lecture 5 on metric methods. There we discussed that distances can depend on the units in which features are measured. In PCA, scale matters as well.
9.1. Why units of measurement matter
Suppose we analyse two features:
- height in millimetres, roughly from 1500 to 2000;
- weight in kilograms, roughly from 40 to 120.
Even if both features are important in substance, their numerical scales differ.
PCA looks for directions with a large variance. If one feature has a much larger variance because of its unit of measurement, it may influence the result more strongly.
For example, a height of 1.7 metres and a height of 170 centimetres describe the same physical quantity. But the variance of the numerical values in centimetres will be \(100^2=10000\) times greater than the variance in metres. So when analysing the covariance matrix, the result may change if you change the units of one feature without changing the units of the others.
9.2. Standardization
One common way to prepare the data is standardization:
Here:
- \(x\) — the original value;
- \(\mu\) — the mean of the feature;
- \(\sigma\) — the standard deviation of the feature;
- \(x'\) — the standardized value.
The standard deviation is the square root of the variance. It is measured in the same units as the original feature. Consider the values:
The mean is 170. If, for the sake of the example, we use the population standard deviation, then:
Let us standardize the values:
We get approximately:
After such standardization the mean is zero, and the variance, under the chosen convention, is one.
In real libraries, for example with the default settings of StandardScaler in scikit-learn, scaling is usually based on an estimate of the standard deviation from the data, and the details of the normalisation are determined by the implementation.
9.3. When to standardize before PCA
Standardization is often appropriate if:
- the features are measured in different units;
- we want every feature to start the analysis from a comparable scale;
- the absolute magnitudes of the variances should not by themselves determine the priority of a feature.
But it is not always mandatory.
If all the features are measured in the same units and the absolute spread is meaningful, keeping the original scales may be preferable. Standardization can reduce the influence of genuinely important large changes.
A practical rule: centering is a standard part of classical PCA; standardization is a decision that depends on the meaning and the scale of the features.
10. Covariance and the covariance matrix
We have already learned to measure the spread of a single feature with variance. Now the next question arises: how do we measure whether two features change together?
For example, when a person's height is above average, their weight is often above average too. But that is not always the case. We need a way to describe the general tendency.
10.1. What covariance is
Covariance is a measure of how two features deviate from their means together. Suppose there are two features \(X\) and \(Y\).
For each object we compute:
That is, we multiply the deviation of the first feature from its mean by the deviation of the second feature from its mean. Three cases are possible.
- Positive covariance: the features often deviate from their means in the same direction. When the first is above its mean, the second is often above its own too.
- Negative covariance: the features often deviate in opposite directions. When the first is above its mean, the second is more often below its own.
- Covariance near zero: there may be no pronounced linear joint variability.
The last case requires caution: zero covariance does not mean that the features are not related in any way. A non-linear relationship may exist between them.
10.2. The covariance formula
For a complete population:
Here:
- \(n\) — the number of objects;
- \(x_i,y_i\) — the values of the two features for object \(i\);
- \(\mu_X,\mu_Y\) — the means of these features.
For a sample estimate the denominator \(n-1\) is usually used instead of \(n\). Let us look at a small example.
| Object | \(X\) | \(Y\) |
|---|---|---|
| A | 1 | 2 |
| B | 2 | 4 |
| C | 3 | 6 |
The means:
The deviations of the first feature:
The deviations of the second:
We multiply the corresponding deviations:
The sum is 4. Therefore the population covariance is:
It is positive: the features in this set change in the same direction.
10.3. How covariance differs from correlation
Covariance depends on the units of measurement. If height is recorded in centimetres and then converted to millimetres, the numerical value of the covariance changes.
Correlation is a normalised measure of linear association, which usually takes values from −1 to +1. For non-zero standard deviations:
Here \(\sigma_X\) and \(\sigma_Y\) are the standard deviations of the features. Dividing by the product of the standard deviations removes the dependence on the units of measurement.
At the same time, correlation does not establish a cause-and-effect relationship either. It describes a linear association.
10.4. The covariance matrix
When there are many features, it is not enough to store individual values of variances and covariances. It is more convenient to gather them into a single table of numbers — the covariance matrix.
For two centred features it has the form:
The main diagonal holds the variances of the individual features. Off the diagonal are the covariances between pairs of features.
In our example:
Dividing by \(n=3\):
Consequently:
This matrix compactly describes the spread of the two features and their linear joint variability.
Why is it needed for PCA? Because from the covariance matrix you can find the directions along which the variance of the projections is maximal. For that we will need eigenvectors and eigenvalues.
11. Eigenvectors and eigenvalues
This is the central mathematical section. Let us go through it slowly: first we will understand the matrix transformation on its own, and then connect it to PCA.
11.1. What a matrix does to a vector
A matrix is a rectangular table of numbers that can be used to define linear transformations. For example:
Suppose we have a vector:
Let us multiply the matrix by the vector:
Multiplying each row of the matrix by the vector gives:
The original vector \((1,1)\) has turned into \((2,3)\). Its direction has changed. But consider another vector:
Then:
The direction has not changed: the result is simply twice as long as the original vector. This special property is exactly what we need.
11.2. The formal definition
A non-zero vector \(v\) is called an eigenvector of the matrix \(A\) if, when multiplied by \(A\), the result is a scalar multiple of it:
Here:
- \(A\) — a square matrix;
- \(v\) — a non-zero eigenvector;
- \(\lambda\) — the corresponding eigenvalue;
- \(Av\) — the result of multiplying the matrix by the vector;
- \(\lambda v\) — the vector \(v\) multiplied by the number \(\lambda\).
An eigenvector keeps its direction up to a sign, and the eigenvalue shows the coefficient of change. If \(\lambda=2\), the vector is stretched by a factor of two.
If \(\lambda=1\), it stays unchanged. If \(\lambda=0\), it turns into the zero vector.
If \(\lambda<0\), the direction is reversed, and the length changes according to the absolute value of the eigenvalue.
11.3. Checking an eigenvector directly
Take the matrix:
And the vector:
The multiplication:
Now let us compare with:
We got \(Av=2v\). The equality holds, so \(v\) is an eigenvector and \(\lambda=2\) is the corresponding eigenvalue. Similarly:
The vector \((0,1)\) is also an eigenvector, but its eigenvalue is 3.
11.4. How this relates to PCA
Now let us go back to the covariance matrix.
It describes the variances of the features and their covariances. But we want to know in which directions the spread of the data is maximal.
It turns out that, for the covariance matrix, the eigenvectors define the principal directions of PCA, and the corresponding eigenvalues show the variance along these directions under the standard normalisation.
The covariance matrix has important properties:
- it is symmetric;
- its eigenvalues are non-negative;
- its eigenvectors can be chosen mutually orthogonal.
This lets us build a system of mutually perpendicular axes along which the data has successively decreasing variance.
11.5. Why an eigenvalue is related to variance
Let \(C\) be the covariance matrix of the centred data and \(v\) a unit direction. The variance of the projections onto this direction can be written as:
Here the notation \(Xv\) denotes the column of projection coordinates of all objects onto the direction \(v\), and the expression \(v^\top C v\) is the numerical value of the variance of the projections under a consistent normalisation.
If \(v\) is an eigenvector of the matrix \(C\), then:
Let us substitute this into the expression for the variance:
Since \(\lambda\) is a number, it can be taken outside:
The vector \(v\) is a unit vector, so \(v^\top v=1\). Consequently:
We have obtained an important result: the variance of the projections onto a unit eigenvector of the covariance matrix is equal to the corresponding eigenvalue.
Now it becomes clear why PCA sorts the eigenvalues in decreasing order: the largest eigenvalue corresponds to the direction with the maximum variance, that is, to the first principal component.
12. How PCA is formulated mathematically
Now that we have gone through variance, projection, the covariance matrix and eigenvectors, we can state the PCA problem more precisely.
12.1. The optimisation formulation
The first principal component looks for a unit vector \(v\) that maximises the variance of the projections of the centred data:
Let us decode the notation:
- \(\max\) means "find the maximum possible value";
- \(v\) — the direction we are looking for;
- \(C\) — the covariance matrix;
- \(v^\top C v\) — the variance of the projections onto the direction \(v\);
- \(\lVert v \rVert = 1\) means that the length of the vector is one.
Why restrict the length of the vector? Without this constraint one could increase the length of \(v\) arbitrarily, and with it the expression \(v^\top C v\). Then we would be maximising not the quality of the direction but its scale. This is a standard constrained optimization problem.
12.2. Why the solution is related to an eigenvector
For a symmetric covariance matrix, the solution of this problem is given by the eigenvector corresponding to the largest eigenvalue.
So we do not use eigenvectors merely because they are convenient for computation. They mathematically describe the optimal directions of variance.
The following components are found in the same way, but with additional constraints: every new direction must be orthogonal to the components already chosen.
12.3. Three levels of understanding PCA
| Level | What you need to understand |
|---|---|
| Geometric | Find the directions along which the cloud of points is stretched the most |
| Mathematical | Maximise the variance of the projections subject to constraints on length and orthogonality |
| Computational | Find the eigenvectors of the covariance matrix or apply SVD |
These are three descriptions of one idea, not three different algorithms.
13. Explained variance: how much variance the components preserve
Now we know that the eigenvalues show the variance along the principal components. We can use them to assess how well the chosen components represent the data.
13.1. The share of explained variance
Let the eigenvalues be:
The total variance is the sum:
The share of variance explained by component \(i\):
Here:
- \(r_i\) — the share of explained variance of an individual component;
- \(\lambda_i\) — the eigenvalue of that component;
- \(\sum_j\lambda_j\) — the sum of the eigenvalues of all components.
In our example:
It turns out that the first component explains 60% of the total variance, the second 30%, and the third 10%.
In this context "explains" means that the corresponding share of the total variance falls on this direction. It does not mean that the component explains 60% of the causes of what is happening or 60% of the prediction accuracy.
13.2. The cumulative share of explained variance
If we keep only the first component, we preserve 60% of the variance. If we keep the first two:
If we keep all three, we preserve 100% of the variance in this linear representation. The cumulative share of explained variance is the sum of the shares of the first \(k\) components:
Here \(k\) is the number of chosen components and \(p\) is the total number of components. In the example:
| Number of components | Cumulative share |
|---|---|
| 1 | 60% |
| 2 | 90% |
| 3 | 100% |
13.3. How to choose the number of components
In practice you can set a guideline: for example, preserve at least 90% of the total variance. In our example two components are enough. If you choose a threshold of 95%, you will have to keep all three.
But 90% and 95% are not universal laws. Sometimes two components are kept for visualisation even if they explain only 60% of the variance. Sometimes, for preprocessing before a model, it is important to preserve a higher share. The decision depends on the goal.
There is another important point: even 95% of explained variance does not guarantee that we have preserved 95% of the useful information for classification or regression. These concepts are not equivalent.
14. What SVD is and how it relates to PCA
14.1. Why decompose a matrix
Until now we looked at the data through the covariance matrix. But there is another way to find the principal directions — to work directly with the data matrix.
For this, SVD (Singular Value Decomposition) is used.
The idea is this: the data matrix can be represented as the product of several matrices, each of which describes a certain part of the transformation.
The general form:
Here:
- \(X\) — the original data matrix, usually centred for PCA;
- \(U\) — the matrix of left singular vectors;
- \(\Sigma\) — the diagonal matrix of singular values;
- \(V^\top\) — the transposed matrix of right singular vectors.
Instead of studying all the properties of these matrices, let us focus on what matters for PCA.
14.2. What singular values give
Singular values show how pronounced the corresponding directions are in the data.
The larger the singular value, the greater the spread of the data along the corresponding principal direction, provided the data matrix is centred beforehand and the standard connection with PCA is used.
For a centred matrix \(X\) containing \(n\) objects, the covariance matrix under sample normalisation is:
If the singular value decomposition has the form:
then the eigenvalues of the covariance matrix are related to the singular values by the formula:
Here:
- \(s_i\) — the \(i\)-th singular value;
- \(\lambda_i\) — the corresponding eigenvalue of the covariance matrix;
- \(n\) — the number of objects.
Why is the singular value squared? Because the covariance matrix contains the product \(X^\top X\), and when SVD is substituted into that product the singular values enter squared.
If normalisation by \(n\) is used instead of the sample covariance, the formula changes:
So the normalising factor depends on the definition of the covariance matrix.
14.3. Why SVD is used for PCA
SVD makes it possible to compute the principal directions directly from the centred data matrix. There is no need to build the covariance matrix first.
This is especially useful for large or high-dimensional data: explicitly building the covariance matrix can be expensive when the number of features is large.
Besides that, numerical SVD algorithms often have good stability properties. Let us remember the main points:
- the eigenvectors of the covariance matrix define the directions of PCA;
- the right singular vectors of the centred data matrix define the same principal directions;
- the squares of the singular values are related to the variances of the components;
- SVD is a common computational way to obtain PCA.
Eigenvalues and singular values should not be treated as one and the same. They are related, but they belong to different matrix decompositions.
15. A numerical example of PCA from start to finish
Now let us bring the theory together on a small dataset where all the computations can be checked by hand. Take four objects with two features:
| Object | \(x_1\) | \(x_2\) |
|---|---|---|
| A | 1 | 2 |
| B | 2 | 4 |
| C | 3 | 6 |
| D | 4 | 8 |
The second feature is twice the first. Therefore all the points lie on the line \(x_2=2x_1\).
This is a deliberately chosen, idealised example in which the first principal component can be computed without cumbersome algebra.
Step 1. Find the mean of each feature
For the first column:
For the second:
Step 2. Centre the data
Subtract the mean of each column:
| Object | \(x_1-\bar{x}_1\) | \(x_2-\bar{x}_2\) |
|---|---|---|
| A | −1.5 | −3 |
| B | −0.5 | −1 |
| C | +0.5 | +1 |
| D | +1.5 | +3 |
Now the mean of each column is zero.
Note that centering did not change the shape of the cloud. The points still lie on one line; the centre of the data is simply at the origin now.
Step 3. Is standardization needed?
In this example the second feature is exactly twice the first. Both columns describe the same linear structure at different scales.
We can perform PCA without standardization. To demonstrate the connection between variance and the covariance matrix, we will keep the original scale.
In a real task the decision about standardization depends on the units of measurement and the meaning of the features.
Step 4. Compute the covariance matrix
For simplicity we use division by \(n=4\). The variance of the first feature:
The variance of the second feature:
The covariance:
We get:
Step 5. Find the first principal direction
In this example you can see that the second feature is always twice the first. The direction of the line can be given by the vector:
But for PCA it is more convenient to use a unit vector. The length of this vector is:
So let us normalise it:
Let us check that this is an eigenvector of the covariance matrix.
The first coordinate:
The second coordinate:
Consequently:
We have checked the equality directly:
So \(v_1\) is an eigenvector, and the corresponding eigenvalue is:
This is the first principal component.
Step 6. Find the second component
In two-dimensional space the direction perpendicular to the first component can be given by the vector:
Let us check orthogonality:
The dot product is zero, so the directions are perpendicular. Multiplying the covariance matrix by this vector gives the zero vector:
Therefore:
This matches our geometric picture: all the points lie exactly on one line, so there is no spread perpendicular to that line.
Step 7. Compute the share of explained variance
The sum of the eigenvalues:
The first component explains:
The second:
In this artificial example the first component preserves 100% of the variance. In real data this is rare, because clouds of points usually do not lie exactly on one line.
Step 8. Project the objects onto the first component
For every centred point we compute:
For object A with centred coordinates \((-1.5,-3)\):
For object B:
For object C:
For object D:
The result:
| Object | Original features | PC1 coordinate |
|---|---|---|
| A | (1, 2) | −3.354 |
| B | (2, 4) | −1.118 |
| C | (3, 6) | +1.118 |
| D | (4, 8) | +3.354 |
We have moved from two features to one.
Step 9. What did we lose?
In this example nothing was lost in the sense of exact linear reconstruction of the original data: the second feature is always twice the first, and all the points lie on the first principal component.
In the general case the data does not lie exactly on one line. Then, after projection, we lose the coordinates perpendicular to the chosen direction, and the original objects cannot be reconstructed without error.
That is why PCA is called a dimensionality reduction method and not a lossless one.
16. Limitations of PCA
PCA is a powerful mathematical tool, but it solves a specific problem. To apply it correctly in ML it is important to understand what it does not do.
16.1. PCA looks for linear directions
Standard PCA looks for straight directions in the feature space. It describes well the structure that can be represented by linear combinations of the original features.
But data can lie along a curve.
Imagine points arranged along a circle. They may have a pronounced structure, but there is no single straight line that describes the whole circle well. PCA will still find the directions with maximum variance, but such a representation may reflect the original geometry poorly.
16.2. Large variance does not mean high predictive value
Suppose we want to predict whether a person will fall ill.
Feature A varies strongly between people but is not related to the illness at all. Feature B is almost the same for most people, yet a small change in B is closely related to the risk of illness.
PCA may prefer the direction associated with A, because it has a larger variance.
This is not an error of PCA. The method was not given information about the target variable and never promised to maximise prediction quality.
16.3. Components can be harder to interpret
The original features often have a clear meaning: age, height, weight, price, time. After PCA a new component may be expressed by a formula:
This is a mathematically correct characteristic, but it is harder to explain to a domain expert, especially if the combination includes hundreds of features.
16.4. The result depends on scale
As we have already discussed, PCA is sensitive to the units of measurement and the scales of the features. The choice between the original scales and standardization can substantially change the directions of the components.
16.5. Outliers can influence the result
An outlier is an observation that differs noticeably from the bulk of the data.
Because PCA uses variance, a distant point can substantially influence the covariance matrix and the direction of the first component.
That is why, before PCA, it is useful to study the distributions of the features and to understand how sensitive the data is to extreme values.
16.6. PCA loses part of the information when the number of components is reduced
If you keep only a few components, part of the spread will not enter the final representation.
Even if the remaining components explain 95% of the variance, that does not guarantee exact reconstruction of the original values, let alone the preservation of 95% of the usefulness for the target task.
16.7. PCA is an unsupervised method
In standard PCA there is no target variable \(y\). The method receives the feature matrix \(X\) and looks for directions that describe its spread.
This approach is called unsupervised learning or an unsupervised transformation of the data.
By contrast, in supervised learning the algorithm uses pairs of "features — target answer" to solve a prediction task.
PCA can be applied as a feature preparation step for a subsequent supervised model. But the PCA transformation itself is not trained to predict the target variable.
17. Where PCA is applied in practice
17.1. Visualising multidimensional data
If every object has 50 features, an ordinary two-dimensional plot cannot show them all at once. PCA lets you obtain a two-dimensional representation: PC1 on the horizontal axis and PC2 on the vertical one.
In this way you can explore the general structure of the data, look for unusual observations and see whether there are visible patterns.
But visualisation through two components may hide differences that lie in the remaining directions.
17.2. Reducing redundancy
If many features are strongly related, PCA can describe a significant part of their joint variation with fewer components.
This is especially useful when the number of original features is large while the effective number of directions along which the data really changes is noticeably smaller.
17.3. Data compression
Instead of storing all the original coordinates, you can store the coordinates of the chosen components.
But there is a nuance: if you need to reconstruct the original data, you will also have to store information about the transformation — the chosen directions and the mean values of the original features. In some tasks this still gives a significant saving in memory.
17.4. Preprocessing before a model
PCA can be applied before some algorithms, for example to reduce the number of features and remove part of the redundancy.
However, it does not always improve quality. For some tasks dimensionality reduction helps; for others it removes a useful signal. The result should be checked on held-out data or in a correct cross-validation procedure, and the quality of the final model should be assessed with the chosen metric.
If PCA is used in a supervised model, it must be trained only on the training part of the data inside the corresponding pipeline. Otherwise there is a risk of data leakage.
17.5. Exploring embeddings
An embedding is a vector representation of an object, for example a text or an image. Imagine that every text corresponds to a vector of 768 numbers. We can apply PCA in order to:
- see how these vectors are distributed;
- obtain a two-dimensional representation for visualisation;
- explore the major directions of variation;
- reduce dimensionality before some further processing steps.
At the same time, PCA does not create semantic meaning out of nothing and does not guarantee that all semantic differences will survive the dimensionality reduction.
18. PCA, feature selection and other dimensionality reduction methods
Let us examine three concepts that are easy to confuse in an interview.
| Approach | What it does | What you get |
|---|---|---|
| Feature selection | Keeps part of the original features | A subset of the original columns |
| Feature extraction | Creates new characteristics out of the original ones | New columns obtained by transformation |
| PCA | Builds orthogonal linear combinations of the original features | New features ordered by explained variance |
| Random projection | Projects the data onto a randomly chosen low-dimensional subspace | A compact representation without searching for maximum variance |
PCA belongs to feature extraction, not to feature selection.
Why? Because the first component does not have to coincide with any single original column. It can use many features at once.
Random projection is an additional approach that in some tasks makes it possible to reduce dimensionality without computing the principal components. But it does not look for the directions of maximum variance, so it does not replace PCA in meaning. PCA does not coincide with clustering either: the former changes the coordinate system, the latter splits objects into groups.
19. Practice in the interactive lab
Three actions for this lecture: look at the data, change the representation, explain the result.
-
Look at the data — open "PCA in 3D: the axis of most variance" and rotate the cloud of points with your mouse. You can see that the data is stretched not along the feature axes but along its own direction.
-
Change the representation — in the same place, move the projection axis slider and press "N — find the best axis": the spread of the projections grows, and the HUD shows what share of the variance is explained. Switch the dataset — linear correlation, almost a sphere, two clusters — and compare how the best axis behaves.
-
Explain the result — open "Embeddings, PCA and k-means" and "Polynomial degree: overfitting". The first shows the division of objects into groups — a different task, not a change of coordinate system. The second shows how the choice of model complexity changes the result — the same logic as when choosing the number of components.
Check yourself
20. Typical mistakes and misconceptions
| Misconception | How to reason correctly |
|---|---|
| "PCA simply selects the most important original features" | PCA builds new features — linear combinations of the original ones. It does not have to select individual columns. |
| "The first component is the most important original feature" | The first component is the direction with the maximum variance of the projections. It is not necessarily a separate original feature and not necessarily the most useful one for prediction. |
| "Large variance means high predictive value" | Variance shows spread. It does not directly measure the relationship with the target variable. |
| "Standardization is always mandatory before PCA" | Centering is a standard step of classical PCA, while standardization depends on the scale and meaning of the features. |
| "PCA preserves the information completely" | Dimensionality reduction usually loses part of the information. Exact reconstruction is possible in special cases, for example when the data lies in the chosen subspace. |
| "Eigenvectors are the new feature values" | Eigenvectors define the directions of the components. The new values for objects are obtained after projection onto those directions. |
| "An eigenvalue and a singular value are the same thing" | They are different quantities. For a centred data matrix, the square of a singular value divided by the chosen normalising factor gives the corresponding eigenvalue of the covariance matrix. |
| "PCA and k-means solve the same problem" | PCA transforms the feature space. k-means groups objects by distances in that space. |
| "Model quality will definitely improve after PCA" | It may improve, get worse or hardly change at all. The result depends on the data, the algorithm and the task. |
| "The more components, the better the result" | More components preserve more variance but reduce the degree of compression. The optimal choice depends on the goal, not only on the number of components kept. |
21. ML interview questions
Below are questions with detailed answers. We will pay special attention to those where you need not only to reproduce a definition but also to explain why the method works the way it does.
Basic level
1. What is PCA and what is it for?
PCA is a dimensionality reduction method that builds new mutually orthogonal features as linear combinations of the original ones. The components are ordered by decreasing variance of the projections. The method is used for compression, visualisation and studying the structure of data.
2. What is a principal component?
It is a direction in the feature space. The first component maximises the variance of the projections of the centred data. The value of the component for a particular object is the coordinate of its projection onto that direction.
3. Why does PCA reduce dimensionality?
Instead of all the original coordinates, you can keep only the first \(k\) components. If they describe most of the variance, the representation becomes more compact at the cost of a relatively small loss of information about the linear structure of the data.
4. Does PCA select original features or create new ones?
It creates new ones. Each component is a linear combination of the original features.
Intermediate level
5. Why does PCA usually centre the data?
Centering moves the origin to the mean of the data. Classical PCA must analyse the spread relative to the centre, not mix it with an arbitrary offset of the whole cloud of points.
6. How does centering differ from standardization?
Centering means subtracting the mean. Standardization additionally divides the result by the standard deviation, so the scale of the feature changes.
7. What is the explained variance ratio?
It is the share of the total variance that falls on a component. It is computed as the ratio of its eigenvalue to the sum of the eigenvalues of all components.
8. How do you choose the number of components?
One approach is to choose the smallest number of components that reaches a given threshold of the cumulative explained variance ratio. But the threshold depends on the task, and it should be verified with the subsequent use of the data in mind.
9. Why are the PCA components orthogonal?
For classical PCA the covariance matrix is symmetric. Its eigenvectors can be chosen mutually orthogonal. Geometrically, this makes it possible to describe the data along directions that are independent in terms of the linear covariance structure.
Advanced level
10. Why do the eigenvectors of the covariance matrix define the principal components?
The variance of the projections onto a unit vector \(v\) is expressed as \(v^\top Cv\). Maximising this quantity subject to the constraint \(\lVert v \rVert = 1\) leads to the eigenvector with the largest eigenvalue. The eigenvalue itself equals the variance along the direction found.
11. How is PCA related to SVD?
For a centred data matrix \(X\), we have \(C=X^\top X/(n-1)\) under sample normalisation. If \(X=U\Sigma V^\top\), the columns of \(V\) define the principal directions, and the squares of the singular values divided by \(n-1\) give the eigenvalues of the covariance matrix.
12. Why can SVD be preferable to explicitly building the covariance matrix?
SVD lets you work directly with the data matrix and does not require forming \(X^\top X\) first. For some matrix sizes this is cheaper in terms of memory and computation, and it can also provide better numerical stability.
13. Can PCA make classification quality worse?
Yes. PCA does not use the class labels and preserves the directions with large variance. A direction with small variance may be useful for separating classes, and after the corresponding component is removed the classification quality can get worse.
14. What does a zero eigenvalue mean in PCA?
It means that the variance along the corresponding principal direction is zero. In the ideal case this indicates a linear dependence or redundancy of the coordinates: the data does not change along that direction.
At an interview it is especially important to explain questions 9–13 confidently. They test not knowledge of names but an understanding of the logic of the method.
22. Practice tasks
First try to solve the tasks on your own. They are arranged from simple to more difficult. The solutions are given separately below.
Tasks for independent work
Try to do the calculations on paper first. You can tick off the tasks you have completed.
1. Dimensionality of the space
The table has 250 objects and 12 features. What is the dimensionality of the feature space? What happens to the dimensionality if only 4 PCA components are kept?
2. Mean and variance
For the values \(2,4,6\), find the mean and the variance, treating them as a complete population. Then compute the sample variance.
3. Centering
Centre the feature \(10,12,14,16\). What is the mean after centering?
4. Standardization
Explain the difference between centering and standardization. If the mean is 10, the standard deviation is 2, and the value of the feature is 14, what is the standardized value?
5. Covariance
Consider the pairs of values: \((1,2),(2,4),(3,6)\). What is the sign of the covariance? Compute it with division by \(n\).
6. Checking an eigenvector
Given the matrix \(A=\begin{pmatrix}2&0\\0&3\end{pmatrix}\) and the vector \(v=\begin{pmatrix}1\\0\end{pmatrix}\). Check whether \(v\) is an eigenvector and find the eigenvalue.
7. The meaning of eigenvalues
A PCA has eigenvalues equal to 8, 2 and 0. What can you say about the variance along the components?
8. Explained variance ratio
The eigenvalues are 5, 3 and 2. Compute the share of variance of each component.
9. Choosing components
The eigenvalues are 7, 2 and 1. How many components must be kept to preserve at least 90% of the variance?
10. Projection
An object has centred coordinates \((3,4)\), and the direction is given by the unit vector \((0.8,0.6)\). Find the projection coordinate. Explain what is lost when moving from two coordinates to one.
Show detailed solutions
1. The dimensionality of the feature space equals the number of features, that is, 12. The number of objects does not affect the dimensionality. After PCA with four components every object is described by four coordinates, so the dimensionality of the representation becomes 4, while the number of objects stays the same — 250.
2. The mean: \(\bar{x}=\frac{2+4+6}{3}=4\). The deviations: \(-2,0,+2\), their squares: \(4,0,4\). The population variance: \(\sigma^2=\frac{4+0+4}{3}=\frac{8}{3}\approx2.67\). The sample variance uses the denominator \(n-1\): \(s^2=\frac{8}{2}=4\).
3. The mean of the original feature: \(\frac{10+12+14+16}{4}=13\). After centering we get \(10-13=-3\), \(12-13=-1\), \(14-13=+1\), \(16-13=+3\), that is, \((-3,-1,+1,+3)\). The mean of the centred values is zero.
4. Centering only subtracts the mean and does not change the scale of the spread. Standardization subtracts the mean and divides by the standard deviation. For \(x=14\), \(\mu=10\), \(\sigma=2\): \(x'=\frac{14-10}{2}=2\).
5. The means: \(\bar{x}=2\), \(\bar{y}=4\). The deviations of the first feature: \((-1,0,1)\), of the second: \((-2,0,2)\). The products: \(2,0,2\), and their sum is 4. The covariance with division by \(n=3\): \(\operatorname{Cov}(X,Y)=\frac{4}{3}\approx1.33\). It is positive: the features change in the same direction.
6. We multiply the matrix by the vector: \(Av=\begin{pmatrix}2\cdot1+0\cdot0\\0\cdot1+3\cdot0\end{pmatrix}=\begin{pmatrix}2\\0\end{pmatrix}\). On the other hand, \(2v=\begin{pmatrix}2\\0\end{pmatrix}\). The equality \(Av=2v\) holds, so \(v\) is an eigenvector and the eigenvalue is \(\lambda=2\).
7. The eigenvalues are equal to the variances along the corresponding principal directions: 8, 2 and 0. The total variance is 10. A zero value means that there is no spread along the third direction — the data does not change along it, that is, the coordinates are linearly dependent or redundant.
8. The sum of the eigenvalues: \(5+3+2=10\). The shares: \(r_1=\frac{5}{10}=0.5\), \(r_2=\frac{3}{10}=0.3\), \(r_3=\frac{2}{10}=0.2\). That is 50%, 30% and 20% respectively.
9. The sum of the eigenvalues: \(7+2+1=10\). One component explains \(7/10=70\%\), which is less than 90%. Two components explain \((7+2)/10=90\%\), exactly the threshold. So two components must be kept.
10. The projection coordinate: \(z=3\cdot0.8+4\cdot0.6=2.4+2.4=4.8\). When moving from two coordinates to one, the component perpendicular to the chosen direction is lost: objects that differed only in it may get the same coordinate after projection.
23. The final map of the topic
23.1. The logical chain of PCA
-
Initial data
Matrix of objects and features \(X\)
-
Centering
Subtract the mean of each feature
-
Scaling, if necessary
Take the units of measurement and the scales into account
-
Analysis of the spread
Covariance matrix or SVD
-
Principal directions
Eigenvectors or right singular vectors
-
Choosing the number of components
Eigenvalues and the explained variance ratio
-
Projection
The new representation \(Z=X_{\text{centered}}V_k\)
23.2. Where mathematics and SVD sit in this chain
- The covariance matrix describes the variances of individual features and the covariances between them.
- The eigenvectors of the covariance matrix define the principal directions.
- The eigenvalues show the variance along the corresponding directions.
- SVD makes it possible to find the principal directions directly from the matrix of centred data.
- The projection translates the original coordinates into the coordinates of the chosen components.
- The explained variance ratio helps to estimate how much variance is preserved when a given number of components is chosen.
23.3. A short summary for revision
PCA is a dimensionality reduction method that builds new features as linear combinations of the original ones.
The first principal component defines the direction of maximum variance of the projections of the centred data. Subsequent components are orthogonal to the previous ones and are arranged by decreasing variance.
Centering is subtracting the mean of each feature. Standardization is subtracting the mean and then dividing by the standard deviation.
The covariance matrix describes the spread and the joint changes of the features. Its eigenvectors define the directions of PCA, and its eigenvalues determine the variance along them.
SVD is an alternative computational way to obtain the principal directions directly from the data matrix. The squares of the singular values are related to the eigenvalues of the covariance matrix.
The explained variance ratio is the share of the total variance that falls on a component. The cumulative share helps to choose the number of components.
PCA does not use the target variable in the standard formulation, does not guarantee an improvement of the model, and does not necessarily preserve the features that are most useful for prediction.
23.4. The main PCA formulas
| Concept | Formula | Meaning |
|---|---|---|
| Mean | \(\bar{x}=\frac1n\sum_i x_i\) | The centre of the values |
| Population variance | \(\sigma^2=\frac1n\sum_i(x_i-\mu)^2\) | Spread relative to the mean |
| Centering | \(x_i'=x_i-\bar{x}\) | Moving the mean to zero |
| Standardization | \(x_i'=\frac{x_i-\mu}{\sigma}\) | Mean 0, standard deviation 1 |
| Projection | \(z=x^\top v\) | The coordinate along a direction |
| Eigenvector | \(Av=\lambda v\) | A special direction of the matrix |
| Share of variance | \(r_i=\frac{\lambda_i}{\sum_j\lambda_j}\) | The share of variance of a component |
| Cumulative share | \(R_k=\frac{\sum_{i=1}^k\lambda_i}{\sum_{j=1}^p\lambda_j}\) | The share of the first \(k\) components |
| Covariance matrix | \(C=\frac{X^\top X}{n-1}\) | For a centred matrix \(X\) and sample normalisation |
| SVD | \(X=U\Sigma V^\top\) | Singular value decomposition of a matrix |
| The link between SVD and PCA | \(\lambda_i=\frac{s_i^2}{n-1}\) | Under sample normalisation of the covariance |
The formulas use the following notation:
- \(n\) — the number of objects;
- \(p\) — the number of original features;
- \(k\) — the number of components kept;
- \(x_i\) — an individual value of a feature;
- \(\mu,\bar{x}\) — the mean;
- \(\sigma\) — the standard deviation;
- \(v\) — a direction vector;
- \(A,C\) — matrices;
- \(\lambda_i\) — an eigenvalue;
- \(s_i\) — a singular value;
- \(X\) — the data matrix;
- \(Z\) — the data matrix after projection.
23.5. Glossary of terms
| Term | Simple explanation |
|---|---|
| Dimensionality reduction | Representing data with fewer coordinates |
| Principal Component Analysis (PCA) | Searching for the directions of maximum variance |
| Principal component | A direction in the feature space |
| Feature | A characteristic of an object |
| Sample / observation | One row of the dataset |
| Variance | A measure of spread |
| Covariance | A measure of the joint change of two features |
| Covariance matrix | A matrix of variances and covariances |
| Projection | Representing a point by a coordinate along a direction |
| Eigenvector | A vector whose direction is preserved when it is transformed by a matrix |
| Eigenvalue | The coefficient of change of an eigenvector |
| Singular Value Decomposition (SVD) | Representing a matrix as a product of other matrices |
| Singular value | A quantity characterising the corresponding direction of the decomposition |
| Explained variance | The variance attributed to a component |
| Explained variance ratio | The share of the total variance that falls on one component |
| Cumulative explained variance | The total share of the first few components |
| Centering | Subtracting the mean |
| Standardization | Subtracting the mean and dividing by the standard deviation |
| Feature selection | Selecting part of the original columns |
| Feature extraction | Creating new features out of the original ones |
| Orthogonality | Perpendicularity of vectors |
| Outlier | An unusual observation |
| Unsupervised learning | Analysing data without target answers |
| Data leakage | Using information that must not take part in training at a given stage |
23.6. One-page cheat sheet
Goal: reduce the number of coordinates while preserving the largest possible share of the variance.
The main idea: a cloud of points can be stretched along several directions. PCA finds those directions and lets you describe objects by their coordinates along them.
The order of actions:
- Prepare the matrix of objects and features.
- Centre the features.
- Standardize if necessary.
- Find the principal directions through the covariance matrix or SVD.
- Order the components by variance.
- Choose the number of components.
- Project the data onto the chosen directions.
Four key formulas:
The coordinate of an object along a unit direction.
The eigenvectors of the covariance matrix define the principal directions, and the eigenvalues correspond to the variances.
The share of the total variance explained by a component.
The SVD of the data matrix; the right singular vectors give the principal directions under the appropriate conditions. Do not confuse:
- The direction of a component is a vector; the value of a component is a number after projection.
- Centering is subtracting the mean; standardization also divides by the standard deviation.
- PCA is a transformation of the data; k-means is clustering.
- Large variance is not a guarantee of usefulness for prediction.
- PCA does not guarantee an improvement of the model.
23.7. What is useful to review before the next lectures
To make the following material easier to absorb, it is worth reviewing five small topics:
- Vectors and matrices. How a vector is arranged, what the size of a matrix means, and how to multiply a matrix by a vector.
- The dot product. Multiplying the corresponding coordinates and adding the results; the connection with projection and with the angle between vectors.
- Variance and covariance. How the spread of one feature differs from the joint change of two features.
- Eigenvectors and eigenvalues. What \(Av=\lambda v\) means and why this equality helps to find the directions of PCA.
- Linear combinations. How a new feature is obtained from several original ones.
There is no need to master all of linear algebra in advance. To understand PCA it is enough to be confident with exactly these foundations; the remaining mathematical details can be studied as the need arises.
A final word: how to check that you have mastered the topic
Try to answer three questions in your own words, without formulas or hints.
- Why does PCA look for the directions of maximum variance instead of simply selecting the features with the largest spread?
- Why does an eigenvalue of the covariance matrix show the variance along the corresponding principal direction?
- Why can the first two components describe the general structure of the data well and yet turn out to be insufficient for predicting the target variable?
If it is still difficult to answer, that is normal. You can go back to the sections on variance, projection and eigenvectors — they form the mathematical core of the whole lecture.
The main thing to take away from this module: PCA does not simply shorten the table of features. It finds a new coordinate system in which the first few directions preserve the largest possible share of the linear spread of the data. It is precisely the connection between geometry, variance and linear algebra that makes this method useful in machine learning.