Pytorch random tensor generation with one fix value and rest of random value
In my testing dataset, I have to always include one specific image(image at position 0) in each batch but others values can be randomly selected. So I am making a tensor which will have 1st value 0 (for 1st image) and the rest of others can be anything other than 0. My code snippet is below.
a= torch.randperm(len(l-1)) #where l is total no of testing image in dataset, code output-&gt;tensor([10, 0, 1, 2, 4, 5])
b=torch.tensor([0]) # code output-&gt; tensor([0])
c=torch.cat((b.view(1),a))# gives output as -&gt; tensor([0, 10, 0, 1, 2, 4, 5]) and 0 is used twice so repeated test image

However, above approach can include 0 twice as torch.randperm many times includes 0. Is there a way in torch to generate random number skipping one specific value. Or if you think another approach will be better please comment.

You could just remove these 0s using conditional indexing (also assumed you meant len(l) - 1):
a= torch.randperm(len(l)-1) #where l is total no of testing image in dataset, code output-&gt;tensor([10, 0, 1, 2, 4, 5])
a=a[a!=0]
b=torch.tensor([0]) # code output-&gt; tensor([0])
c=torch.cat((b,a))# gives output as -&gt; tensor([0, 10, 0, 1, 2, 4, 5]) and 0 is used twice so repeated test image

Or if you want to make sure it's never put in:
a=torch.arange(1,len(l)) 
a=a[torch.randperm(a.shape[0])]
b=torch.tensor([0]) 
c=torch.cat((b,a))

The second approach is a bit more versatile as you can have whatever values you'd like in your initial a declaration as well as replacement.
