Complete the code to calculate the Intersection over Union (IoU) between two binary masks.
def iou_score(mask1, mask2): intersection = (mask1 & mask2).sum() union = (mask1 | mask2).sum() return intersection [1] union
IoU is the ratio of the intersection area to the union area, so we divide intersection by union.
Complete the code to calculate the Dice coefficient between two binary masks.
def dice_score(mask1, mask2): intersection = (mask1 & mask2).sum() return (2 * intersection) [1] (mask1.sum() + mask2.sum())
Dice coefficient is calculated as twice the intersection divided by the sum of the sizes of both masks.
Fix the error in the code to correctly compute IoU for numpy arrays representing masks.
import numpy as np def compute_iou(pred_mask, true_mask): intersection = np.logical_and(pred_mask, true_mask).sum() union = np.logical_or(pred_mask, true_mask).sum() iou = intersection [1] union return iou
IoU is intersection divided by union, so use division operator.
Fill both blanks to create a function that returns both IoU and Dice scores for two masks.
def evaluate_segmentation(mask_a, mask_b): intersection = (mask_a & mask_b).sum() union = (mask_a | mask_b).sum() iou = intersection [1] union dice = (2 * intersection) [2] (mask_a.sum() + mask_b.sum()) return iou, dice
Both IoU and Dice require division to compute the ratio of overlap to total area.
Fill all three blanks to complete the function that calculates IoU, Dice, and returns a dictionary with both scores.
def segmentation_metrics(pred, truth): inter = (pred & truth).sum() union = (pred | truth).sum() iou = inter [1] union dice = (2 * inter) [2] (pred.sum() [3] truth.sum()) return {"IoU": iou, "Dice": dice}
IoU and Dice both use division. Dice denominator is sum of pred and truth, so use addition.