Implement Dice Loss for segmentation tasks. This loss measures overlap between prediction and ground truth masks, widely used in image segmentation where pixel imbalance is common.
Dice Coefficient & Loss:
Dice Coefficient (with smoothing epsilon for numerical stability):
Dice(P,Y)=∑P+∑Y+ϵ2∑PY+ϵDice Loss:
Dice Loss=1−Dicep: array-like - Predicted probabilities, shape (N,) or (H,W)y: array-like - Binary mask {0,1}, same shape as peps: float = 1e-8 - Smoothing epsilon added to both numerator and denominatorInput: p=[0.9, 0.7, 0.1, 0.0], y=[1, 1, 0, 0], eps=1e-8
Output: 0.135
Good overlap: Dice ≈ 0.865, Loss ≈ 0.135
Input: p=[1.0, 1.0, 0.0, 0.0], y=[1, 1, 0, 0], eps=1e-8
Output: 0.0
Perfect overlap: Dice = 1.0, Loss = 0.0
Input: p=[1.0, 1.0], y=[0, 0], eps=1e-8
Output: 1.0
No overlap: Dice ≈ 0.0, Loss ≈ 1.0
Flatten arrays with .flatten() to handle both 1D and 2D inputs uniformly.
Intersection is np.sum() of element-wise product, union is sum of both arrays.
Add eps to both numerator and denominator: (2*intersection + eps) / (sum_p + sum_y + eps).
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
Implement Dice Loss for segmentation tasks. This loss measures overlap between prediction and ground truth masks, widely used in image segmentation where pixel imbalance is common.
Dice Coefficient & Loss:
Dice Coefficient (with smoothing epsilon for numerical stability):
Dice(P,Y)=∑P+∑Y+ϵ2∑PY+ϵDice Loss:
Dice Loss=1−Dicep: array-like - Predicted probabilities, shape (N,) or (H,W)y: array-like - Binary mask {0,1}, same shape as peps: float = 1e-8 - Smoothing epsilon added to both numerator and denominatorInput: p=[0.9, 0.7, 0.1, 0.0], y=[1, 1, 0, 0], eps=1e-8
Output: 0.135
Good overlap: Dice ≈ 0.865, Loss ≈ 0.135
Input: p=[1.0, 1.0, 0.0, 0.0], y=[1, 1, 0, 0], eps=1e-8
Output: 0.0
Perfect overlap: Dice = 1.0, Loss = 0.0
Input: p=[1.0, 1.0], y=[0, 0], eps=1e-8
Output: 1.0
No overlap: Dice ≈ 0.0, Loss ≈ 1.0
Flatten arrays with .flatten() to handle both 1D and 2D inputs uniformly.
Intersection is np.sum() of element-wise product, union is sum of both arrays.
Add eps to both numerator and denominator: (2*intersection + eps) / (sum_p + sum_y + eps).
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number