tf.matmul()和tf.multipy()的区别

首先我们分析一下下面的代码:

import tensorflow as tf
import numpy as np

a=tf.constant([[1., 2., 3.],[4., 5., 6.]])
b=np.float32(np.random.randn(3,2))
#c=tf.matmul(a,b)
c=tf.multiply(a,b)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    print(c.eval())

问题是上面的代码编译正确吗?编译一下就知道,错误信息如下:

ValueError: Dimensions must be equal, but are 2 and 3 for 'Mul' (op: 'Mul') with input shapes: [2,3], [3,2].

显然,tf.multiply()表示点积,因此维度要一样。而tf.matmul()表示普通的矩阵乘法。

而且tf.multiply(a,b)和tf.matmul(a,b)都要求a和b的类型必须一致。但是之间存在着细微的区别。

在tf中所有返回的tensor,不管传进去是什么类型,传出来的都是numpy ndarray对象。

看看官网API介绍:

tf.matmul(
    a,
    b,
    transpose_a=False,
    transpose_b=False,
    adjoint_a=False,
    adjoint_b=False,
    a_is_sparse=False,
    b_is_sparse=False,
    name=None
)
tf.multiply(
    x,
    y,
    name=None
)

但是tf.matmul(a,b)函数不仅要求a和b的类型必须完全一致,同时返回的tensor类型同a和b一致;而tf.multiply(a,b)函数仅要求a和b的类型显式一致,同时返回的tensor类型与a一致,即在不声明类型的情况下,编译不报错。

例如:

#类型一致,可以运行
import tensorflow as tf
import numpy as np

a=tf.constant([[1, 2, 3],[4, 5, 6]],dtype=np.float32)
b=np.float32(np.random.randn(3,2))
c=tf.matmul(a,b)
#c=tf.multiply(a,b)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    print (type(c.eval()),type(a.eval()),type(b))
#类型不一致,不可以运行
import tensorflow as tf
import numpy as np

a=tf.constant([[1, 2, 3],[4, 5, 6]])
b=np.float32(np.random.randn(3,2))
c=tf.matmul(a,b)
#c=tf.multiply(a,b)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    print (type(c.eval()),type(a.eval()),type(b))
#类型不一致,可以运行,结果的类型和a一致
import tensorflow as tf
import numpy as np

a=tf.constant([[1, 2, 3],[4, 5, 6]])
b=np.float32(np.random.randn(2,3))
#c=tf.matmul(a,b)
c=tf.multiply(a,b)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    print (c.eval())
    print (type(c.eval()),type(a.eval()),type(b))
#类型不一致,不可以运行
import tensorflow as tf
import numpy as np

a=tf.constant([[1, 2, 3],[4, 5, 6]], dtype=np.float32)
b=tf.constant([[1, 2, 3],[4, 5, 6]], dtype=np.int32)
#c=tf.matmul(a,b)
c=tf.multiply(a,b)
init=tf.global_variables_initializer()
with tf.Session() as sess:
    print (c.eval())
    print (type(c.eval()),type(a.eval()),type(b))

 

转载于:https://www.cnblogs.com/cvtoEyes/p/9035706.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值