当前位置 博文首页 > numpy和tensorflow中的各种乘法(点乘和矩阵乘)

    numpy和tensorflow中的各种乘法(点乘和矩阵乘)

    作者:MHyourh 时间:2021-05-07 17:44

    点乘和矩阵乘的区别:

     1)点乘(即“ * ”) ---- 各个矩阵对应元素做乘法

    若 w 为 m*1 的矩阵,x 为 m*n 的矩阵,那么通过点乘结果就会得到一个 m*n 的矩阵。

    4e48b4586b56c7efd0ed30b97d9cddef.png

    若 w 为 m*n 的矩阵,x 为 m*n 的矩阵,那么通过点乘结果就会得到一个 m*n 的矩阵。

    830b6ddf1793c4b6efd8da31b6b8640f.png

    w的列数只能为 1 或 与x的列数相等(即n),w的行数与x的行数相等 才能进行乘法运算。

    2)矩阵乘 ---- 按照矩阵乘法规则做运算

    若 w 为 m*p 的矩阵,x 为 p*n 的矩阵,那么通过矩阵相乘结果就会得到一个 m*n 的矩阵。

    只有 w 的列数 == x的行数 时,才能进行乘法运算

    145ad3efea8533f6dd2a2e7e7f435705.png

    1. numpy

    1)点乘

     import numpy as np
     
     w = np.array([[0.4], [1.2]])
     x = np.array([range(1,6), range(5,10)])
     
     print w
     print x
     print w*x
    

    运行结果如下图:

    697d8fff16325c33465de3c71a448660.png

    2)矩阵乘

    import numpy as np
     
    w = np.array([[0.4, 1.2]])
    x = np.array([range(1,6), range(5,10)])
     
    print w
    print x
    print np.dot(w,x)

    运行结果如下:

    67254df72c038258e75d3a528848d691.png

    2. tensorflow

    1)点乘

    import tensorflow as tf
     
    w = tf.Variable([[0.4], [1.2]], dtype=tf.float32) # w.shape: [2, 1]
    x = tf.Variable([range(1,6), range(5,10)], dtype=tf.float32) # x.shape: [2, 5]
    y = w * x   # 等同于 y = tf.multiply(w, x)  y.shape: [2, 5]
     
    sess = tf.Session()
    init = tf.global_variables_initializer()
    sess.run(init)
    
    print sess.run(w)
    print sess.run(x)
    print sess.run(y)
    

    运行结果如下:

    6e694c88a2f7766144e549a450533f82.png

    2)矩阵乘

    # coding:utf-8
    import tensorflow as tf
    
    w = tf.Variable([[0.4, 1.2]], dtype=tf.float32) # w.shape: [1, 2]
    x = tf.Variable([range(1,6), range(5,10)], dtype=tf.float32) # x.shape: [2, 5]
    y = tf.matmul(w, x) # y.shape: [1, 5]
    
    sess = tf.Session()
    init = tf.global_variables_initializer()
    sess.run(init)
    
    print sess.run(w)
    print sess.run(x)
    print sess.run(y)

    运行结果如下:

    abbd11625ed3915b36a9a1a6e73adc19.png

    js
    下一篇:没有了