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.Variable(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)

参考:
[1]. https://stackoverflow.com/questions/38235555/tensorflow-matmul-of-input-matrix-with-batch-data
[2]. https://stackoverflow.com/questions/34183343/how-does-tensorflow-batch-matmul-work

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文链接:https://yq.aliyun.com/articles/178374 0. 简介 在过去,我写的主...
    dopami阅读 5,701评论 1 3
  • 简单线性回归 import tensorflow as tf import numpy # 创造数据 x_dat...
    CAICAI0阅读 3,573评论 0 49
  • 中国很多穷乡僻壤,一千几百元可以实质地供他们改善生活,特别是小孩。对于在一线城市工作的大部分人,这点钱应该不至于影...
    gabz阅读 307评论 0 0
  • 人活着究竟是为了什么呢?是为了那还没有还完贷款的房子还是那辆看了很多遍却依旧不属于自己的车子? 纵使自己已经事业有...
    炎炎的幸福部落阅读 304评论 0 1
  • 魔都是远方 临港坐落成家 1 天光乍破遇,暮雪白头老 初遇,便是一生。...
    南南向北阅读 230评论 0 1