python - 转换为共享字符串数组的 Numpy 字符串矩阵会导致类型不匹配

标签 python numpy multiprocessing ctypes shared-memory

我正在尝试 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']]

我尝试解决问题的方法:

  1. 我尝试更改 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/

    相关文章:

    python - 尝试在 python 中对数组进行线性回归,我不断收到错误 'array must not contain infs or NaNs' 。没有 inf 或 NaN

    java - 如何在 Java 线程上使用共享内存?

    python - 在 Django 商店中本地化价格的正确方法是什么?

    python - 多个列表的字典

    python - 如何选取函数返回的 x 元组的某些元素?

    python - opencv在numpy矢量化后显示黑色图像

    python - 使用 multiprocessing.Pool().map 更改传递给它的变量的值

    Python、图像压缩和多重处理

    Python,使用多处理进一步加速cython函数

    Python:无法导入lxml.etree.xml文件