'How do I clamp the magnitude of a PyTorch tensor?

I know I can use torch.clamp to clamp a tensor's values within some min / max, but how can I do this if I want to clamp by the magnitude (absolute value)? Example:

import torch
t = torch.tensor([-5.0, -250, -1, 0.003, 7, 1238])
min_mag = 1 / 10
max_mag = 100
# desired output:
tensor([  -5.0000, -100.0000,   -1.0000,    0.1000,    7.0000,  100.0000])


Solution 1:[1]

One way is to multiply the sign of elements by the clamped version of the absolute elements as follows:

output = torch.sign(t) * torch.clamp(torch.abs(t), min_mag, max_mag)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akbarnejad