如何对形状为[1,16,16,3]和[1,4,4,3]的两个4d张量执行元素明智乘法

时间:2018-11-08 03:50:43

标签: python tensorflow

我想将两个4d张量元素相乘并将结果存储在4d张量中。我有一个形状为[batch_size,16,16,3]的张量'A'和一个形状为[batch_size]的张量'B' ,4,4,3]。我想执行一种平铺操作,以使张量“ A”的每个4x4x3块都与张量“ B”进行元素明智的乘法。 结果存储在与张量'A'相同的张量'C'中,即[batch_size,16,16,3]。 AS张量'B'的高度和宽度是张量'A'的高度和宽度的倍数。我应该在张量“ C”中连接,累加或分配4个元素乘法的结果。

1 个答案:

答案 0 :(得分:1)

这可以通过重塑并使用broadcasting来完成。

import tensorflow as tf

batch_size = 50

# These are the tensors we want to multiply
a = tf.random_normal(shape=(batch_size,16,16,3))
b = tf.random_normal(shape=(batch_size,4,4,3))

# We reshape the tensors so that they their shapes are
# compatible for broadcasting
a_reshape = tf.reshape(a,(-1,4,4,4,4,3))
b_reshape = tf.reshape(b,(-1,4,1,4,1,3))

# we perform the multiplication. Each dimenshion of size 1 in `b_reshape`
# will be tiled to have the corresponding size 4 of `a_reshape`
c_reshape = a_reshape*b_reshape

# convert result to required shape
c = tf.reshape(c_reshape,(-1,16,16,3))