Keras
code debugging
accuracy metric
machine learning
neural networks

Why my keras code doesn't show the accuracy value?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

If your Keras model training output shows loss but not accuracy, the most common cause is not including metrics=['accuracy'] in the model.compile() call. Keras only tracks and displays metrics that are explicitly specified at compilation time. Other causes include using the wrong metric name for your task, using a custom training loop that does not log metrics, or running an older Keras version with different metric naming. This article covers all the reasons and fixes.

Cause 1: Missing metrics in model.compile()

python
1import tensorflow as tf
2
3model = tf.keras.Sequential([
4    tf.keras.layers.Dense(64, activation='relu', input_shape=(10,)),
5    tf.keras.layers.Dense(1, activation='sigmoid')
6])
7
8# WRONG: no metrics specified — only loss is shown
9model.compile(optimizer='adam', loss='binary_crossentropy')
10model.fit(X_train, y_train, epochs=5)
11# Output: Epoch 1/5 - loss: 0.6931
12
13# FIX: add metrics
14model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
15model.fit(X_train, y_train, epochs=5)
16# Output: Epoch 1/5 - loss: 0.6931 - accuracy: 0.5120

metrics=['accuracy'] tells Keras to compute and display accuracy after each epoch.

Cause 2: Wrong Metric Name

python
1# For binary classification with sigmoid output
2model.compile(
3    optimizer='adam',
4    loss='binary_crossentropy',
5    metrics=['accuracy']  # Works — Keras maps to BinaryAccuracy
6)
7
8# For multi-class with softmax output and one-hot labels
9model.compile(
10    optimizer='adam',
11    loss='categorical_crossentropy',
12    metrics=['accuracy']  # Works — maps to CategoricalAccuracy
13)
14
15# For multi-class with integer labels (not one-hot)
16model.compile(
17    optimizer='adam',
18    loss='sparse_categorical_crossentropy',
19    metrics=['accuracy']  # Works — maps to SparseCategoricalAccuracy
20)
21
22# Explicit metric classes (recommended for clarity)
23model.compile(
24    optimizer='adam',
25    loss='sparse_categorical_crossentropy',
26    metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]
27)

Keras automatically selects the right accuracy variant when you pass 'accuracy' as a string, but using the explicit class avoids ambiguity.

Cause 3: Regression Task (Accuracy Does Not Apply)

python
1# Regression — accuracy is meaningless
2model.compile(optimizer='adam', loss='mse', metrics=['accuracy'])
3# Accuracy shows ~0.0 — continuous values are rarely exactly equal
4
5# FIX: use regression metrics
6model.compile(
7    optimizer='adam',
8    loss='mse',
9    metrics=['mae', tf.keras.metrics.RootMeanSquaredError()]
10)
11model.fit(X_train, y_train, epochs=5)
12# Output: Epoch 1/5 - loss: 0.2345 - mae: 0.3456 - root_mean_squared_error: 0.4842

Accuracy compares predictions to labels for exact equality. For regression, use MAE, MSE, or RMSE instead.

Cause 4: Custom Training Loop Without Metric Tracking

python
1# Custom loop that doesn't track metrics
2model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
3
4for epoch in range(5):
5    for batch_x, batch_y in train_dataset:
6        with tf.GradientTape() as tape:
7            predictions = model(batch_x, training=True)
8            loss = loss_fn(batch_y, predictions)
9        grads = tape.gradient(loss, model.trainable_variables)
10        optimizer.apply_gradients(zip(grads, model.trainable_variables))
11    # No accuracy is printed — custom loops don't auto-track metrics
12
13# FIX: manually track metrics
14accuracy_metric = tf.keras.metrics.BinaryAccuracy()
15
16for epoch in range(5):
17    accuracy_metric.reset_state()
18    for batch_x, batch_y in train_dataset:
19        with tf.GradientTape() as tape:
20            predictions = model(batch_x, training=True)
21            loss = loss_fn(batch_y, predictions)
22        grads = tape.gradient(loss, model.trainable_variables)
23        optimizer.apply_gradients(zip(grads, model.trainable_variables))
24        accuracy_metric.update_state(batch_y, predictions)
25
26    print(f"Epoch {epoch+1} - Accuracy: {accuracy_metric.result().numpy():.4f}")

Cause 5: Verbose Setting

python
1# verbose=0 suppresses all output
2model.fit(X_train, y_train, epochs=5, verbose=0)
3# No output at all
4
5# verbose=1 shows progress bar with metrics (default)
6model.fit(X_train, y_train, epochs=5, verbose=1)
7# Epoch 1/5 ████████████████████ - loss: 0.69 - accuracy: 0.52
8
9# verbose=2 shows one line per epoch
10model.fit(X_train, y_train, epochs=5, verbose=2)
11# Epoch 1/5 - loss: 0.6931 - accuracy: 0.5120

Viewing Accuracy History

python
1history = model.fit(X_train, y_train, epochs=10,
2                    validation_data=(X_val, y_val),
3                    metrics=['accuracy'])
4
5# Access accuracy values
6print(history.history['accuracy'])       # Training accuracy per epoch
7print(history.history['val_accuracy'])   # Validation accuracy per epoch
8
9# Plot
10import matplotlib.pyplot as plt
11plt.plot(history.history['accuracy'], label='Train')
12plt.plot(history.history['val_accuracy'], label='Validation')
13plt.xlabel('Epoch')
14plt.ylabel('Accuracy')
15plt.legend()
16plt.show()

Common Pitfalls

  • Forgetting metrics=['accuracy'] in compile(): This is the most common cause. Without explicitly requesting accuracy, Keras only computes and displays the loss function. Always pass the desired metrics list.
  • Using 'accuracy' for regression tasks: Accuracy measures exact match between predicted and true values. For continuous regression outputs, accuracy is always near zero. Use 'mae' or 'mse' for regression tasks.
  • Recompiling the model without metrics after loading: Loading a saved model with tf.keras.models.load_model() restores metrics, but if you call model.compile() again without metrics, the previously saved metrics are lost.
  • Confusing 'acc' with 'accuracy': Older Keras versions (pre-2.3) used 'acc' as the metric key in history.history. Modern Keras uses 'accuracy'. Check your version if history.history['accuracy'] raises KeyError.
  • Not including validation data: val_accuracy only appears if you pass validation_data or validation_split to model.fit(). Without it, only training accuracy is shown.

Summary

  • Add metrics=['accuracy'] to model.compile() — this is the fix for most cases
  • Keras auto-selects the right accuracy variant (binary, categorical, sparse) based on the loss function
  • Do not use accuracy for regression — use MAE, MSE, or RMSE instead
  • Custom training loops must manually track metrics using tf.keras.metrics classes
  • Access accuracy history via history.history['accuracy'] and history.history['val_accuracy']
  • Set verbose=1 or verbose=2 in model.fit() to see metric output during training

Course illustration
Course illustration

All Rights Reserved.