C1W4: Handling Complex Images - Happy or Sad Dataset#

  • 80 150x150 rgb images of emoji-like faces, 40 happy and 40 sad

import tensorflow as tf
from tensorflow.keras import layers, losses
base_dir = '../../../data/happy_sad/'
train_dataset = tf.keras.utils.image_dataset_from_directory(
    base_dir,
    label_mode='binary',
    batch_size=10,
    image_size=(150, 150)
).cache().prefetch(tf.data.AUTOTUNE)
Found 80 files belonging to 2 classes.
class myCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs={}):
        if logs.get('accuracy') is not None and logs.get('accuracy') > 0.999:
            print('\nReached 99.9% accuracy so cancelling training!')
            self.model.stop_training = True
def train_happy_sad_model(train_dataset):

    callbacks = myCallback()

    model = tf.keras.Sequential([
        layers.Conv2D(16, 3, activation='relu', input_shape=(150, 150, 3)),
        layers.MaxPooling2D(),
        layers.Conv2D(32, 3, activation='relu'),
        layers.MaxPooling2D(),
        layers.Conv2D(64, 3, activation='relu'),
        layers.MaxPooling2D(),

        layers.Flatten(),
        layers.Dense(512, activation='relu'),
        layers.Dense(1)])

    model.compile(optimizer='rmsprop',
                  loss=losses.BinaryCrossentropy(from_logits=True),
                  metrics=['accuracy'])
    
    history = model.fit(train_dataset, epochs=15, callbacks=[callbacks])

    return history
history = train_happy_sad_model(train_dataset)
Epoch 1/15
8/8 [==============================] - 3s 23ms/step - loss: 479.7974 - accuracy: 0.5000
Epoch 2/15
8/8 [==============================] - 0s 22ms/step - loss: 9.9217 - accuracy: 0.6625
Epoch 3/15
8/8 [==============================] - 0s 22ms/step - loss: 0.1157 - accuracy: 0.9875
Epoch 4/15
7/8 [=========================>....] - ETA: 0s - loss: 8.6139e-07 - accuracy: 1.0000
Reached 99.9% accuracy so cancelling training!
8/8 [==============================] - 0s 21ms/step - loss: 7.5373e-07 - accuracy: 1.0000
print(f'The model reached the desired accuracy after {len(history.epoch)} epochs')
The model reached the desired accuracy after 4 epochs
history.model.metrics_names
['loss', 'accuracy']