Search
 
SCRIPT & CODE EXAMPLE
 

CPP

pca compact trick

PCA PCA_trick(const Mat& pcaset, int maxComponents)
{
     int n = pcaset.rows, p = pcaset.cols;
     cout << "	calculating 'true' means, varance and standard deviation..." << endl;
     Mat means(1, p, CV_32FC1);
     Mat variance(1, p, CV_32FC1);
     for (size_t i = 0; i < p; i++)
     {
       float avg = mean(pcaset.col(i)).val[0];
       means.at<float>(0, i) = avg;
       Mat p2 = Mat(1, n, CV_32F);
       for (size_t j = 0; j < n; j++)
         p2.at<float>(0, j) = pow(pcaset.at<float>(j, i), 2);
       variance.at<float>(0, i) = (1 / (float)n) * sum(p2).val[0] - pow(avg, 2);
     }

     //covariance matrix, AA', not the A'A like usual
     Mat M;
     Mat centred(n, p, CV_32FC1);
     for (size_t i = 0; i < n; i++)
       centred.row(i) = (pcaset.row(i) - means) / variance;
     mulTransposed(centred, M, 0);

     //compute eigenvalues and eigenvectors
     PCA pca;
     pca = PCA(M, cv::Mat(), CV_PCA_DATA_AS_ROW, maxComponents);

     //this is the compact trick
     pca.mean = means;
     pca.eigenvectors = pca.eigenvectors * centred;
     pca.eigenvectors = pca.eigenvectors.rowRange(Range(0, maxComponents));

     return pca;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: lambda - print-out array and add comment 
Cpp :: Required Length 
Cpp :: 1603. Design Parking System leetcode solution in c++ 
Cpp :: is there anything like vector<intx[100] 
Cpp :: c++ programming 
Cpp :: icon on win32 button 
Cpp :: The elements are store at contiguous memory locations in C++ 
Cpp :: split date and time in a column in db browser 
Cpp :: c++ rainbow text 
Cpp :: 771. Jewels and Stones leetcode solution in c++ 
Cpp :: ex:c++ gcc start adress 
Cpp :: how to get the numbers in a vector c++ sfml 
Cpp :: scope resolution operator in c++ 
Cpp :: c++ if else if 
Cpp :: c++ set element at index 
Cpp :: cpp queue 
Cpp :: what do we use c++ vectors for 
Cpp :: open a url with dev c 
Cpp :: what does for do in c++ 
C :: hello word c 
C :: c distance in the cartesian plane 
C :: pygame draw transparent rectangle 
C :: get window width height glfw 
C :: c how to get an integer from user input 
C :: thread in c 
C :: dynamically create matrix c 
C :: va_list in c 
C :: stdio.h in c 
C :: vbnet create and write on file 
C :: print short in c 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =