Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyTorch - Element-wise signed min/max?

I may be missing something obvious, but I can't find a way to compute this.

Given two tensors, I want to keep the minimum elements in each one of them as well as the sign.

I thought about

sign_x = torch.sign(x)
sign_y = torch.sign(y)
min = torch.min(torch.abs(x), torch.abs(y))

in order to eventually multiply the signs with the obtained minimums, but then I have no method to multiply the correct sign to each element that was kept and must choose one of the two tensors.

like image 707
fjrivasf Avatar asked Jun 28 '26 04:06

fjrivasf


1 Answers

Here is one way to do it. Multiply torch.sign(x) and torch.sign(y) by a tensor of booleans representing whether x or y is the result of the min calculation. Then take the logical or (|) of the two resulting tensors to combine them, and multiply that by the min calculation.

mins = torch.min(torch.abs(x), torch.abs(y))

xSigns = (mins == torch.abs(x)) * torch.sign(x)
ySigns = (mins == torch.abs(y)) * torch.sign(y)
finalSigns = xSigns.int() | ySigns.int()

result = mins * finalSigns

If x and y have the same absolute value for a certain element, in the code above the sign of x takes precedence. For y to take precedence, swap the order and use finalSigns = ySigns.int() | xSigns.int() instead.

like image 88
jdaz Avatar answered Jun 30 '26 18:06

jdaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!