vision icon indicating copy to clipboard operation
vision copied to clipboard

Transform.normalize with 1 channel inverts tensor shape

Open jctaillandier opened this issue 8 years ago • 3 comments

I'm using DatasetFolder and I can train a model to recognize single channel, 100x100 images with no problem (black and white image). However if I add a transform.Normalize:

        self.train_data = datasets.DatasetFolder(self.path, np.load, list(('npy'))
                                                 , transform=transforms.Compose([
                                                 transforms.ToTensor(),
                                                 # Standardize with mean and std computed on train set
                                                  transforms.Normalize((0.5,), (0.5, )),
                                            ])
                                                
                                      )

Then the shape of the input tensor changes from [batch, 1, 100, 100] to [batch, 100, 1, 100] and I have no idea why.

for inputs, targets in pre_model.train_loader:
    print(inputs.shape)

returns torch.Size([150, 100, 1, 100])

Whereas without the transform.normalize, it outputs [1, 100, 100]

jctaillandier avatar Nov 21 '18 20:11 jctaillandier

The size of your input tensor to normalize should be CxHxW, and it looks like you have an extra batch dimension, that shouldn't be there for the normalize transform. Plus, none of the transforms that we have will work with batch images, they operate on single images, and the batching happens in the DataLoader.

fmassa avatar Nov 23 '18 09:11 fmassa

The size of my input tensor to normalize is CxHxW (1x100x100). The batch size was only added afterwards when using DataLoader. Hence above, the train_loader is created using Dataloader(train_data), and I am not calling the transform on a tensor with a batch size, but a tensor of CxHxW (1x100x100).

jctaillandier avatar Nov 23 '18 19:11 jctaillandier

I just tried the following snippet and everything worked out as expected

In [1]: import torch

In [2]: import torchvision

In [3]: a = torch.rand(1, 100, 100)

In [4]: t = torchvision.transforms.Normalize((0.5,), (0.5,))

In [5]: t(a).shape
Out[5]: torch.Size([1, 100, 100])

fmassa avatar Nov 27 '18 10:11 fmassa