File size: 1,326 Bytes
d2a9154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""
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}