fml  0.1-0
Fused Matrix Library
pca.hh
1 // This file is part of fml which is released under the Boost Software
2 // License, Version 1.0. See accompanying file LICENSE or copy at
3 // https://www.boost.org/LICENSE_1_0.txt
4 
5 #ifndef FML_CPU_STATS_PCA_H
6 #define FML_CPU_STATS_PCA_H
7 #pragma once
8 
9 
10 #include "../dimops.hh"
11 
12 #include "../linalg/svd.hh"
13 #include "../linalg/xpose.hh"
14 
15 
16 namespace fml
17 {
19 namespace stats
20 {
39  template <typename REAL>
40  void pca(const bool rm_mean, const bool rm_sd, cpumat<REAL> &x,
41  cpuvec<REAL> &sdev, cpumat<REAL> &rot)
42  {
43  dimops::scale(rm_mean, rm_sd, x);
44 
45  cpumat<REAL> u;
46  cpumat<REAL> trot;
47  linalg::svd(x, sdev, u, trot);
48 
49  const REAL d = 1.0 / sqrt((REAL)std::max(x.nrows()-1, 1));
50  sdev.scale(d);
51 
52  linalg::xpose(trot, rot);
53  }
54 
55 
56 
58  template <typename REAL>
59  void pca(const bool rm_mean, const bool rm_sd, cpumat<REAL> &x,
60  cpuvec<REAL> &sdev)
61  {
62  dimops::scale(rm_mean, rm_sd, x);
63 
64  linalg::svd(x, sdev);
65 
66  const REAL d = 1.0 / sqrt((REAL)std::max(x.nrows()-1, 1));
67  sdev.scale(d);
68  }
69 }
70 }
71 
72 
73 #endif
fml::cpumat
Matrix class for data held on a single CPU.
Definition: cpumat.hh:36
fml::linalg::xpose
void xpose(const cpumat< REAL > &x, cpumat< REAL > &tx)
Computes the transpose out-of-place (i.e. in a copy).
Definition: xpose.hh:37
fml::unimat::nrows
len_t nrows() const
Number of rows.
Definition: unimat.hh:36
fml::stats::pca
void pca(const bool rm_mean, const bool rm_sd, cpumat< REAL > &x, cpuvec< REAL > &sdev, cpumat< REAL > &rot)
Principal components analysis.
Definition: pca.hh:40
fml::cpuvec
Vector class for data held on a single CPU.
Definition: cpuvec.hh:31
fml::dimops::scale
void scale(const bool rm_mean, const bool rm_sd, cpumat< REAL > &x)
Remove the mean and/or the sd from a matrix.
Definition: dimops.hh:376
fml::cpuvec::scale
void scale(const T s)
Multiply all values by the input value.
Definition: cpuvec.hh:421
fml::linalg::svd
void svd(cpumat< REAL > &x, cpuvec< REAL > &s)
Computes the singular value decomposition.
Definition: svd.hh:101
fml
Core namespace.
Definition: dimops.hh:10