Reputation: 826
I have to add two tensors, one with a shape multiple of the other in the depth direction. Here an example
t1 = tf.constant(3, shape=[2, 2, 2], dtype=tf.float32)
t2 = tf.constant(1, shape=[2, 2, 1], dtype=tf.float32)
I want to use something like tf.add
to add the second tensor to the first but only in the first layer of the third component of the shape. With numbers
t1 = [[[3, 3], [3, 3]],
[[3, 3], [3, 3]]]
t2 = [[[1, 1], [1, 1]]]
output = [[[4, 4], [4, 4]],
[[3, 3], [3, 3]]]
Is there a built-in function to do that?
Upvotes: 1
Views: 295
Reputation: 214927
Add the first 'column' of t1
with t2
and then concat it with the rest columns of t1
:
t1 = tf.constant(3, shape=[2, 2, 2], dtype=tf.float32)
t2 = tf.constant(1, shape=[2, 2, 1], dtype=tf.float32)
tf.InteractiveSession()
tf.concat((t1[...,0:1] + t2, t1[...,1:]), axis=2).eval()
#array([[[4., 3.],
# [4., 3.]],
# [[4., 3.],
# [4., 3.]]], dtype=float32)
Notice your second example t2
has a different shape, i.e. (1,2,2)
instead of (2,2,1)
, in which case, slice and concat by the first axis:
tf.concat((t1[0:1] + t2, t1[1:]), axis=0).eval()
#array([[[4., 4.],
# [4., 4.]],
# [[3., 3.],
# [3., 3.]]], dtype=float32)
Upvotes: 2