j.doe
j.doe

Reputation: 11

Keras ValueError when checking target

I'm trying to build a model in keras. I followed a tutorial almost to the letter, but I'm getting an error that says:

ValueError: Error when checking target: expected activation_5 to have shape (None, 1) but got array with shape (16, 13)

The code I have is the following:

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])


batch_size = 16
epochs = 50
number_training_data = 999
number_validation_data = 100

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

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
        'data/train',  # this is the target directory
        target_size=(200, 200),
        batch_size=batch_size,
        class_mode='categorical')

validation_generator = test_datagen.flow_from_directory(
        'data/validation',
        target_size=(200, 200),
        batch_size=batch_size,
        class_mode='categorical')

model.fit_generator(
    train_generator,
    steps_per_epoch=number_training_data // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=number_validation_data // batch_size)

The dataset I have has 13 classes, so the shape of the array in the error message corresponds to the batch size and the number of classes. Any idea why I'm getting this error?

Upvotes: 1

Views: 130

Answers (1)

Dr. Snoopy
Dr. Snoopy

Reputation: 56347

Your model is configured to perform binary classification, not multi-class classification with 13 classes. To do that you should change:

  • The number of units in the last dense to 13, the number of classes.
  • The activation at the output to softmax.
  • The loss to categorical cross-entropy (categorical_crossentropy).

Upvotes: 2

Related Questions