Skip to content

Instantly share code, notes, and snippets.

@KeAWang
Created November 14, 2023 18:32
Show Gist options
  • Save KeAWang/e3d1cbb57c3dfe53618ee4f0ea7ed685 to your computer and use it in GitHub Desktop.
Save KeAWang/e3d1cbb57c3dfe53618ee4f0ea7ed685 to your computer and use it in GitHub Desktop.
Constrain and unconstrain
import torch
def constrain(x, min, max, temperature:float=1.):
return (max - min) * torch.sigmoid(x / temperature) + min
def unconstrain(y, min, max, temperature:float=1, EPS:float=1e-8):
assert torch.all(y >= min) and torch.all(y <= max)
# ensure both numerator and denominator are positive
numerator = y - min
denominator = max - min
return temperature * torch.logit(numerator / denominator, eps=EPS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment