如何为采用 6 个不同类型和大小的参数的函数实现多处理
how to implement multiprocessing for function that takes 6 parameters with different types and sizes
我有一个函数需要 5 个或更多参数作为输入,这些参数有不同的类型和大小,我如何在这种情况下应用多处理。
假设在这个虚拟样本中
函数:
def func(arr1, arr2, arr3, mtx1, mtx2, st):
# the function will output three arrays that has the same size as the arr1
result1 = np.zeros((len(arr1), 1))
result2 = np.zeros((len(arr1), 1))
result3 = np.zeros((len(arr1), 1))
# the function will make iteration through the 0 to the length of the arr1
for i, _ in enumerate(arr1):
# it does a lot of computations using the #th number of arr1, arr2, arr3, but takes the whole matrices mtx1 amd mtx2
# some details of the calculation based on the setting of the string
return result1, result2, result3
主要功能是定义所有的参数,然后输入到函数中。
if name == 'main':
arr1 = np.array([100,200,300])
arr2 = np.array([400,500,600])
arr3 = np.array([700,800,900])
mtx1 = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])
mtx2 = np.random.rand(10,10)
st = 'string'
results = func(arr1, arr2, arr3, mtx1, mtx2, str)
我尝试按照其他人的建议使用 Pool 和 map,例如:
p = Pool()
results = p.map(func, arr1, arr2, arr3, mtx1, mtx2, st)
p.close()
p.join()
这会给出错误:
map() 接受 3 到 4 个位置参数,但给出了 8 个
我在网上找到的multiprocessing的例子,大部分都是采用与函数输入相同大小的数组,而且函数只做很简单的数学计算。但是我的不是这种情况,我该如何解决这个问题呢?
谢谢!
您对 map
的用法有点不对。第二个参数应该是 iterable
- 即元组或列表。像这样:
results = p.map(func, (arr1, arr2, arr3, mtx1, mtx2, st))
对于同一函数的多次调用,您可以尝试使用星图:https://docs.python.org/dev/library/multiprocessing.html#multiprocessing.pool.Pool.starmap
星图的参数应该是可迭代的,将为您的函数解压缩。
我有一个函数需要 5 个或更多参数作为输入,这些参数有不同的类型和大小,我如何在这种情况下应用多处理。
假设在这个虚拟样本中
函数:
def func(arr1, arr2, arr3, mtx1, mtx2, st):
# the function will output three arrays that has the same size as the arr1
result1 = np.zeros((len(arr1), 1))
result2 = np.zeros((len(arr1), 1))
result3 = np.zeros((len(arr1), 1))
# the function will make iteration through the 0 to the length of the arr1
for i, _ in enumerate(arr1):
# it does a lot of computations using the #th number of arr1, arr2, arr3, but takes the whole matrices mtx1 amd mtx2
# some details of the calculation based on the setting of the string
return result1, result2, result3
主要功能是定义所有的参数,然后输入到函数中。
if name == 'main':
arr1 = np.array([100,200,300])
arr2 = np.array([400,500,600])
arr3 = np.array([700,800,900])
mtx1 = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])
mtx2 = np.random.rand(10,10)
st = 'string'
results = func(arr1, arr2, arr3, mtx1, mtx2, str)
我尝试按照其他人的建议使用 Pool 和 map,例如:
p = Pool()
results = p.map(func, arr1, arr2, arr3, mtx1, mtx2, st)
p.close()
p.join()
这会给出错误:
map() 接受 3 到 4 个位置参数,但给出了 8 个
我在网上找到的multiprocessing的例子,大部分都是采用与函数输入相同大小的数组,而且函数只做很简单的数学计算。但是我的不是这种情况,我该如何解决这个问题呢?
谢谢!
您对 map
的用法有点不对。第二个参数应该是 iterable
- 即元组或列表。像这样:
results = p.map(func, (arr1, arr2, arr3, mtx1, mtx2, st))
对于同一函数的多次调用,您可以尝试使用星图:https://docs.python.org/dev/library/multiprocessing.html#multiprocessing.pool.Pool.starmap
星图的参数应该是可迭代的,将为您的函数解压缩。