r - 将决策树节点映射到独热向量的最快方法是什么?

标签 r machine-learning classification

考虑一下函数 f,它采用决策树节点参数 {-1,+1} 并将其映射到 one-hot 向量 [0,0,0,1]。

enter image description here

我认为这最终将成为我正在开发的程序的瓶颈之一,所以我想知道是否有人找到更快的方法将参数映射到向量。

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) 而不是 (-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)))
  }
)

最佳 乔尼

关于r - 将决策树节点映射到独热向量的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575905/

相关文章:

matlab - 向量尽力分类算法

python - 咖啡分类器

r - 如何在CARET中自定义一个模型来执行PLS-[Classifier]两步分类模型?

r - 如何将自定义函数导出到 multidplyr 中的集群?

r - lubridate with_tz 不与 dplyr group_by 一起工作

R 中的相对频率

artificial-intelligence - 将自然语言表示为 RDF

r - 如何将 rbind 数据帧转换为 rbind 数据帧?

python - 使用 KerasRegressor 得到非常糟糕的预测

python-3.x - 没有收到检测到的汽车上的盒子