the lastest pca lib by Castle

Dependents:   the-lastest-code mbed-test-i2c-PCA-biquad-peakdet

Files at this revision

API Documentation at this revision

Comitter:
castlefei
Date:
Mon Nov 25 14:26:29 2019 +0000
Commit message:
PCA lib by Castle; ;

Changed in this revision

pca.cpp Show annotated file Show diff for this revision Revisions of this file
pca.h Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r 8670ef66c0e3 pca.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pca.cpp	Mon Nov 25 14:26:29 2019 +0000
@@ -0,0 +1,72 @@
+
+#include "pca.h"
+#include <Eigen/Dense.h>
+
+using namespace Eigen;
+
+ /*
+  * Normalize the Matrix X
+  */
+ MatrixXd PCA::featurnormail(MatrixXd &X)
+{
+    //I don't know why to use the transpose
+    //compute the mean of every dimension
+    MatrixXd X1 = X.transpose();
+    MatrixXd meanval = X1.colwise().mean();
+    
+    //normalization
+    RowVectorXd meanvecRow = meanval;
+    X1.rowwise() -= meanvecRow;
+    
+    return X1.transpose();
+}
+
+ /*
+  * Compute the Covariane Matrix of X, put to C
+  * C = 1/m * X * X.transpose 
+  */
+void PCA::ComComputeCov(MatrixXd &X, MatrixXd &C)
+{
+   
+    C = X*X.adjoint();//same as XT*X a
+    //translate to array
+    C = C.array() / X.cols();
+}
+ 
+ 
+/*
+ * Compute the eigenvalue and eigenvector of C
+ * val = (first eigenvalue) --smallest --not important
+ *              .
+ *              .
+ *              .
+ *       (last eigenvalue)  --largest -- important
+ *
+ * vec = (first eigenvector, ... , last eigenvector)
+ *           not important          important
+ */
+void PCA::ComputEig(MatrixXd &C, MatrixXd &vec, MatrixXd &val)
+{
+    //SelfAdjointEigenSolver will sort the values automatically
+    SelfAdjointEigenSolver<MatrixXd> eig(C);
+    vec = eig.eigenvectors();
+    val = eig.eigenvalues();
+}
+ 
+/* Compute the dimension need to include enough information of raw data.
+ * form large index to small index, since the val is sorted from small to large.
+ * in some cases, just decide the number of dimension, instead of compute it.
+ */
+int PCA::ComputDim(MatrixXd &val)
+{
+    int dim;
+    double sum = 0;
+    for (int i = val.rows() - 1; i >= 0;--i)
+    {
+        sum += val(i, 0);
+        dim = i;
+        if (sum / val.sum()>=0.8)//80% of the information
+            break;
+    }
+    return val.rows() - dim;
+}
\ No newline at end of file
diff -r 000000000000 -r 8670ef66c0e3 pca.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pca.h	Mon Nov 25 14:26:29 2019 +0000
@@ -0,0 +1,24 @@
+#ifndef PCA_H
+#define PCA_H
+
+
+#include <Eigen/Dense.h>
+
+
+using namespace Eigen;
+
+class PCA {
+    
+public:
+    MatrixXd featurnormail(MatrixXd &X);
+    void ComComputeCov(MatrixXd &X, MatrixXd &C);
+    void ComputEig(MatrixXd &C, MatrixXd &vec, MatrixXd &val);
+    int ComputDim(MatrixXd &val);
+ 
+    
+    //MatrixXd acc_raw(3,0);
+ };
+
+
+
+#endif //PCA_H
\ No newline at end of file