Metrics argument in model.compile

Hello. I thought it should not be different to use one of these for metric argument.
metrics=[tf.keras.metrics.Accuracy()]
Or
metrics=[‘accuracy’]

but I wonder why when I use the first form ([tf.keras.metrics.Accuracy()]) I get to an error about the dimensions!

(model.compile(optimizer = tf.keras.optimizers.Adam(),
loss = ‘sparse_categorical_crossentropy’,
metrics=[tf.keras.metrics.Accuracy()])
)

metrics=[tf.keras.metrics.Accuracy()]
Or
metrics=[‘accuracy’]

when you pass metric to accuracy, we are converting metric to one of the categories of tf.keras.metrics.BinaryAccuracy, tf.keras.metrics.CategoricalAccuracy, tf.keras.metrics.SparseCategoricalAccuracy based on the used loss function and your model output.

So when you use metric = accuracy, it will be converted to desired or related accuracy automatically, in this case SparseCategoricalAccuracy.

When you are using metrics=tf.keras.metrics.Accuracy, it creates two local variables, total and count that are used to compute the frequency with which y_pred matches y_true . This frequency is ultimately returned as binary accuracy, and as you have used loss in your model as sparse_categorical_crossentropy, it comes as an error.

Hope you understood.

Keep Learning!!!

Regards
DP

1 Like

Many Thanks Deepti_Prasad

What a convincing answer!!

Regards