爱因斯坦求和约定(Einstein Notation)
在数学中,爱因斯坦求和约定是一种标记法,也称为Einstein Summation Convention,在处理关于坐标的方程式时十分有效。简单来说,爱因斯坦求和就是简化掉求和式中的求和符号 ,这样就会使公式更加简洁
- 转置
import numpy as np
a = np.arange(0, 9).reshape(3, 3)
print(a)
b = np.einsum('ij->ji', a)
print(b)
Output:
a: [[0 1 2]
[3 4 5]
[6 7 8]]
b: [[0 3 6]
[1 4 7]
[2 5 8]]
- 全部元素求和
import numpy as np
a = np.arange(0, 9).reshape(3, 3)
print(a)
b = np.einsum('ij->', a)
print(b)
Output:
a: [[0 1 2]
[3 4 5]
[6 7 8]]
b: 36
- 某一维度求和
import numpy as np
a = np.arange(0, 9).reshape(3, 3)
print(a)
b = np.einsum('ij->i', a)
print(b)
Output:
a: [[0 1 2]
[3 4 5]
[6 7 8]]
b: [ 3 12 21]
- 矩阵对应维度相乘(广播形式)
import numpy as np
a = np.arange(0, 12).reshape(3, 4)
print(a)
b = np.arange(0, 4).reshape(4)
print(b)
c = np.einsum('ij,j->ij', a, b)
print(c)
Output:
a: [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
b: [0 1 2 3]
c: [[ 0 1 4 9]
[ 0 5 12 21]
[ 0 9 20 33]]
- 矩阵对应维度相乘(求和形式)
import numpy as np
a = np.arange(0, 12).reshape(3, 4)
print(a)
b = np.arange(0, 4).reshape(4)
print(b)
c = np.einsum('ij,j->i', a, b)
print(c)
Output:
a: [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
b: [0 1 2 3]
c: [14 38 62]
- 矩阵点积
import numpy as np
a = np.arange(0, 12).reshape(3, 4)
print(a)
b = np.arange(0, 12).reshape(3, 4)
print(b)
c = np.einsum('ij,ij->', a, b)
print(c)
Output:
a: [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
b: [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
c: 506
- 矩阵外积(相乘)
import numpy as np
a = np.arange(0, 12).reshape(3, 4)
print(a)
b = np.arange(0, 12).reshape(4, 3)
print(b)
c = np.einsum('ik,kj->ij', a, b)
print(c)
Output:
a: [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
b: [[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
c: [[ 42 48 54]
[114 136 158]
[186 224 262]]
网友评论