Edit RandomErasing to fill only with uniform values [0,1)

I’d like to edit the function used to generate random values in RandomErasing. Currently, values are generated with torch.normal_():

v = torch.empty([img_c, h, w], dtype=torch.float32).normal_()

This function sometimes generates values outside of [0, 1). Due to experimental constraints my network input needs to be scaled to this range.

Using this implementation to min-max normalize the output of RandomErasing, unfortunately, results in pixel artifacts. Trying the min-max normalization on the individual channels results in greyed images. (See respective images below.)

I would like RandomErasing to only generate uniform [0,1) random values. I believe the implementation I need would look like this:

v = torch.rand((img_c, h, w), dtype=torch.float64)

I don’t believe it is possible to fork Pytorch source code and edit it.

How else could I edit a built-in transform?

Alternatively, is there something I’m not seeing regarding the min-max normalization?

(@developers FYI: I believe the default RandomErasing scale values are incorrect. According to the paper the optimal values are: scale=(0.02, 0.4).)

Could something simpler (perhaps slower depending on the use case) be achieved with masking?


import torch
import torchvision

a = torch.ones(16, 3, 224, 224)
t = torchvision.transforms.RandomErasing(p=1.0, value=-1)
o = t(a)
mask = o == -1.0
l = torch.sum(mask)
vals = torch.rand(l)
o[mask] = vals

That is a clever work-around, @eqy .

I’ve yet to test it out in my project, but it tests out okay in the DataLoader.

Thanks very much :smiley:

class RandomUniformValues(object):
    Class that fills -1.0 values in image with uniform random [0, 1).
    def __call__(self, image):
        if -1 not in image:
            return image
            mask = torch.eq(input=image, other=-1.0)
            random_values = torch.rand((image.shape[0], image.shape[1], image.shape[2]), dtype=torch.float32)
            return image.masked_scatter_(mask=mask, source=random_values)

transforms = transforms.Compose([
    RandomErasing(scale=(0.02, 0.4), value=-1),

1 Like