How to merge sequential integer values into intervals in PyTorch?

Viewed 77

I have a 1D array:

[3, 4, 5, 6, 7, 20, 31, 32, 33, 34]

which I want to turn into a 2D interval array by merging every consecutive values into intervals:

[
  [ 3,  7],
  [20, 20],
  [32, 34]
]

What would be a decent, possibly GPU-friendly, way to do it?

1 Answers

Not sure if this is ideal, but you can try cumsum() on the differences compared to 1. Then use that to slice the original data:

# mark the consecutive blocks
blocks = torch.cat([torch.tensor([0]),(t[1:] - t[:-1]) != 1]).cumsum(dim=0)

# where the blocks shift
mask =  blocks[1:] != blocks[:-1]

out = torch.cat([t[:1], t[:-1][mask],t[1:][mask], t[-1:]]).reshape(-1,2)

Output:

tensor([[ 3,  7],
        [20, 20],
        [31, 34]])
Related