Search code examples
pythonmachine-learningkerastensorflow2.0keyerror

Keras KeyError: 'metrics' line ---> 13 callbacks=callbacks while executing model.fit()


I was trying out this course in Coursera when I stumbled upon this problem. Whenever I try to run the model.fit() it shows this error.

Error shown:


KeyError                                  Traceback (most recent call last)

<ipython-input-83-0ef54ef3afb9> in <module>()
     11     validation_steps = len(x_val) // batch_size,
     12     epochs=12,
---> 13     callbacks=callbacks
     14 )

3 frames

/usr/local/lib/python3.6/dist-packages/livelossplot/generic_keras.py in on_train_begin(self, logs)
     29 
     30     def on_train_begin(self, logs={}):
---> 31         self.liveplot.set_metrics([metric for metric in self.params['metrics'] if not metric.startswith('val_')])
     32 
     33         # slightly convolved due to model.complie(loss=...) stuff

KeyError: 'metrics'

Here is my actual Code:

from tensorflow.keras.layers import Dense, Input, Dropout,Flatten, Conv2D
from tensorflow.keras.layers import BatchNormalization, Activation, MaxPooling2D

from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.optimizers import Adam, SGD
from tensorflow.keras.callbacks import ModelCheckpoint

Initialising the CNN

model = Sequential()

1st Convolution

model.add(Conv2D(32,(5,5), padding='same', input_shape=(64, 128, 1)))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

2nd Convolution layer

model.add(Conv2D(64, (5,5), padding='same'))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

Flattening

model.add(Flatten())

Fully connected layer

model.add(Dense(1024))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.4))

model.add(Dense(4, activation='softmax'))

Learning Rate Scheduling and Compile the Model

initial_learning_rate=0.005
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
    initial_learning_rate = initial_learning_rate,
    decay_steps=5,
    decay_rate=0.96,
    staircase=True
)
optimizer = Adam(learning_rate=lr_schedule)

model.compile(loss='categorical_crossentropy', optimizer=optimizer , metrics=["accuracy"])
model.summary()

Training the Model

checkpoint = ModelCheckpoint('model_weight.h5', monitor='val_loss', 
                             save_weights_only=True, mode='min', verbose=0)
callbacks=[PlotLossesCallback(), checkpoint]

batch_size=32

history = model.fit(
    datagen_train.flow(x_train, y_train, batch_size=batch_size, shuffle=True),
    steps_per_epoch = len(x_train) // batch_size,
    validation_data = datagen_val.flow(x_val, y_val, batch_size=batch_size, shuffle=True),
    validation_steps = len(x_val) // batch_size,
    epochs=12,
    callbacks=callbacks
)

How can I resolve this?


Solution

  • Try changing your import statement

    from livelossplot.tf_keras import PlotLossesCallback
    

    to

    from livelossplot.inputs.tf_keras import PlotLossesCallback