简体   繁体   English

Numpy einsum广播

[英]Numpy einsum broadcasting

Can someone please explain how broadcasting (ellipsis) works in the numpy.einsum() function? 有人可以解释广播(省略号)如何在numpy.einsum()函数中工作?

Some examples to show how and when it can be used would be greatly appreciated. 将非常感谢一些示例来说明如何以及何时使用它。

I've checked the following official documentation page but there are only 2 examples and I can't seem to understand how to interpret it and use it. 我检查了以下官方文档页面,但只有2个例子,我似乎无法理解如何解释它并使用它。

http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.einsum.html http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.einsum.html

The ellipses are a shorthand roughly standing for "all the remaining axes not explicitly mentioned". 椭圆是一个粗略的缩写,代表“未明确提到的所有剩余轴”。 For example, suppose you had an array of shape (2,3,4,5,6,6): 例如,假设您有一个形状数组(2,3,4,5,6,6):

import numpy as np
arr = np.random.random((2,3,4,5,6,6))

and you wish to take a trace along its last two axes: 你希望沿着最后两个轴追踪:

result = np.einsum('ijklmm->ijklm', arr)
result.shape
# (2, 3, 4, 5, 6)

An equivalent way to do that would be 一种等效的方法是

result2 = np.einsum('...mm->...m', arr)
assert np.allclose(result, result2)

The ellipses provide a shorthand notation meaning (in this case) "and all the axes to the left". 省略号提供简写符号(在这种情况下)“和所有轴向左”。 The ... stand for ijkl . ...代表ijkl

One nice thing about not having to be explicit is that 关于不必明确的一件好事是

np.einsum('...mm->...m', arr)

works equally well with arrays of any number of dimensions >= 2 (so long as the last two have equal length), whereas 同样适用于任意数量维数> = 2的数组(只要最后两个具有相等的长度),而

np.einsum('ijklmm->ijklm', arr)

only works when arr has exactly 6 dimensions. 仅当arr正好有6个维度时才有效。


When the ellipses appear in the middle, it is shorthand for "all the middle axes not explicitly mentioned". 当椭圆出现在中间时,它是“未明确提到的所有中轴”的简写。 For example, below, np.einsum('ijklmi->ijklm', arr) is equivalent to np.einsum('i...i->i...', arr) . 例如,下面, np.einsum('ijklmi->ijklm', arr)相当于np.einsum('i...i->i...', arr) Here the ... stand for jklm : 这里...代表jklm

arr = np.random.random((6,2,3,4,5,6))
result = np.einsum('ijklmi->ijklm', arr)
result2 = np.einsum('i...i->i...', arr)
assert np.allclose(result, result2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM