Hi,
I can select every 3rd. element using tensor[2::3]
, but how can I select every element except the 3rd.?
You can do that by creating the indexes of the elements that you want. I have the following example:
>>> a = torch.randn(100)
>>> inx = np.array([i for i in range(len(a)) if i%3!=0])
>>> inx
array([ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25,
26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50,
52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76,
77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98])
>>> b = a[inx]
>>> b.shape
torch.Size([66])
As another approach, you can use reshape
:
>>> a = torch.arange(12)
>>> a
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> a.reshape(-1,3)[:,:2].reshape(-1)
tensor([ 0, 1, 3, 4, 6, 7, 9, 10])
It shouldn’t work. The following code works for any modulus.
def exceptEvery(nth, a):
m = a.size(0) // nth * nth
return torch.cat((a[:m].reshape(-1,nth)[:,:nth-1].reshape(-1), a[m:m+nth-1]))
>>> exceptEvery(2, torch.arange(11))
tensor([ 0, 2, 4, 6, 8, 10])
>>> exceptEvery(3, torch.arange(11))
tensor([ 0, 1, 3, 4, 6, 7, 9, 10])
>>> exceptEvery(4, torch.arange(11))
tensor([ 0, 1, 2, 4, 5, 6, 8, 9, 10])
1 Like