brunch

You can make anything
by writing

C.S.Lewis

by 라인하트 Nov 27. 2020

앤드류 응의 머신러닝(14-4): PCA 알고리즘

   온라인 강의 플랫폼 코세라의 창립자인 앤드류 응 (Andrew Ng) 교수는 인공지능 업계의 거장입니다. 그가 스탠퍼드 대학에서 머신 러닝 입문자에게 한 강의를 그대로 코세라 온라인 강의 (Coursera.org)에서 무료로 배울 수 있습니다. 이 강의는 머신러닝 입문자들의 필수코스입니다. 인공지능과 머신러닝을 혼자 공부하면서 자연스럽게 만나게 되는 강의입니다. 


Dimensionality Reduction 

(차원 축소)


Principal Component Analysis (주성분 분석) 


PCA Algorithm (PCA 알고리즘)    


   In this video I'd like to tell you about the principle components analysis algorithm. And by the end of this video you know to implement PCA for yourself. And use it reduce the dimension of your data. 


   이번 강의에서 주성분 분석 알고리즘을 설명합니다. 이번 강의를 마치면 여러분들은 PCA로 차원 축소를 직접 구현할 수 있습니다.   



   Before applying PCA, there is a data pre-processing step which you should always do. Given the training sets of the examples is important to always perform mean normalization, and then depending on your data, maybe perform feature scaling as well. this is very similar to the mean normalization and feature scaling process that we have for supervised learning.  In fact it's exactly the same procedure except that we're doing it now to our unlabeled data, X1 through Xm. 

   So for mean normalization we first compute the mean of each feature and then we replace each feature, X, with X minus its mean, and so this makes each feature now have exactly zero mean. The different features have very different scales. So for example, if x1 is the size of a house, and x2 is the number of bedrooms, to use our earlier example, we then also scale each feature to have a comparable range of values. And so, similar to what we had with supervised learning, we would take x, i substitute j, that's the j feature and so we would subtract of the mean, now that's what we have on top, and then divide by sj. Here, sj is some measure of the beta values of feature j. So, it could be the max minus min value, or more commonly, it is the standard deviation of feature j.  Having done this sort of data pre-processing.


   PCA를 적용 전에 반드시 데이터 전처리를 합니다. 데이터 전처리는 학습 셋에 대해 평균 정규화 (Mean Nomalization)와 피처 스케일링(Feature Scaling)을 수행하는 것입니다. 지도 학습의 정규화와 피처 스케일링 프로세스와 매우 비슷합니다. 실제로 레이블이 없는 데이터 x1, x2,.., xm에 대해 수행한다는 점 외에 모든 절차는 동일합니다.  

   따라서, 평균 정규화(Mean Normalization)를 위해 각 피처 xj 당 평균 μj를 계산합니다.

   학습 예제 x^(i)의 각 피처 (x^(i)j)를 각 피처의 평균(μj)으로 뺍니다. 

   평균 정규화로 인해 xj의 평균은 0입니다. 평균 정규화는 서로 다른 피처의 범위를 0을 중심으로 정규화합니다. 예를 들어, x1은 주택의 크기이고, x2는 침실의 개수입니다. 각 피처의 평균을 빼 값의 범위를 0을 중심으로 움직입니다. 지도 학습의 피처 스케일링과 마찬가지로  학습 예제 x^(i)를 전처리합니다.


   

   여기서, sj는 피처 xj의 최대값에서 최소값을 뺀 값이거나, 피처 xj의 표준 편차일 수 있습니다. 데이터 전처리 작업은 평균 정규화 및 피처 스케일링을 이용합니다.  



   Here's what the PCA algorithm does. We saw from the previous video that what PCA does is, it tries to find a lower dimensional sub-space onto which to project the data, so as to minimize the squared projection errors, sum of the squared projection errors, as the square of the length of those blue lines that and so what we wanted to do specifically is find a vector, u1, which specifies that direction or in the 2D case we want to find two vectors, u1 and u2, to define this surface onto which to project the data.


  여기에 PCA 알고리즘의 동작 방식을 설명한 그림이 있습니다. 지난 강의에서 PCA는 데이터를 투영할 더 낮은 차원의 표면을 찾기 위해 투영 오차의 제곱의 합을 최소화합니다. 투영 오차는 파란색 선분입니다. 즉, 왼쪽 그림에서 벡터 u^(1)을 찾는 것입니다. 벡터 u^(1)는 방향을 결정합니다. 오른쪽 그림은 3D를 2D로 차원 축소를 하므로 두 개의 벡터 u^(1)과 u^(2)를 찾아서 데이터를 투영할 표면을 정의합니다. 



   So, just as a quick reminder of what reducing the dimension of the data means, for this example on the left we were given the examples xI, which are in r2. And what we like to do is find a set of numbers zI in r push to represent our data. So that's what from reduction from 2D to 1D means. So specifically by projecting data onto this red line there. We need only one number to specify the position of the points on the line. So i'm going to call that number z or z1. Z here [xx] real number, so that's like a one dimensional vector. So z1 just refers to the first component of this, you know, one by one matrix, or this one dimensional vector. And so we need only one number to specify the position of a point. So if this example here was my example X1, then maybe that gets mapped here. And if this example was X2maybe that example gets mapped And so this point here will be Z1 and this point here will be Z2, and similarly we would have those other points for These, maybe X3, X4, X5 get mapped to Z1, Z2, Z3.


   차원 축소가 의미하는 바는 R^(2) 차원 벡터인 x^(i)를 실수인 z^(i)를 대체합니다. 데이터 x^(i)를 직선 u^(1)에 투영한 점 z^(i)를 찾습니다. 이것이 2D에서 1D로 차원 축소하는 방법입니다. 투영 오차를 최소화하는 빨간색 직선에 데이터를 투영합니다. 직선에서 점의 위치를 지정할 때는 단지 하나의 숫자만 필요합니다. 그 숫자를 z 또는 z1이라고 합니다. z는 실수이므로 R^(1) 차원 벡터입니다. 첫 번째 예제 x^(1)를 투영한 위치는 z^(1)입니다. 두 번째 예제 x^(2)를 투영한 위치는 z^(2)입니다. 다른 예제들도 마찬가지로 투영합니다.  


   So What PCA has to do is we need to come up with a way to compute two things. One is to compute these vectors, u1, and in this case u1 and u2. And the other is how do we compute these numbers, Z. So on the example on the left we're reducing the data from 2D to 1D. In the example on the right, we would be reducing data from 3 dimensional as in r3, to zi, which is now two dimensional. So these z vectors would now be two dimensional. So it would be z1 z2 like so, and so we need to give away to compute these new representations, the z1 and z2 of the data as well. 

   So how do you compute all of these quantities? It turns out that a mathematical derivation, also the mathematical proof, for what is the right value U1, U2, Z1, Z2, and so on. That mathematical proof is very complicated and beyond the scope of the course. But once you've done [xx] it turns out that the procedure to actually find the value of u1 that you want is not that hard, even though so that the mathematical proof that this value is the correct value is someone more involved and more than i want to get into. 


   그래서, PCA는 두 가지를 계산하기 위한 방법을 찾습니다. 하나는 왼쪽 그래프 경우는 벡터 u^(1), 오른쪽 그래프의 경우는 벡터 u^(1), u^(2)를 계산합니다. 다른 하나는 숫자 z를 계산합니다. 따라서, 왼쪽의 예는 2D에서 1D로 차원을 축소하기 때문에 실수 z1을 계산합니다. 오른쪽의 예는 3D에서 2D로 차원을 축소하기 때문에 이차원 벡터 z1과 z2을 계산합니다.  즉, z = [z1; z2]입니다. 새로운 피처 z1과 z2 데이터를 계산합니다. 

   이 모든 것들을 어떻게 계산해야 할까요? u^(1), u^(2), z^(1), z^(2) 등이 무엇인지를 수학적 증명을 할 수 있지만 하지 않을 것입니다. 증명은 매우 복잡하고 이 과정의 범위를 벗어납니다. 일단 실행하면 u^(1)의 값을 찾는 절차는 어렵지 않습니다. 수학적 증명은 이미 많은 사람들이 하였으므로 우리는 믿을 것입니다.  

 


   But let me just describe the specific procedure that you have to implement in order to compute all of these things, the vectors, u1, u2, the vector z. Here's the procedure. Let's say we want to reduce the data to n dimensions to k dimension What we're going to do is first compute something called the covariance matrix, and the covariance matrix is commonly denoted by this Greek alphabet which is the capital Greek alphabet sigma. It's a bit unfortunate that the Greek alphabet sigma looks exactly like the summation symbols. So this is the Greek alphabet Sigma is used to denote a matrix and this here is a summation symbol. So hopefully in these slides there won't be ambiguity about which is Sigma Matrix, the matrix, which is a summation symbol, and hopefully it will be clear from context when I'm using each one. 


   벡터 u^(1), u^(2), 벡터 z 등의 모든 것들 계산하기 위한 절차를 설명합니다. 차원 축소는 n 차원의 데이터를 k차원으로 줄이는 것입니다. 먼저 공분산 행렬(Covariance matrix)을 계산합니다. 

   공분산 행렬은 그리스 알파벳 대문자인 시그마로 표시합니다. 시그마가 합산 기호와 똑같지만 의미는 다릅니다. 여기서 그리스 알파벳 시그마는 행렬을 나타냅니다. 더 큰 시그마가 합산 기호입니다.  수식에서 시그마 행렬과 합산 기호가 혼동하지 않기를 바랍니다. 각각을 사용할 때 분명하게 이해할 것입니다. 


   추가적으로 공분산 행렬을 설명합니다. 예를 들어, 국어 점수와 영어 점수를 바탕으로 데이터를 시각화합니다. 단순하게 두 점수의 평균을 취할 수 있고, 또는 난이도에 따른 가중치를 줄 수 있습니다. 국어 100점, 영어 80점일 때 다음과 같이 계산할 수 있습니다.  


   1) 100 X 0.5 + 80 X 0.5 = 50 + 40 = 90점 (평균)

   2) 100 X 0.6 + 80 X 0.4 = 60 + 32 = 92점 (난이도를 고려)


    위의 식을 그대로 벡터의 내적으로 표현할 수 있습니다.  2차원 평면의 벡터 (100, 80)를 벡터 (0.5, 0.5)와 내적 합니다. 두 벡터의 내적은 식 1)과 동일합니다. 또한 2차원 평면의 벡터 (100, 80)을 벡터 (0.6, 0.4)와 내적 합니다. 두 벡터의 내적은 식 2)와 동일합니다. 기하학적으로 (0.5, 0.5) 벡터와 (0.6, 0.6) 벡터에 벡터(100,80)를 직교 사영 또는 직교 투영한 것입니다. 



   공분산은 데이터의 구조를 설명하면서 피처 쌍이 얼마나 함께 변하는 지를 행렬로 나타냅니다. 데이터 행렬(국어와 영어 점수)에 공분산 행렬(난이도)을 내적 하면 또는 직교 사영하면 데이터가 어떤 방향으로 분산되는 지를 보여줍니다. 


   데이터 행렬 X에 대한 공분산 행렬(∑)을 구하는 공식은 다음과 같습니다. 

 

   그런데, 데이터 행렬 X에 대한 공분산 행렬 X^TX는 피처 n의 개수가 증가할수록 내적의 값은 계속 증가합니다. 데이터를 모을수록 결과값이 더 커지는 문제를 방지하기 위해 데이터의 총 개수 m으로 나누어줍니다. 


   How do you compute this matrix sigma? let's say we want to store it in an octave variable called sigma. What we need to do is compute something called the eigenvectors of the matrix sigma. And an octave, the way you do that is you use this command, u s v equals s v d of sigma. SVD, by the way, stands for singular value decomposition. This is a much more advanced single value composition. It is much more advanced linear algebra than you actually need to know but now It turns out that when sigma is a covariance matrix, there is a few ways to compute. these are eigenvectors and If you are an expert in linear algebra and if you've heard of eigenvectors before. you may know that there is another octave function called eig(), which can also be used to compute the same thing. and It turns out that the SVD function and the eig function it will give you the same eigenvectors, although SVD is a little more numerically stable. So I tend to use SVD, although I have a few friends that use the eig function to do this as well but when you apply this to a covariance matrix sigma it gives you the same thing. This is because the covariance matrix always satisfies a mathematical Property called symmetric positive definite. You really don't need to know what that means, but the SVD and I-functions are different functions but when they are applied to a covariance matrix which can be proved to always satisfy this mathematical property; they'll always give you the same thing.

     

   공분산 행렬 시그마(∑)를 어떻게 계산할까요? 옥타브 프로그램은 공분산 행렬 시그마(∑)를 계산할 때 다음과 같은 코드를 사용합니다.   


           [U, S, V ] = svd(sigma); 


   여기서 svd() 함수의 svd는 특이값 분해 (svd, singular value decomposition)의 준말입니다. svd는 매우 복잡한 고급 선형 대수입니다. 시그마(∑)가 공분산 행렬일 때 계산하는 방법이 몇 가지 있습니다. 여러분이 선형 대수 전문가이거나 고유 벡터를 들어본 적이 있다면, 옥타브 프로그램의 eig() 함수도 알 것입니다. svd()와 eig() 함수는 같은 고유 벡터를 제공하지만 svd가 수학적으로 조금 더 안정적입니다. 저는 eig() 보다는 svd()를 주로 사용합니다. 몇몇 친구들은 eig() 함수를 선호합니다. 두 함수를 공분산 행렬 시그마(∑)에 적용하면 동일한 결과를 얻을 수 있습니다. 공분산 행렬이 항상 대각선을 기준으로 대칭이라는 수학적 속성을 충족하기 때문입니다. 이것이 의미하는 바를 알 필요는 없습니다.  svd() 함수와 eig() 함수는 서로 다른 함수지만 공분산 행렬에 적용할 때 같은 결과를 반환합니다. 


   특이값 분해(svd, Singular Value Decomposition)는 m X n 차원의 행렬 A를 분해하는 방법 중에 하나입니다. 


   행렬 A에 대한 특이값 분해 (SVD)의 의미는 행렬 A와 동일한 크기를 갖는 여러 개의 행렬로 분해할 수 있고, 분해한 각 행렬의 성분의 값의 크기는 대각 행렬 시그마(∑)의 성분에 의해 결정됩니다. 

    특이값 분해는 행렬을 분해한 후 다시 조합할 수 있습니다. 특이값 p개의 정보량만으로 A'라는 행렬을 복원할 수 있습니다.   




   Okay, that was probably much more linear algebra than you needed to know. In case none of that made sense, don't worry about it. All you need to know is that this system command you should implement in Octave. And if you're implementing this in a different language than Octave or MATLAB, what you should do is find the numerical linear algebra library that can compute the SVD or singular value decomposition, and there are many such libraries for probably all of the major programming languages. People can use that to compute the matrices u, s, and d of the covariance matrix sigma. 


   선형 대수에 대해 여러분이 알아야 할 것보다 더 많이 설명했습니다. 아무것도 이해할 수 없다고 걱정할 필요는 없습니다. 여러분이 알아야 할 것은 옥타브 프로그램에서 함수를 호출하여 구현한다는 것입니다. 옥타브/매트랩 또는 다른 언어로 구현할 때 svd() 또는 특이값 분해를 계산할 수 있는 선형 대수 라이브러리를 찾습니다. 아마도 거의 대부분의 프로그래밍 언어에는 수많은 라이브러리가 있습니다. 사람들은 공분산 행렬 ∑를 계산하기 위해 다음과 같은 코드를 사용합니다.


      [U, S, V ] = svd(sigma);  



   So just to fill in some more details, this covariance matrix sigma will be an n by n matrix. And one way to see that is if you look at the definition this is an n by 1 vector and this here I transpose is 1 by N so the product of these two things is going to be an N by N matrix. 1xN transfers, 1xN, so there's an NxN matrix and when we add up all of these you still have an NxN matrix. 


   따라서 더 자세한 정보를 입력하기 위해 공분산 행렬 ∑는 n X n 행렬입니다. 그것을 살펴보는 한 가지 방법은 공분산 행렬 ∑의 수학적 정의를 보는 것입니다. x^(i)는 n X 1 벡터이고, (x^(i))^T는 x^(i)의 전치 행렬이므로 1 X n 벡터입니다. 두 행렬의 곱은 n X n 행렬입니다. 이 모든 행렬을 더하면 n X n 행렬입니다.    


   And what the SVD outputs three matrices, u, s, and v. The thing you really need out of the SVD is the u matrix. The u matrix will also be a mxm matrix. And if we look at the columns of the U matrix it turns out that the columns of the U matrix will be exactly those vectors, u1, u2 and so on. So u, will be matrix. And if we want to reduce the data from n dimensions down to k dimensions, then what we need to do is take the first k vectors that gives us u1 up to uK which gives us the K direction onto which we want to project the data.


      [U, S, V ] = svd(sigma);  

   그리고 svd() 함수는 U, S, V라는 세 개의 행렬을 출력합니다. 특이값 분해 공식은 A = U*S*V' 이고, svd() 함수는 입력값 시그마(∑)에 대해 U, S, V 값을 반환합니다. svd() 함수에서 실제로 필요한 것은 U행렬입니다. U행렬도 m X m 행렬입니다. U행렬의 열은 정확히 벡터 u^(1), u^(2), u^(3).. u^(m)입니다. 그리고, 데이터를 n차원에서 k차원으로 축소하기 위해 먼저 u^(1), u^(2),.. u^(k)까지 가져옵니다.  데이터를 투영하길 원하는 K 방향을 정의합니다. 



   Let me describe the rest of the procedure from this SVD numerical linear algebra routine we get this matrix u. We'll call these columns u1-uN. So, just to wrap up the description of the rest of the procedure, from the SVD numerical linear algebra routine we get these matrices u, s, and d. we're going to use the first K columns of this matrix to get u1-uK. Now the other thing we need to is take my original data set, X which is an RN And find a lower dimensional representation Z, which is a R K for this data.


  행렬 U를 얻을 수 있는 svd() 선형 대수 루틴의 나머지 절차를 설명합니다. 행렬 U는 u^(1), u^(2),..., u^(n)까지 있습니다. SVD() 선형 대수 루틴에서 행렬 U, 행렬 S, 행렬 D를 얻습니다. u^(1)에서 u^(k)까지 얻기 위해 행렬의 처음 k개의 열을 사용합니다. R^(n) 차원인 원래 데이터 셋 x를 가져와 더 낮은 R^(k) 차원의 데이터 셋 z를 찾는 것입니다. 



 So the way we're going to do that is take the first K Columns of the U matrix. Construct this matrix. Stack up U1, U2 and so on up to U K in columns. It's really basically taking, you know, this part of the matrix, the first K columns of this matrix. And so this is going to be an N by K matrix. I'm going to give this matrix a name. I'm going to call this matrix U, subscript "reduce, " sort of a reduced version of the U matrix maybe. I'm going to use it to reduce the dimension of my data. And the way I'm going to compute Z is going to let Z be equal to this U reduce matrix transpose times X. Or alternatively, you know, to write down what this transpose means. When I take this transpose of this U matrix, what I'm going to end up with is these vectors now in rows. I have U1 transpose down to UK transpose. Then take that times X, and that's how I get my vector Z. Just to make sure that these dimensions make sense, this matrix here is going to be k by n and x here is going to be n by 1 and so the product here will be k by 1.   And so z is k dimensional, is a k dimensional vector, which is exactly what we wanted. And of course these x's here right, can be Examples in our training set can be examples in our cross validation set, can be examples in our test set.


   새로운 행렬 Z는 행렬 U의 첫 번째 k열을 사용합니다. u^(1), u^(2),..., u^(k)까지 행렬 U의 일부분을 사용합니다. 행렬 U의 부분 행렬 Z는 n X k 행렬입니다. 이 행렬의 이름은 U에 아래 첨자로 reduce라고 쓸 것입니다. Ureduce는 행렬 U의 축소된 버전입니다. Ureduce는 데이터의 차원을 줄이기 위해 사용합니다. 행렬 Z를 계산하는 방법은 다음과 같습니다. 

   전치 행렬은 열로 된 u^(1), u^(2),..., u^(k)를 행으로 전환하기 위해 전치합니다. 이것이 벡터 z를 얻는 법입니다. Ureduce^T는 k X n 행렬이고, x는 n X 1 행렬입니다. 따라서, 벡터 z는 k X 1 행렬입니다. z는 R^(k) 차원 벡터입니다. 우리가 정확히 원했던 것입니다. 여기 x는 학습 셋, 교차 검증 셋 또는 테스트 셋의 예제가 될 수 있습니다.



   And for example if you know, I wanted to take training example i, I can write this as xi XI and that's what will give me ZI over there.


    예를 들어, 학습 예제 x^(i)는 k방향에 투영한 z^(i)를 반환합니다.  

   


   So, to summarize, here's the PCA algorithm on one slide. After mean normalization to ensure that every feature is zero mean and optional feature scaling which You really should do feature scaling if your features take on very different ranges of values. After this pre-processing we compute the carrier matrix Sigma like so by the way if your data is given as a matrix like this if you have your data Given in rows like this. If you have a matrix X which is your time training sets written in rows where x1 transpose down to x1 transpose, this covariance matrix sigma actually has a nice vectorizing implementation. You can implement in octave, you can even run sigma equals 1 over m, times x, which is this matrix up here, transpose times x and this simple expression, that's the vectorize implementation of how to compute the matrix sigma. 


   요약하자면, 

