11 - Principal Component Analysis and Autoencoders
Class: CSCE-421
Notes:
We will use linear algebra only!
Linear Algebra - Matrix multiplication
Matrix times Vector - 2 Ways
/CSCE-421/Ex2/Visual%20Aids/image-43.png)
At first, you learn (Mv1). But when you get used to viewing it as (Mv2), you can understand
Notes:
- If you need to know anything about linear algebra, this is the most important thing to know, matrix and vector multiplication!
Vector times matrix - 2 Ways
/CSCE-421/Ex2/Visual%20Aids/image-44.png)
A row vector
/CSCE-421/Ex2/Visual%20Aids/image-45.png)
The product
Notes:
- Vector matrix multiplication is the linear combination of the rows
- vM2 is basically a scaled version of the rows in B added together
- Linear combination coefficients come from each element in A
Matrix times Matrix - 4 ways
/CSCE-421/Ex2/Visual%20Aids/image-46.png)
Notes:
- MM1 is a natural way, but turns out it is not the most used
- It is typycal row by column approach
- The most important view is MM4
- You take a column vector and multiply it by a row vector, what do you get? a matrix
- You do this for every column and every row and then add the matrices together (they will be of the same size)
- This is kind of like an outer product.
- What can you learn from this approach?
- You take the first column on matrix A, then you take the first row B, you multiply them together to get a matrix
- The only thing that matters is the cross balance
- This doesn't tell you that if you permute the columns, the matrix will be the same
- But if you permute both the columns and row, then your matrices will be the same
- Note this gives rank 1 columns because they are not linearly independent since they are scaled by the same column vector.
- What about MM2?
- You take each column and multiply it with a matrix, a linear combination of columns with the matrix (Matrix - vector multiplication).
- MM3 is just the row way of doing MM2?
Practical Patterns
/CSCE-421/Ex2/Visual%20Aids/image-47.png)
Burn this into your memories and you can see ...
Notes:
- P1: Linear combination of the columns on A.
- Matrix A * Diagonal Matrix D
- Individual elements in the diagonal of the diagonal matrix scale each of the columns of A
- P2: Is the same thing but the diagonal matrix is on the left.
- Only the elements on the diagonal are non-zero so this makes sense
- Note this one is not a linear combination, you are just multiplying the numbers from the diagonal matrix * the rows in matrix B
/CSCE-421/Ex2/Visual%20Aids/image-48.png)
Notes:
- How to interpret P4 (it is the most important one)?
- We can do step by step
- First we use P1' (columns * diagonal) And then you multiply that column matrix to the row matrix
- In practice what is the result? How do I interpret this?
- You still look at the matrix from P1' as a column matrix but with each column multiplied with a number, then we need to multiply each column with each row of the row matrix.
- The diagonal matrix is represented by a sigma sign
- Each of the diagonal elements of these matrix basically scales the outer product of the ith column with the ith row
- We can do step by step
- Why are we talking about this?
- Later on, what we will do is to have a matrix, but we will decompose this matrix into products of matrices, with the one on the center being a diagonal matrix.
- The reason why we view linear algebra this way, is that if you docompose in this way, you can view this decomposition as an outer product (P4)
- The size of this matrix is the same size as the original matrix, but each column are linearly dependent so the rank of this matrix is 1.
- Is a sequence of rank 1 matrices summed together.
- The size of this matrix is the same size as the original matrix, but each column are linearly dependent so the rank of this matrix is 1.
- There is something that is easy but most people do not know.
- In most of these decomposition, they require the diagonal elements to be in non-increasing order?, why is this a requirement?
- Because the order of the matrices does not matter, you can always rearrange in sorted order.
- If the diagonal terms are not in sorted order, you can always rearrange the terms of the sum of matrices at the end
- Other thing is that the result is nonnegative?
- Because if they are negative, you can just flip the sign of the outside.
- You can always split the sign by multiplying a column or a row times a -1
- You either leave the sign in the column or in the row, but not in both
- We always assume that the diagonal terms are always non-negative and in sorted order?
Orthogonal Matrices
(1) An orthogonal matrix is a square matrix whose columns and rows are orthogonal unit vectors, i.e., orthonormal vectors. That is, if a matrix
(2) It leads to
(3) For an orthogonal
(4) Furthermore, suppose
Notes:
- Certain matrices are called orthogonal matrices, these matrices are square matrices (equal number of rows and columns)
- Note that by convention we require orthogonal matrices to have normalized rows and columns (orthonormal vectors)
- If you have a square matrix, it is orthogonal if all columns are orthogonal to each other
- If you take any different columns and you compute the inner product, the inner product is 0.
- Each column needs to be normalized with each row?
- Each column is normalized to have a unit ... then the rows will automatically satisfy the orthogonal requirement
- The requirement is intuitively translated into
- Remember Identity matrix (I) is all elements 0 except by the diagonal elements which are 1.
: are rows, and are columns, its product tells you the columns are normalized : tells you the rows are normalized
- If a matrix is orthogonal the inverse is simply the transpose of that matrix!
- There is something else that is important to talk about:
- If I have an orthogonal matrix
(view it as columns) - it has to be a square matrix - Somehow we will split this into 2 matrices:
, of course and are no longer squared matrices - They are not orthogonal matrices anymore, but they are vey important
- In general when we talk about
, it is a matrix with orthonormal columns. - All the columns are orthonormal to each other and each column is also normalized
- In this case we would have:
- Rows are no longer orthogonal and normalized!
- Rows are no longer orthogonal and normalized!
- If I have an orthogonal matrix
Notes:
- We know that:
- How do I write this in terms of
and ? - You multiply the first part together, and then you multiply the second part together and sum them
- There is an interesting property here (FYIO):
- These two matrices added together equals the Identity matrix
- For these two matrices the sum of the diagonal elements of these matrices is also the Identity matrix
- What would be the rank of these two matrices?
- Is there an upper bound? Yes, the upper-bound is 1.
- The diagonal elements are nonnegative, each of them have to be smaller or equal to 1.
- Note this is not required for this class.
- These two matrices added together equals the Identity matrix
Eigen-Decomposition
Eigen-Decomposition (1)
(1) A square
where
(2) Note that only diagonalizable matrices can be factorized in this way.
(3) If
Notes:
- Definition of eigenvalues & eigenvectoes?
- Matrix has to be a squared matrix
- If you have squared matrix
(n * n) - The eigen values and eigen vectors are:
- note eigen values and eigen vectors are paired to each other.
- We just want it to be a matrix = a matrix
- We want to have a matrix
so that each of its columns can be paired as eigenvectors: - Then we have another matrix, which is a diagonal matrix:
& \lambda_2 & \
& & \lambda_3
\end{array}\right]$$- If you want to multiply each number times the columns, the diagonal matrix has to be on the right and the column matrix on the left:
- If you want to multiply each number times the columns, the diagonal matrix has to be on the right and the column matrix on the left:
- Note that when doing
, we are multiplying the first column of the matrix S times , and so on.
- we can represent this a
- We then can say:
- We are just equaling each column to each other on
- You can assume
is non-singular. and therefore you are able to do:
- This happens since
- If all columns are orthogonal to each other, they are not linear independent
- (orthogonal means they have 90 degree angle), this is a stronger condition
-
S is a symmetric matrix, and in that case
will be an orthogonal matrix (non-singular). Where the inverse becomes the transpose. -
Definition (only works when S is symmetric):
iff (for all ) iff (for all )
-
Remember this only applies for a squared matrix
Question:
- Look at:$$
\boldsymbol{S}=\boldsymbol{Q} \boldsymbol{\Lambda} \boldsymbol{Q}^T .- Then we know the matrix i the middle is a diagonal matrix with eigenvalues
- Since
is symmetric, we can be sure that all the eigenvalues are real numbers (but they still can be + or -) - The dilemma is that:
- somehow in this decomposition, we can somehow manage to make them positive?
- No, because then we will affect transpose
- Why can't you make these to be non-negative?
- Because
and will be the same value, so multiplying them will become the square
- Because
- You are kind of flipping two times
- Therefore you cannot make the eigenvalues (the diagonal elements of the middle matrix) to always be positive.
- Note this is different in singular value decomposition, where
and are different matrices.
- Note this is different in singular value decomposition, where
- somehow in this decomposition, we can somehow manage to make them positive?
Eigen-Decomposition (2)
/CSCE-421/Ex2/Visual%20Aids/image-49.png)
Notes:
- Why is this useful?
- Because each outer product can be view as a projection matrix
- Why are we calling these a projection matrix?
- Because
are all unit vectors - If we take any vector
, the result will equal the projection lens - The projection of
in the direction of will project any vector to will project any vector to - ...
- The projection of
- Because
- As we project to each axis (each
), they will all be orthogonal to each other - If we assume that the
is an identity matrix, we can rewrite in the second form - What this means is that we can recover the original vector
- The last relation means that any of two projections are perpendicular to each other
- They will be aligned to
- They will be aligned to
Checkpoint 1 (eigen-decomposition)
To understand Principal Component Analysis (PCA), we first need to understand the mathematical engine that makes it work: Eigen-Decomposition.
Imagine a matrix as a machine that stretches, squashes, and rotates data vectors. Eigen-decomposition is a way of "taking the machine apart" to reveal its fundamental, underlying structure. It tells us the core directions in which the machine stretches the data, and by exactly how much.
1. The Basic Formula (
(The Directions): This is a square matrix where every single column is an eigenvector of . Think of an eigenvector as a special, fundamental axis. When the matrix acts on its eigenvector, it doesn't knock it off its line or rotate it; it only stretches or shrinks it. (The Scales): This is a diagonal matrix (zeros everywhere except down the main diagonal). The numbers on this diagonal are the eigenvalues. Each eigenvalue corresponds to an eigenvector in and tells you exactly how much the data is stretched or shrunk along that specific axis. : This is simply the inverse of the matrix.
Note: This specific decomposition is only possible for "diagonalizable" square matrices with linearly independent eigenvectors.
2. The Symmetric Magic (
- Orthogonal Eigenvectors: The eigenvectors (the fundamental axes) become perfectly perpendicular (orthogonal) to each other.
- The Inverse Becomes the Transpose: Because the columns of
are orthogonal unit vectors, becomes an "orthogonal matrix". A magical property of orthogonal matrices is that calculating their inverse is as easy as flipping them on their side: .
Because of this, the decomposition formula for symmetric matrices simplifies beautifully to:
3. Positive Semi-Definite (PSD) Matrices Your professor introduces the concept of a Positive Semi-Definite matrix. By definition, a symmetric matrix
- Why does this matter? Because if a symmetric matrix is PSD, it guarantees that all of its eigenvalues are real, non-negative numbers (they cannot be imaginary or negative). As you will see later, covariance matrices are always PSD, meaning their eigenvalues are always positive or zero.
- A warning: In pure eigen-decomposition, if the matrix is not PSD, the eigenvalues (the numbers inside
) can be negative. You cannot arbitrarily flip their signs to make them positive, because flipping the sign inside would mathematically alter the original matrix .
4. Eigen-Decomposition (2): The Projection View Instead of looking at
- What is
? This is the "outer product" of a single eigenvector with itself, which creates a matrix. - The Meaning: This matrix acts as a projection matrix. If you multiply any data point
by this matrix, it acts like a flashlight, projecting a shadow of directly onto the axis defined by . - The Big Picture: This equation tells us that the entire complex matrix
is actually just a combination of independent 1D projections. Each projection onto a fundamental axis ( ) is scaled by its importance ( ) and then added together. This is the exact mechanism PCA uses to reduce dimensions—it simply throws away the projections that have the smallest scaling factors!
Singular Value Decomposition (SVD)
Singular Value Decomposition (1)
/CSCE-421/Ex2/Visual%20Aids/image-50.png)
Notes:
- Using practical pattern 4
- Correspond to first outer product and then the linear combination of them scaled with each diagonal term
- Lets say we have an
matrix , the shape of will be , and the shape of will be - Sigma will also have a shape of
, where only the diagonal elemets are non-zero - But note that
can also be a square matrix
- Sigma will also have a shape of
- This gives a very useful decomposition
- How do we interpret it? Given a matrix
, how do we get , sigma and ? - In order to prove that this decomposition exists what do we need to do?
- We need to learn how to calculate U, how to calculate sigma, and how to calculate V
- These can actually be obtained from eigenvalue decomposition.
Singular Value Decomposition (2)
The singular value decomposition (SVD) of an
where
where
Notes:
-
Note that the elements in the sigma matrix are always non-negative singular values! This is very important
- Typically we will always prefer to order these values
- The number of singular values directly tells you the rank of
-
Exists for any matrix
-
A matrix R can be decomposed into further 3 matrices
and are orthogonal matrices may not be a squared matrix
-
We assume that
has more rows than columns (like a vertical rectangle shape) - -
The upper part of
is what we call the sigma, it is a diagonal matrix, and everything below is 0 - Remember that you can assume this is in sorted order from large to small
- Little sigmas are either positive or zero (they are nonnegative)
- We can always flip the sign in either
or to make it positive - But remember the diagonal elements have to have a negative (for eigenvalues)
- We can always flip the sign in either
- If the rank of the
matrix is , then the first are greater than 0. - The number of positive singular values is the rank of that matrix
-
So the conditions come to be: Square matrix + positive semi-definite + symmetric
- otherwise eigenvalues may not be even real numbers
- otherwise
values would be negative
-
This is called Full SVD
Relation to Eigen-Deconposition
The columns of
It is easy to verify them as we have
and
Notes:
- Note
is an matrix - If we do
, this will give us a square matrix ( ), - then from this we can do an eigen-decomposition to get
- then from this we can do an eigen-decomposition to get
- But we can also do
, which will also give us a square matrix - then from this we can also do an eigen-decomposition to get
- Key properties:
is a symmetrical matrix - It will always have positive eigenvalues
- These properties allows it to be written as
- then from this we can also do an eigen-decomposition to get
- Now to verify this, recall this:
- Note that
will correspond to
- Why is
always properties?
SVD and eigen-decomposition
(1) Under what conditions are SVD and eigen-decomposition the same? First,
(2) The difference between
Compact SVD
By removing zero components, we obtain
where
Notes:
is a product of 3 matrices, we can write this multiplication into some kind of process to take an element/row/column of each one and modularly multiply them - You take
, multiply with , and multipy by . - This makes a matrix
- You continue with
- Then you add every matrix produced
- It is a different way to talk about matrix multiplication
- The lower method is called Compact SVD
- Remember
is basically the upper part of the matrix - This is exactly equivalent to summing each multiplication of
until - So basically in compact SVD we just throw away all rows and columns corresponding to the 0 elements
- Remember
- Now what happens if we do
to where - You still get a matrix but it will not be exactly be equal to
, though it will still have the same size as .
- You still get a matrix but it will not be exactly be equal to
Truncated SVD and Best Low-Rank Approximation
We can also approximate the matrix
Apparently,
where
Notes:
- The
matrix is the best rank- approximation to - See this is very important because for each
we have a matrix, so then we will have matrices added together - This happens element-wise because they have the same size
- What do we know about the rank of the resulting matrix once they are summed?
- When you add a matrix of rank 3 and a matrix of rank 4, the resulting matrix rank cannot be larger than 7, this is guaranteed!
- There is no lower bound though
- In this case the
matrix will have rank
- The most important part is that this matrix is the closest one to the original
- The error is related to the size of
-> size of the sigma that you throw away? - Frobenius norm is basically to take the element-wise difference of the two matrices, and ...
- Remember again that Sigma is sorted from large to small
- You always try to throw away smaller sigmas
- When using
there will always be error, since it is smaller than - In practice (i.e think about images)
- Color images of 500x500x3
- Each location can have 256 different values
- The total number of possible images of this size is
- In reality all the existing images is a tiny fraction of the actual number of possible images
- Intrinsic dimension is quite small even when dimension is large
Checkpoint 2 (SVD)
To understand Singular Value Decomposition (SVD), we must realize that pure eigen-decomposition has a severe limitation: it only works for square matrices. In machine learning, our raw data is almost always a rectangular matrix (e.g.,
1. Singular Value Decomposition & SVD (2) SVD is the ultimate mathematical tool because it exists for any real matrix, no matter its shape. If you have a rectangular data matrix
(Left-Singular Vectors): An orthogonal matrix. (Right-Singular Vectors): An orthogonal matrix. (The Singular Values): A diagonal matrix. Unlike eigenvalues, the numbers on this diagonal (called singular values, ) are strictly non-negative and are always sorted from largest to smallest ( ). - The Rank: The number of strictly positive singular values (
) tells you the exact mathematical rank ( ) of the matrix.
2. Relation to Eigen-Decomposition If
- If we multiply
, we get a square symmetric matrix. The eigenvectors of exactly form the columns of our matrix. - If we multiply
, we get a square symmetric matrix. The eigenvectors of exactly form the columns of our matrix. - Because of how the math cancels out (
), the singular values ( ) are simply the square roots of the eigenvalues ( ) obtained from these squared matrices.
3. SVD and eigen-decomposition When are SVD and eigen-decomposition the exact same thing? Because SVD enforces that all singular values (
4. Compact SVD If the rank (
5. Truncated SVD and Best Low-Rank Approximation Compact SVD throws away exact zeros. But what if we throw away small (but non-zero) singular values to intentionally compress the data? If we stop the summation early at some number
- Why is this amazing? Linear algebra guarantees that this truncated matrix
is the absolute best rank- approximation of the original data matrix . - There is no other rank-
matrix in existence that will give you a smaller reconstruction error (measured by the Frobenius or spectral norms). The error is exactly tied to the values you decided to throw in the trash.
Principal Component Analysis (PCA)
What is PCA?
(1) Principal Component Analysis (PCA) is a statistical procedure that can be used to achieve feature (dimensionality) reduction.
(2) Note, feature reduction is different from feature selection. After feature reduction, we still use all the features, while feature selection selects a subset of features to use.
(3) The goal of PCA is to project the high-dimensional features to a lower-dimensional space with maximal variance and minimum reconstruction error simultaneously.
(9) We derive PCA based on maximizing variance, and then we show the solution also minimizes reconstruction error.
(6) In machine learning, PCA is an unsupervised learning technique, and therefore does not need labels.
Notes:
- The calculation of PCA is simply SVD
- There is a very small difference but important that we need to do
- SVD is unsupervised, so we are only given
(no labels)
PCA to 1D
(1) To introduce PCA, we start from the simple case where PCA projects the features to a 1 -dimensional space.
(2) Formally, suppose we have
(3) Let
(4) PCA aims to solve
(5) Note that the variance of the reduced data is
which means that PCA tries to find the projection with the maximum variance in reduced data.
Notes:
- We have some data points (each is P dimensional) and want to make them shorter dimensional (for example a single number)
- Each of the inputs become a
-dimensional vector - We want each of the input vectors to be a shorter vector while still keeping most of the information
- What information to keep? we will talk about it
- Lets say we want to reduce each of the long inputs (
) to 1 dimension (the simplest one) - Come up with an
(unknown for now), then what we want to do is to compute the inner product: - This is basically a reduced (low-dimensional) representation of
- By using this
, we basically reduced to a number - If that
is applied to every you get a set of values, which are just 1D single values
- This is basically a reduced (low-dimensional) representation of
- This is already basically PCA
- Now we need to talk about how to compute
- What kind of
's are intuitively good? - Lets say you r data is 2-dimensional (p=2), and you want to reduce to 1D
needs to project this data into a 1D space - It needs to project data in some direction
- i.e. if you project in the x axis you lose a coordinate
- What about a diagonal? some differences disappear, points on top of each other diagonally will become a single point
- This is exactly what PCA tries to do!
- You can compute the variance to check that the spread is large
- So our job is to pick
that takes advantage of a maximum variance - "Compute
so that the reduced data has maximum variance"
- "Compute
- It needs to project data in some direction
- How to do it?
- We have each of the
's are computed using , so that each of them have maximum awareness is the mean of - PCA will try to arg max the variance (basically maximize the variance)
- We want to compute variance so that it is as large as possible?
- We have each of the
- PCA is an unsupervised dimensional thing
PCA to 1D (process)
Since
the problem can be written as
where
Notes:
- Lets start from
, the mean of the numbers - We know that each
is - We know that
is actually not changing so we can move it out of the summation - Instead, first produce the mean of the original data (
) and then multiply by - This basically shows that the operation is linear
- At this point we know
- Then we actually calculate and try to maximize the variance using arg max
- Then we substitute our
and by their representations in terms of is basically a number, and when we do we want to write it twice - This is a number being squared (it multiplies by itself)
- We can write it as
- Then we can apply the summation, and at this point we realize we can actually take
out of the summation, since it is not changing at all
- The whole point here is that we need to do something with this matrix:
- Note the matrix in the brackets only depends on your input data, this is called the covariance matrix (completely out of your dataset)
- It basically represents the reverse of the reduced data
- At the end what we do is: $$\text{arg max }a^TCa$$
- where C is the covariance matrix completely dependent on your data
- What is the covariance matrix?
- How do we get rid of that summation and write it in terms of matrices?
- Note we have a column vector
and the same vector transposed - So basically we can write this as a multiplication of two matrices
- Instead suppose we have the data matrix:
- Just subtract each column of
by the mean
- Just subtract each column of
- Now given this
, how do we compute the covariance matrix? This will be in the exam! $$C = \frac{1}{n}\tilde{X}\tilde{X}^T$$
- Note we have a column vector
- How do we get rid of that summation and write it in terms of matrices?
PCA to k-dimensional space
(1) What if we want to project the features to a
where
Notes:
- If you want to predict at k-dimensional vector
- For each dimension you need to have an entry on the A matrix (
), each being a -dimensional vector - Note for 1D:
- Variance of z =
- Variance of z =
- For k-dimension
- For each of the
you just do the same thing, this gives you a number, then sum all of them together - Summation of the variance along each projection
- This summation can be written as
- where
is just the summation of the diagonal elements
- where
- For each of the
- Concerns:
- Each of the columns of
is orthogonal to each other and is normalized - Orthonormal columns
- Each of the columns of
- There would be a question on PCA in the final exam!
- Remember C is given
- A will be computed by taking eigen-vectors and eigen-values for this matrix
Ky Fan Theorem
(1) Solving the problem in Eqn. (2) requires the follow theorem.
(2) Theorem. (Ky Fan) Let
and the corresponding eigenvectors
And the optimal
Notes:
- To solve k-dimensional PCA we use the Key Fan Theorem
- This theorem basically tells you that the solution:
- Compute Eigenvalue and eigenvectors of the
matrix and take the eigenvector corresponding to the -largest eigenvalues. - Put these eigenvectors as columns on matrix
?
- Compute Eigenvalue and eigenvectors of the
Solutions to PCA
(1) Note that in Eqn. (2), the covariance matrix
where
(2) It also follows from the above theorem that solutions to PCA are not unique, and they differ by an orthogonal matrix. We used the special case where
Notes:
- We need to compute C, it is the covariance matrix dependent only on your data
- We need to do eigen-decomposition of the covariance matrix
Checkpoint 3 (PCA and solutions)
To understand Principal Component Analysis (PCA), imagine you are holding a 3D cloud of data points (like a swarm of bees). If you want to draw this 3D cloud on a 2D piece of paper, you have to squash it flat. If you squash it from the wrong angle, all the bees will overlap and look like a single blob. If you squash it from the right angle, you can still see the distinct shape and spread of the swarm. PCA is the mathematical tool that finds the absolute best angle to squash (project) your data.
1. What is PCA? PCA is an unsupervised dimensionality reduction technique.
- Unsupervised means we do not care about labels or classes (like "cat" or "dog"); we only care about the raw data points (
). - Dimensionality reduction means taking data with hundreds of features (like a 10,000-pixel image) and compressing it into a much smaller, manageable set of features (like 50 numbers) without losing the core structure.
- To do this successfully, PCA has two equivalent goals: Maximize the variance (keep the data as spread out as possible so points don't overlap) and Minimize the reconstruction error (ensure we can rebuild the original data from the compressed version as accurately as possible).
2. PCA to 1D Let's start with the simplest case: compressing a
- We define a vector
(which has a length of 1, written as ). This vector represents the direction of the 1D line we want to project our data onto. - When we project an original data point
onto this line, it becomes a single scalar number: . - The Goal: We want to choose the line
that results in the new points being as spread out as possible. In statistics, "spread" is measured by variance. Therefore, we want to find the that maximizes the variance of .
3. PCA to 1D (process) How do we mathematically maximize this variance?
- The formula for the variance of our projected points is:
. - If we substitute
with our projection formula ( ), we can use algebra to pull the vector completely outside of the summation. - When we pull
out, the messy sum of data points left in the middle perfectly simplifies into the Covariance Matrix ( ) of our original data. - The Result: The entire complex problem boils down to a very clean linear algebra objective: Find
to maximize .
4. PCA to k-dimensional space Usually, we want to compress our data to
- Instead of a single line
, we now need a matrix made up of different lines (vectors). - These
lines must be perfectly perpendicular (orthogonal) to each other, which is written mathematically as . - Instead of maximizing a single variance, we want to maximize the sum of the variances across all
directions. In matrix math, the sum of the diagonal (which contains these variances) is called the trace. Thus, our new goal is to maximize the .
5. Ky Fan Theorem & Solutions to PCA How on earth do we actually solve
- The theorem states that if you have a symmetric matrix (and our Covariance Matrix
is always symmetric), the absolute maximum possible trace you can achieve when projecting onto dimensions is simply the sum of its largest eigenvalues ( ). - Furthermore, the theorem tells us exactly how to achieve this maximum: the optimal projection matrix
is built by simply taking the eigenvectors that correspond to those largest eigenvalues. - Summary: To compress your data to the best possible
dimensions, just calculate the eigenvectors of your data's covariance matrix, pick the ones with the biggest eigenvalues, and use them as your projection axes!
Computing the covariance matrix:
To understand this, we have to look at how linear algebra allows us to take a long, tedious summation formula and compress it into a single, highly efficient matrix multiplication.
1. The Original Summation Formula The standard statistical formula for the Covariance Matrix (
is a single data point (a column vector of size ). is the mean of all data points (also a column vector of size ). is just the data point with the mean subtracted. It is still a column vector. is that exact same vector, but transposed into a row vector ( ).
When you multiply a column vector by a row vector, you get a full matrix (this is an outer product). The summation symbol
2. Step 1: Constructing the Centered Data Matrix (
- The Math Trick: To do this in pure matrix math, you take the mean vector
and multiply it by a row vector of all 1s ( ). This perfectly copies the mean vector times side-by-side so it becomes a matrix of the exact same size as . - Then, you just subtract them:
. Now, is a massive matrix where column 1 is , column 2 is , and so on.
3. Step 2: The Matrix Multiplication Trick Now we have our centered data matrix
By simply computing
Therefore, the entire messy summation formula perfectly collapses into: $$C = \frac{1}{n}\tilde{X}\tilde{X}^T$$
EXAM TOPIC: How to compute Covariance Matrix (
If you are asked to compute the covariance matrix efficiently using matrices (no summations):
- Find the Mean: Calculate the mean column vector
from your data. - Center the Data (
): Subtract the mean vector from every column of your original data matrix . - Matrix Form:
(where is a row vector of ones used to duplicate the mean vector across all columns).
- Matrix Form:
- Compute Covariance (
): Multiply the centered matrix by its transpose and divide by the number of samples ( ). - Matrix Form:
.
- Matrix Form:
- Why it works: Multiplying
(columns) by (rows) perfectly replicates the sum of outer products via standard matrix multiplication rules (Pattern MM4).
How to compute PCA efficiently?
(1) We define
where
(2) Then we have
If
Notes:
- We can also write the covariance matrix as: $$C = \frac{1}{n}\tilde{X}\tilde{X}^T$$-
is each column summed together and divided by - It represents the mean vector of your data
- This is how you could do it if you only had 3 lines of code and no loop
- How can we subtract the data vector (
) by the mean vector ( )? - You need a matrix of the same size as
, then subtract the matrix - You multiply a matrix of all 1s but transposed
- This is to simply copy that vector
times, and become a matrix - Now each column of that matrix is simply
- (i.e.
)
- (i.e.
- This is to simply copy that vector
- You need a matrix of the same size as
- These 3 operations are just one line of code!
- Now the second line is the following:
- Actually get the covariance matrix by doing:
- Note this matrix is commonly symmetric
- Actually get the covariance matrix by doing:
- In theory if we are dealing with a small dataset, that is fine, this is the way to do it.
- After this step we would just do eigen-decomposition of the covariance matrix
- If p (number of dimensions) is very large, the resulting matrix will be a
matrix, where is the dimension of your data - In practice this is hard, if
is very large, this is commonly not practical
- In practice this is hard, if
- You will need to know how to compute from
to in the exam! - What does a covariance matrix really tell you (not needed for exam)?
- What does a
matrix tell you? what are these numbers? - The relationship between the variance of the dataset with each variable?
- What are the diagonal elements?
- Compute inner product with itself, for each row in
- Each row is the same feature for all data points
- Tells you how much this number (for each two vectors) is different from the mean
- Compute inner product with itself, for each row in
- The other elements tell you each variable variance across its mean
- What does a
- The better way to do it is in #Relation to Eigen-Deconposition (you compute the SVD of the
matrix) - You only need to compute the SVD of R
- Remember how we move the transpose inside the parenthesis (we need to swap the order of the matrices)
- Columns of
will be the eigenvector - And remember
is simply - This is basically the second line of code (compute SVD of
) - What can you see from the eigen-decomposition of the
matrix - Diagonal matrix squared is just the square of each of the diagonal elements
- So this covariance matrix is positive semi-definite.
- You can prove just by definition: $$x^TRR^Tx = (R^TX^T)(R^TX)$$
- This is just a vector transpose of a vector
- What can you see from the eigen-decomposition of the
- Note up to here everything still depends on the data vector
- So if
is very large, you have another way to do it. - Compute
(centered data matrix) - YOU NEED TO KNOW HOW TO COMPUTE THIS - It is just a subtracted mean - Compute the covariance matrix
- Then compute eigen-decomposition of this
matrix, which is equivalent to computing the SVD of
- Compute
(1) However, we show that the SVD of
(2) With the SVD of
Then the projected features are
It is worth noting that the
Notes:
- This is a quick summary:
- You are given
- You compute
- You compute the SVD of
- G is a matrix we will use to transform our data, we just need to get the
columns of .
- You are given
- Centered data is better to use because it is zero-mean, numerically it is better (though nothing is wrong predicting the original data)
- The way to project that is to take
- This is basically the last (third) line of your code
is now your reduced data! - Each column in
is -dimensional
- This is very nice because:
- We can write SVD in terms of a summation of
- This tells you something interesting:
- We can do this operation incrementally
- You do not need to redo calculations, if you want more dimensions, you just need to add the projections necessary to get to that dimension
- Example: if you calculate k = 3, and you want to get k = 4, k = 5, etc. you do not have to repeat k = 3, you just need one more projection for k = 4 and one other projection for k = 5
- We can write SVD in terms of a summation of
- We still have a large step after this, which is to do reconstruction
- Suppose you want to transfer images to someone but they are too large? you can give
and to that person, then they will be able to reconstruct some version of (a low rank approximation to ) - This has nothing to do with passing the exam
- Suppose you want to transfer images to someone but they are too large? you can give
- Look at the covariance matrix and think about what it means
Centered or not?
(1) Note that we project the centered data matrix
(2) But the minimal reconstruction error can only be achieved when
(3) A common practice to avoid any confusion is to center the data before applying PCA, and use the centered data matrix in all computations.
Notes:
- Basically if you do not want to be wrong use
Have We Achieved the Minimal Reconstruction Error?
(1) First, we perform the verification in the case where we project and reconstruct the centered data matrix
(2) Given the projection
the reconstruction process is
and the reconstruction error is
(3) We will show that
which means
(4) We've already learned that
Notes:
- Suppose
is a bunch of images, what you do is to convert each image into a long vector, that vector is the columns of (a flatten image) - Z is a matrix where each column is a data point
- If you want an image to maintain more information, use larger
. - Remember both
and depend on .
- Remember both
- We can get an approximate
matrix by doing the reconstruction step: $$
\check{\boldsymbol{X}}=\boldsymbol{G} \boldsymbol{Z}=\boldsymbol{G} \boldsymbol{G}^T \tilde{\boldsymbol{X}},
\begin{aligned}
\boldsymbol{G G}^T \tilde{\boldsymbol{X}} & =\boldsymbol{U}_k \boldsymbol{U}_k^T \boldsymbol{U} \tilde{\boldsymbol{\Sigma}} \boldsymbol{V}^T \
& =\boldsymbol{U}_k \boldsymbol{U}_k^T\left[\boldsymbol{U}k \quad \boldsymbol{U}\right] \tilde{\boldsymbol{\Sigma}} \boldsymbol{V}^T \
& =\boldsymbol{U}_k\left[\begin{array}{ll}
\boldsymbol{I} & 0
\end{array}\right] \tilde{\boldsymbol{\Sigma}} \boldsymbol{V}^T \
& =\left[\begin{array}{ll}
\boldsymbol{U}_k & 0
\end{array}\right] \tilde{\boldsymbol{\Sigma}} \boldsymbol{V}^T \
& =\boldsymbol{U}_k \boldsymbol{\Sigma}_k \boldsymbol{V}k^T \
& =\sum^k \sigma_i \boldsymbol{u}_i \boldsymbol{v}_i^T
\end
\min _{\boldsymbol{B}: \operatorname{rank}(\boldsymbol{B}) \leq k}|\tilde{\boldsymbol{X}}-\boldsymbol{B}|_F=\left|\tilde{\boldsymbol{X}}-\boldsymbol{G} \boldsymbol{G}^T \tilde{\boldsymbol{X}}\right|F=\sqrt{\sum^n \sigma_i^2} .