Krotos Modules 3
Loading...
Searching...
No Matches
PCA.cpp
Go to the documentation of this file.
1namespace krotos
2{
3
4PCA::PCA()
5{
6 //
7}
8
9PCA::~PCA()
10{
11 //
12}
13
14void PCA::reserve(const std::size_t& n) { data.reserve(n); }
15
16void PCA::insert(const std::vector<float>& x)
17{
18 data.insert(data.end(), x.begin(), x.end());
19 rows += 1;
20}
21
22void PCA::fit(const std::size_t& n_components)
23{
24 assert(rows > 0);
25
26 std::size_t cols = data.size() / rows;
27 assert(n_components <= cols);
28
29 auto X = Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(data.data(), rows,
30 cols); // RowMajor
31
32 // centre data
33 X = X.rowwise() - X.colwise().mean();
34
35 // SVD
36 if (rows < n_components)
37 {
38 Eigen::JacobiSVD<Eigen::MatrixXf> svd(X, Eigen::ComputeFullV);
39
40 // PCA
41 Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> U =
42 (X * svd.matrixV()).leftCols(n_components);
43
44 // PCA data in row major format
45 principal_components.assign(U.data(), U.data() + U.size());
46 }
47 else
48 {
49 Eigen::JacobiSVD<Eigen::MatrixXf> svd(X, Eigen::ComputeThinV);
50
51 // PCA
52 Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> U =
53 (X * svd.matrixV()).leftCols(n_components);
54
55 // PCA data in row major format
56 principal_components.assign(U.data(), U.data() + U.size());
57 }
58
59 is_fitted = true;
60}
61
62std::vector<float> PCA::getPrincipalComponents(const std::size_t& i)
63{
64 assert(is_fitted);
65
66 const std::size_t n_components = principal_components.size() / rows;
67 const std::size_t idx = i * n_components;
68 std::vector<float> result(principal_components.data() + idx, principal_components.data() + idx + n_components);
69 return result;
70}
71
72void PCA::clear()
73{
74 data.clear();
75 principal_components.clear();
76 rows = 0;
77 is_fitted = false;
78}
79
80void PCA::toCSV(const std::string& filename)
81{
82 std::ofstream f(filename);
83 if (f.is_open())
84 {
85
86 std::size_t cols = data.size() / rows;
87 for (std::size_t row = 0; row < rows; ++row)
88 {
89 for (std::size_t col = 0; col < cols; ++col)
90 f << data[row * cols + col] << ",";
91 f << std::endl;
92 }
93 }
94 else
95 {
96 DBG("failed to open csv file");
97 }
98}
99
100} // namespace krotos
Definition AirAbsorptionFilter.cpp:2