美文网首页做实验
PCA原理及实现-R

PCA原理及实现-R

作者: jamesjin63 | 来源:发表于2020-10-01 14:52 被阅读0次

    PCA分析与解释

    PCA是一种无参数的数据降维方法,常用的机器学习算法一种,这篇文章主要从PCA应用于解释两个方面介绍。关于PCA原理,详情这里

    PCA主要是,在数据处理与分析时候,一个数据集有很多变量(维度),譬如患者肿瘤发生,有吸烟,饮食等生活史,和临床生化检查等,这些变量间相互关联,纳入模型,影响效率与模型构建。所以PCA就是从众多变量中找出特征值,能够代表这些变量,来解释最终结果。

    接下来,就在R环境中,用iris数据,来构建PCA模型与解释如何应用PCA模型。

    PCA实例

    通过iris数据集,根据测量花瓣的长度,宽度等信息,对花Species的种类进行聚类分析。首先将iris数据集分成两部分,train用于训练,test用于测试。在进行PCA分析之前,需要确保所有的变量数据类型为连续性变量,分类变量是不识别的!而且为避免变量与变量之间量纲差异,需要对连续性变量进行scale标准化。

    #####
    library(factoextra)
    library(tidyverse)
    
    # Split Data into Training and Testing in R 
    sample_size = floor(0.8*nrow(iris))
    set.seed(777)
    
    # randomly split data in r
    picked = sample(seq_len(nrow(iris)),size = sample_size)
    df1 =iris[picked,] %>% as.tbl()
    df2 =iris[-picked,] %>% as.tbl()
    
    ## 1.pca
    res.pca <- prcomp(df1[,-5], scale = T) # 标准化
    
    

    现在可以对数据进行PCA分析了,一般有多少个连续变量,就会有多少特征向量,特征向量是什么,见这里。为什么要计算特征向量就是要将所有变量转换为特征值eigen vector,每个特征值都可以解释的差异百分比!Factors that add minimal variance explanation can be removed.
    可以对PCA模型进行,plot

    ## 2.the percentage of variances explained by each principal component.
    fviz_eig(res.pca)
    
    
    image.png

    这个图表示,前两个特征向量(PCA)解释了超过95%的方差,仅第一个维度就解释了73.1%。我们可以放心地将聚类分析集中在两个维度上,原来6个变量,可以用两个特征向量来表示!现在根据PCA 1与PCA 2,来对数据进行绘图!

    ## 3.Individuals with a similar profile are grouped together.
    fviz_pca_ind(res.pca,
                 col.ind = "cos2", # Color by the quality of representation
                 gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
                 repel = TRUE     # Avoid text overlapping
    )
    
    
    image.png

    进一步我们需要知道,每个变量与特征向量的关系如何,PCA bilplot!
    这个图表显示了每个原始变量对每个新PCA的影响程度。对于PCA1来说,"Sepal.Length"、"Petal.Length"、 "Petal.Width" 都是正相关,只有"Sepal.Width" 是负相关,根据Dim1的坐标判断。而对于PCA2,全是负相关PCA biplot解释,根据Dim1的坐标判断。而对于PCA2,全是正相关。根据变量之间的夹角,还可以判断变量与变量间的相关系,夹角小于90度为正相关,大于90度为负相关,等于90度,没有相关性,可以验证下。

    ## 3.Individuals with a similar profile are grouped together.
    
    fviz_pca_var(res.pca, col.var = "contrib", 
                 gradient.cols = c("white", "blue", "red"),
                 ggtheme = theme_minimal())
    
    fviz_pca_biplot(res.pca, label = "var", habillage=df1$Species,
                    addEllipses=TRUE, ellipse.level=0.95,
                    ggtheme = theme_minimal())
    
    cor(df1[,-5])
                 Sepal.Length Sepal.Width Petal.Length Petal.Width
    Sepal.Length    1.0000000  -0.1183494    0.8625614   0.8117941
    Sepal.Width    -0.1183494   1.0000000   -0.4480079  -0.3872041
    Petal.Length    0.8625614  -0.4480079    1.0000000   0.9633883
    Petal.Width     0.8117941  -0.3872041    0.9633883   1.0000000
    
    image.png

    根据两个特征向量,可以确定花的种类分布,那么图上每一类species散点落在一个范围内,我们计算这个范围的中心点。

    ## 4.Graph of Coordinate
    fviz_pca_ind(res.pca,
                 col.ind = df1$Species, # color by groups
                 palette = c("#00AFBB",  "#FC4E07","black"),
                 addEllipses = TRUE, # Concentration ellipses
                 ellipse.type = "confidence",
                 ellipse.level=0.95,
                 legend.title = "Groups",
                 ggtheme = theme_minimal())
    
    ## 5. Coordinate of groups
    coord.groups <- res.ind$coord %>%
      as_data_frame() %>%
      select(Dim.1, Dim.2) %>%
      mutate(Species = df1$Species) %>%
      group_by(Species) %>%
      summarise(
        Dim.1 = mean(Dim.1),
        Dim.2 = mean(Dim.2))
    
    coord.groups
    
    # A tibble: 3 x 3
    Species     Dim.1  Dim.2
    <fct>       <dbl>  <dbl>
      1 setosa      2.10   0.278
    2 versicolor -0.570 -0.529
    3 virginica  -1.82   0.248
    
    image.png

    PCA预测

    根据上面建立的PCA!我们用test数据集,测试下,预测分类的准确性!
    余下的30个数据, 用predict,放入Sepal.Length Sepal.Width Petal.Length Petal.Width四个变量。然后提取PCA1与PCA2,根据PCA1,PCA2对应的坐标,可以看出,30个点在图上的位置,及对应的区。

    ### predict
    #ind.sup=veteran %>% select(-trt) %>% as.tbl() %>% slice(101:136)
    ind.sup.coord <- predict(res.pca, newdata = df2)
    ind.sup.coord[, 1:4]
    
    # df1
    coord1 = res.ind$coord %>%
      as_data_frame() %>%
      select(Dim.1, Dim.2) %>%
      mutate(Species = df1$Species) %>% set_names("PC1","PC2","Species")
    
    # df2
    coord2 =ind.sup.coord[, 1:2] %>% as_data_frame() %>% 
      mutate(Species = df2$Species) 
    
    # plot
    coord1 %>% bind_rows(coord2) %>% 
      ggplot()+
      geom_point(aes(PC1,PC2,group=Species,color=Species),shape=0,size=3)+
      geom_point(data=coord2,aes(PC1,PC2),fill=0.1)
    
    image.png

    获取PCA各个参数

    library(factoextra)
    # Eigenvalues
    eig.val <- get_eigenvalue(res.pca)
    eig.val
    
    # Results for Variables
    res.var <- get_pca_var(res.pca)
    res.var$coord          # Coordinates
    res.var$contrib        # Contributions to the PCs
    res.var$cos2           # Quality of representation 
    # Results for individuals
    res.ind <- get_pca_ind(res.pca)
    res.ind$coord          # Coordinates
    res.ind$contrib        # Contributions to the PCs
    res.ind$cos2           # Quality of representation 
    

    未完待续;下一篇将介绍如何确定聚类分区

    参考

    1. General methods for principal component analysis
    2. PCA in R
    3. 一文了解R语言数据分析 ----主成分分析

    相关文章

      网友评论

        本文标题:PCA原理及实现-R

        本文链接:https://www.haomeiwen.com/subject/hrbsuktx.html