【问题标题】:How to plot a new vector onto a PCA space in R如何将新向量绘制到 R 中的 PCA 空间上
【发布时间】:2016-09-19 11:45:40
【问题描述】:

我是 R 中主成分分析的新手,我的问题很幼稚。我已经使用 R 中的函数 'prcomp' 完成了矩阵 (A) 的 PCA。现在我想在 A 的 PC1 和 PC2 的 PCA 空间上绘制一个向量。我该如何绘制这个向量?

【问题讨论】:

    标签: r machine-learning data-mining pca


    【解决方案1】:

    使用biplot(红色箭头是原始空间中的尺寸):

    a <- princomp(iris[1:4])
    biplot(a, cex=0.5)
    

    您也可以自行投影到 PCA 空间,如下所示:

    library(ggplot2)
    data <- iris[1:4]
    labels <- iris[,5]
    res <- princomp(data)
    res.proj <- as.matrix(data) %*% res$loadings[,1:2]
    ggplot(as.data.frame(res.proj), aes(Comp.1, Comp.2, col=labels)) + geom_point()
    

    使用 prcomp 的相同图(数值更稳定):

    data <- iris[1:4]
    labels <- iris[,5]
    res <- prcomp(data)
    res.proj <- as.matrix(data) %*% res$rotation[,1:2]
    ggplot(as.data.frame(res.proj), aes(PC1, PC2, col=labels)) + geom_point()
    

    更高级的 ggbiplot:

    library(ggbiplot)
    g <- ggbiplot(res, obs.scale = 1, var.scale = 1, 
                  groups = labels, ellipse = TRUE, 
                  circle = TRUE)
    g <- g + scale_color_discrete(name = '')
    g <- g + theme(legend.direction = 'horizontal', 
                   legend.position = 'top')
    print(g)
    

    【讨论】:

    • 值得注意的是,使用prcomp是R中的首选方式。princomp的存在是为了与S-PLUS兼容。
    • 如果需要数值稳定性,请使用 prcomp 代替,因为它使用 svd。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多