Introduction
Categorical cross-entropy loss helps measure how well a model predicts categories by comparing predicted probabilities to the true category labels.
Jump into concepts and practice - no test required
tf.keras.losses.CategoricalCrossentropy(from_logits=False, label_smoothing=0, axis=-1)
loss = tf.keras.losses.CategoricalCrossentropy() loss_value = loss(y_true, y_pred)
loss = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
loss_value = loss(y_true, logits)loss = tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1)
loss_value = loss(y_true, y_pred)import tensorflow as tf import numpy as np # True labels (one-hot encoded for 3 classes) y_true = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]], dtype=np.float32) # Predicted probabilities from model # Each row sums to 1 and shows predicted chance for each class y_pred = np.array([[0.05, 0.9, 0.05], [0.8, 0.1, 0.1], [0.1, 0.2, 0.7]], dtype=np.float32) # Create loss function loss_fn = tf.keras.losses.CategoricalCrossentropy() # Calculate loss loss_value = loss_fn(y_true, y_pred).numpy() print(f"Categorical cross-entropy loss: {loss_value:.4f}")
import tensorflow as tf loss_fn = tf.keras.losses.CategoricalCrossentropy(from_logits=False) y_true = [[0, 1, 0]] y_pred = [[0.1, 0.8, 0.1]] loss = loss_fn(y_true, y_pred).numpy() print(round(loss, 3))
import tensorflow as tf loss_fn = tf.keras.losses.CategoricalCrossentropy(from_logits=True) y_true = [[0, 1, 0]] y_pred = [[0.1, 0.8, 0.1]] loss = loss_fn(y_true, y_pred).numpy() print(loss)