Consider the following TensorFlow custom metric function that calculates accuracy by comparing rounded predictions to true labels. What will be the printed output after running the code?
import tensorflow as tf import numpy as np class CustomAccuracy(tf.keras.metrics.Metric): def __init__(self, name='custom_accuracy', **kwargs): super().__init__(name=name, **kwargs) self.total = self.add_weight(name='total', initializer='zeros') self.count = self.add_weight(name='count', initializer='zeros') def update_state(self, y_true, y_pred, sample_weight=None): y_pred_rounded = tf.round(y_pred) values = tf.cast(tf.equal(y_true, y_pred_rounded), tf.float32) self.total.assign_add(tf.reduce_sum(values)) self.count.assign_add(tf.cast(tf.size(y_true), tf.float32)) def result(self): return self.total / self.count def reset_states(self): self.total.assign(0) self.count.assign(0) metric = CustomAccuracy() y_true = tf.constant([0, 1, 1, 0], dtype=tf.float32) y_pred = tf.constant([0.1, 0.8, 0.4, 0.3], dtype=tf.float32) metric.update_state(y_true, y_pred) print(f"Custom accuracy: {metric.result().numpy():.2f}")
Think about how rounding predictions affects the comparison to true labels.
The predictions are rounded: [0.1 -> 0, 0.8 -> 1, 0.4 -> 0, 0.3 -> 0]. Comparing to true labels [0,1,1,0], matches occur at positions 0,1, and 3, so 3 correct out of 4 total, resulting in 0.75 accuracy.
You want to create a custom metric in TensorFlow to measure the mean absolute error (MAE) during training of a regression model. Which of the following custom metric implementations correctly computes MAE?
MAE is the average of absolute differences between true and predicted values.
Option B correctly sums absolute errors and divides by count to get mean absolute error. Option B sums means repeatedly, inflating error. Option B computes RMSE, not MAE. Option B sums raw errors, which can cancel out.
You implemented a custom metric in TensorFlow that accumulates values over batches during training. If you increase the batch size significantly, what is the most likely effect on the metric's reported value after one epoch?
Think about how floating point addition and number of updates affect accumulated sums.
Changing batch size changes how many times update_state is called. Fewer calls with larger batches can cause slight differences due to floating point precision, but the metric should still be correct overall. Overflow is unlikely with typical batch sizes.
Examine the following custom metric code. What error will occur when this metric is used during model training?
import tensorflow as tf class FaultyMetric(tf.keras.metrics.Metric): def __init__(self): super().__init__() self.total = 0 self.count = 0 def update_state(self, y_true, y_pred, sample_weight=None): values = tf.cast(tf.equal(y_true, tf.round(y_pred)), tf.float32) self.total += tf.reduce_sum(values) self.count += tf.size(y_true) def result(self): return self.total / self.count def reset_states(self): self.total = 0 self.count = 0
Check how variables are initialized and updated inside a TensorFlow metric.
TensorFlow metrics require state variables created with add_weight to track values across batches. Using plain Python ints and += causes TypeError when adding tensors to ints.
Which of the following is the best reason to implement a custom metric in TensorFlow instead of using built-in metrics?
Think about why you might want to track something special during training.
Custom metrics allow tracking of problem-specific performance measures that built-in metrics do not provide. Built-in metrics are optimized and reliable. Custom metrics do not inherently improve accuracy or simplify state management.
