【问题标题】:Memory and time efficient competition of correlation between each column in a large matrix and a vector大矩阵中每一列与向量之间的相关性的内存和时间有效竞争
【发布时间】:2016-10-20 17:00:16
【问题描述】:

这个问题扩展了this post,与machine learningfeature selection 过程有关,其中我有一个大的特征矩阵,我想通过测量feature selection 之间的correlation每对特征和响应之间的外积,因为我将使用random forestboosting classifier

特征数约为 60,000,响应数约为 2,200,000。

考虑到无限的内存,最快的解决方法可能是生成一个matrix,其中列是所有功能对的外部产品,并使用cor 中的matrix 来对抗响应。作为一个更小的维度示例:

set.seed(1)
feature.mat <- matrix(rnorm(2200*100),nrow=2200,ncol=100)
response.vec <- rnorm(2200)

#generate indices of all unique pairs of features and get the outer products:
feature.pairs <- t(combn(1:ncol(feature.mat),2))
feature.pairs.prod <- feature.mat[,feature.pairs[,1]]*feature.mat[,feature.pairs[,2]]

#compute the correlation coefficients
res <- cor(feature.pairs.prod,response.vec)

但是对于我的真实尺寸feature.pairs.prod 是 2,200,000 x 1,799,970,000,显然无法存储在内存中。

所以我的问题是,是否以及如何在合理的计算时间内获得所有相关性?

我在想也许将feature.pairs.prod 分解为适合内存的块,然后在它们之间执行corresponse.vec 一次将是最快的,但我不确定如何自动测试在R 我需要这些块的尺寸。

另一种选择是applyfeature.pairs 之上的一个函数,它将计算外积,然后在它和response.vec 之间计算cor

有什么建议吗?

【问题讨论】:

  • 从某种意义上说,这非常相似,最合理的解决方案是我的第一个建议是将 feature.pairs.prod 矩阵分解为块并循环它们。不过,给定 feature.mat,是否有一种 R 方法可以从我的系统资源中计算出块大小?

标签: r memory matrix correlation memory-efficient


【解决方案1】:

是的,分块计算是要走的路。这在Out of memory when using outer in solving my big normal equation for least squares estimation 中也是类似的。

步骤无需更改:

set.seed(1)
feature.mat <- matrix(rnorm(2200*100),nrow=2200,ncol=100)
response.vec <- rnorm(2200)

#generate indices of all unique pairs of features and get the outer products:
feature.pairs <- t(combn(1:ncol(feature.mat),2))
j1 <- feature.pairs[,1]
j2 <- feature.pairs[,2]

但是我们需要将j1j2 分成块:

## number of data
n <- nrow(feature.mat)
## set a chunk size
k <- 1000
## start and end index of each chunk
start <- seq(1, length(j1), by = k)
end <- c(start[-1] - 1, length(j1))

## result for the i-th chunk
chunk_cor <- function (i) {
  jj <- start[i]:end[i]
  jj1 <- j1[jj]; jj2 <- j2[jj]
  feature.pairs.prod <- feature.mat[,jj1] * feature.mat[,jj2]
  cor(feature.pairs.prod,response.vec)
  }

## now we loop through all chunks and combine the result
res <- unlist(lapply(1:length(start), chunk_cor))

主要问题是如何决定k

如链接答案所示,我们可以计算内存占用。如果您有n 行和k 列(块大小),则n * k 矩阵的内存成本为n * k * 8 / 1024 / 1024/ 1024 GB。您可以设置进入的内存限制;那么既然知道n,就可以解k

检查函数 f 的内存成本:feature.mat[,jj1]feature.mat[,jj2]feature.pairs.prod 都需要生成和存储。所以我们有内存大小:

3 * n * k * 8 / 1024 / 1024/ 1024 GB

现在假设我们要限制4GB下的内存占用,给定n,我们可以解决k

k <- floor(4 * 2^30 / (24 * n))

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多