Complete the code to define a custom metric that calculates accuracy.
import tensorflow as tf def custom_accuracy(y_true, y_pred): correct = tf.equal(tf.argmax(y_true, axis=1), tf.argmax(y_pred, axis=1)) return tf.reduce_mean(tf.cast(correct, [1]))
The custom metric converts boolean correct predictions to float32 before averaging to get accuracy.
Complete the code to create a custom metric class that tracks mean squared error.
import tensorflow as tf class CustomMSE(tf.keras.metrics.Metric): def __init__(self, name='custom_mse', **kwargs): super().__init__(name=name, **kwargs) self.sum_squared_error = self.add_weight(name='sse', initializer='zeros') self.count = self.add_weight(name='count', initializer='zeros') def update_state(self, y_true, y_pred, sample_weight=None): error = tf.square(y_true - y_pred) self.sum_squared_error.assign_add(tf.reduce_sum(error)) self.count.assign_add(tf.cast(tf.size(y_true), [1])) def result(self): return self.sum_squared_error / self.count
The count variable must be a floating point type to allow division in the result method.
Fix the error in the custom metric update_state method by completing the blank.
def update_state(self, y_true, y_pred, sample_weight=None): error = tf.abs(y_true - y_pred) if sample_weight is not None: error = error * sample_weight self.total.assign_add(tf.reduce_sum(error)) self.count.assign_add(tf.cast(tf.shape(y_true)[0], [1]))
Counting samples as float32 ensures correct division later in the metric calculation.
Fill both blanks to complete the custom metric that calculates mean absolute error with sample weights.
class WeightedMAE(tf.keras.metrics.Metric): def __init__(self, name='weighted_mae', **kwargs): super().__init__(name=name, **kwargs) self.total_error = self.add_weight(name='total_error', initializer='zeros') self.total_weight = self.add_weight(name='total_weight', initializer='zeros') def update_state(self, y_true, y_pred, sample_weight=None): error = tf.abs(y_true - y_pred) if sample_weight is not None: error = error * sample_weight weight = sample_weight else: weight = tf.ones_like(error) self.total_error.assign_add(tf.reduce_sum(error)) self.total_weight.assign_add(tf.reduce_sum([1])) def result(self): return self.total_error / self.total_weight if self.total_weight > 0 else 0.0 metric = WeightedMAE() metric.update_state(y_true, y_pred, [2])
The total weight is the sum of the weights used, and the update_state call uses the sample_weight argument.
Fill all three blanks to complete a custom metric that calculates precision for binary classification.
class CustomPrecision(tf.keras.metrics.Metric): def __init__(self, name='custom_precision', **kwargs): super().__init__(name=name, **kwargs) self.true_positives = self.add_weight(name='tp', initializer='zeros') self.predicted_positives = self.add_weight(name='pp', initializer='zeros') def update_state(self, y_true, y_pred, sample_weight=None): y_pred_labels = tf.cast(y_pred > [1], tf.float32) true_positives = tf.reduce_sum(y_true * y_pred_labels) predicted_positives = tf.reduce_sum(y_pred_labels) self.true_positives.assign_add(true_positives) self.predicted_positives.assign_add(predicted_positives) def result(self): return self.true_positives / (self.predicted_positives + [2]) def reset_states(self): self.true_positives.assign(0) self.predicted_positives.assign(0) metric = CustomPrecision() metric.update_state(y_true, y_pred, sample_weight=[3])
The threshold for binary classification is 0.5, a small epsilon (1e-7) avoids division by zero, and sample_weight can be None if no weighting is used.
