-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPrincipalComponentAnalysis.cpp
More file actions
65 lines (52 loc) · 1.88 KB
/
PrincipalComponentAnalysis.cpp
File metadata and controls
65 lines (52 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "PrincipalComponentAnalysis.h"
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
using namespace boost::accumulators;
using namespace std;
using namespace cv;
PrincipalComponentAnalysis::PrincipalComponentAnalysis()
{
}
void PrincipalComponentAnalysis::pre_process(const FeatureCollection fset, Mat& data)
{
int num_samples = fset.size();
int num_features = fset[0].size();
for(int i = 0; i < num_samples; ++i){
Feature feat = fset[i];
accumulator_set<float, stats<tag::mean, tag::moment<2> > > acc;
for(int k = 0; k < num_features; ++k)
acc(feat[k]);
float mu = boost::accumulators::mean(acc);
float std = sqrt(moment<2>(acc));
for(int j = 0; j < num_features; ++j){
data.at<float>(j,i) = (feat[j]-mu)/std;
}
}
}
void PrincipalComponentAnalysis::compute(const Mat data, const PascalImageDatabase db)
{
int num_principal_components = 2;
PCA pca(data, Mat(), CV_PCA_DATA_AS_COL, num_principal_components);
PCA pca2(data, Mat(), CV_PCA_DATA_AS_COL);
for(int i = 0; i < data.cols; ++i)
{
Mat proj = pca.project(data.col(i));
int label = db.getLabel(i);
_projectedPoints.push_back(proj);
_labels.push_back(label);
proj.release();
}
float percentage = (pca.eigenvalues.at<float>(0) + pca.eigenvalues.at<float>(1))/cv::sum(pca2.eigenvalues)[0];
LOG(INFO) << "Percentage of variability retained in first two dimensions: " << percentage*100 << "%";
}
void PrincipalComponentAnalysis::savePCAFile(const string pcaFilename)
{
ofstream f(pcaFilename.c_str());
for (int i = 0; i < _projectedPoints.size(); ++i) {
f << _labels[i] << " " << _projectedPoints[i].at<float>(0,0) << " " << _projectedPoints[i].at<float>(0,1) << "\n";
}
f.close();
LOG(INFO) << "Output generated in file: " << pcaFilename;
}