Kartik Singh
Kartik Singh

Reputation: 43

ValueError: Error when checking target: expected dense_3 to have shape (1,) but got array with shape (5,)

How to Fix this error? I tried visiting all the forums searching for answers to rectify this issue. There are 5 classes in train_set and test_Set.

from keras.models import Sequential

from keras.preprocessing.image import ImageDataGenerator

from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense
classifier=Sequential()
#1st Convolution Layer
classifier.add(Convolution2D(32, 3, 3, input_shape=(64,64,3),activation="relu"))
#Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Adding a second convolutional layer
classifier.add(Convolution2D(32, 3, 3, activation = 'relu'))

classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Flattening
classifier.add(Flatten())

classifier.add(Dense(output_dim = 128, activation = 'relu'))

classifier.add(Dense(output_dim = 64, activation = 'relu'))

classifier.add(Dense(output_dim = 1, activation = 'softmax'))

classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
print(classifier.summary())

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set= train_datagen.flow_from_directory('flowers/train_set',
                                                target_size=(64,64),
                                                batch_size=32,
                                                class_mode='categorical')


test_set= test_datagen.flow_from_directory('flowers/test_set',
                                                target_size=(64,64),
                                                batch_size=32,
                                                class_mode='categorical')

classifier.fit_generator(training_set,
                         samples_per_epoch = 3000,
                         nb_epoch = 25,
                         validation_data = test_set,
                         nb_val_samples=1000)

Here i have attached the image of the error for review. error

Upvotes: 1

Views: 2878

Answers (1)

rawwar
rawwar

Reputation: 5012

in your code , the following line is wrong

classifier.add(Dense(output_dim = 1, activation = 'softmax'))

change it to

classifier.add(Dense(output_dim = 5, activation = 'softmax'))

why? its because, your final layer is of 5 dimension. How did i know that output dimension is 5? because, you used categorical_crossentropy and also, it looks like the dataset's labels have 5 categories(based on the first line of the output in the image)

Upvotes: 5

Related Questions