• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

TensorFlow中tf.batch_matmul()的用法

python 搞代码 4年前 (2022-01-07) 28次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了TensorFlow中tf.batch_matmul()的用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

TensorFlow中tf.batch_matmul()用法

如果有两个三阶张量,size分别为

 a.shape = [100, 3, 4] b.shape = [100, 4, 5] c = tf.batch_matmul(a, b) 

则c.shape = [100, 3, 5] //将每一对 3×4 的矩阵与 4×5 的矩阵分别相乘。batch_size不变

100为张量的batch_size。剩下的两个维度为数据的维度。

不过新版的tensorflow已经移除了上面的函数,使用时换为tf.matmul就可以了。与上面注释的方式是同样的。

附: 如果是更高维度。例如(a, b, m, n) 与(a, b, n, k)之间做matmul运算。则结果的维度为(a, b, m, k)。

TensorFlow如何实现batch_matmul

我们知道,在tensorflow早期版本中有tf.batch_matmul()函数,可以实现多维tensor和低维tensor的直接相乘,这在使用过程中非常便捷。

但是最新版本的tensorflow现在只有tf.matmul()函数可以使用,不过只能实现同维度的tensor相乘, 下面的几种方法可以实现batch matmul的可能。

例如: tensor A(batch_size,m,n), tensor B(n,k),实现batch matmul 使得A * B。

方法1: 利用tf.matmul()

对tensor B 进行增维和扩展

 A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3))) B = tf.Variable(tf.random_normal(shape=(3, 5))) B_exp = tf.tile(tf.expand_dims(B,0),[batch_size, 1, 1]) #先进行增维再扩展 C = tf.matmul(A, B_exp)

方法2: 利用tf.reshape()

对tensor A 进行reshape操作,然后利用tf.matmul()

 A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3))) B = tf.Variable(tf.random_normal(shape=(3, 5))) A = tf.reshape(A, [-1, 3]) C = tf.reshape(tf.matmul(A, B), [-1, 2, 5])

方法3: 利用tf.scan()

利用tf.scan() 对tensor按第0维进行展开的特性

 A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3))) B = tf.Variable(tf.random_normal(shape=(3, 5))) initializer = tf.Variab<div style="color:transparent">来源gaodai^.ma#com搞#代!码网</div>le(tf.random_normal(shape=(2,5))) C = tf.scan(lambda a,x: tf.matmul(x, B), A, initializer)

方法4: 利用tf.einsum()

 A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3))) B = tf.Variable(tf.random_normal(shape=(3, 5))) C = tf.einsum('ijk,kl->ijl',A,B)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持gaodaima搞代码网

以上就是TensorFlow中tf.batch_matmul()的用法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:TensorFlow中tf.batch_matmul()的用法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址