gpt4 book ai didi

r - 在 R 中有效地居中大型矩阵

转载 作者:行者123 更新时间:2023-12-03 03:00:37 24 4
gpt4 key购买 nike

我有一个大矩阵,我想将其居中:

X <- matrix(sample(1:10, 5e+08, replace=TRUE), ncol=10000)

使用 colMeans 可以快速高效地查找均值:

means <- colMeans(X)

但是从每列中减去各自的平均值的好(快速且内存高效)方法是什么?这可行,但感觉不对:

for (i in 1:length(means)){
X[,i] <- X[,i]-means[i]
}

有更好的方法吗?

/edit:这是 DWin 在更大的矩阵上编写的各种基准的修改,包括其他发布的建议:

require(rbenchmark)
X <- matrix(sample(1:10, 5e+07, replace=TRUE), ncol=10000)
frlp.c <- compiler:::cmpfun(function(mat){
means <- colMeans(mat)
for (i in 1:length(means)){
mat[,i] <- mat[,i]-means[i]
}
return(mat)
})

mat.c <- compiler:::cmpfun(function(mat){
t(t(X) - colMeans(X))
})

swp.c <- compiler:::cmpfun(function(mat){
sweep(mat, 2, colMeans(mat), FUN='-')
})

scl.c <- compiler:::cmpfun(function(mat){
scale(mat, scale=FALSE)
})

matmult.c <- compiler:::cmpfun(function(mat){
mat-rep(1, nrow(mat)) %*% t(colMeans(mat))
})

benchmark(
frlp.c=frlp.c(X),
mat=mat.c(X),
swp=swp.c(X),
scl=scl.c(X),
matmult=matmult.c(X),
replications=10,
order=c('replications', 'elapsed'))

matmult 函数似乎成为新的赢家!我真的很想在 5e+08 元素矩阵上尝试这些,但我的 RAM 一直不够用。

     test replications elapsed relative user.self sys.self user.child sys.child
5 matmult 10 11.98 1.000 7.47 4.47 NA NA
1 frlp.c 10 35.05 2.926 31.66 3.32 NA NA
2 mat 10 50.56 4.220 44.52 5.67 NA NA
4 scl 10 58.86 4.913 50.26 8.42 NA NA
3 swp 10 61.25 5.113 51.98 8.64 NA NA

最佳答案

这对你有用吗?

sweep(X, 2, colMeans(X)) # this substracts the colMean to each col
scale(X, center=TRUE, scale=FALSE) # the same

sweep(X, 2, colMeans(X), FUN='/') # this makes division

如果您想加速基于 for 循环的代码,您可以使用 compiler 包中的 cmpfun 。示例

X <- matrix(sample(1:10, 500000, replace=TRUE), ncol=100) # some data
means <- colMeans(X) # col means

library(compiler)

# One of your functions to be compiled and tested
Mean <- function(x) {
for (i in 1:length(means)){
X[,i] <- X[,i]-means[i]
}
return(X)
}



CMean <- cmpfun(Mean) # compiling the Mean function

system.time(Mean(X))
user system elapsed
0.028 0.016 0.101
system.time(CMean(X))
user system elapsed
0.028 0.012 0.066

也许这个建议可以帮助你。

关于r - 在 R 中有效地居中大型矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12332310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com