【问题标题】:Using multiprocessing to create two arrays in python simultaneously使用多处理在python中同时创建两个数组
【发布时间】:2017-04-04 10:42:53
【问题描述】:

我编写了一个 python 脚本,它使用 numpy 从不同的数据源创建两个数组并将它们相互比较。构建数组是一个相当缓慢的过程,所以我想找到一种同时构建它们的方法来加快脚本的速度。我尝试使用这样的多处理模块来做到这一点:

if __name__=='__main__':
       p1 = Process(target=network_matrix_main_function(input_network))
       p1.start()
       p2 = Process(target=tree_matrix_main_function(input_tree))
       p2.start()
       print p1
       print p2

但我收到以下错误消息:

Process Process-1:
Traceback (most recent call last):
  File "/Users/bj5/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/Users/bj5/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 113, in run
    if self._target:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
<Process(Process-1, stopped[1])>
<Process(Process-2, started)>
Process Process-2:
Traceback (most recent call last):
  File "/Users/bj5/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/Users/bj5/homebrew/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 113, in run
    if self._target:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

在我看来,python 正在努力处理这样一个事实,即两个并行进程的输出都是一个数组而不是单个值。我尝试使用谷歌搜索 a.any() 和 a.all() (它建议在错误消息的最后一行使用)以用于多处理和数组,但找不到任何告诉我如何使用它们。

谁能向我解释为什么我的脚本不起作用以及我需要做什么才能并行运行两个函数:network_matrix_main_function 和 tree_matrix_main_function?

【问题讨论】:

  • 从文档看来,target 应该是 function。但是network_matrix_main_function(input_network)function 还是某种类型的值?它看起来像一个函数调用,它立即计算出一个值,而不是 function
  • 这是一个函数调用,如果你只是对函数的名称你如何给函数的参数?

标签: python arrays numpy multiprocessing


【解决方案1】:

这很容易解决。你看,使用多处理你必须将函数和参数分开:

p1 = Process(target=[some function], args=[(some arguments,other args)])

另外,你不应该打印进程,而是在它们的函数中定义它们应该打印出一些东西,

最后,您应该使用 .join() 函数重新加入进程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    相关资源
    最近更新 更多