簡體   English   中英

加快R中的循環

[英]Speed up a loop in R

我正在使用以下函數來估計某些數據的內核密度

KDens = function(x,h,N) {
         fx = matrix(0,N,1)
         Kx = AK(x,h,N)
         for (i in 1:N) {
         fx[i] = sum(Kx[i,], na.rm=T)/N
         }
         return(fx) }

我知道這不是關於加快循環速度的第一個問題。 我在該站點中進行了檢查,發現有時使用一些apply功能會更快,但是如果您能夠正確設置循環,這種情況並非總是如此。

在上面的代碼中,每個“不需要的東西”都被排除在循環之外,因為-如果我理解正確的話-建議加快計算速度。 但是,我將上述KDens函數與默認情況下在R中實現的density函數進行了比較。 好吧, density需要1或2秒,而我的機器上KDens需要30秒。

trywiththis <- rnorm(4800)
x = trywiththis
N = length(trywiththis)
h = 1.059*sd(trywiththis , na.rm=T)*(N^(-0.2))

編輯:我提供的信息不完整

kerf = function(x){ return(dnorm(x)) }
ker = function(x,x0,h){
       temp = kerf((x-x0)/h)/h
       return(temp)
       }

AK = function(x,h,N) {
      K = array(0,c(N,N))                 
         for (i in 1:N) {
         for (j in 1:N) {
         K[i,j] = ker(x[i],x[j],h) 
       }}
       return(K) }

假設我想加快KDens功能,我該怎么做?

嘗試一下...對於原始的4800長度數據集,此過程需要2.5秒。

KDens2 = function(x,h,N) {
Kx <- outer( x , x , FUN = function(x,y) dnorm( ( x-y ) / h ) / h )
fx <- as.matrix( rowSums( Kx ) / N , ncol = 1 )
return( fx )
}

測試中

set.seed(1)
trywiththis <- rnorm(480)
x = trywiththis
N = length(trywiththis)
h = 1.059*sd(trywiththis , na.rm=T)*(N^(-0.2))

#Produce same result? (posibly not identical because of 'dnorm' function)
all.equal( KDens(x,h,N) , KDens2(x,h,N) )
[1] TRUE

#Rough timing on N=480 length data...
system.time( KDens2(x,h,N) )
#   user  system elapsed 
#   0.01    0.00    0.02 

system.time( KDens(x,h,N) )
#   user  system elapsed 
#    2.7     0.0     2.7 

N=4800 ...

system.time( KDens2(x,h,N) )
   user  system elapsed 
   2.33    0.19    2.51

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM