Kangzeroo
Kangzeroo

Reputation: 341

Keras 2.2.4 How to replicate merge( ) from Keras 1.x.x

I am trying to convert Keras 1.x.x code into 2.2.x, with TensorFlow backend.

I have the below in Keras 1.x.x which takes the following inputs:

I wish to combine the image with the mask to get a new cropped image where the mask area is missing. To do so, I first take the inverse of mask using 1 - mask, where 1 is a tensor of ones. Then I element-wise multiply org_image * (1 - mask) to get the newly cropped image. The code looks like below in Keras 1.x.x

from keras.layers import Input, merge

input_shape = (256,256,3)

org_img = Input(shape=input_shape)
mask = Input(shape=(input_shape[0], input_shape[1], 1))
input_img = merge([org_img, mask],
                   mode=lambda x: x[0] * (1 - x[1]),
                   output_shape=input_shape)

In Keras 2.2.x a breaking change was introduced that replaced the merge() function with Add(), Subtract(), Multiply() ...etc. The previous merge() had the convinence of mode=lambda x: x[0] * (1 - x[1]) which is equal to mode=lambda [org_img, mask]: org_img * (1 - mask).

How can I replicate the 1 - mask in Keras 2.2.x? Do I need to import in tf.backend.ones?

Or perhaps I need to tf.enable_eager_execution()?

I'm pretty new to this so I know a lot is going over my head. I'd really appreciate it if someone could clarify where my misconception is, thank you!

Upvotes: 3

Views: 498

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86600

Use Lambda layers for custom functions or lambda expressions:

input_img = Lambda(lambda x: x[0] * (1 - x[1]), output_shape=input_shape)([org_img, mask])

Where output_shape is optional if you're using tensorflow as backend.

Other useful layers:

  • Concatenate(axis=...)(list_of_inputs)
  • Add()(list_of_inputs)
  • Multiply()(list_of_inputs)

Upvotes: 1

Related Questions