嗨,我正在嘗試使用foreach如下方式以并行方式呼叫帶有 reticulate 的 python 函式:
library(reticulate)
library(doParallel)
library(foreach)
library(parallel)
py_install("wandb")
wandb <- import("wandb")
cl <- makeCluster(detectCores(), type = 'PSOCK')
registerDoParallel(cl)
foreach(i = 1:5) %dopar% {
wandb$init(project = "test")
}
給出:
Error in {: task 1 failed - "attempt to apply non-function"
Traceback:
1. foreach(i = 1:5) %dopar% {
. wandb$init(project = "test")
. }
2. e$fun(obj, substitute(ex), parent.frame(), e$data)
是否foreach包不具網作業?
uj5u.com熱心網友回復:
您不能將網狀 python.builtin.module物件從一個 R 行程匯出到另一個行程。它們旨在僅在它們創建的同一個 R 行程中作業。如果嘗試過,那么您將收到報告中的錯誤。
如果您使用未來的框架進行并行化,那么您可以對其進行檢查并立即提供資訊性錯誤訊息,例如
library(reticulate)
library(foreach)
library(doFuture)
registerDoFuture()
cl <- parallelly::makeClusterPSOCK(2L)
plan(cluster, workers = cl)
## Detect non-exportable objects and give an error asap
options(future.globals.onReference = "error")
# py_install("wandb")
wandb <- import("wandb")
res <- foreach(i = 1:5) %dopar% {
wandb$init(project = "test")
sqrt(i)
}
呼叫foreach()將導致:
Error: Detected a non-exportable reference ('externalptr') in one of
the globals ('wandb' of class 'python.builtin.module') used in the
future expression
您可以在https://future.futureverse.org/articles/future-4-non-exportable-objects.html#package-reticulate 中閱讀更多相關資訊。
一種解決方法是wandb在每次迭代中創建物件,該物件在作業端運行。就像是:
res <- foreach(i = 1:5) %dopar% {
wandb <- import("wandb")
wandb$init(project = "test", mode = "offline")
sqrt(i)
}
免責宣告:我對“wandb”Python 模塊一無所知。上面的可能沒有意義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334576.html
上一篇:因式分解導致NA
