I want to implement the following dice score : Where N is the number of test images. The output y_pred is of shape (batch_size,channel,height,width, where y_pred presents a binary mask output for a semantic segmentation problem ( foreground vs background), so the channel = 1. I am confused regarding the implementation. Here is my current implementation: def dice_score(y_true, y_pred): """ Compute the Dice score for binary segmentation tasks with a single channel. Args: y_true (Tensor): Ground truth tensor with shape (batch_size, 1, height, width). y_pred (Tensor): Predicted tensor with shape (batch_size, 1, height, width). Returns: dice (float): Dice score for the entire batch. """ threshold = 0.5 epsilon = 1e-8 # Small constant to avoid division by zero # Binarize predictions y_pred = tf.cast(y_pred > threshold, tf.float32) # Compute TP, FP, FN TP = tf.reduce_sum(y_pred * y_true, axis=[2, 3]) # Sum over spatial dimensions (height, width) FP = tf.reduce_sum(y_pred * (1 - y_true), axis=[2, 3]) # False positives FN = tf.reduce_sum((1 - y_pred) * y_true, axis=[2, 3]) # False negatives # Compute Dice score per batch element dice_per_batch = (2 * TP + epsilon) / (2 * TP + FP + FN + epsilon) # Average Dice score over the batch dice_score = tf.reduce_mean(dice_per_batch) return dice_score My confusion is I dont know whether to sum over the axis 2 and 3 only to compute TP,FP, and FN and compute the dice score as in the current implementation, or I need to sum over axis 1,2,and 3 then do a mean reduction over the batch ( test images) to get the dice score ? Continue reading...