假设我有一个张量 t1
大小 (a, b, c)
和另一个张量 t2
大小 (c, d)
. 有没有办法把这些乘法得到一个张量?t3
大小 (a, d, b)
(不是 (a, b, d)
)而不使用 tf.transpose
操作?
工作实例。
import tensorflow as tf # version 2.1.0
t1 = tf.constant(tf.reshape(range(24), (2, 3, 4)))
t2 = tf.constant(tf.reshape(range(20), (4, 5)))
t3 = tf.transpose(tf.tensordot(t1, t2, axes=[[2], [0]]), [0, 2, 1]) # shape = (2, 5, 3)
我想得到的是 t3
从 t1
和 t2
而不使用 tf.transpose
据称,这是很昂贵的(链接1, 链接2).
我使用Tensorflow 2.1.0和Python 3.7。
import tensorflow as tf
t1 = tf.constant(tf.reshape(range(24), (2, 3, 4)))
t2 = tf.constant(tf.reshape(range(20), (4, 5)))
t3 = tf.linalg.matmul(t2, t1, transpose_a=True, transpose_b=True)
这是一种有效的方法,可以在不实际计算和存储转置的情况下进行矩阵乘法。