相信,看了這系列的文章後,讀者應該對Dimension Reduction和PCA都有些基本的認識了。接下來,讓我們進入實作的成面。
下面,我們將介紹R的兩個內建計算PCA的指令 — princomp / prcomp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
首先,我們先測試最簡單的直線的data。
整個Data躺在 這條直線上。其中 。
如下方的code和圖:
N_data <- 30 test_data <- as.matrix(1:N_data) test_data <- cbind(test_data,0.5*test_data)
接下來,我們分別用兩種指令,對test_data作PCA的分析:
(1) 使用princomp:
執行下方的code後
test_data_PCA_princomp <-princomp(test_data) str(test_data_PCA_princomp)
我們會在R console中看到:
> test_data_PCA_princomp <- princomp(test_data) > str(test_data_PCA_princomp) List of 7 $ sdev : Named num [1:2] 9.68 0 ..- attr(*, "names")= chr [1:2] "Comp.1" "Comp.2" $ loadings: loadings [1:2, 1:2] -0.894 -0.447 0.447 -0.894 ..- attr(*, "dimnames")=List of 2 .. ..$ : NULL .. ..$ : chr [1:2] "Comp.1" "Comp.2" $ center : num [1:2] 15.5 7.75 $ scale : num [1:2] 1 1 $ n.obs : int 30 $ scores : num [1:30, 1:2] 16.2 15.1 14 12.9 11.7 ... ..- attr(*, "dimnames")=List of 2 .. ..$ : NULL .. ..$ : chr [1:2] "Comp.1" "Comp.2" $ call : language princomp(x = test_data) - attr(*, "class")= chr "princomp"
也就是說,princomp這個指令所回傳的物件中,有7個attributes:sdev、loadings、center、scale、n.obs、scores、call
其中,比較常使用的,如下:
- sdev:為 Row data Matrix 的 Eigenvalues
- loadings:為 Row data Matrix 的 Eigenvectors
- center:為 Row data 的 Mean
- scores:為 Row data Matrix 投影在 Eigenvectors 上面的坐標
~~~~~~~~~~~~~~~~~~~~~~
(2) 使用prcomp:
同樣的,執行下方的code後
test_data_PCA_prcomp <- prcomp(test_data) str(test_data_PCA_prcomp)
我們會在R console中看到:
> test_data_PCA_prcomp <- prcomp(test_data) > str(test_data_PCA_prcomp) List of 5 $ sdev : num [1:2] 9.84 3.33e-16 $ rotation: num [1:2, 1:2] 0.894 0.447 0.447 -0.894 ..- attr(*, "dimnames")=List of 2 .. ..$ : NULL .. ..$ : chr [1:2] "PC1" "PC2" $ center : num [1:2] 15.5 7.75 $ scale : logi FALSE $ x : num [1:30, 1:2] -16.2 -15.1 -14 -12.9 -11.7 ... ..- attr(*, "dimnames")=List of 2 .. ..$ : NULL .. ..$ : chr [1:2] "PC1" "PC2" - attr(*, "class")= chr "prcomp"
也就是說,prcomp這個指令所回傳的物件中,有5個attributes:sdev、rotation、center、scale、x
其中,比較常用的attributes如下:
- sdev:為 Row data Matrix 的 Eigenvalues
- rotation:為 Row data Matrix 的 Eigenvectors
- center:為 Row data 的 Mean
- x:為 Row data Matrix 投影在 Eigenvectors 上面的坐標
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
回Topic: Introduction to Dimension Reduction
上一篇:
下一篇: R的內建PCA指令 — princomp / prcomp [簡單的例子]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~