Skip to content

Commit

Permalink
Refactor loss fns to losses.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Sam Sepiol committed Oct 1, 2021
1 parent f5fac0a commit bb96df3
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions cgd/losses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import torch as th
from torch.nn import functional as tf


def range_loss(input):
return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])


def spherical_dist_loss(x: th.Tensor, y: th.Tensor):
"""(Katherine Crowson) - Spherical distance loss"""
x = tf.normalize(x, dim=-1)
y = tf.normalize(y, dim=-1)
return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)


def tv_loss(input: th.Tensor):
"""(Katherine Crowson) - L2 total variation loss, as in Mahendran et al."""
input = tf.pad(input, (0, 1, 0, 1), "replicate")
x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]
y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]
return (x_diff ** 2 + y_diff ** 2).mean([1, 2, 3])

0 comments on commit bb96df3

Please sign in to comment.