[SOLVED]Torch.grid_sample?

Hi, thank you always for your support.
I cannot understand the output torch.grid_sampler at the end or the torch.nn.functional.grid_sample.
Before watching the code, I expected that the grid_sample function calculate an output torch tensor sampled from the input tensor.
What does the grid_sample do?

Thank you in advance:)

The method samples the output from the input using the specified grid.
Have a look at this example:

input = torch.arange(4*4).view(1, 1, 4, 4).float()
print(input)
> tensor([[[[ 0.,  1.,  2.,  3.],
          [ 4.,  5.,  6.,  7.],
          [ 8.,  9., 10., 11.],
          [12., 13., 14., 15.]]]])

# Create grid to upsample input
d = torch.linspace(-1, 1, 8)
meshx, meshy = torch.meshgrid((d, d))
grid = torch.stack((meshy, meshx), 2)
grid = grid.unsqueeze(0) # add batch dim

output = torch.nn.functional.grid_sample(input, grid)
print(output)
> tensor([[[[ 0.0000,  0.4286,  0.8571,  1.2857,  1.7143,  2.1429,  2.5714,
            3.0000],
          [ 1.7143,  2.1429,  2.5714,  3.0000,  3.4286,  3.8571,  4.2857,
            4.7143],
          [ 3.4286,  3.8571,  4.2857,  4.7143,  5.1429,  5.5714,  6.0000,
            6.4286],
          [ 5.1429,  5.5714,  6.0000,  6.4286,  6.8571,  7.2857,  7.7143,
            8.1429],
          [ 6.8571,  7.2857,  7.7143,  8.1429,  8.5714,  9.0000,  9.4286,
            9.8571],
          [ 8.5714,  9.0000,  9.4286,  9.8571, 10.2857, 10.7143, 11.1429,
           11.5714],
          [10.2857, 10.7143, 11.1429, 11.5714, 12.0000, 12.4286, 12.8571,
           13.2857],
          [12.0000, 12.4286, 12.8571, 13.2857, 13.7143, 14.1429, 14.5714,
           15.0000]]]])
1 Like

Thank you always for your kind reply, ptrblck.
Your provided sample code is quite understandable and helpful for me.
I now see what torch.grid_sample does.
I am grateful for your continuous support!

1 Like