tensorflowkerasmobilenet

TensorFlow Keras Use MobileNetV2 Model with Inputs less than 32x32


I want to use the MobileNetV2 model without weights with a size less than 32x32. If I try

model = tf.keras.applications.MobileNetV2(input_shape=(10,10,3),include_top=False,weights=None)

gives the error

ValueError: Input size must be at least 32x32; got `input_shape=(10, 10, 3)

I understand I can't use all the layers because the resolution gets reduced too much in the model, so let's assume I want to use the first 30 layers of the model.

How can I create a model which uses MobileNetV2's first 30 layers and has an input shape of 10x10x3? I don't want to manually create the MobileNetV2 model, but I want to use the tf.keras.applications.MobileNetV2 method to load it.


Solution

  • Create a new model from MobileNet with the first 30 layers as outputs (i.e. a multiple output model). Here is how:

    base = tf.keras.applications.MobileNetV2(include_top=False,weights=None)
    features_list = [layer.output for layer in base.layers[:30]]
    model = keras.Model(inputs=base.input, outputs=features_list)
    
    len(model.layers) # 30
    

    Test

    img = np.random.random((1, 10, 10, 3)).astype("float32")
    model(img)
    
    [<tf.Tensor: shape=(1, 10, 10, 3), dtype=float32, numpy=
     array([[[[0.7529889 , 0.18826886, 0.9792667 ],
              [0.52218866, 0.36510527, 0.4743469 ],
    ...
    ...
    

    Based on your comment. We can do that. Here is how to do it if you want the model to have a single output which is the output of the 30th layer of the MobileNetV2 model.

    from keras import layers
    input_s = layers.Input((10,10,3))
    
    import tensorflow as tf 
    base = tf.keras.applications.MobileNetV2(include_top=False,
                                             weights=None,  
                                             input_tensor = input_s)
    
    from tensorflow import keras
    model = keras.Model(inputs=base.input, outputs=base.layers[30].output)
    model.summary()
    ...
    ...