R语言 进行主成分分析

R语言 进行主成分分析

R编程中的主成分分析(PCA) ,是对所有现有属性的线性成分的分析。主成分是数据集中原始预测因子的线性组合(正交变换)。它是EDA(探索性数据分析)的一种有用的技术,可以让你更好地可视化具有许多变量的数据集中存在的变化。

R语言 主成分分析

第一个主成分 捕捉到了数据集中的最大差异。它决定了更高的变异性方向。 第二个主成分 捕捉了数据中剩余的变异,与PC1不相关。PC1和PC2之间的相关性应该为零。因此,所有后续的主成分都遵循同样的概念。它们捕捉剩余的方差,而不与前一个主成分相关。

数据集

数据集 mtcars (motor trend car road test)包括32辆汽车的油耗和汽车设计和性能的10个方面。它预先安装了R语言中的dplyr包。

# Installing required package
install.packages("dplyr")
 
# Loading the package
library(dplyr)
 
# Importing excel file
str(mtcars)

输出

用R编程进行主成分分析

使用R语言的主成分分析数据集

我们对包含32个汽车品牌和10个变量的 MTCars 进行主成分分析。

# Loading Data
data(mtcars)
 
# Apply PCA using prcomp function
# Need to scale / Normalize as
# PCA depends on distance measure
my_pca <- prcomp(mtcars, scale = TRUE,
                center = TRUE, retx = T)
names(my_pca)
 
# Summary
summary(my_pca)
my_pca
 
# View the principal component loading
# my_pcarotation[1:5, 1:4]
my_pcarotation
 
# See the principal components
dim(my_pcax)
my_pcax
 
# Plotting the resultant principal components
# The parameter scale = 0 ensures that arrows
# are scaled to represent the loadings
biplot(my_pca, main = "Biplot", scale = 0)
 
# Compute standard deviation
my_pcasdev
 
# Compute variance
my_pca.var <- my_pcasdev ^ 2
my_pca.var
 
# Proportion of variance for a scree plot
propve <- my_pca.var / sum(my_pca.var)
propve
 
# Plot variance explained for each principal component
plot(propve, xlab = "principal component",
            ylab = "Proportion of Variance Explained",
            ylim = c(0, 1), type = "b",
            main = "Scree Plot")
 
# Plot the cumulative proportion of variance explained
plot(cumsum(propve),
    xlab = "Principal Component",
    ylab = "Cumulative Proportion of Variance Explained",
    ylim = c(0, 1), type = "b")
 
# Find Top n principal component
# which will atleast cover 90 % variance of dimension
which(cumsum(propve) >= 0.9)[1]
 
# Predict mpg using first 4 new Principal Components
# Add a training set with principal components
train.data <- data.frame(disp = mtcarsdisp, my_pcax[, 1:4])
 
# Running a Decision tree algporithm
## Installing and loading packages
install.packages("rpart")
install.packages("rpart.plot")
library(rpart)
library(rpart.plot)
 
rpart.model <- rpart(disp ~ .,
                    data = train.data, method = "anova")
 
rpart.plot(rpart.model)

输出

  • 生物图

用R编程进行主成分分析

  • 结果主成分被绘制成 Biplot。 标度值为0表示箭头按比例代表负荷。
  • 每个主成分的方差解释

用R编程进行主成分分析

  • Scree Plot 表示方差和主成分的比例。从图中可以清楚地看到,在2个主成分以下,有一个最大的方差比例。
  • 累积方差比例

用R编程进行主成分分析

  • Scree Plot 表示方差和主成分的累积比例。在2个主成分以上,有一个最大的累积方差比例,这在图中可以清楚地看到。
  • 决策树模型

用R编程进行主成分分析

  • 决策树 模型的建立是为了利用数据集中的其他变量和方差分析方法来预测 disp 。决策树图被绘制出来并显示了相关信息。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程