我工作缓慢的代码的简化示例(函数rbf
来自kernlab
包),需要加速:
install.packages('kernlab')
library('kernlab')
rbf <- rbfdot(sigma=1)
test <- matrix(NaN,nrow=5,ncol=10)
for (i in 1:5) {
for (j in 1:10) { test[i,j] <- rbf(i,j)}
}
我尝试过outer()
,但它不起作用,因为rbf
函数没有返回所需的长度(50)。我需要加速这段代码,因为我有大量的数据。我读到矢量化将是加速的圣杯,但我不知道怎么做。
你能告诉我正确的方向吗?
发布于 2012-01-07 00:38:14
如果rbf
确实是调用rbfdot
的返回值,那么body(rbf)
看起来像这样
{
if (!is(x, "vector"))
stop("x must be a vector")
if (!is(y, "vector") && !is.null(y))
stop("y must a vector")
if (is(x, "vector") && is.null(y)) {
return(1)
}
if (is(x, "vector") && is(y, "vector")) {
if (!length(x) == length(y))
stop("number of dimension must be the same on both data points")
return(exp(sigma * (2 * crossprod(x, y) - crossprod(x) -
crossprod(y))))
}
}
由于这大部分都是由检查函数组成的,而当您只传入标量时,crossprod
会进行简化,因此我认为您的函数可以简化为
rbf <- function(x, y, sigma = 1)
{
exp(- sigma * (x - y) ^ 2)
}
要获得可能的进一步加速,请使用compiler
包(需要R-2.14.0或更高版本)。
rbf_loop <- function(m, n)
{
out <- matrix(NaN, nrow = m, ncol = n)
for (i in seq_len(m))
{
for (j in seq_len(n))
{
out[i,j] <- rbf(i,j)
}
}
out
)
library(compiler)
rbf_loop_cmp <- cmpfun(rbf_loop)
然后将rbf_loop_cmp(m, n)
的时间与您之前使用的时间进行比较。
相反,简化步骤更容易看到。如果你expand (x - y) ^ 2
,你得到的是x ^ 2 - 2 * x * y + y ^ 2
,它减去了rbf
函数中的东西。
发布于 2012-01-07 23:17:09
使用内核实验室中的函数kernelMatrix(),它应该比循环内核函数快几个数量级:
library(kernlab)
rbf <- rbfdot(sigma=1)
kernelMatrix(rbf, 1:5, 1:10)
https://stackoverflow.com/questions/8760632
复制相似问题