传递给numpy.einsum()的下标是什么意思?

时间:2019-05-17 20:23:31

标签: python numpy-einsum

我正在尝试理解python代码,该代码使用$ wine REG QUERY "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v ProductName HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion ProductName REG_SZ Microsoft Windows 7 将4维numpy数组numpy.einsum()转换为2维或3维数组。传递给A的下标如下:

numpy.einsum()

等按照(Understanding NumPy's einsum和(Python - Sum 4D Array)的答案,我尝试使用Mat1 = np.einsum('aabb->ab', A) Mat2 = np.einsum('abab->ab', A) Mat3 = np.einsum('abba->ab', A) T1 = np.einsum('abcb->abc' A) T2 = np.einsum('abbc->abc', A) 来理解上述下标的含义,例如numpy.sum(),但我无法复制结果,这是我用Mat1 = np.sum(A, axis=(0,3))获得的。 有人可以解释在numpy.einsum()中如何解释这些下标吗?

1 个答案:

答案 0 :(得分:1)

我建议您阅读Einstein notation on Wikipedia

这是您问题的简短答案:

np.einsum('aabb->ab', A)

表示:

res = np.empty((max_a, max_b), dtype=A.dtype)
for a in range(max_a):
  for b in range(max_b):
    res[a, b] = A[a, a, b, b]
return res

简短说明:
aabb表示索引及其相等性(请参见A[a, a, b, b]);
->ab表示形状为(max_a, max_b),并且您不需要在这两个索引上有两个具有和。 (如果它们也是c,那么您应将所有内容用c求和,因为它们不会在->之后出现)

其他示例:

np.einsum('abab->ab', A)

# Same as (by logic, not by actual code)

res = np.empty((max_a, max_b), dtype=A.dtype)
for a in range(max_a):
  for b in range(max_b):
    res[a, b] = A[a, b, a, b]
return res
np.einsum('abba->ab', A) 

# Same as (by logic, not by actual code)

res = np.empty((max_a, max_b), dtype=A.dtype)
for a in range(max_a):
  for b in range(max_b):
    res[a, b] = A[a, b, b, a]
return res
np.einsum('abcb->abc', A)

# Same as (by logic, not by actual code)

res = np.empty((max_a, max_b, max_c), dtype=A.dtype)
for a in range(max_a):
  for b in range(max_b):
    for c in range(max_c):
      res[a, b, c] = A[a, b, c, b]
return res
np.einsum('abbc->abc', A)

# Same as (by logic, not by actual code)

res = np.empty((max_a, max_b, max_c), dtype=A.dtype)
for a in range(max_a):
  for b in range(max_b):
    for c in range(max_c):
      res[a, b, c] = A[a, b, b, c]
return res

一些代码来检查它是否真实:

import numpy as np


max_a = 2
max_b = 3
max_c = 5

shape_1 = (max_a, max_b, max_c, max_b)
A = np.arange(1, np.prod(shape_1) + 1).reshape(shape_1)

print(A)
print()
print(np.einsum('abcb->abc', A))
print()

res = np.empty((max_a, max_b, max_c), dtype=A.dtype)
for a in range(max_a):
  for b in range(max_b):
    for c in range(max_c):
      res[a, b, c] = A[a, b, c, b]

print(res)
print()