Home > Enterprise >  ValueError: Input 0 of layer conv2d is incompatible with the layer: expected ndim=4, found ndim=3. F
ValueError: Input 0 of layer conv2d is incompatible with the layer: expected ndim=4, found ndim=3. F

Time:10-07

Hi I'm trying to build a simple CNN Model that is used for classification.I'm getting the below error.Thanks for the help in advance

    
    path=os.listdir(imgs_path)
    data = []
    labels = []
    flag=0
    classes = len(list_dir)
    for i in path:
        img_path = imgs_path  i   os.sep
        for img in os.listdir(img_path):
            im = Image.open(img_path   os.sep   img)
            im = im.resize((30,30))
            im = np.array(im)
            data.append(im)
            labels.append(flag)
        flag=flag 1
    x_train = np.array(data)
    y_train = np.array(labels)
    model = Sequential()
    model.add(Conv2D(filters=32, kernel_size=(5,5), activation="relu",input_shape=x_train.shape[1:]))
    model.add(Conv2D(filters=32, kernel_size=(5,5), activation="relu"))
    model.add(MaxPool2D(pool_size=(2,2)))
    model.add(Dropout(rate=0.25))
    model.add(Conv2D(filters=64, kernel_size=(3,3), activation="relu"))
    model.add(Conv2D(filters=64, kernel_size=(3,3), activation="relu"))
    model.add(MaxPool2D(pool_size=(2,2)))
    model.add(Dropout(rate=0.5))
    model.add(Flatten())
    model.add(Dense(256, activation="relu"))
    model.add(Dropout(rate=0.25))
    model.add(Dense(classes, activation="softmax"))

    model.compile(loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"])

ValueError: Input 0 of layer conv2d is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 30, 30]

However it works for some images but not all ,Not sure why this happens

CodePudding user response:

Some of your images are b&w, they have only 2 dimensions. Use numpy.atleast_3d. This will add a dimension if there are only 2, and not change arrays with already 3 dims.

...
im = im.resize((30,30))
im = np.atleast_3d(im)
data.append(im)
...

So if you have a color image, for example (30, 30, 3), it will not be changed. But if you have a b/w image with shape (30, 30), it will be reshaped to (30, 30, 1)

CodePudding user response:

Conv2d layer expects images in batches, so try adding a batch dimension to the input.

You might be giving the input images in the shape of the images only, like for example (224,224,3) as in 224X224 image_size with 3 color channels.

Try doing:

x_train = np.expand_dims(x_train,axis=0)

this will expand the image dimensions from (224,224,3) to (1,224,224,3), adding an extra batch_size dimension as in the 4 dimensions the conv2d layer expects.

  • Related