【问题标题】:Efficient way of multiply 3D-tensor with matrix in Tensorflow?在Tensorflow中将3D张量与矩阵相乘的有效方法?
【发布时间】:2018-02-22 11:46:20
【问题描述】:

我有 2 个 3D 张量 A 的形状(batch_size,dim1,dim2)和 B 的大小(batch_size,dim2,dim3)。我想执行以下计算:

C = np.zeros((batch_size, dim1, dim3))
for i in range(batch_size):
    c[i] = A[i].dot(B[i])

我尝试了C = tf.matmul(A,B),但得到了错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError:形状 必须是 2 级,但对于带有输入的“MatMul”(操作:“MatMul”)是 3 级 形状:[10,100,100]、[10,100]

在 TensorFlow 中是否有任何有效的方法来实现这一点? 谢谢!

【问题讨论】:

  • 你试过C=tf.matmul(A,B)吗?
  • @mikkola 是的,我得到了更新描述中的错误
  • @Roger your 表示 A 和 B 的排名为 2 和 3。尝试排名为 3 的两者

标签: tensorflow matrix-multiplication tensor


【解决方案1】:

让我们先用numpy:

import numpy as np
batch_size = 5
dim1 = 7
dim2 = 2
dim3 = 3

A = np.random.rand(batch_size, dim1, dim2)
B = np.random.rand(batch_size, dim2, dim3)  
C = np.zeros((batch_size, dim1, dim3)) 

for i in range(batch_size):                         
    c[i] = A[i].dot(B[i])
print(np.einsum('ikl,ilm->ikm',A,B)) - C # prints a zero array

现在让我们使用tensorflow:

import tensorflow as tf
a = tf.constant(A) # reusing numpy arrays
b = tf.constant(B)
op = tf.einsum('ikl,ilm->ikm',a,b)
with tf.Session() as sess:       
    print(sess.run(op) - C) # prints a zero array

现在根据这个answer,看起来性能应该与幼稚的实现相当相似。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 2016-12-11
    • 2021-07-17
    • 1970-01-01
    相关资源
    最近更新 更多