r - 如何提高 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
解决方案
这看起来像是 Renjin 的即时循环编译器的一个很好的用例。但是,在当前版本中默认情况下未启用它。您可以在命令行上使用该--compile-loops
标志或使用 JVM 标志启用它-Drenjin.compile.loops=true
如果它没有提供加速,请在 GitHub 上打开一个问题。
推荐阅读
- java - 如何在动作事件中修复一个文本字段到 3 个字段的转换
- python - Shrinking dataset to group individual data for one day using groupby and aggregate functions
- javascript - SQLite PHP Not Filling HTML Table
- ios - 在屏幕锁定期间接听来电时音频不工作 - 迅速
- elasticsearch - 在同一台机器上启动 2 个 ElasticSearch 节点:RemoteTransportException: failed to send join request to master
- php - 为什么使用 ->value (php / xpath / xml 查询) 后我得到 null?
- python - 如何加速多处理python
- python - 计算每个给定时间戳的特定间隔的值
- powershell - 使用按钮执行应用程序时,Powershell 阻止 GUI 关闭
- flutter - 无法将 rest api json 转换为 dart 对象