gpt4 book ai didi

python - 如何在第一个轴上使用 numpy.nditer 进行缩减

转载 作者:太空狗 更新时间:2023-10-29 19:29:43 25 4
gpt4 key购买 nike

我正在尝试了解如何使用 nditer 来做一个减少,在我的例子中将 3d 数组转换为 2d 数组。

我按照这里的帮助 http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html和设法创建一个函数,在最后一个轴上应用缩减的输入。有了这个功能

def nditer_sum(data, red_axes):
it = numpy.nditer([data, None],
flags=['reduce_ok', 'external_loop'],
op_flags=[['readonly'], ['readwrite', 'allocate']],
op_axes=[None, red_axes])
it.operands[1][...] = 0

for x, y in it:
y[...] = x.sum()

return it.operands[1]

我可以得到等同于 data.sum(axis=2) 的东西

>>> data = numpy.arange(2*3*4).reshape((2,3,4))
>>> nditer_sum(data, [0, 1, -1])
[[ 6 22 38]
[54 70 86]]
>>> data.sum(axis=2)
[[ 6 22 38]
[54 70 86]]

所以为了得到等同于 data.sum(axis=0) 的东西,我认为它足以将参数 red_axes 更改为 [-1, 0,1]但结果却截然不同。

>>> data = numpy.arange(2*3*4).reshape((2,3,4))
>>> data.sum(axis=0)
[[12 14 16 18]
[20 22 24 26]
[28 30 32 34]]
>>> nditer_sum(data, [-1, 0, 1])
[[210 210 210 210]
[210 210 210 210]
[210 210 210 210]]

在nditer_sum里面的for循环中(for x,y in it:),迭代器是循环 2 次并每次给出一个长度为 12 的数组,而不是循环 12 次,每次给出一个长度为 2 的数组。我有多次阅读 numpy 文档并用谷歌搜索到徒劳无功。我正在使用 numpy 1.6 和 python 2.7

最佳答案

如果 nditer 顺序更改为 F,则 axis=0 情况可以正常工作。现在有 12 个步骤,大小为 (2,) 的数组,如您所愿。

it = np.nditer([data, None],
flags=['reduce_ok', 'external_loop'],
op_flags=[['readonly'], ['readwrite', 'allocate']],
order='F', # ADDED to loop starting with the last dimension
op_axes=[None, red_axes])

但是对于中间的 axis=1 情况,没有这样的解决方案。


另一种对选定维度进行迭代的方法是在降维数组上构造一个“multi_index”迭代器。我在 https://stackoverflow.com/a/25097271/901925 中发现np.ndindex 使用这个技巧来执行“浅迭代”。

对于 axis=0 的情况,这个函数有效:

def sum_1st(data):
y = np.zeros(data.shape[1:], data.dtype)
it = np.nditer(y, flags=['multi_index'])
while not it.finished:
xindex = tuple([slice(None)]+list(it.multi_index))
y[it.multi_index] = data[xindex].sum()
it.iternext()
return y

或推广到任何轴:

def sum_any(data, axis=0):
yshape = list(data.shape)
del yshape[axis]
y = np.zeros(yshape, data.dtype)
it = np.nditer(y, flags=['multi_index'])
while not it.finished:
xindex = list(it.multi_index)
xindex.insert(axis, slice(None))
y[it.multi_index] = data[xindex].sum()
it.iternext()
return y

关于python - 如何在第一个轴上使用 numpy.nditer 进行缩减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12663215/

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