Search code examples
kerasvalueerror

Keras Input 0 of layer "conv2d_1" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 1)


I am trying to create a branched Keras model to output multiple classes (age and gender)

My input X_train and X_test have the shape:

(4000,128,128,3) and (1000,128,128,3)

this is my code to create the layers:

from keras.models import Sequential,load_model,Model
from keras.layers import Conv2D,MaxPool2D,MaxPooling2D,Dense,Dropout,BatchNormalization,Flatten,Input
from keras.layers import *
#model creation 
# input_shape = (128, 128, 3)
# inputs = Input((input_shape))

input = Input(shape=(128,128,3))
conv1 = Conv2D(32,(3,3),activation="relu")(input)
pool1 = MaxPool2D((2,2))(conv1)
conv2 = Conv2D(64,(3,3),activation="relu")(pool1)
pool2 = MaxPool2D((2,2))(conv2)
conv3 = Conv2D(128,(3,3),activation="relu")(pool2)
pool3 = MaxPool2D((2,2))(conv3)
flt = Flatten()(pool3)
#age
age_l = Dense(128,activation="relu")(flt)
age_l = Dense(64,activation="relu")(age_l)
age_l = Dense(32,activation="relu")(age_l)
age_l = Dense(1,activation="relu")(age_l)

#gender
gender_l = Dense(128,activation="relu")(flt)
gender_l = Dense(80,activation="relu")(gender_l)
gender_l = Dense(64,activation="relu")(gender_l)
gender_l = Dense(32,activation="relu")(gender_l)
gender_l = Dropout(0.5)(gender_l)
gender_l = Dense(2,activation="softmax")(gender_l)

modelA = Model(inputs=input,outputs=[age_l,gender_l])


modelA.compile(loss=['mse', 'sparse_categorical_crossentropy'], optimizer='adam', metrics=['accuracy', 'mae'])

modelA.summary()

however, i keep getting this error:

ValueError                                Traceback (most recent call last)
Cell In [27], line 1
----> 1 save = modelA.fit(X_train_arr, [y_train, y_train2],
      2                  validation_data = (X_test, [y_test, y_test2]),
      3                  epochs = 30)

ValueError: Exception encountered when calling layer "model" "                 f"(type Functional).
    
    Input 0 of layer "conv2d_1" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 1)
    
    Call arguments received by layer "model" "                 f"(type Functional):
      • inputs=tf.Tensor(shape=(None, 1), dtype=string)
      • training=False
      • mask=None

I cannot see what the issue is as the input dimensions seem to be correct?

Apologies I have tried studying similar posts and the required text but still do not understand what the issue is!


Solution

  • I have checked your code and run it with some dummy data, here at my end it is running fine, I think the problem is with your dataset, kindly check your dataset before passing it to the model.