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

Issue

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

Solution

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)

Answered By – AndrzejO

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published