How to compute pairwise distance between two torch tensors of different dimensions?

I’m looking for a method that takes an m-by-d tensor (x1) and an n-by-d tensor (x2) and computes the pairwise distance between each element of x2 with each elements of x1.

I’ve seen nn.PairwiseDistance in the documentation, which requires the tensors to have the same dimensions and only computes the distance between their corresponding rows.
An inefficient solution would be to use nn.PairwiseDistance and iterate over different rows of x2 to compare each row of x2 with all rows of x1.


take a look at the package torch-two-sample, and in particular the file. Hope this helps.


Is torch.cdist what you’re looking for?

1 Like