1) 데이터를 전처리합니다. 모든 피처가 0을 기준으로 평균 정규화와 서로 비슷한 범위의 피처 값을 갖도록 피처 스케일링합니다. 


2) 데이터 행렬 X에 대한 공분산 행렬 ∑를 구합니다.    

   캐리어 행렬 시그마를 계산합니다. 학습 셋 X 가 있을 때 옥타브 프로그램에서 공분산 행렬 ∑를 구할 수 있는 코드는 다음과 같습니다. 


         Sigma = 1/m * X' * X;


   x'x의 간단한 표현식은 공분산 행렬 ∑를 계산하는 벡터화 구현입니다. 


   I'm not going to prove that today. This is the correct vectorization whether you want, you can either numerically test this on yourself by trying out an octave and making sure that both this and this implementations give the same answers or you can try to prove it yourself mathematically. Either way but this is the correct vectorizing implementation, without compusing 


   이것을 수학적으로 증명하지 않을 것입니다. 옥타브 프로그램으로 구현한 것과 실제 계산한 것이 동일한 답을 제공합니다. 직접 테스트하거나 수학적으로 증명 가능합니다. 이것은 올바른 벡터화 구현입니다. 



   Next, we can apply the SVD routine to get u, s, and d. And then we grab the first k columns of the u matrix you reduce and finally this defines how we go from a feature vector x to this reduce dimension representation z. And similar to k Means if you're apply PCA, they way you'd apply this is with vectors X and RN. So, this is not done with X-0 1. So that was the PCA algorithm. 

   One thing I didn't do is give a mathematical proof that this. It actually give the projection of the data onto the K dimensional subspace that actually minimizes the square projection error Proof of that is beyond the scope of this course. Fortunately the PCA algorithm can be implemented in not too many lines of code. and if you implement this in octave or algorithm, you actually get a very effective dimensionality reduction algorithm. So, that was the PCA algorithm.


   PCA 알고리즘을 벡터화 구현을 한 것은 다음과 같습니다. 


   Sigma = (1/m) * X' * X;     % 공분산 행렬 Sigma를 구함

   [U, S, V] = svd(Sigma);     % svd() 루틴을 적용하여 행렬 U, S, D를 얻음

   Ureduce = U (:, 1:k);         % u^(1)에서 u^(k)까지의 열을 가져와 Ureduce 행렬 생성

   z = Ureduce' * x                % z 방향으로 투영한 x^(i)의 값을 구함

 

   PCA 알고리즘은 n 차원의 데이터를 k차원의 데이터로 줄이기 위한 것입니다. x0는 무시합니다. 

   수학적으로  증명하지 않았습니다. 증명은 이 과정의 범위를 벗어납니다. 옥타브 프로그램에서 벡터화 구현은 실제로 데이터를 k 차원 표면에 투영하여 투영 오차의 제곱을 최소화합니다. 다행히 PCA 알고리즘은 간단한 코드로 구현할 수 있습니다. 이 간단한 코드로 매우 효과적인 차원 감소 알고리즘을 얻습니다. 이것이 바로  PCA 알고리즘입니다. 


   One thing I didn't do was give a mathematical proof that the U1 and U2 and so on and the Z and so on you get out of this procedure is really the choices that would minimize these squared projection error. Right, remember we said What PCA tries to do is try to find a surface or line onto which to project the data so as to minimize to square projection error. So I didn't prove that this that, and the mathematical proof of that is beyond the scope of this course. But fortunately the PCA algorithm can be implemented in not too many lines of octave code. And if you implement this, this is actually what will work, or this will work well, and if you implement this algorithm, you get a very effective dimensionality reduction algorithm. That does do the right thing of minimizing this square projection error.


    설명하지 않은 또 다른 한 가지는 u^(1), u^(2),... 등과 z 등이 절차에서 벗어난 것은 투영 오차의 제곱을 최소화하는 선택이라는 수학적 증명을 하지 않았습니다. PCA는 투영 오차의 제곱을 최소화하기 위해 데이터를 투영할 표면이나 선을 찾는 것입니다. 이것을 증명하지 않았습니다. 증명은 과정의 범위를 벗어납니다. 다행히 PCA 알고리즘은 간단한 코드로 구현할 수 있습니다. 실제로 잘 작동하고 매우 효과적인 차원 축소 알고리즘을 얻을 수 있습니다. 이것이 투영 오차를 최소화하는 올바른 방법입니다. 



