R:向后主成分计算

时间:2014-07-07 06:49:00

标签: r pca

我想在R中执行向后主成分计算,这意味着:通过PCA对象本身获取原始矩阵。

这是一个示例案例:

# Load an expression matrix
load(url("http://www.giorgilab.org/allexp_rsn.rda"))
# Calculate PCA
pca <- prcomp(t(allexp_rsn))

为了获得原始矩阵,人们应该将PCA本身的旋转倍增,如下:

test<-pca$rotation%*%pca$x

但是,正如您可能检查的那样,计算出的“测试”矩阵与原始的“allexp_rsn”矩阵完全不同。我究竟做错了什么?函数prcomp是否在svs过程中添加了其他内容?

谢谢: - )

3 个答案:

答案 0 :(得分:2)

使用USArrests

pca <- prcomp(t(USArrests))
out <- t(pca$x%*%t(pca$rotation))
out <- sweep(out, 1, pca$center, '+')
apply(USArrests - out, 2, sum)
   Murder       Assault      UrbanPop          Rape 
1.070921e-12 -2.778222e-12  3.801404e-13  1.428191e-12 

答案 1 :(得分:1)

请记住,执行PC分析的先决条件是缩放和居中数据。我相信prcomp过程会这样做,因此pca$x会返回缩放的原始数据(平均值为0,标准值等于1)。

答案 2 :(得分:1)

这是一个使用特征函数的解决方案,应用于B / W图像矩阵来说明这一点。该功能使用越来越多的PC,但您可以使用所有这些PC,或仅使用其中一些

library(gplots)
library(png) 
# Download an image:
download.file("http://www.giorgilab.org/pictures/monalisa.tar.gz",destfile="monalisa.tar.gz",cacheOK = FALSE)
untar("monalisa.tar.gz")
# Read image:
img <- readPNG("monalisa.png")
# Dimension
d<-1
# Rotate it:
rotate <- function(x) t(apply(x, 2, rev))
centermat<-rotate(img[,,d])
# Plot it
image(centermat,col=gray(c(0:100)/100))
# Increasing PCA
png("increasingPCA.png",width=2000,height=2000,pointsize=20)
par(mfrow=c(5,5),mar=c(0,0,0,0))
for(end in (1:25)*12){
    for(d in 1){
        centermat<-rotate(img[,,d])
        eig <- eigen(cov(centermat))
        n <- 1:end
        eigmat<-t(eig$vectors[,n] %*% (t(eig$vectors[,n]) %*% t(centermat)))
        image(eigmat,col=gray(c(0:100)/100))
    }
}
dev.off()

backwards PCA reconstruction by Federico Manuel Giorgi