请考虑函数f
,该函数采用决策树节点参数{-1,+ 1}并将其映射到一个热向量[0,0,0,1]。
我认为这最终将成为我正在开发的程序的瓶颈之一,所以我想知道是否有人找到了一种将参数映射到向量的更快方法。
f<-function(h){
# function takes as arguments:
# an m-bit vector of potential split decisions (h)
# function returns:
# an m+1-length one-hot indicator vector
theta_vec = c(rep(0,length(h)+1))
position = length(h)+1
for(bit in seq(1,length(h),2)){
if(h[bit]>0){
position=position
}
else{
position=position/2
}
}
theta_vec[position]=1
return(theta_vec)
}
谢谢您的帮助
答案 0 :(得分:1)
我认为我有一个解决方案可以在四分之一的时间内运行。您是否可以重构,以便使用(0,1)而不是(-1,1);并将其用作行列表而不是向量?尽管可以将下面的函数重写为使用向量作为输入,但是我在考虑问题时发现它更易于解释。
findPos <- function(h){
# find number of rows from input
N <- length(h)
# go through and pick out the values in each tree that are valid based
# on previous route
out <- c(h[[1]], rep(0, N-1))
for(i in 2:N){
out[i] <- h[[i]][sum(out[i:(i-1)] * 2^(i-1)/(2^((i-1):1))) + 1]
}
# now find the final position in the bottom row and return as a vector
out_pos <- sum(out * 2^N/(2^(1:N))) + 1
full_vec <- rep(0, 2^N)
full_vec[out_pos] <- 1
return(full_vec)
}
# couple of e.gs
f(c(0,1,1))
findPos(list(0, c(1,1)))
f(c(1,1,1))
findPos(list(1, c(1,1)))
# works with larger trees
findPos(list(1, c(1,1), c(1,0,0,0)))
# check time using microbenchmark package
microbenchmark::microbenchmark(
"old" = {
f(c(0,1,1))
},
"new" = {
findPos(list(0, c(1,1)))
}
)
最佳 强尼