【发布时间】:2020-11-15 18:39:22
【问题描述】:
使用以下 Box1 的 R 代码进行了两种不同的主成分分析方法来分析以下数据 (ch082.dat)。
https://drive.google.com/file/d/1xykl6ln -bUnXIs-jIA3n5S3XgHjQbkWB/view?usp=sharing
第一种方法使用旋转矩阵(参见 Box1 代码的“#rotated data”下的“ans_mat”),并且, 第二种方法使用'pcomp'函数(参见Box1代码的'#rotated data'下的'rpca')。
但是,使用旋转矩阵的方法和使用“pcomp”函数的方法之间的答案存在细微的差异。 让它匹配
我的问题
我应该怎么做才能使基于旋转矩阵的方法的结果与'pcomp'函数的结果相匹配?
就我尝试过的各种数据(包括其他数据)而言,实际差异似乎仅限于规模变化和镜像转换。
- 基于旋转矩阵的方法的结果显示在左侧面板中。
- 基于 pcomp 函数的方法的结果显示在右侧面板中。
镜像反转可见“ch082.dat”数据。(见图1);
似乎在某些 j 中,“相关矩阵的第 j 个特征向量”的符号和“prcomp 函数的输出值的第 j 列”的符号可能是相反的。如果特征值有一定程度的重叠,则差异可能比镜像反演更复杂。
图1
尽管对数据进行了集中化和标准化,但 Box2 的数据存在规模变化(参见图 2)。
图2
Box.1
#dataload
##Use the 'setwd' function to specify the directory containing 'ch082.dat'.
##For example, if you put this file directly under the C drive of your Windows PC, you can run the following command.
setwd("C:/") #Depending on where you put the file, you may need to change the path.
getwd()
w1<-read.table("ch082.dat",header = TRUE,row.names = 1,fileEncoding = "UTF-8")
w1
#Function for standardizing data
#Thanks to https://qiita.com/ohisama2/items/5922fac0c8a6c21fcbf8
standalize <- function(data)
{ for(i in length(data[1,]))
{
x <- as.matrix(data[,i])
y <- (x-mean(x)/sd(x))
data[,i] <- y
}
return(data)}
#Method using rotation matrix
z_=standalize(w1)
B_mat=cor(z_) #Compute correlation matrix
eigen_m <- eigen(B_mat)
sample_mat <- as.matrix(z_)
ans_mat=sample_mat
for(j in 1:length(sample_mat[1,])){
ans_mat[,j]=sample_mat%*%eigen_m$vectors[,j]
}
#Method using "rpca" function
rpca <- prcomp(w1,center=TRUE, scale=TRUE)
#eigen vectors
eigen_m$vectors
rpca
#rotated data
ans_mat
rpca$x
#Graph Plots
par(mfrow=c(1,2))
plot(
ans_mat[,1],
ans_mat[,2],
main="Rotation using eigenvectors"
)
plot(rpca$x[,1], rpca$x[,2],
main="Principal component score")
par(mfrow=c(1,1))
#summary
summary(rpca)$importance
盒子2。
sample_data <- data.frame(
X = c(2,4, 6, 5,7, 8,10),
Y = c(6,8,10,11,9,12,14)
)
X = c(2,4, 6, 5,7, 8,10)
Y = c(6,8,10,11,9,12,14)
plot(Y ~ X)
w1=sample_data
参考
https://logics-of-blue.com/principal-components-analysis/
(用日文写的)
【问题讨论】:
标签: r statistics pca