前两篇博客分别总结了numpy和Pytorch中常用的乘法函数:
numpy常用乘法函数总结:np.dot()、np.multiply()、*、np.matmul()、@、np.prod()、np.outer()-CSDN博客
Pytorch常用乘法函数总结:torch.mul()、*、torch.mm()、torch.bmm()、torch.mv()、torch.dot()、@、torch.matmul()-CSDN博客
本文总结TensorFlow常用的乘法函数,代码示例以TensorFlow2.x为例,其中 tf.tensordot() 这个函数的用法比较复杂;tf.einsum() 可以理解为一个通用的函数模板,在numpy和Pytorch中也有类似的函数和用法
tf.multiply(x, y) 等价于 x*y,为矩阵的element-wise乘法,要求两个矩阵的shape一致,或其中一个维度为1(扩展为另一个矩阵对应位置的维度大小)
import tensorflow as tf
X = tf.constant([[1, 2, 3], [4, 5 ,6]], dtype=tf.float32)
Y = tf.constant([[1, 1, 1], [2, 2 ,2]], dtype=tf.float32)
Z = tf.multiply(X, Y) # 乘法操作,对应位置元素相乘
out:
tf.Tensor(
[[ 1. 2. 3.]
[ 8. 10. 12.]], shape=(2, 3), dtype=float32)
tf.matmul(x, y) 等价于 x@y,为矩阵乘法,参与运算的是最后两维形成的矩阵
import tensorflow as tf
X = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32)
Y = tf.constant([[1, 2], [1, 2], [1, 2]], dtype=tf.float32)
Z = tf.matmul(X, Y) # 矩阵乘法操作
out:
tf.Tensor(
[[ 6. 12.]
[15. 30.]], shape=(2, 2), dtype=float32)
标量和张量相乘(标量乘标量或向量或矩阵)
import tensorflow as tf
x = tf.constant(2, dtype=tf.float32)
Y1 = tf.constant(3, dtype=tf.float32)
Z1 = tf.scalar_mul(x, Y1) # 标量×标量
Y2 = tf.constant([1, 2, 3], dtype=tf.float32)
Z2 = tf.scalar_mul(x, Y2) # 标量×向量
Y3 = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32)
Z3 = tf.scalar_mul(x, Y3) # 标量×矩阵
out:
tf.Tensor(6.0, shape=(), dtype=float32)
tf.Tensor([2. 4. 6.], shape=(3,), dtype=float32)
tf.Tensor(
[[ 2. 4. 6.]
[ 8. 10. 12.]], shape=(2, 3), dtype=float32)
参考了博客 tensorflow和num