np.ufunc.at 和 np.ix_ 的 Numpy 多维索引 [英] Numpy multidimensional indexing for np.ufunc.at and np.ix_
问题描述
我想知道如何从数组中获取索引并与另一个数组相乘.我有两个 4d 数组和一个 2d 索引数组:
I would like to know how I can take index from an array and multiply with another array. I have two 4d arrays and one 2d index array:
base = np.ones((2, 3, 5, 5))
to_multiply = np.arange(120).reshape(2, 3, 4, 5)
index = np.array([[0, 2, 4, 2], [0, 3, 3, 2]])
索引数组的行索引对应base和to_multiply的第1维,索引数组的值对应base的第3维.我想根据索引从 base 取切片并与 to_multiply 相乘.
The row index of the index array corresponds to the 1st dimension of base and to_multiply, and the value of the index array corresponds to the 3rd dimension of base. I want to take the slice from base according to the index and multiply with to_multiply.
使用 for 循环和 np.multiply.at(因为我可能有相同的索引)我可以通过以下方式实现:
Using for loops and np.multiply.at (because I may have same index) I can achieve it by:
for i, x in enumerate(index):
np.multiply.at(base[i, :, :, :], np.s_[:, x, :], to_multiply[i, :, :, :])
以上正确性可以通过以下方式验证:
The correctness of above can be validated by:
to_multiply[0, 0, :, 0]
array([ 0, 5, 10, 15])
base[0, 0, :, 0]
array([ 0., 1., 75., 1., 10.])
但是,我想知道是否有使用 np.multiply.at 和 np.ix_ 的单行解决方案
我尝试使用 np.ix_ 但我对此感到非常困惑,因为在这种情况下它是多维的.
I tried to use np.ix_ but I'm very confused about it because in this case it's multidimensional.
推荐答案
不能用 ix_
完成.从它的文档:
Can't be done with ix_
. From its docs:
该函数采用 N 个一维序列并返回 N 个输出,其中 N每个维度,
This function takes N 1-D sequences and returns N outputs with N dimensions each,
你的 index
是 2d.
但是,我们可以手动"进行等效的操作:
However, we can do the equivalent 'by-hand':
In [196]: np.multiply.at(base1, (np.arange(2)[:,None,None],np.arange(3)[:,None],index[:,None,:]), to_
...: multiply)
In [197]: np.allclose(base,base1)
Out[197]: True
目标是制作 3 个一起广播的数组以匹配 to_multiply
(最后一个尺寸为 5 的维度除外).
The goal was to make 3 arrays that broadcast together to match to_multiply
(except for the last size 5 dimension).
即 (2,1,1), (1,3,1) 和 (2,1,4) =>(2,3,4)
That is a (2,1,1), (1,3,1) and (2,1,4) => (2,3,4)
In [199]: np.broadcast_arrays(np.arange(2)[:,None,None],np.arange(3)[:,None],index[:,None,:])
Out[199]:
[array([[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]]),
array([[[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2]],
[[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2]]]),
array([[[0, 2, 4, 2],
[0, 2, 4, 2],
[0, 2, 4, 2]],
[[0, 3, 3, 2],
[0, 3, 3, 2],
[0, 3, 3, 2]]])]
虽然我对要去的地方有一个大致的想法,但我必须先尝试很多想法.
While I had a general idea of where I wanted to go, I had to try quite a number of ideas first.
这篇关于np.ufunc.at 和 np.ix_ 的 Numpy 多维索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!