Reputation: 135
I want to multiply element-wise two 4d tensor and store the result in a 4d tensor.I have a tensor say 'A' of shape [batch_size,16,16,3] and tensor 'B' of shape [batch_size,4,4,3]. I want to perform a sort of tiling operation such that each 4x4x3 block of tensor 'A' does element wise multiplication with tensor 'B'. The result is stored in a tensor 'C' of shape same as tensor 'A' i.e. [batch_size,16,16,3]. AS tensor 'B' has height and width are multiples of height and width of tensor 'A'. I should concatenate or accumulate or assign the results of 4 elementwise multiplication in tensor 'C'.
Upvotes: 0
Views: 340
Reputation: 2019
This can be done by reshaping and using 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))
Upvotes: 1