-1

Lets suppose I have specified mobilenet from keras models this way:

base_model = MobileNetV2(weights='imagenet', include_top=False,  input_shape=(224, 224, 3))

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x) 
predictions = Dense(12, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(loss='categorical_crossentropy', optimizer = Adam(),
              metrics=['accuracy'])

But I would like to add custom layer to preporess input image this way:

def myFunc(x):
     return K.reshape(x/255,(-1,224,224,3))
new_model = Sequential()
new_model.add(Lambda(myFunc,input_shape =( 224, 224, 3),  output_shape=(224, 224, 3)))
new_model.add(model)
new_model.compile(loss='categorical_crossentropy', optimizer = Adam(),
              metrics=['accuracy'])
new_model.summary()

It works pretty well but now I need to have it input shape 224 224 3 instead of (None, 224, 224, 3) - how to make it

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Rocketq
  • 5,423
  • 23
  • 75
  • 126
  • I don't get your question. I guess you are taking about input_shape=(224, 224, 3) in your Lambda layer. Actually batch_size of None is the default value if you use 'input_shape` . If you really want to specify the batch_size, you can use batch_input_shape instead of input_shape. The only situation I know which requires specific batch_size in tensor is stateful LSTM blocks – meowongac Jun 14 '19 at 07:03

1 Answers1

2

In order to expand the dimension of your tensor, you can use

import tensorflow.keras.backend as K  
# adds a new dimension to a tensor
K.expand_dims(tensor, 0)

However, I do not see why you would need it, just like @meonwongac mentioned.

If you still want to use a Lambda layer instead of resizing / applying other operations on images with skimage/OpenCV/ other library, one way of using the Lambda layer is the following:

import tensorflow as tf
input_ = Input(shape=(None, None, 3))
next_layer = Lambda(lambda image: tf.image.resize_images(image, (128, 128))(input_)
Vlad
  • 8,225
  • 5
  • 33
  • 45
Timbus Calin
  • 13,809
  • 5
  • 41
  • 59