一种使这种数组/矩阵乘法更快的方法?在R

时间:2015-02-14 21:31:40

标签: r matrix parallel-processing

我想不出能让这段代码更快的方法。是否有运行速度更快的应用功能?现在,我使用for循环并行运行这个循环,它仍然需要很长时间。

ndraws=20000
nhousehold=18831
m=12


    elasticitydraws = array(0,c(m,ndraws,nhousehold))
    MAPelasticity = matrix(0,nhousehold,m)
    medianpricemat = matrix(rnorm(12,15,1),12,1)                                 


# dim(out$betadraw) = 18831, 12, 20000
# dim(medianpricemat) = 12, 1

    library(foreach)
    library(doMC)
    registerDoMC(10)

    elasticitylist = foreach(i=1:nhousehold) %dopar% {

            pricedraws = out$betadraw[i,12,] 
            elasticitydraws[,,i]= probarray[,,i] %*% diag(pricedraws)
            elasticitydraws[,,i] = elasticitydraws[,,i] * as.vector(medianpricemat)
            MAPelasticity[i,] = apply(elasticitydraws[,,i],1,mean)

    } 

1 个答案:

答案 0 :(得分:2)

代码中的瓶颈是创建一个大密集对角矩阵和矩阵乘法。最好使用稀疏矩阵和Matrix包。这节省了内存和计算时间。我还包括了卡尔的评论,并在循环之外创建了一些向量。

library(Matrix)

medianpricemat <-  as.vector(medianpricemat)
D1 <- Diagonal(x=pricedraws)

elasticitylist = foreach(i=1:nhousehold) %dopar% {
    pricedraws = out$betadraw[i,12,] 
    tmp = probarray[,,i] %*% D1
    elasticitydraws[,,i] = as.matrix(tmp) * medianpricemat
    MAPelasticity[i,] = rowMeans(elasticitydraws[,,i])
} 

不太明显的黑客是避免创建对角矩阵和 矩阵乘法:

D2 <- rep(pricedraws, each=m)

elasticitylist = foreach(i=1:nhousehold) %dopar% {
    pricedraws = out$betadraw[i,12,] 
    tmp = probarray[,,i] * D2  # element wise multiplication 
    elasticitydraws[,,i] = as.matrix(tmp) * medianpricemat
    MAPelasticity[i,] = rowMeans(elasticitydraws[,,i]) 
}