Max of a tensor and a scalar
There are workarounds, but an easy direct way of doing it would be more concise and probably efficient. Thanks!
vadimkantorov
<SCODE>X = th.FloatTensor([
    [-1, 2],
    [2, -1]
])
scalar = th.FloatTensor([1])

th.max(X, scalar.expand_as(X))
<ECODE> gives you <SCODE> 1  2
 2  1
[torch.FloatTensor of size 2x2]
<ECODE> Please keep in mind that I’m playing with PyTorch for few days only, so that may not be the optimal solution.
elanmart
vadimkantorov
<SCODE>torch.clamp(tensor, max=value) # cmin
torch.clamp(tensor, min=value) # cmax
<ECODE> Edited to reflect what vadim said below
smth
Seems it’s the other way around: It works but is a little confusing at first.
vadimkantorov
fmassa
Maybe someone is looking for this. Is there a way to do this without that much code? <SCODE>def min_(value1, value2):
    if is_number(value1) and isinstance(value2, torch.Tensor):
        return torch.clamp(value2, max=value1)
    elif is_number(value2) and isinstance(value1, torch.Tensor):
        return torch.clamp(value1, max=value2)
    elif isinstance(value1, torch.Tensor) and isinstance(value2, torch.Tensor):
        return torch.min(value1, value2)


def max_(value1, value2):
    if is_number(value1) and isinstance(value2, torch.Tensor):
        return torch.clamp(value2, min=value1)
    elif is_number(value2) and isinstance(value1, torch.Tensor):
        return torch.clamp(value1, min=value2)
    elif isinstance(value1, torch.Tensor) and isinstance(value2, torch.Tensor):
        return torch.max(value1, value2)

min_(2, torch.tensor(3))
min_(torch.tensor(3), 2)
min_(torch.tensor(3), torch.tensor(2))<ECODE>
HectorAnadon