shantanuo
shantanuo

Reputation: 32306

Binary and multi-class classification code change

I am using almost similar code that I found here...

https://towardsdatascience.com/classify-butterfly-images-with-deep-learning-in-keras-b3101fe0f98

The example is related to binary classification. The data that I am testing with is calling for multi-class classification. I guess I need to change activation and loss function. Can I use the same code found here if I have more than 2 types?

https://github.com/bertcarremans/Vlindervinder/blob/master/model/CNN.ipynb


update: I have one more question. Is augmentation necessary if I have enough data?

Upvotes: 1

Views: 1212

Answers (2)

Vlad
Vlad

Reputation: 8585

Just change binary_crossentropy to categorical_crossentropy:

cnn.compile(loss='categorical_crossentropy',
            optimizer='rmsprop',
            metrics=['accuracy'])

If your labels are not one-hot encoded modify these lines:

train_generator = train_datagen.flow_from_directory(
    'data/train',
    target_size=(IMG_SIZE,IMG_SIZE),
    batch_size = BATCH_SIZE,
    class_mode='categorical')

validation_generator = validation_datagen.flow_from_directory(
    'data/validation',
    target_size=(IMG_SIZE,IMG_SIZE),
    batch_size = BATCH_SIZE,
    class_mode='categorical')

Upvotes: 1

nuric
nuric

Reputation: 11225

No, that is multi-label classification. You said multi-class. Here is a summary for you:

  • Binary: You have single output of 0 or 1. You use something like Dense(1, activation='sigmoid') in the final layer and binary_cross_entropy as loss function.
  • Multi-label: You have multiple outputs of 0s or 1s; Dense(num_labels, activation='sigmoid') and again binary_cross_entropy. In this case, an example can belong to multiple labels at the same time.
  • Multi-class: Example belongs to 1 out of N classes, they are mutually exclusive. You use Dense(num_classes, activation='softmax') with softmax_crossentropy.

Upvotes: 2

Related Questions