How to random flip a tensor in a batch from dataloader

Hello all, I have a batch from dataloader likes

images, targets=batch

The size of images is BxCXHxW. I want to random flip each image in images batch. How to do it ? I am using for loop but I guess we have better way

for i in range (images.size(0)):
    image= images[i,...]
    if np.random.randn()>0.5:
        image = image.flip(2)
        images[i,...]= image
   

If you are using pytorch dataloader you can do it inside getittem. This way you avoid for loop and apply it over all the images

Sorry i did not use it. I write my customer dataloader because it is hdf5 dataset. But you gave me one idea. I can change the flip inside getitem

Hmmm then you can try this:
Generate a random the same size as your batch size. Expand it to match the tensor size. Threshold it to have a Boolean tensor and then in-place modify the images tensor.
Like

Images[bool_tensor]=images[bool_tensor].flip(0)

Or a simple way. I hope you are shuffling batches. If you are choosing random numbers from a uniform distribution then half of them should be flipped.

Therefore you can just flip one out of 2.
Images[::2,…]=images[::2,…].flip(0)

1 Like

Actually, I do flip, transpose also, so the prob is not half. I think do it in __get_item__ is good idea, just one need is that we have to use copy() function Torch.from_numpy not support negative strides