gpt4 book ai didi

python - 使用多处理模块填充复杂的 numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:40 25 4
gpt4 key购买 nike

我遇到过这个演示https://jonasteuwen.github.io/numpy/python/multiprocessing/2017/01/07/multiprocessing-numpy-array.html关于如何使用多处理模块填充 numpy 数组。我想在我的代码中做类似的事情,但我正在填充的数组,即我的 X 是一个复杂的数组。 ctypes 模块给我一个类似于 NotImplementedError: Converting dtype('complex128') to a ctypes type 的错误。

因此,在链接的示例中,我想要的是在非并行版本中有效替换:

X = np.random.random((100, 100))

X = np.random.random((100, 100)) + 1j * np.random.random((100, 100))

tmp = np.zeros((100, 100))

tmp = np.zeros((100, 100)) + 1j * np.random.random((100, 100))

我不确定如何使用 numpy.ctypes 模块来做到这一点,但我愿意接受其他想法来实现类似的事情。谢谢。

最佳答案

通过将数组分成实部和虚部,分别处理它们,然后组合形成复数变量来解决这个问题。

import numpy as np
import itertools
from multiprocessing import Pool # Process pool
from multiprocessing import sharedctypes

size = 100
block_size = 4

X = np.random.random((size, size)) + 1j * np.random.random((size, size))
X_r = X.real
X_i = X.imag
result_r = np.ctypeslib.as_ctypes(np.zeros((size, size)))
result_i = np.ctypeslib.as_ctypes(np.zeros((size, size)))
shared_array_r = sharedctypes.RawArray(result_r._type_, result_r)
shared_array_i = sharedctypes.RawArray(result_i._type_, result_i)

def fill_per_window(args):
window_x, window_y = args
tmp_r = np.ctypeslib.as_array(shared_array_r)
tmp_i = np.ctypeslib.as_array(shared_array_i)

for idx_x in range(window_x, window_x + block_size):
for idx_y in range(window_y, window_y + block_size):
tmp_r[idx_x, idx_y] = X_r[idx_x, idx_y]
tmp_i[idx_x, idx_y] = X_i[idx_x, idx_y]

window_idxs = [(i, j) for i, j in
itertools.product(range(0, size, block_size),
range(0, size, block_size))]

p = Pool()
res = p.map(fill_per_window, window_idxs)
result_r = np.ctypeslib.as_array(shared_array_r)
result_i = np.ctypeslib.as_array(shared_array_i)
result = result_r + 1j * result_i
print(np.array_equal(X, result))

关于python - 使用多处理模块填充复杂的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55221242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com