Search code examples
tensorflowkerastensorflow2.0keras-layertensorflow-hub

TensorflowHub pretrained MobileNetV2 change input shape and transfer learning


I'm creating a NN using MobileNetV2 140 224 from Tensorflow Hub as pretrained convnet. Now I would like to change input layer size, I'd like to input 500x500 images. Is this possible? What is the best way to achieve this?

This is my code:

IMG_SHAPE = (224, 224, 3)
base_model = hub.KerasLayer('https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/feature_vector/4', input_shape=IMG_SHAPE)
base_model.trainable = False
model = Sequential([
  base_model,
  Dropout(0.25),
  Dense(3, activation='softmax')
])
adam = Adam(learning_rate=0.0001)
model.compile(optimizer=adam,
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

Can I do it only by changing IMG_SHAPE = (500, 500, 3) or I have to add input layers or something else?


Solution

  • Changing IMG_SHAPE as you suggest results in an informative error message (abridged):

      ValueError: Could not find matching function to call loaded from the SavedModel. Got:
          Positional arguments (4 total):
            * Tensor("inputs:0", shape=(None, 500, 500, 3), dtype=float32)
            ...
    
        Expected these arguments to match one of the following 4 option(s):
    
        Option 1:
          Positional arguments (4 total):
            * TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name='inputs')
            ...
    

    Turns out https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/feature_vector/4 has its input size hard-wired to 224x224. This is due to a limitation of the underlying TF-Slim code, which requires a tf.Placeholder of known height and width for building the SavedModel.