R实现PCA降维
PCA(Principal Component Analysis),即主成分分析方法,是一种使用广泛的数据降维算法。详细的概念可以参照https://zhuanlan.zhihu.com/p/37777074
一般将多个样本降维就可以得到二维的分布,相似的样本成为一群,但有时候我们想知道哪些特征导致了这样的分群。
这里我们主要讨论怎么样用R实现以及提取我们需要的特征:
用R实现PCA有多个方法:
prcomp() and princomp() [built-in R stats package],
PCA() [FactoMineR package],
dudi.pca() [ade4 package],
and epPCA() [ExPosition package]
install.packages(c("FactoMineR", "factoextra"))
library("FactoMineR")
library("factoextra")
#输入的data.frame
data(decathlon2)
head(decathlon2)

decathlon2是一个27行,13列的data.frame,分析之前需要用scale()函数进行标准化,消除不同量纲之间的差距。在计算PCA的时候也有很多内置的scale参数,如:FactoMineR包里函数PCA(X, scale.unit = TRUE, ncp = 5, graph = TRUE)里面的 scale.unit = TRUE,则进行标准化,或者
library("FactoMineR")
decathlon2.active <- decathlon2[1:23, 1:10]
res.pca <- PCA(decathlon2.active, graph = T)
降维的分群图(这个没有明显的分群)

作为分群依据的特征值和特征向量

我们可以通过这些函数提取需要的数据:
get_eigenvalue(res.pca): 提取特征值
fviz_eig(res.pca): 可视化特征值
library("factoextra")
eig.val <- get_eigenvalue(res.pca)
eig.val

从中我们看到前两个PC可以涵盖59.6%variance,一般用涵盖百分之八十以上的variance就够了,也可以用碎石图展示。
fviz_eig(res.pca, addlabels = TRUE, ylim = c(0, 50))

cos2cos2 (square cosine, squared coordinates) 能够代表某个PC的代表性的特征值:
var<-get_pca_var(res.pca)
var

head(var$cos2, 10)

fviz_pca_var(res.pca, col.var = "cos2",
gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
repel = TRUE # Avoid text overlapping
)

欢迎关注~