앤드류 응의 머신러닝 동영상 강의



정리하며


   PCA는 차원 축소 문제를 해결하는 가장 인기 있는 알고리즘 중 하나입니다. 수학적으로 데이터가 직교 투영할 때 점과 표면 사이의 거리의 제곱의 합이 최소가 되는 더 낮은 차원의 표면 또는 직선을 찾는 것입니다. PCA는 n 차원 데이터를 k차원으로 축소하고 k <= n입니다. PCA는 데이터를 투영할 더 낮은 차원을 찾아서 직교 투영합니다. 그리고, 투영 오차의 제곱을 최소화합니다.  


   PCA 알고리즘은 n 차원의 데이터를 k차원의 데이터로 줄입니다. PCA 알고리즘을 벡터화 구현으로 옥타브 프로그램에서 다음과 같이 계산합니다. 


1) 데이터 전처리 

    모든 피처가 0을 기준으로 평균을 갖는 정규화와 서로 다른 범위의 값을 피처를 비슷한 범위의 값으로 만드는 피처 스케일링을 합니다.  지도 학습에서 공부한 정규화와 피처 스케일링 프로세스는 매우 비슷합니다. 실제로 레이블이 없는 데이터 x1, x2,.., xm에 대해 수행한다는 점을 제외하면 정확히 절차는 동일합니다. 


