hk_03
hk_03

Reputation: 311

ValueError: Error when checking target: expected conv2d_21 to have 4 dimensions, but got array with shape (26, 1)

I have images with shape (3600, 3600, 3). I'd like to use an autoencoder on them. My code is:

from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator


input_img = Input(shape=(3600, 3600, 3))  

x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)



x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')




batch_size=2


datagen = ImageDataGenerator(rescale=1. / 255)

# dimensions of our images.
img_width, img_height = 3600, 3600

train_data_dir = 'train'
validation_data_dir = validation




generator_train = datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        )



generator_valid = datagen.flow_from_directory(
        validation_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode=None,
        shuffle=False)



autoencoder.fit_generator(generator=generator_train,
            validation_data = generator_valid,
            )

When I run the code I get this error message:

ValueError: Error when checking target: expected conv2d_21 to have 4 dimensions, but got array with shape (26, 1)

I know the problem is somewhere in the shape of the layers, but I couldn't find it. Can someone please help me and explain the solution?

Upvotes: 0

Views: 1166

Answers (1)

today
today

Reputation: 33470

There are the following issues in your code:

  1. Pass class_mode='input' to flow_from_directory method to give input images as the labels as well (since you are creating an autoencoder).

  2. Pass padding='same' to the third Conv2D layer in the decoder:

    x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
    
  3. Use three filers in the last layer since your images are RGB:

    decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
    

Upvotes: 1

Related Questions