🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEtensorflow

tensorflow Documentation

LOADING ENGINE...

metrics.Accuracy()

AI & DATA SCIENCE // metrics-accuracy

tf.keras.metrics.Accuracy() calculates how often a model's predictions exactly match the true labels, expressed as the fraction of correct predictions.

Syntax

tf.keras.metrics.Accuracy()

Deep Dive Course

Accuracy compares predictions directly against true labels and computes the simple fraction that match exactly, updated incrementally across batches via its update_state() method and read at any point with result(). It's an intuitive, easy-to-interpret metric, but unlike a loss function it's not differentiable, since it's based on discrete exact matches rather than a smooth numeric difference, which is exactly why it's tracked purely for monitoring rather than ever being used as the loss that training actually optimizes.

1Understanding metrics.Accuracy()

Accuracy compares predictions directly against true labels and computes the simple fraction that match exactly, updated incrementally across batches via its update_state() method and read at any point with result(). It's an intuitive, easy-to-interpret metric, but unlike a loss function it's not differentiable, since it's based on discrete exact matches rather than a smooth numeric difference, which is exactly why it's tracked purely for monitoring rather than ever being used as the loss that training actually optimizes.

💡

tf.keras.metrics.Accuracy() expects already-computed discrete predictions to compare, not raw probabilities — for typical classification model outputs, the string shortcut 'accuracy' passed to compile()'s metrics argument automatically handles converting probabilities to predicted classes first, which is what you almost always want instead of instantiating Accuracy() directly.

editor.html
import tensorflow as tf

acc = tf.keras.metrics.Accuracy()
acc.update_state([1, 0, 1, 1], [1, 0, 0, 1])
print(acc.result().numpy())
localhost:3000

2Practical Example

Here is a real-world application of metrics.Accuracy() showing how it is used in production TensorFlow code.

editor.html
import tensorflow as tf

acc = tf.keras.metrics.Accuracy()
acc.update_state([1, 0], [1, 0])
acc.update_state([1, 1], [0, 1])
print(acc.result().numpy())
localhost:3000

3Best Practices

Follow these guidelines when working with metrics.Accuracy():

1. Use the string shortcut 'accuracy' in compile()'s metrics argument for typical classification models, letting Keras handle converting probabilities to predicted classes automatically

2. Remember accuracy alone can be misleading on an imbalanced dataset, where predicting only the majority class can still produce a deceptively high accuracy score

3. Track precision, recall, or AUC alongside accuracy for classification tasks where class imbalance is a concern

⚠️

Tip: tf.keras.metrics.Accuracy() expects already-computed discrete predictions to compare, not raw probabilities — for typical classification model outputs, the string shortcut 'accuracy' passed to compile()'s metrics argument automatically handles converting probabilities to predicted classes first, which is what you almost always want instead of instantiating Accuracy() directly.

editor.html
import tensorflow as tf

acc = tf.keras.metrics.Accuracy()
acc.update_state([1, 0, 1, 1], [1, 0, 0, 1])
print(acc.result().numpy())
localhost:3000

Examples

Example 01Basic Usage
import tensorflow as tf

acc = tf.keras.metrics.Accuracy()
acc.update_state([1, 0, 1, 1], [1, 0, 0, 1])
print(acc.result().numpy())
Example 02Advanced Example
import tensorflow as tf

acc = tf.keras.metrics.Accuracy()
acc.update_state([1, 0], [1, 0])
acc.update_state([1, 1], [0, 1])
print(acc.result().numpy())

Best Practices

  • Use the string shortcut 'accuracy' in compile()'s metrics argument for typical classification models, letting Keras handle converting probabilities to predicted classes automatically
  • Remember accuracy alone can be misleading on an imbalanced dataset, where predicting only the majority class can still produce a deceptively high accuracy score
  • Track precision, recall, or AUC alongside accuracy for classification tasks where class imbalance is a concern

Interview Question

Why is Accuracy never used directly as a loss function during training, even though it's the metric most people actually care about for a classification task?

Hint: Think about whether accuracy changes smoothly as a model's weights change slightly, and what that means for computing a gradient.

Accuracy is computed from discrete, exact matches between predicted and true classes, which means it only changes in sudden, discontinuous jumps as a model's weights shift, a prediction either flips from wrong to right or it doesn't; there's no smooth, continuous relationship between a small nudge to the weights and a small nudge to the accuracy value. Backpropagation fundamentally requires computing a gradient, the smooth rate of change of the loss with respect to each weight, and a function that's flat almost everywhere with sudden jumps has a gradient of zero almost everywhere, providing no useful signal at all for how to adjust the weights. A loss function like categorical crossentropy, in contrast, changes smoothly and continuously as the underlying predicted probabilities shift even slightly, providing a well-defined, useful gradient everywhere, which is exactly why it's used to drive training while accuracy is reserved for human-facing monitoring instead.

Exercises

MediumPractice using metrics.Accuracy() in a real scenario.
View Solution
import tensorflow as tf

acc = tf.keras.metrics.Accuracy()
acc.update_state([1, 0, 1, 1], [1, 0, 0, 1])
print(acc.result().numpy())

Frequently Asked Questions

Why is Accuracy never used directly as a loss function during training, even though it's the metric most people actually care about for a classification task?

Accuracy is computed from discrete, exact matches between predicted and true classes, which means it only changes in sudden, discontinuous jumps as a model's weights shift, a prediction either flips from wrong to right or it doesn't; there's no smooth, continuous relationship between a small nudge to the weights and a small nudge to the accuracy value. Backpropagation fundamentally requires computing a gradient, the smooth rate of change of the loss with respect to each weight, and a function that's flat almost everywhere with sudden jumps has a gradient of zero almost everywhere, providing no useful signal at all for how to adjust the weights. A loss function like categorical crossentropy, in contrast, changes smoothly and continuously as the underlying predicted probabilities shift even slightly, providing a well-defined, useful gradient everywhere, which is exactly why it's used to drive training while accuracy is reserved for human-facing monitoring instead.

Related Functions

metrics-auclosses-categoricalcrossentropymodel-evaluate