Dittsche
Dittsche

Reputation: 33

Subtract each row of a tensor A by each row of a Tensor B

I want to subtract every row of Tensor A from every row in Tensor B. This is what I want (this does not produce the result):

A = tf.constant([[1,2],[2,4]])
B = tf.constant([[1,2],[3,4]])
C = tf.math.subtract(A,B)
tf.Session().run(C)
print(C)
[[0 0]
 [-1 0]]
I want:
>>> C = [[[0,0],[-2,-2]],[[1,2],[-1,0]]]

I am aware that I Could make both arrays big (bassically repeat the entries such that they have the same dimensions), so that I can simply use tf.math.subtract. However this is not an option as I would have to decrease my batch size very much and wont be able to train my model properly

Upvotes: 0

Views: 516

Answers (1)

Dittsche
Dittsche

Reputation: 33

I figured it out by now. In case any other person stumbles upon the same problem. Here is the solution I found:

A = tf.constant([[1,2],[2,4]])
B = tf.constant([[1,2],[3,4]])
C = tf.math.subtract(tf.expand_dims(A,axis=2),tf.expand_dims(B,axis=0))
tf.Session().run(C)
[[[0,0],[-2,-2]],[[1,2],[-1,0]]]

It basically takes advantage of the broadcasting mechanics in Tensorflow, which is conviniently leaned twoards numpys broadcasting mechanics.

Upvotes: 1

Related Questions