Search code examples
torchsubtractionpytorch

subtraction of scalar from tensor yields 'inconsistent tensor size' in pytorch


I'm using PyTorch and my variables are

    x = [torch.FloatTensor of size 1x3x32x32]
    mean = Variable containing:
    1.00000e-02 *
      2.0518
    [torch.FloatTensor of size 1]

what I want to do is subtract the scalar mean from x by doing

    x = x - mean

However, I'm getting this error:

    RuntimeError: inconsistent tensor size at /py/conda-
    bld/pytorch_1493670682084/work/torch/lib/TH/generic/THTensorMath.c:831

What am I doing wrong? Thanks a lot


Solution

  • what you are trying only works if mean is truly a scalar, i.e. a float() (in this case) and not a torch.FloatTensor of size 1. You can either extract a true scalar from mean or expand mean to the size of x in order to perform the subtraction.

    To extract the float from mean, do:

    x = x - mean[0]
    

    To expand mean to the size of x, do:

    x = x - mean.expand_as(x)
    

    Note that both of these methods subtract the mean from each element in your tensor.