Custom metrics help you measure exactly what matters for your model. They let you track special goals beyond built-in scores.
Custom metrics in TensorFlow
def custom_metric(y_true, y_pred): # calculate metric value return metric_value
The function takes y_true (real labels) and y_pred (model predictions).
Return a single tensor value representing the metric.
def mean_pred(y_true, y_pred): return tf.reduce_mean(y_pred)
def binary_accuracy(y_true, y_pred): y_pred_labels = tf.round(y_pred) return tf.reduce_mean(tf.cast(tf.equal(y_true, y_pred_labels), tf.float32))
This example shows how to create a custom metric for mean absolute error (MAE). The model is trained on simple data, and the custom MAE is printed after training.
import tensorflow as tf # Define a custom metric: mean absolute error manually @tf.function def custom_mae(y_true, y_pred): return tf.reduce_mean(tf.abs(y_true - y_pred)) # Create a simple model model = tf.keras.Sequential([ tf.keras.layers.Dense(1, input_shape=(1,)) ]) # Compile model with custom metric model.compile(optimizer='sgd', loss='mse', metrics=[custom_mae]) # Sample data x = tf.constant([[1.0], [2.0], [3.0], [4.0]]) y = tf.constant([[2.0], [4.0], [6.0], [8.0]]) # Train model history = model.fit(x, y, epochs=3, verbose=0) # Evaluate model loss, mae = model.evaluate(x, y, verbose=0) print(f"Loss: {loss:.4f}") print(f"Custom MAE: {mae:.4f}")
Custom metrics must use TensorFlow operations to work well with training.
Use @tf.function decorator for better performance but it's optional.
Custom metrics appear in training logs just like built-in metrics.
Custom metrics let you track special scores during model training.
They take true labels and predictions, then return a single number.
Use TensorFlow ops inside custom metric functions for compatibility.
Practice
Solution
Step 1: Understand what metrics do
Metrics measure how well the model performs by comparing true labels and predictions.Step 2: Identify the role of custom metrics
Custom metrics let you define your own way to measure performance during training.Final Answer:
To track a special score based on true labels and predictions during training -> Option AQuick Check:
Custom metric = special score tracking [OK]
- Confusing metrics with model architecture changes
- Thinking metrics speed up training
- Believing metrics save model weights
Solution
Step 1: Check TensorFlow compatibility
Custom metrics must use TensorFlow operations like tf.reduce_mean for compatibility.Step 2: Identify correct function
def my_metric(y_true, y_pred): return tf.reduce_mean(tf.abs(y_true - y_pred)) uses tf.reduce_mean and tf.abs correctly; def my_metric(y_true, y_pred): return np.mean(np.abs(y_true - y_pred)) uses numpy which is incompatible.Final Answer:
def my_metric(y_true, y_pred): return tf.reduce_mean(tf.abs(y_true - y_pred)) -> Option DQuick Check:
Use TensorFlow ops in custom metrics [OK]
- Using numpy functions inside metric causing errors
- Returning tensors without reduction to scalar
- Printing values instead of returning metric
def custom_metric(y_true, y_pred):
diff = tf.abs(y_true - y_pred)
return tf.reduce_mean(diff)Solution
Step 1: Calculate absolute differences
Differences: |1-1|=0, |2-2|=0, |3-4|=1Step 2: Compute mean of differences
Mean = (0 + 0 + 1) / 3 = 0.3333Final Answer:
0.3333 -> Option CQuick Check:
Mean absolute difference = 0.3333 [OK]
- Summing differences without averaging
- Using squared difference instead of absolute
- Mixing up y_true and y_pred order
def faulty_metric(y_true, y_pred):
return tf.reduce_sum(y_true - y_pred)Solution
Step 1: Understand metric output
Metrics should return a scalar representing average error, not total sum.Step 2: Fix by averaging
Replacing tf.reduce_sum with tf.reduce_mean returns average difference, a better metric.Final Answer:
Use tf.reduce_mean instead of tf.reduce_sum to get average error -> Option BQuick Check:
Average error metric needs reduce_mean [OK]
- Using reduce_sum causing large values
- Mixing TensorFlow and numpy operations
- Not returning a scalar metric
Solution
Step 1: Identify correct comparison and casting
We must compare differences with 0.5 and cast boolean to float for summation.Step 2: Check TensorFlow functions used
def count_large_diff(y_true, y_pred): diff = tf.abs(y_true - y_pred) return tf.reduce_sum(tf.cast(diff > 0.5, tf.float32)) uses tf.abs, comparison, tf.cast to float32, and tf.reduce_sum correctly.Final Answer:
def count_large_diff(y_true, y_pred): diff = tf.abs(y_true - y_pred) return tf.reduce_sum(tf.cast(diff > 0.5, tf.float32)) -> Option AQuick Check:
Cast booleans to float before summing [OK]
- Not casting boolean mask before summing
- Using reduce_mean instead of reduce_sum
- Using wrong data type cast like tf.int32
Ready to prove it?
Pass the test and this pattern moves unknown