2) PCA 알고리즘의 공분산 행렬 시그마를 벡터화로 구현


   

      학습 셋 X 가 있을 때  공분산 행렬 시그마(∑)는 훌륭한 벡터화 구현합니다.  


         ∑ = 1/m * X' * X;


       실제 옥타브 프로그램에서 다음과 같이 구현합니다.


      Sigma = (1/m) * X' * X;     % 공분산 행렬 Sigma를 구함

   

3) 공분산 행렬을 적용하여 행렬을 분할

  

        [U, S, V] = svd(Sigma);     % svd() 루틴을 적용하여 행렬 U, S, D를 얻음


  svd() 함수와 eig() 함수는 서로 다른 함수지만 공분산 행렬에 적용할 때 같은 결과를 반환합니다. 


4) 차원 축소를 진행


         Ureduce = U (:, 1:k);         % u^(1)에서 u^(k)까지의 열을 가져와 Ureduce 행렬 생성


5) z 방향으로 직교 투영한 값을 구함


          z = Ureduce' * x                % z 방향으로 투영한 x^(i)의 값을 구함

 

     PCA는 투영 오차의 제곱을 최소화하기 위해 데이터를 투영할 표면이나 선을 찾는 것입니다.


 


문제 풀이


   PCA 알고리즘입니다. zj에 대한 올바른 답은?

  정답은 4번입니다. 



참조자료

https://angeloyeo.github.io/2019/08/01/SVD.html


매거진의 이전글 앤드류 응의 머신러닝(14-3): PCA와 차원 축소
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari