• tf.matmul


    矩阵乘法

    tf.matmul

    矩阵乘法-维基百科

    理解矩阵乘法 - 阮一峰的网络日志

    当A是个 4×2 矩阵和B是个 2×3 矩阵时。分别来自两个矩阵的元素都依箭头方向而两两配对,把每一对中的两个元素相乘,再把这些乘积加总起来,最后得到的值即为箭头相交位置的值。

    矩阵相乘最重要的方法是一般矩阵乘积。它只有在第一个矩阵的列数(column)和第二个矩阵的行数(row)相同时才有定义。一般单指矩阵乘积时,指的便是一般矩阵乘积。若A为 m*n 矩阵,B为 n*p 矩阵,则他们的乘积AB(有时记做A · B)会是一个 m*p 矩阵。

    # 2-D
    with tf.Session() as sess:
        a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
        # [[1 2 3]
        #  [4 5 6]]
        print(sess.run(a))
    
        b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])
        # [[ 7  8]
        #   [ 9 10]
        #   [11 12]]
        print(sess.run(b))
        c = tf.matmul(a, b)
        # [[ 58  64]
        #  [139 154]]
    
        # 1*7+2*9+3*11=58
        # 1*8+2*10+3*12=64
        # 4*7+5*9+6*11=139
        # 4*8+5*10+6*12=154
        print(sess.run(c))
    
    # 3-D
    import numpy as np
    with tf.Session() as sess:
       a = tf.constant(np.arange(1, 13, dtype=np.int32),
                        shape=[2, 2, 3])
        # [[[1.  2.  3.]
        #   [4.  5.  6.]],
        # [[7.  8.  9.]
        #  [10. 11. 12.]]]
        print(sess.run(a))
    
        b = tf.constant(np.arange(13, 25, dtype=np.int32),
                        shape=[2, 3, 2])
        # [[[13. 14.]
        #   [15. 16.]
        #   [17. 18.]],
        #  [[19. 20.]
        #   [21. 22.]
        #   [23. 24.]]]
        print(sess.run(b))
    
        c = tf.matmul(a, b)
        # [[[94 100]
        #   [229 244]],
        #  [[508 532]
        #   [697 730]]]
    
        # 1*13+2*15+3*17=94
        # 1*14+2*16+3*18=100
        # 4*13+5*15+6*17=229
        # 4*14+5*16+6*18=244
        # 7*19+8*21+9*23=508
        # 7*20+8*22+9*24=532
        # 10*19+11*21+12*23=697
        # 10*20+11*22+12*24=730
        print(sess.run(c))
    

    Python3.5之后支持新的语法 @

    # Since python >= 3.5 the @ operator is supported (see PEP 465).
    # In TensorFlow, it simply calls the `tf.matmul()` function, so the
    # following lines are equivalent:
    d = a @ b @ [[10.], [11.]]
    d = tf.matmul(tf.matmul(a, b), [[10.], [11.]])
    
  • 相关阅读:
    BZOJ4675: 点对游戏
    Codeforces 1097 Alex and a TV Show
    UOJ#349. 【WC2018】即时战略
    DNS解析过程详解
    js中bind、call、apply函数的用法
    jQuery.extend 函数详解
    JQuery Mobile
    JQuery Mobile 页面参数传递
    HTML div 滚动条样式设计
    JavaScript 加载动画Canvas 设计
  • 原文地址:https://www.cnblogs.com/guqiangjs/p/7807622.html
Copyright © 2020-2023  润新知