Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix focal loss and implement integration test

edgarribabc0b82663cfb
diff --git a/test/integration/test_focal.py b/test/integration/test_focal.py
new file mode 100644
index 000000000..2cbef3e0e
--- /dev/null
+++ b/test/integration/test_focal.py
@@ -0,0 +1,70 @@
+import logging
+import pytest
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.optim as optim
+import torchgeometry as tgm
+
+logger = logging.getLogger(__name__)
+
+
+class TestIntegrationFocalLoss:
+ # optimization
+ thresh = 1e-1
+ lr = 1e-3
+ num_iterations = 1000
+ num_classes = 2
+
+ # focal loss
+ alpha = 2.0
+ gamma = 2.0
+
+ def generate_sample(self, base_target, std_val=0.1):
+ target = base_target.float() / base_target.max()
+ noise = std_val * torch.rand(1, 1, 6, 5)
+ return target + noise
+
+ @staticmethod
+ def init_weights(m):
+ if isinstance(m, nn.Conv2d):
+ torch.nn.init.xavier_uniform_(m.weight)
+
+ def test_conv2d_relu(self):
+
+ # we generate base sample
+ target = torch.LongTensor(1, 6, 5).fill_(0)
+ for i in range(1, self.num_classes):
+ target[..., i:-i, i:-i] = i
+
+ m = nn.Sequential(
+ nn.Conv2d(1, self.num_classes, kernel_size=3, padding=1),
+ nn.ReLU(True),
+ )
+ m.apply(self.init_weights)
+
+ optimizer = optim.Adam(m.parameters(), lr=self.lr)
+
+ criterion = tgm.losses.FocalLoss(
+ alpha=self.alpha, gamma=self.gamma, reduction='mean')
+ # NOTE: uncomment to compare against vanilla cross entropy
+ # criterion = nn.CrossEntropyLoss()
+
+ for iter_id in range(self.num_iterations):
+ sample = self.generate_sample(target)
+ output = m(sample)
+ loss = criterion(output, target)
+ logger.debug("Loss: {}".format(loss.item()))
+
+ optimizer.zero_grad()
+ loss.backward()
+ optimizer.step()
+
+ sample = self.generate_sample(target)
+ output_argmax = torch.argmax(m(sample), dim=1)
+ logger.debug("Output argmax: \n{}".format(output_argmax))
+
+ # NOTE: replace by IoU
+ val = F.mse_loss(output_argmax.float(), target.float())
+ assert val.item() < self.thresh, val
diff --git a/torchgeometry/losses/focal.py b/torchgeometry/losses/focal.py
index bf55fe7c4..a5f3c183b 100644
--- a/torchgeometry/losses/focal.py
+++ b/torchgeometry/losses/focal.py
@@ -74,16 +74,16 @@ class FocalLoss(nn.Module):
"input and target must be in the same device. Got: {}" .format(
input.device, target.device))
# compute softmax over the classes axis
- input_soft = F.softmax(input, dim=1)
+ input_soft = F.softmax(input, dim=1) + self.eps
# create the labels one hot tensor
target_one_hot = one_hot(target, num_classes=input.shape[1],
device=input.device, dtype=input.dtype)
# compute the actual focal loss
- prob = input_soft * target_one_hot + self.eps
- focal = -torch.log(prob) * self.alpha * (1. - prob) ** self.gamma
- loss_tmp = torch.sum(focal, dim=1)
+ weight = torch.pow(1. - input_soft, self.gamma)
+ focal = -self.alpha * weight * torch.log(input_soft)
+ loss_tmp = torch.sum(target_one_hot * focal, dim=1)
loss = -1
if self.reduction == 'none':