美文网首页
TensorFlow中如何实现batch_matmul

TensorFlow中如何实现batch_matmul

作者: ziyu123 | 来源:发表于2018-07-02 20:49 被阅读0次

      我们知道,在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

    相关文章

      网友评论

          本文标题:TensorFlow中如何实现batch_matmul

          本文链接:https://www.haomeiwen.com/subject/skgluftx.html