Python 传递给numpy.einsum()的下标的含义是什么?
我试图理解一个python代码,它使用Python 传递给numpy.einsum()的下标的含义是什么?,python,numpy,numpy-einsum,Python,Numpy,Numpy Einsum,我试图理解一个python代码,它使用numpy.einsum()将一个4维numpy数组a转换为2维或3维数组。传递给numpy.einsum()的下标如下: 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->
numpy.einsum()
将一个4维numpy数组a
转换为2维或3维数组。传递给numpy.einsum()
的下标如下:
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()得到的结果。
有人能解释一下这些下标在numpy.einsum()
中是如何解释的吗?我建议您阅读
以下是对你问题的简短回答:
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)
,这两个索引不需要两个have sum。(如果它们也是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
一些用于检查其是否真实的代码:
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()
非常感谢@CrafterKolyan这些都是对角线上的变体。使用4d阵列,可以选择多种对角线。
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()