Using transforms.Normalize on a single tensor

Hello, I’m relatively new to PyTorch, I want to to apply Instance Normalization to my images. I am wondering if I can use Normalize as a stand alone function, without needing a tranforms.Compose() or any of the sort. Here is how I am currently trying to implement it:

img = someTensor # dimensions [1x224x224] I am using grayscale images
mean, std = img.mean(), img.std()
normal  = Normalize(mean,std)
normal(tensor = img)

I am getting the following error:
IndexError: too many indices for tensor of dimension 0

For now, I will apply element-wise normalisation (i.e. x-mu/sigma) but I would like to make it work with the torch functions too!

I would really appreciate if anyone could help me clarify how all this works!

Thanks in advance!

You should unsqueeze the statistics, as you are currently passing scalar values:

normal = transforms.Normalize(mean.unsqueeze(0), std.unsqueeze(0))

This should avoid the error, which is caused by mean[:, None, None] inside Normalize.

1 Like

That makes sense, thank you so much for the speedy reply!