How do I take the squared difference of two Keras tensors?

Viewed 7587

I have a Keras Model which calculates two tensors, r1 and r2 of the same shape. I would like to have the model calculate (r1 - r2)**2.

I can take the sum of these tensors with keras.layers.add(r1, r2). I can take a product with keras.layers.multiply(r1, r2). If there was a subtract function, I'd write

r = keras.layers.subtract(r1, r2)
square_diff = keras.layers.multiply(r, r)

but there doesn't appear to be a keras.layers.subtract function.

In lieu of that I've been trying to figure out how to multiply one of my inputs by a constant -1 tensor and then adding, but I can't figure out how to create that -1 tensor. I've tried a number of variants on

negative_one = keras.backend.constant(np.full(r1.get_shape()), -1)

none of which work. Presumably because the dimensionality of r1 is (?, 128) (i.e. the first dimension is a batch size, and the second represents 128 hidden elements.)

What is the correct way in Keras to take the difference of two tensors?

2 Answers
Related