Skip to content Skip to sidebar Skip to footer

Cnn: Error When Checking Input: Expected Dense To Have 2 Dimensions, But Got Array With Shape (391, 605, 700, 3)

I'm getting a list of images to train my CNN. model = Sequential() model.add(Dense(32, activation='tanh', input_dim=100)) model.add(Dense(1, activation='sigmoid')) model.compile(o

Solution 1:

You are feeding images to the Dense Layer. Either flatten the images using .flatten() or use a model with CNN Layers. The shape (391,605,700,3) means you have 391 images of size 605x700 having 3 dimensions(rgb).

    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(605, 700, 3)))
    model.add(MaxPooling2D((2, 2)))
    model.add(Flatten())
    model.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))
    model.add(Dense(1, activation='sigmoid'))
    model.compile(optimizer='rmsprop',
          loss='binary_crossentropy',
          metrics=['accuracy'])

This link has good explanations for basic CNN.

Solution 2:

This is no CNN. A Convolutional Neural Network is defined by having Conv Layer. Those Layers work with imput shapes in 4D (Batchsize, ImageDimX, ImageDimY, ColorChannels). The Dense Layers(aka. Fully connected) you are using 2D input (Batchsize, DataAsAVector)

Solution 3:

You need to first flatten the image if you want to pass the image directly to dense layers as Dense layer takes input in 2 dimensions only and since you are passing whole image there is 4 dimensions in it i.e. Number of images X Height X Width X Number of channels (391, 605, 700, 3). You are not actually doing any convolutions on the image. To do convolutions you need to add CNN layers after initialising the model as sequential. To add dense layer :

model = Sequential()
model.add(Flatten())
model.add(Dense(32, activation='tanh', input_dim=100))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])

To add CNN layer and then flatten it :

 model = Sequential()
    model.add(Conv2D(input_shape=(605,700,3), filters=64, kernel_size=(3,3), 
    padding="same",activation="relu"))
    model.add(Flatten())
    model.add(Dense(32, activation='tanh', input_dim=100))
    model.add(Dense(1, activation='sigmoid'))
    model.compile(optimizer='rmsprop',
                  loss='binary_crossentropy',
                  metrics=['accuracy'])

Post a Comment for "Cnn: Error When Checking Input: Expected Dense To Have 2 Dimensions, But Got Array With Shape (391, 605, 700, 3)"