愛因斯坦求和約定(Einstein Notation)
在數(shù)學(xué)中涎劈,愛因斯坦求和約定是一種標(biāo)記法算撮,也稱為Einstein Summation Convention轩触,在處理關(guān)于坐標(biāo)的方程式時(shí)十分有效壹蔓。簡單來說杭攻,愛因斯坦求和就是簡化掉求和式中的求和符號(hào) ,這樣就會(huì)使公式更加簡潔
- 轉(zhuǎn)置
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]
- 矩陣對應(yīng)維度相乘(廣播形式)
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]]
- 矩陣對應(yīng)維度相乘(求和形式)
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]
- 矩陣點(diǎn)積
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]]