如果我有两个像这样的 numpy 数组
a = np.array([1, 2])
b = np.array([3, 4])
我想添加所有成对组合,我可以轻松做到
c = a + b[:, None]
c
array([[4, 5],
[5, 6]])
得到1+3、2+3和1+4、2+4的结果>。
为什么会这样? “无”在做什么?我可以打印出来
b[:, None]
[[3]
[4]]
但我不确定为什么这会告诉 numpy 进行成对组合。我也很好奇,与 itertools.combinations 相比,它是否在幕后有效实现。
最佳答案
要回答问题的第一部分,b[:, None]
是一种特殊类型的切片,其行为与 b[:, np.newaxis]
,因为它将长度为 1 的轴添加到您的数组。
>>> b.shape
(2,)
>>> b[:, None].shape
(2, 1)
此行为记录在 numpy
docs [1] 中,强调我的:
The
newaxis
object can be used in all slicing operations to create an axis of length one.newaxis
is an alias forNone
, andNone
can be used in place of this with the same result.
所以现在我们有两个数组:
array([1, 2]) + array([[3],
[4]])
将这两个数组相加得到:
array([[4, 5],
[5, 6]])
这背后的“魔法”是numpy
broadcasting[2] . This article [3]是开始理解该主题的极好资源。
文章的主要内容如下:
numpy
操作通常逐个元素地完成,这需要两个数组具有完全相同的形状。但是,如果两个数组具有相同的尾随轴,或者其中一个尾随轴等于一个(这是您的情况下表现出的行为),则此约束会放宽).
在您的例子中,发生了广播,因此该操作等效于对以下 2x2 数组求和:
array([[1, 2], + array([[3, 3],
[1, 2]]) [4, 4]])
由于 numpy 操作是逐个元素完成的,因此将产生所需的输出:
array([[4, 5],
[5, 6]])
[1] https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis
[2] https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html
[3] http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc
关于python - 使用 'None' 进行成对操作的 numpy 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51091560/