Chained numerical comparisons in PyTorch

In PyTorch we can do comparisons between elements in tensors like so:

import torch

a = torch.tensor([[1,2], [2,3], [3,4]])
b = torch.tensor([[3,4], [1,2], [2,3]])

# torch.Size([3, 2])
# torch.Size([3, 2])

c = a[:, 0] < b[:, 0]

# tensor([ True, False, False])

However, when we try to add a condition, the snippet fails:

c = a[:, 0] < b[:, 1] < b[:, 0]

The expected output is

 tensor([ False, False,  False])

So, for each element in a, compare its first element with the second element of the corresponding item in b, and compare that element with the first element of the same item in b.

Traceback (most recent call last):
File “”, line 9, in
c = a[:, 0] < b[:, 1] < b[:, 0]
RuntimeError: bool value of Tensor with more than one value is ambiguous

Why is that, and how can we solve it?

c = (a[:, 0] < b[:, 1])< b[:, 0]

I don’t know if the parentheses will solve the problem, it depends what you compare and when

That seems an odd construct. Aren’t you then doing implicit casting?

c = (floattensor(true or false)) < other_tensor

In “regular Python” we can do x < y < z, which is the same as “x < y and y < z”.