【问题标题】:Parallel processing in R shiny, calling Python scriptR闪亮中的并行处理,调用Python脚本
【发布时间】:2018-12-05 04:25:27
【问题描述】:

我正在尝试在 R Shiny 中进行并行处理,我想做的并行任务是调用 python 脚本。但是它不起作用并且无法将结果从 python 获取回 R。 下面是示例 R 闪亮和 Python 代码。 App.R

library(shiny)
library(reticulate)
library(doParallel)
library(foreach)
ui <- fluidPage(

   # Application title
   titlePanel("Sample Program"),

      mainPanel(
         uiOutput("txtValue")
      )   
)
server <- function(input, output) {

  source_python("../../PythonCode/Multiprocessing/multip.py")  

  cl <- makeCluster(detectCores(), type='PSOCK')
  registerDoParallel(cl)

  result <- foreach(i=1:5) %dopar% fsq(i)
  stopCluster(cl)     
   output$txtValue <- renderUI({
    result   
   }) 

}
shinyApp(ui = ui, server = server)

Python 代码 (multip.py)

def fsq(x):
    return x**2

【问题讨论】:

  • source_python 来自哪里? “它不起作用”是什么意思?
  • python函数调用未执行,结果行报错
  • source_python是引用python脚本,来自reticulate包。错误消息是“反序列化错误(socklist[[n]]):从连接读取错误”

标签: python r parallel-processing shiny doparallel


【解决方案1】:

错误信息独立于shiny:

library(reticulate)
library(doParallel)
library(foreach)
library(parallel)

source_python("multip.py")  

cl <- makeCluster(detectCores(), type = 'PSOCK')
registerDoParallel(cl)

# throws: Error in unserialize(socklist[[n]]) : error reading from connection
foreach(i = 1:5) %dopar% fsq(i)

stopCluster(cl)     

我对此的解释是,不能像序列化 R 函数那样序列化 Python 函数。一个简单的解决方法是在循环中使用source_python

library(doParallel)
library(foreach)
library(parallel)

cl <- makeCluster(detectCores(), type = 'PSOCK')
registerDoParallel(cl)

foreach(i = 1:5) %dopar% {
  reticulate::source_python("multip.py")  
  fsq(i)
}
stopCluster(cl)     

【讨论】:

  • 这行得通,谢谢!是的,在循环中包含并行任务的完整代码是有意义的,尤其是当它引用外部脚本/函数时
  • 扩展 Ralf Stubner 的回答:fsq R 函数依赖于 externalptr 类型的对象。除非此类对象背后的开发人员已实现对此类对象的支持,否则此类对象不能被序列化/反序列化。 (我还得看一个例子。)
猜你喜欢
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 2015-11-16
  • 1970-01-01
  • 2012-11-14
  • 2012-07-18
相关资源
最近更新 更多