【问题标题】:Incorrect number of dimensions - parallel R computation维数不正确 - 并行 R 计算
【发布时间】:2015-11-19 20:57:55
【问题描述】:

我在 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)

【问题讨论】:

    标签: r tm snow


    【解决方案1】:

    问题是不同的节点不会自动加载tm 包。但是,加载包是必要的,因为它为相关对象类定义了[ 方法。

    以下代码执行以下操作:

    1. 启动集群
    2. 在所有节点中加载tm
    3. 将所有对象导出到所有节点
    4. 运行函数
    5. 停止集群

    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)
    

    【讨论】:

    • 你是完全正确的..多么愚蠢的错误。我假设一旦计算了矩阵,就不再需要库,而不考虑 [ 方法在包内。非常感谢!
    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多