[英]Fast Calculation Matrix in R
我有簡單的代碼,但是使用小數據集進行一次迭代花了0.006秒,我擔心這是因為我要在大數據集上使用它。 這是我的代碼
d1 = matrix(0, nrow(x), num.clust)
for(i in 1:ncol(d.num){
#For numeric attribute
d1.temp = (w*(d.num - matrix(rep(as.numeric(num.centroid[i,]), nrows),nrow = nrows, byrow = T)))^2
d1[,i] = rowSums(d1.temp)
}
這是我使用的數據框
> head(d.num)
x3 x4
4.842316 11.754403
6.405585 11.643502
6.590780 11.478245
6.656699 11.293404
> num.centroid
[,1] [,2]
[1,] 7.605837 12.59816
[2,] 7.895469 12.92275
w是大小為d.num的數據幀。 有什么建議可以減少這種情況下的執行時間嗎?
如果您按照我的建議將數據幀轉換為矩陣,則可以進行比較。
# original code
f1 <- function(n){
d.num <- data.frame(x3=round(rnorm(n)), x4 = round(rnorm(n)))
w <- d.num
num.centroid <- matrix(c(7,8,9,10), nrow=2)
nrows = nrow(d.num)
d1 <- matrix(NA_real_, nrow=nrows, ncol=ncol(d.num))
for(i in 1:ncol(d.num)){
d1.temp = (w*(d.num - matrix(rep(num.centroid[i,], nrows),
nrow = nrows, byrow = TRUE)))^2
d1[,i] = rowSums(d1.temp)
}
return(d1)
}
# using as.matrix
f2 <- function(n){
d.num <- data.frame(x3=round(rnorm(n)), x4 = round(rnorm(n)))
w <- d.num
d.num <- as.matrix(d.num)
w <- as.matrix(w)
num.centroid <- matrix(c(7,8,9,10), nrow=2)
nrows = nrow(d.num)
d1 <- matrix(NA_real_, nrow=nrows, ncol=ncol(d.num))
for(i in 1:ncol(d.num)){
d1.temp = (w*(d.num - matrix(rep(num.centroid[i,], nrows),
nrow = nrows, byrow = TRUE)))^2
d1[,i] = rowSums(d1.temp)
}
return(d1)
}
基准:
> library(microbenchmark)
> n <- 10
> microbenchmark(
+ code1 = f1(n),
+ code2 = f2(n),
+ times = 1000
+ )
Unit: microseconds
expr min lq mean median uq max neval
code1 1432.443 1480.8605 1628.889978 1545.789 1631.022 6229.565 1000
code2 263.284 278.9020 313.293371 290.505 307.239 3138.880 1000
> n <- 1000
> microbenchmark(
+ code1 = f1(n),
+ code2 = f2(n),
+ times = 1000
+ )
Unit: microseconds
expr min lq mean median uq max neval
code1 1884.934 1924.873 2290.409508 1974.183 2111.8490 114038.521 1000
code2 571.192 583.687 642.682019 601.537 637.4595 3499.891 1000
第二個代碼顯然更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.