forked from Lightning-AI/torchmetrics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
total_variation.py
50 lines (39 loc) · 1.78 KB
/
total_variation.py
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
39
40
41
42
43
44
45
46
47
48
49
50
import torch
from torchmetrics.metric import Metric
class TotalVariation(Metric):
"""Computes Total Variation loss.
Adapted from: https://github.com/jxgu1016/Total_Variation_Loss.pytorch
Args:
dist_sync_on_step: Synchronize metric state across processes at each ``forward()``
before returning the value at the step.
compute_on_step: Forward only calls ``update()`` and returns None if this is set to
False.
"""
is_differentiable = True
higher_is_better = False
current: torch.Tensor
total: torch.Tensor
def __init__(self, dist_sync_on_step: bool = False, compute_on_step: bool = True):
super().__init__(dist_sync_on_step=dist_sync_on_step, compute_on_step=compute_on_step)
self.add_state("current", default=torch.tensor(0, dtype=torch.float), dist_reduce_fx="sum")
self.add_state("total", default=torch.tensor(0, dtype=torch.int), dist_reduce_fx="sum")
def update(self, img: torch.Tensor) -> None:
"""Update method for TV Loss.
Args:
img (torch.Tensor): A NCHW image batch.
Returns:
A loss scalar value.
"""
_height = img.size()[2]
_width = img.size()[3]
_count_height = self.tensor_size(img[:, :, 1:, :])
_count_width = self.tensor_size(img[:, :, :, 1:])
_height_tv = torch.pow((img[:, :, 1:, :] - img[:, :, : _height - 1, :]), 2).sum()
_width_tv = torch.pow((img[:, :, :, 1:] - img[:, :, :, : _width - 1]), 2).sum()
self.current += 2 * (_height_tv / _count_height + _width_tv / _count_width)
self.total += img.numel()
def compute(self):
return self.current.float() / self.total
@staticmethod
def tensor_size(t):
return t.size()[1] * t.size()[2] * t.size()[3]