【问题标题】:Rscript - long time of executionRscript - 执行时间长
【发布时间】:2017-12-28 09:18:44
【问题描述】:

我正在尝试在 R 的插入符号包中创建预测模型,并从终端/cmd 调用新数据的预测。这是可重现的示例:

# Sonar_training.R
  ## learning and saving model
library(caret)
library(mlbench)
data(Sonar)
set.seed(107)
inTrain <- createDataPartition(y = Sonar$Class, p = .75,list = FALSE)
training <- Sonar[ inTrain,]
testing  <- Sonar[-inTrain,]
saveRDS(testing,"test.rds")
ctrl <- trainControl(method = "repeatedcv",
                 repeats = 3)
plsFit <- train(Class ~ .,data = training,method = "pls",
            tuneLength = 15,
            trControl = ctrl,
            preProc = c("center", "scale"))

plsClasses <- predict(plsFit, newdata = testing)

saveRDS(plsFit,"fit.rds")

这是由 Rscript.exe 调用的脚本:

# script.R
  ##reading model and predict test data
t <- Sys.time()
pls <- readRDS("fit.rds")
testing <- readRDS("test.rds")
head(predict(pls, newdata = testing))
print(Sys.time() - t)

我使用以下语句在终端中运行它:

pawel@pawel-MS-1753:~$ Rscript script.R
Loading required package: pls

Attaching package: ‘pls’

The following object is masked from ‘package:stats’:

loadings

[1] M M R M R R
Levels: M R
Time difference of 2.209697 secs

有什么方法可以更快/更有效地做到这一点?例如,是否有可能不每次执行都加载包? readRDS 在这种情况下读取模型是否正确?

【问题讨论】:

  • 分析您的代码。

标签: r r-caret rscript


【解决方案1】:

您可以尝试使用“profvis”包来分析您的代码:

#library(profvis)
profvis({    

   for (i in 1:100){
    #your code here
    }

})

我试过了,99% 的执行时间是训练时间,1% 是保存/加载 RDS 数据,其余的成本大约为 0(加载包,加载数据,...):

所以如果你不想优化训练功能本身,你似乎没有多少方法可以减少执行时间。

【讨论】:

  • 训练函数的时间在这里并不重要。一旦我学会了模型,我只在 readRDS 函数中使用它。我只关心控制台中执行 script.R 的时间。但是感谢您提供 profvis 包,现在我看到 2.2 秒中的 1.5 秒正在读取模型。
【解决方案2】:

我已经看到 PLS 分类模型会发生这种情况,但我不确定这个问题。但是,请尝试改用 method = "simpls"。您将得到大致相同的答案,并且应该很快完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-19
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多