首页 > 解决方案 > 如何提高 R 中循环的处理时间,手动 xgboost 预测

问题描述

我有一个训练有素的xgboost模型R,我的应用程序服务器可以运行 R 但无法安装package:xgboost(renjin 不支持,它是 R 的基于 JVM 的解释器)。因此,为了部署我的模型,我需要一种无需xgb.predict. 现在,我使用由 制作的数据框在 R 中编写了一个评分函数,该函数xgb.model.dt.tree运行良好但速度极慢。单条记录耗时 7 秒。我想知道如何使我的代码运行得更快,任何帮助将不胜感激。

我使用 2 个 for 和 1 个 while 循环,这在 R 中显然非常慢。显然我应该尝试对它们进行矢量化,但我不知道如何。

Rcpp似乎是一种选择,但我不知道 C++。

这是我的代码。其多类分类有 18 类(0,500,1000 等)。模型是用nrounds=50所以有总18*50=900助推器。树深度设置为 8,转储数据框a为 size 238252 X 10

fun_score <- function (testsample) {
  df <- data.frame('0'=NA,'500'=NA,'1000'=NA,'1500'=NA,'2000'=NA,'3000'=NA,'5000'=NA,'6000'=NA,'8000'=NA,
                   '10000'=NA,'15000'=NA,'20000'=NA,'25000'=NA,'40000'=NA,'50000'=NA,'70000'=NA,'77000'=NA,'120000'=NA)
for (i in 0:17) { 
    twght <- 0
    for(tree_num in seq(i,899,18)){
      tr=a[Tree==tree_num]
      rid <- which(tr[,2]==0)
      splitvar <- as.character(tr[rid,4])
      while (grepl("Leaf",tr[rid,4])==F) {
        next_split <- as.character(ifelse(is.null(testsample[splitvar]), tr[rid,7],
                                          ifelse( as.numeric(testsample[splitvar]) < tr[rid,5], tr[rid,6],tr[rid,7])))
        rid <- which(tr[,3] == next_split)
        splitvar <- as.character(tr[rid,4])
      }
      w=(tr[rid,9])
      twght=twght+w
    }
    twght=twght+0.5 # bias 0.5
    df[,i+1]=twght
}
  df = as.data.frame(t(apply(df, 1, function(x)(exp(x))/(sum(exp(x))))))
  df$class=substr(colnames(df)[apply(df,1,which.max)],2, nchar(colnames(df)[apply(df,1,which.max)]))
  return(df)
}

树 data.frame 看起来像这样

> head(a)
   Tree Node  ID Feature     Split  Yes   No Missing    Quality     Cover
1:    0    0 0-0     DBR 14.900000  0-1  0-2     0-1 31579.3008 28727.481
2:    0    1 0-1     DBR  8.815001  0-3  0-4     0-3  4707.3477 15235.673
3:    0    2 0-2     DBR 20.584999  0-5  0-6     0-5  3631.3484 13491.809
4:    0    3 0-3    DSLR 18.500000  0-7  0-8     0-7  1703.1209  6624.963
5:    0    4 0-4     RAD -0.500000  0-9 0-10     0-9  1390.2230  8610.710
6:    0    5 0-5    DSLR 27.500000 0-11 0-12    0-11   861.4305  4966.624

标签: rperformancefor-loopxgboostrenjin

解决方案


这看起来像是 Renjin 的即时循环编译器的一个很好的用例。但是,在当前版本中默认情况下未启用它。您可以在命令行上使用该--compile-loops标志或使用 JVM 标志启用它-Drenjin.compile.loops=true

如果它没有提供加速,请在 GitHub 上打开一个问题。


推荐阅读