python中的全局变量多处理.池班

2024-06-01 20:10:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个相对简单的可并行化问题,它给我带来了太多的问题,无法有效地实现。我的程序的核心是两个矩阵和两个向量,我希望执行的两个计算中的每一个都有一个矩阵和向量。在

在密码里,这意味着我

import numpy as np
matrices = dict([("type1", np.random.rand(10,10)), ("type2", np.random.rand(10,10))])
vectors = dict([("type1", np.random.rand(10)), ("type2", np.random.rand(10))])

我想做的是(不是真的,但在简化的情况下)是:

对于每种类型,我有一个非常大的向量列表:

^{pr2}$

我要计算A*v+b,其中A是矩阵,b是每种类型的向量。在

因此,执行我需要的单线程代码是

def f(input_vector, matricx, vector):
    return np.dot(matrix, input_vector) + vector

results = {}
for type in ['type1', 'type2']:
    results[type] = []
    for input_vector in input_vectors:
        results.append(f(input_vector, matrices[type], vectors[type]))

但是,我想同时做这个。但是,我不知道如何解决这样一个问题,即我要映射到向量列表上的函数不仅仅是向量作为它的输入。在

我想写些像

from multiprocessing import Pool
p = Pool(4)
for type in types:
    p.map(lambda x: f(x, matrices[type], vectors[type] , input_vectors))

但是,这不起作用,因为lambda函数不能被pickle。有一件事可以做,就是把我要乘的矩阵附加到每个向量上,但这在内存方面当然是不可行的。在

对如何优雅地解决我的难题有什么想法吗?在


我希望池中的每个元素都有一个矩阵和向量的副本,它必须与之相乘,但我不知道如何在multiprocessing中做到这一点。在


Tags: inforinputtypenp矩阵random向量
1条回答
网友
1楼 · 发布于 2024-06-01 20:10:30

使用^{}将多个参数传递给map

def f(matrix, vector, input_vector):
    return np.dot(matrix, input_vector) + vector

results = {}
for type_ in types:
    func = partial(f, matrices[type_], vectors[type_])
    results[type_] = p.map(func, input_vectors)

如果您喜欢在启动Pool时将整个matrices和{}列表传递给每个子级,然后在调用map时只传递{},那么您也可以这样做。使用initializer/initargs参数来传递列表,然后在initializer函数中使它们全局化。这将使它们在每个子进程中具有全局性:

^{pr2}$

相关问题 更多 >