""" Reconstruction losses. PerImageWFMRMELoss: relative magnitude error, each pixel weighted by its ground-truth magnitude divided by the mean ground-truth magnitude of the same image. WeightedMSEPlusDiceLoss: MSE with pixels above `threshold` weighted by 1 + pos_weight, plus a soft-Dice term. """ import torch import torch.nn as nn class PerImageWFMRMELoss(nn.Module): def __init__(self, eps=1e-6): super().__init__() self.eps = eps def forward(self, pred, target): t, p = target[:, 0], pred[:, 0] rel = (p - t).abs() / (t + self.eps) w = t / (t.mean(dim=(1, 2), keepdim=True) + self.eps) return (rel * w).mean() class WeightedMSEPlusDiceLoss(nn.Module): def __init__(self, pos_weight=3.0, threshold=0.2, dice_weight=0.5): super().__init__() self.pos_weight, self.threshold, self.dice_weight = pos_weight, threshold, dice_weight def forward(self, pred, target): w = 1.0 + self.pos_weight * (target > self.threshold).float() mse = (w * (pred - target) ** 2).mean() p, t = pred.flatten(1), target.flatten(1) dice = (2 * (p * t).sum(1) + 1e-6) / (p.sum(1) + t.sum(1) + 1e-6) return mse + self.dice_weight * (1 - dice.mean()) REC_LOSSES = {"rme": PerImageWFMRMELoss, "wmd": WeightedMSEPlusDiceLoss}