在R中使用tm包和并行计算时,我遇到了一个问题,我不确定自己是在做些愚蠢的事情还是错误。
我创建了一个小的可复制示例:
# Load the libraries
library(tm)
library(snow)
# Create a Document Term Matrix
test_sentence = c("this is a test", "this is another test")
test_corpus = VCorpus(VectorSource(test_sentence))
test_TM = DocumentTermMatrix(test_corpus)
# Define a simple function that returns the matrix for the i-th document
test_function = function(i, TM){ TM[i, ] }
如果使用此示例运行一个简单的lapply,我将获得预期的结果而没有任何问题:
# This returns the expected list containing the rows of the Matrix
res1 = lapply(1:2, test_function, test_TM)
但是,如果我并行运行它,则会出现错误:
第一个错误:尺寸错误
# This should return the same thing of the lapply above but instead it stops with an error
cl = makeCluster(2)
res2 = parLapply(cl, 1:2, test_function, test_TM)
stopCluster(cl)
问题在于不同的节点不会自动tm
加载程序包。但是,加载包是必需的,因为它定义[
了相关对象类的方法。
下面的代码执行以下操作:
tm
包加载到所有节点cl <- makeCluster(rep("localhost",2), type="SOCK")
clusterEvalQ(cl, library(tm))
clusterExport(cl, list=ls())
res <- parLapply(cl, as.list(1:2), test_function, test_TM)
stopCluster(cl)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句