0
$\begingroup$

I am trying to make a gender classifier. I am using MobileNet from Tensorflow with input shape as (224,224,3). After training the model, I tried to check if the model was working by passing an image to the model to predict, but it throws the error in the title. I tried debugging it and google the error and tried everything I could, but the error still persists. Please help me to understand why the error.

model = tf.keras.applications.mobilenet.MobileNet(input_shape = (224,224,3), include_top = False, pooling = 'avg')
#model.summary()

x = Dropout(rate=0.4)(model.output)
x = Dense(3)(x)
x = Softmax()(x)
model= Model(model.inputs, x)

for layer in model.layers[:-3]:
    layer.trainable = False

model.compile(
    optimizer=Adam(lr=0.001),
    loss='categorical_crossentropy'
)

datagen = tf.keras.preprocessing.image.ImageDataGenerator(preprocessing_function = tf.keras.applications.mobilenet.preprocess_input, 
          shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True, validation_split = 0.1)
training = datagen.flow_from_directory( 
    '...\Pictures\Model', 
    target_size=(224, 224)
)

validation = datagen.flow_from_directory( 
    '...\Pictures\Model',
    target_size=(224, 224)
)

batch_size = 32

history = model.fit_generator(generator = training, steps_per_epoch = training.samples//batch_size, epochs = 10, 
                              validation_data = validation, validation_steps = validation.samples//batch_size, verbose = 2)

man = np.array(tf.keras.preprocessing.image.load_img('...\\Pictures\\Detected Faces\\0156224224_face.jpg', target_size = (224,224)))

model.predict(man) #Here the model throws an error
$\endgroup$
1
$\begingroup$

You need to make sure to add an extra dimension for the batch size, if you are passing in a single image the batch size would be 1. You can use np.expand_dims to add the extra dimension.

$\endgroup$
2
0
$\begingroup$

The error is because the model is expecting input of shape of 4 dimensional data [None, 224, 224, 3] where None is the Batch size which can be anything. but you are giving a single image of shape which is three dimensional.

try model.predict([man]) here we are just changing dimension to 4D with a batch size of 1.

$\endgroup$
2
  • $\begingroup$ I tried that but its showing: ValueError: Input 0 of layer conv1_pad is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [32, 224, 3] Idk why the shape has 32 now. I'm passing (224,224,3) $\endgroup$ Jan 25 at 5:12
  • $\begingroup$ datascience.stackexchange.com/questions/94071/… Hi, could you take a look here? $\endgroup$
    – x89
    May 6 at 22:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.