主要组件功能Incanter

时间:2014-03-26 23:08:01

标签: matrix clojure pca incanter principal-components

我一直在尝试使用Incanter的principal-components功能进行PCA,并且似乎在使用它时偏离轨道。我在PCA教程中在线发现了一些样本数据,并希望对其进行练习:

(def data [[0.69 0.49] [-1.31 -1.21] [0.39 0.99] [0.09 0.29] [1.29 1.09] 
           [0.49 0.79] [0.19 (- 0 0.31)] [(- 0 0.81) (- 0 0.81)] 
           [(- 0 0.31) (- 0 0.31)] [(- 0 0.71) (- 0 1.01)]])

在第一次尝试实现PCA时,我尝试将向量传递给Incanter的矩阵函数,但发现自己传递了太多的参数。此时我决定尝试上面定义的嵌套向量结构,但是想避免这种路由。

如何将data转换为矩阵(Incanter),以便将其作为Incanter函数principal-components的输入。为简单起见,我们调用新的矩阵fooMatrix。

一旦构造了这个矩阵fooMatrix,下面的代码应该可以提取前两个主要组件

     (def pca (principal-components fooMatrix))
     (def components (:rotation pca))
     (def pc1 (sel components :cols 0))
     (def pc2 (sel components :cols 1)) 

然后可以通过

将数据投射到主成分上
     (def principal1 (mmult fooMatrix pc1)) 
     (def principal2 (mmult fooMatrix pc2))

1 个答案:

答案 0 :(得分:1)

查看Incanter API。我相信你只想要(incanter.core/matrix data)。这些是您对Incanter矩阵函数的选择。也许A2是你感兴趣的。

(def A (matrix [[1 2 3] [4 5 6] [7 8 9]])) ; produces a 3x3 matrix
(def A2 (matrix [1 2 3 4 5 6 7 8 9] 3)) ; produces the same 3x3 matrix
(def B (matrix [1 2 3 4 5 6 7 8 9])) ; produces a 9x1 column vector

使用您的数据的示例:

user=> (use '[incanter core stats charts datasets])
nil
user=>(def data [0.69 0.49 -1.31 -1.21 0.39 0.99 0.09 0.29 1.29
                1.09 0.49 0.79 0.19 (- 0 0.31) (- 0 0.81) (- 0 0.81)
                (- 0 0.31) (- 0 0.31) (- 0 0.71) (- 0 1.01)])
user=>(def fooMatrix (matrix data 2))
user=>(principal-components fooMatrix)
{:std-dev (1.3877785387777999 0.27215937850413047), :rotation  A 2x2 matrix
 -------------
-7.07e-01 -7.07e-01 
-7.07e-01  7.07e-01 
}

瞧。嵌套的矢量结构消失了。

相关问题