Tensorflow中的张量乘法

5

我正在尝试在NumPy/Tensorflow中进行张量乘法。

我有3个张量- A (M X h), B (h X N X s), C (s X T)

我相信A X B X C应该产生一个张量D (M X N X T)

以下是代码(同时使用numpy和tensorflow)。

M = 5
N = 2
T = 3
h = 2
s = 3
A_np = np.random.randn(M, h)
C_np = np.random.randn(s, T)
B_np = np.random.randn(h, N, s)

A_tf = tf.Variable(A_np)
C_tf = tf.Variable(C_np)
B_tf = tf.Variable(B_np)

# Tensorflow
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print sess.run(A_tf)
    p = tf.matmul(A_tf, B_tf)
    sess.run(p)

这将返回以下错误:
ValueError: Shape must be rank 2 but is rank 3 for 'MatMul_2' (op: 'MatMul') with input shapes: [5,2], [2,2,3].

如果我们只使用NumPy矩阵进行乘法运算,就会出现以下错误:
np.multiply(A_np, B_np)

ValueError: operands could not be broadcast together with shapes (5,2) (2,2,3)

然而,我们可以使用np.tensordot来实现:

np.tensordot(np.tensordot(A_np, B_np, axes=1), C_np, axes=1)

TensorFlow中是否有相应的操作?

答案

在numpy中,我们会这样做:

ABC_np = np.tensordot(np.tensordot(A_np, B_np, axes=1), C_np, axes=1)

在TensorFlow中,我们会按照以下方式进行:
AB_tf = tf.tensordot(A_tf, B_tf,axes = [[1], [0]])
AB_tf_C_tf = tf.tensordot(AB_tf, C_tf, axes=[[2], [0]])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    ABC_tf = sess.run(AB_tf_C_tf)

np.allclose(ABC_np, ABC_tf) return True.

1个回答

8

尝试

tf.tensordot(A_tf, B_tf,axes = [[1], [0]])

例如:

x=tf.tensordot(A_tf, B_tf,axes = [[1], [0]])
x.get_shape()
TensorShape([Dimension(5), Dimension(2), Dimension(3)])

这里是tensordot文档,这里是相关的github存储库


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接