user570593
user570593

Reputation: 3520

How to calculate the distance between a mini batch and a set of filters in PyTorch

I have a mini-batch of size NxDxWxH, where N is the size of the mini-batch, D is the dimension, and W and H are the width and height respectively. Assume that I have a set of filters F, each with dimension Dx1x1. I need to calculate the pairwise distance between the mini-batch and the filters. The size of the output should be NxFxWxH.

      input:   NxDxWxH
      filters: FxDx1x1
      output:  NxFxWxH

Lets assume a is a vector of size D extracted at the location (x,y) of the input and f is filter of size Dx1x1. Each value in the output should be \sum_{d=1}^D (x_d - f_c)^2.

In other words, instead of convolution I am trying to find the pair-wise L2 distances.

How can I do this in pytorch?

Upvotes: 0

Views: 922

Answers (1)

layog
layog

Reputation: 4811

You can do this by expanding the input and filters for proper automatic shape casting.

# Assuming that input.size() is (N, D, W, H) and filters.size() is (F, D, 1, 1)
input.unsqueeze_(1)
filters.unsqueeze_(0)
output = torch.sum((input - filters)**2, dim=2)

Upvotes: 1

Related Questions