美文网首页
einsum爱因斯坦求和约定

einsum爱因斯坦求和约定

作者: 612twilight | 来源:发表于2020-06-06 15:41 被阅读0次

    爱因斯坦求和约定(Einstein Notation)
    在数学中,爱因斯坦求和约定是一种标记法,也称为Einstein Summation Convention,在处理关于坐标的方程式时十分有效。简单来说,爱因斯坦求和就是简化掉求和式中的求和符号 ,这样就会使公式更加简洁

    1. 转置
      {B_{ji}} = {A_{ij}}
    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]]
    
    1. 全部元素求和
      sum{\rm{ = }}\sum\limits_i {\sum\limits_j {{A_{ij}}} }
    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
    
    1. 某一维度求和
      sum{\rm{ = }}\sum\limits_i {{A_{ij}}}
    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]
    
    1. 矩阵对应维度相乘(广播形式)
      {C_{ij}} = {A_{ij}}{B_j}
    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]]
    
    1. 矩阵对应维度相乘(求和形式)
      {C_i} = \sum\limits_j {{A_{ij}}{B_j}}
    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]
    
    1. 矩阵点积
      C = \sum\limits_i {\sum\limits_j {{A_{ij}}{B_{ij}}} }
    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
    
    1. 矩阵外积(相乘)
      {C_{ij}} = \sum\limits_k {{A_{ik}}{B_{kj}}}
    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]]
    

    相关文章

      网友评论

          本文标题:einsum爱因斯坦求和约定

          本文链接:https://www.haomeiwen.com/subject/cfgxtktx.html