如何在PyTorch中将连续整数值合并为区间?

如何在PyTorch中将连续整数值合并为区间?,pytorch,Pytorch,我有一个一维阵列: [3, 4, 5, 6, 7, 20, 31, 32, 33, 34] 我想通过将每个连续值合并为间隔,将其转换为2D间隔数组: [ [ 3, 7], [20, 20], [32, 34] ] 什么是一种体面的、可能对GPU友好的方法呢?不确定这是否理想,但您可以尝试cumsum()比较1的差异。然后使用它对原始数据进行切片: # mark the consecutive blocks blocks = torch.cat([torch.tensor([0]

我有一个一维阵列:

[3, 4, 5, 6, 7, 20, 31, 32, 33, 34]
我想通过将每个连续值合并为间隔,将其转换为2D间隔数组:

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

什么是一种体面的、可能对GPU友好的方法呢?

不确定这是否理想,但您可以尝试
cumsum()
比较
1
的差异。然后使用它对原始数据进行切片:

# 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)
输出:

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

你能告诉我数字3,7,20,20,32,34是如何选择的吗?数字来自
tnsr.nonzero().flatten()