我正在尝试 multiprocessing in Python ,但是,我在创建一些 shared memory 时遇到了麻烦。以下面的例子来说明我的问题:
引用the following (略有不同,因为他使用充满 float 的矩阵,但原理相同),我想将字符串的 numpy 矩阵转换为 shared memory供进程使用的空间。我有以下内容:
from ctypes import c_wchar_p
import numpy as np
from multiprocessing.sharedctypes import Array
input_array = np.array([['Red', 'Green', 'Blue', 'Yellow'],
['Purple', 'Orange', 'Cyan', 'Pink']]).T
shared_memory = Array(c_wchar_p, input_array.size, lock=False) # Equivalent to just using a RawArray
np_wrapper = np.frombuffer(shared_memory, dtype='<U1').reshape(input_array.shape)
np.copyto(np_wrapper, input_array)
print(np_wrapper)
但是,np_wrapper
仅包含每个字符串的第一个字符:
[['R' 'P']
['G' 'O']
['B' 'C']
['Y' 'P']]
我尝试解决问题的方法:
- 我尝试更改
dtype
frombuffer
的来自<U1
的函数至<U6
,即dtype
input_array
的。但是,它会引发以下异常:
ValueError: buffer size must be a multiple of element size
- 我尝试使用
dtype
的int64
与frombuffer
功能因为我的shared_memory
数组的类型为c_wchar_p
(即字符串指针),我使用的是 64 位 Windows 10 系统。但是,它会引发以下异常:
ValueError: cannot reshape array of size 4 into shape (4,2)
我非常困惑为什么我在这里输入错误。 有人知道如何解决这个问题吗?
最佳答案
这可能有助于理解这个字符串数组包含的内容:
In [643]: input_array = np.array([['Red', 'Green', 'Blue', 'Yellow'],
...: ['Purple', 'Orange', 'Cyan', 'Pink']]).T
...:
...:
In [644]: input_array.size
Out[644]: 8
In [645]: input_array.itemsize
Out[645]: 24
In [646]: input_array.nbytes
Out[646]: 192
由于它是转置,因此形状和步幅与输入数组不同,但字符串按原始顺序排列。
In [647]: input_array.__array_interface__
Out[647]:
{'data': (139792902236880, False),
'strides': (24, 96),
'descr': [('', '<U6')],
'typestr': '<U6',
'shape': (4, 2),
'version': 3}
我的猜测是 Array
应该用 nbytes
定义,而不是 size
。
关于python - 转换为共享字符串数组的 Numpy 字符串矩阵会导致类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50844290/