维数不正确 - 并行 R 计算
Incorrect number of dimensions - parallel R computation
我在 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
包。但是,加载包是必要的,因为它为相关对象 class.
定义了 [
方法
下面的代码执行以下操作:
- 启动集群
- 在所有节点中加载
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)
我在 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
包。但是,加载包是必要的,因为它为相关对象 class.
[
方法
下面的代码执行以下操作:
- 启动集群
- 在所有节点中加载
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)