gpt4 book ai didi

python - 直接从 __array_interface__ 创建 NumPy 数组

转载 作者:太空狗 更新时间:2023-10-30 02:56:47 24 4
gpt4 key购买 nike

假设我有一个 __array_interface__ 字典,我想从字典本身创建一个该数据的 numpy View 。例如:

buff = {'shape': (3, 3), 'data': (140546686381536, False), 'typestr': '<f8'}
view = np.array(buff, copy=False)

但是,这不起作用,因为 np.array 搜索缓冲区或数组接口(interface)作为属性。简单的解决方法如下:

class numpy_holder(object):
pass

holder = numpy_holder()
holder.__array_interface__ = buff
view = np.array(holder, copy=False)

这似乎有点迂回。我是否缺少执行此操作的直接方法?

最佳答案

更正 - 使用正确的“数据”值,您的 holdernp.array 中工作:

np.array 肯定不会工作,因为它需要一个可迭代的东西,比如列表的列表,并解析各个值。

有一个低级构造函数,np.ndarray,它接受一个缓冲区参数。还有一个 np.frombuffer

但我的印象是x.__array_interface__['data'][0]是数据缓冲区位置的整数表示,而不是直接指向缓冲区的指针。我只用它来验证 View 是否共享相同的数据缓冲区,而不是从中构造任何东西。

np.lib.stride_tricks.as_strided 使用 __array_interface__ 作为默认步幅和形状数据,但从数组中获取数据,而不是 __array_interface__ 词典。

===========

带有.data 属性的ndarray 示例:

In [303]: res
Out[303]:
array([[ 0, 20, 50, 30],
[ 0, 50, 50, 0],
[ 0, 0, 75, 25]])
In [304]: res.__array_interface__
Out[304]:
{'data': (178919136, False),
'descr': [('', '<i4')],
'shape': (3, 4),
'strides': None,
'typestr': '<i4',
'version': 3}
In [305]: res.data
Out[305]: <memory at 0xb13ef72c>
In [306]: np.ndarray(buffer=res.data, shape=(4,3),dtype=int)
Out[306]:
array([[ 0, 20, 50],
[30, 0, 50],
[50, 0, 0],
[ 0, 75, 25]])
In [324]: np.frombuffer(res.data,dtype=int)
Out[324]: array([ 0, 20, 50, 30, 0, 50, 50, 0, 0, 0, 75, 25])

这两个数组都是 View 。

好的,使用您的holder 类,我可以做同样的事情,使用这个res.data 作为数据缓冲区。您的类创建了一个公开数组接口(interface)的对象

In [379]: holder=numpy_holder()
In [380]: buff={'data':res.data, 'shape':(4,3), 'typestr':'<i4'}
In [381]: holder.__array_interface__ = buff
In [382]: np.array(holder, copy=False)
Out[382]:
array([[ 0, 20, 50],
[30, 0, 50],
[50, 0, 0],
[ 0, 75, 25]])

关于python - 直接从 __array_interface__ 创建 NumPy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39376892/

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