简体   繁体   English

numpy einsum得到轴排列

[英]numpy einsum to get axes permutation

What I understood in the documentation of 'np.einsum' is that a permutation string, would give a permutation of the axis in a vector. 我在'np.einsum'的文档中理解的是,置换字符串将给出向量中轴的置换。 This is confirmed by the following experiment: 以下实验证实了这一点:

>>> M = np.arange(24).reshape(2,3,4)
>>> M.shape
(2, 3, 4)
>>> np.einsum('ijk', M).shape
(2, 3, 4)
>>> np.einsum('ikj', M).shape
(2, 4, 3)
>>> np.einsum('jik', M).shape
(3, 2, 4)

But this I cannot understand: 但这我无法理解:

>>> np.einsum('kij', M).shape
(3, 4, 2)

I would expect (4, 2, 3) instead... What's wrong with my understanding? 我希望(4,2,3)相反......我的理解有什么问题?

When the output signature is not specified (ie there's no '->' in the subscripts string), einsum will create it by taking the letters it's been given and arranging them in alphabetical order. 如果未指定输出签名(即下标字符串中没有'->' ,则einsum将通过获取已给出的字母并按字母顺序排列它们来创建它。

This means that 这意味着

np.einsum('kij', M)

is actually equivalent to 实际上相当于

np.einsum('kij->ijk', M)

So writing 'kij' labels the axes of the input matrix, not the output matrix, and this leads to the permutation of the axes that you observed. 因此,写'kij'标记输入矩阵的轴,而不是输出矩阵,这会导致您观察到的轴的排列。

This point isn't made explicit in the documentation, but can be seen commented in the C source code for einsum : 这一点在文档中没有明确说明,但可以在einsumC源代码中einsum

/*
 * If there is no output signature, create one using each label
 * that appeared once, in alphabetical order
 */

To ensure the axes of M are permuted in the intended order, it may be necessary to give einsum the labeling for both the input and output matrices: 为了确保M的轴按预期顺序进行置换,可能​​需要为输入和输出矩阵提供einsum标记:

>>> np.einsum('ijk->kij', M).shape
(4, 2, 3)

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

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