Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Keras/Tensorflow批量矩阵跨轴乘法_Tensorflow_Matrix_Keras_Deep Learning - Fatal编程技术网

Keras/Tensorflow批量矩阵跨轴乘法

Keras/Tensorflow批量矩阵跨轴乘法,tensorflow,matrix,keras,deep-learning,Tensorflow,Matrix,Keras,Deep Learning,假设我有张量 a Out[15]: <tf.Tensor 'Placeholder_2:0' shape=(?, 1152, 8) dtype=float32> b Out[16]: <tf.Variable 'Variable:0' shape=(16, 8, 1152, 10) dtype=float32_ref> a 出[15]: B 出[16]: a表示一批1152个8维向量和 b是1152*10,(16,8)矩阵 我想把这些矩阵和a中的8维向量相乘,得到一个

假设我有张量

a
Out[15]: <tf.Tensor 'Placeholder_2:0' shape=(?, 1152, 8) dtype=float32>
b
Out[16]: <tf.Variable 'Variable:0' shape=(16, 8, 1152, 10) dtype=float32_ref>
a
出[15]:
B
出[16]:
a表示一批1152个8维向量和 b是1152*10,(16,8)矩阵

我想把这些矩阵和a中的8维向量相乘,得到一个形状张量(None,161152,10)。我知道在tensorflow中可以使用
einsum
完成这项工作

tf.einsum('ijkl,bkj->bikl',b,a)


给我正确的输出和形状。但是与类似的函数如
K.batch\u dot
tf.tensordot
相比,
tf.einsum
非常慢。然而,我很难理解这些函数是如何处理轴和广播规则的。有什么帮助吗?

通过使用
转置
重塑
可以实现相同的效果:

a : [batch, 1152, 8] --> reshape --> [batch, 1, 1, 1152, 8]
b : [16,8,1152,10]   --> transpose --> [16, 10, 1152, 8] 
                     --> expand_dims --> [1, 16, 10, 1152, 8]
multiply (a, b)      --> [batch, 16, 10, 1152, 8] 
reduce_sum axis 4    --> [batch, 16, 10, 1152]             
代码:


谢谢你的回答。为了进行这样的运算,人们总是必须匹配张量的秩,这是真的吗?也可以用批处理点替换乘法->减少_和吗?对于广播,需要使两个维度相等,或1。我们不能使用批处理点,因为我们这里不做矩阵乘法。
#inputs
import numpy.testing as npt
x = np.random.normal(size=(5,1152,8)) 
y = np.random.normal(size=(16, 8, 1152, 10))

a = tf.placeholder(tf.float32,shape=(None, 1152, 8))
b = tf.constant(y, tf.float32)

out = tf.reduce_sum(tf.expand_dims(tf.transpose(b,[0, 3, 2, 1]),0) 
                   * tf.reshape(a,[-1,1,1,tf.shape(a)[1], tf.shape(a)[2]]), axis=4)
out = tf.transpose(out, [0,1,3,2])
out_ein = tf.einsum('ijkl,bkj->bikl', b, a)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    o = sess.run(out, {a: x})
    e = sess.run(out_ein, {a: x})
    npt.assert_almost_equal(o, e, decimal=5)
    #almost the same