Keras Lambda layer output isn't a "symbolic tensor"

Viewed 2517

I am using Keras with tensorflow as backend. I am trying to define a Lambda layer for image normalisation. When I am trying to feed the output of the Lamba layer to another Conv2D layer, I am getting error:

Layer conv2d_1 was called with an input that isn't a symbolic tensor

I read the online material on Lamba layer, and everyone seems to do the same way as I am doing, but somehow my code fails. I have simply defined a pre-processing function and pass the image through it.

def pre_process(image):

   norm = cv2.normalize(image, None, alpha=0, beta=1, 
          norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

   return norm

input_layer = Input(shape=(size, size, chs))
norm = Lambda(pre_process, output_shape=(size, size, chs))
conv_1 = Conv2D(16, kernel_size=(1, 1), strides=(1, 1), 
                    padding='valid', activation='relu')(norm)

When defining the conv_1 layer I get error:

Layer conv2d_1 was called with an input that isn't a symbolic tensor. Received type: . Full input: []. All inputs to the layer should be tensors.

Edit 1:

I modified the code and ran into new errors. The new code looks like:

   def pre_process(image):    
    return tf.image.per_image_standardization(image[0])

   img_shape = (size, size, chs)
   input_layer = Input(shape=(img_shape))
   norm = Lambda(pre_process)(input_layer)
   conv_1 = Conv2D(16, kernel_size=(1, 1), strides=(1, 1), padding='valid', activation='relu')(norm)

After normalisation, since I am chaning the shape from (1, w, h, 3) to (w, h, 3) I am getting an error as:

ValueError: Input 0 is incompatible with layer conv2d_2: expected ndim=4, found ndim=3

The Lambda layer by default should take the same shape as input layer, but here that is not the case. How can I make sure the shape remains the same?

1 Answers

You didn't call the lambda layer with an input, you should do it like this:

input_layer = Input(shape=(size, size, chs))
norm = Lambda(pre_process, output_shape=(size, size, chs))(input_layer)
conv_1 = Conv2D(16, kernel_size=(1, 1), strides=(1, 1), 
                    padding='valid', activation='relu')(norm)
Related