Pytorch 0.4 error "TypeError: torch.Size() takes an iterable of 'int' (item 2 is 'Tensor')"

I have a function center crop for 5D: BxCxDxHxW. The function works fine in pytorch 0.5 but it has error in pytorch 0.4

This is the code

    def center_crop( x, depth, height, width):
        crop_d = torch.FloatTensor([x.size()[2]]).sub(depth).div(-2)
        crop_h = torch.FloatTensor([x.size()[3]]).sub(height).div(-2)
        crop_w = torch.FloatTensor([x.size()[4]]).sub(width).div(-2)

        return F.pad(x, [
            crop_d.ceil().int()[0], crop_d.floor().int()[0],
            crop_h.ceil().int()[0], crop_h.floor().int()[0],
            crop_w.ceil().int()[0], crop_w.floor().int()[0],
        ])

 variable = Variable(torch.randn(8, 2, 24, 32, 32))
 print(center_crop(variable))

The error in pytorch 0.4 is

  File "main.py", line 7, in center_crop
    crop_w.ceil().int()[0], crop_w.floor().int()[0],
  File "/home/john/anaconda3/lib/python3.6/site-packages/torch/nn/functional.py", line 1929, in pad
    return ConstantPadNd.apply(input, pad, value)
  File "/home/john/anaconda3/lib/python3.6/site-packages/torch/nn/_functions/padding.py", line 27, in forward
    output = input.new(input.size()[:(ctx.l_diff)] + new_dim).fill_(ctx.value)
TypeError: torch.Size() takes an iterable of 'int' (item 2 is 'Tensor')

How could I fix it? Thanks

The code actually mostly runs for me (except the call missing parameters).
There is, however, no reason to not just use python ints for the crop_d,h,w calculation (as in crop_h_floor = (x.size(3)-height)//2 and crop_h_ceil = crop_h_floor = (x.size(3)-height+1)//2 and then using those in the pad call.

Best regards

Thomas

1 Like

I have fixed it by changed from crop_d.ceil().int()[0] to crop_d.ceil().int()[0].item(). We have to add .item() in the crop_h, crop_d and crop_w. Thanks