tensorflow matmul函数

这篇博客探讨了TensorFlow中matmul函数的要求和一些隐性行为。通常,`tf.matmul()`函数要求操作数的最后两维可乘,其余维度相等。然而,它也支持一些隐性的维度匹配,例如通过扩展维度、堆叠或平铺来使得形状兼容。博主展示了几个例子,说明即使维度不完全符合标准要求,TensorFlow仍能通过内部处理使运算成功。但并非所有情况都适用,当无法通过这些方式调整形状时,将会抛出错误。
摘要由CSDN通过智能技术生成

tensorflow 函数matmul要求

a=tf.constant([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
b=tf.constant([[[1,2],[3,4],[5,6]],[[1,2],[3,4],[5,6]]])
print(a.shape) #2*2*3
print(b.shape) #2*3*2
c=tf.matmul(a,b)
print(c)

结论:要求 a、b的最后两维可乘,其他维度相等。但有时会有一些隐性的东西:

a=tf.constant([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
b=tf.constant([[1,2],[3,4],[5,6]])
print(a.shape) 
print(b.shape) #3*2
c=tf.matmul(a,b)
print(c)

比如这个是成立的,tf内部实现时使用了expend_dim以及tile后stack在一起,所以发生了有意思的事情,就是:

a=tf.constant([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
b=tf.constant([[1,2],[3,4],[5,6]])#3*2

a=tf.constant([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
b=tf.constant([[[1,2],[3,4],[5,6]]]) #1*3*2

a=tf.constant([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
b=tf.constant([[[1,2],[3,4],[5,6]],[[1,2],[3,4],[5,6]]]) #2*3*2

这三种方式是等效的,但是当b的维度不可以通过tile达到a的维度时会报错:

a=tf.constant([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
b=tf.constant([[[1,2],[3,4],[5,6]],[[1,2],[3,4],[5,6]],,[[1,2],[3,4],[5,6]]]) #3*3*2
tensorflow.python.framework.errors_impl.InvalidArgumentError: In[0] and In[1] must have compatible batch dimensions: [2,2,3] vs. [3,3,2] [Op:BatchMatMulV2]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值