Rate this Page

torch.cdist#

torch.cdist(x1,x2,p=2.0,compute_mode='use_mm_for_euclid_dist_if_necessary')[source]#

Computes batched the p-norm distance between each pair of the two collections of row vectors.

Parameters:
  • x1 (Tensor) – input tensor where the last two dimensions represent the points and the feature dimension respectively.The shape can beD1×D2××Dn×P×MD_1 \times D_2 \times \cdots \times D_n \times P \times M,wherePP is the number of points andMM is the feature dimension.

  • x2 (Tensor) – input tensor where the last two dimensions also represent the points and the feature dimension respectively.The shape can beD1×D2××Dm×R×MD_1' \times D_2' \times \cdots \times D_m' \times R \times M,whereRR is the number of points andMM is the feature dimension,which should match the feature dimension ofx1.

  • p (float) – p value for the p-norm distance to calculate between each vector pair[0,]\in [0, \infty].

  • compute_mode (str) – ‘use_mm_for_euclid_dist_if_necessary’ - will use matrix multiplication approach to calculateeuclidean distance (p = 2) if P > 25 or R > 25‘use_mm_for_euclid_dist’ - will always use matrix multiplication approach to calculateeuclidean distance (p = 2)‘donot_use_mm_for_euclid_dist’ - will never use matrix multiplication approach to calculateeuclidean distance (p = 2)Default: use_mm_for_euclid_dist_if_necessary.

Return type:

Tensor

If x1 has shapeB×P×MB \times P \times M and x2 has shapeB×R×MB \times R \times M then theoutput will have shapeB×P×RB \times P \times R.

This function is equivalent toscipy.spatial.distance.cdist(input,’minkowski’, p=p)ifp(0,)p \in (0, \infty). Whenp=0p = 0 it is equivalent toscipy.spatial.distance.cdist(input, ‘hamming’) * M. Whenp=p = \infty, the closestscipy function isscipy.spatial.distance.cdist(xn, lambda x, y: np.abs(x - y).max()).

Example

>>>a=torch.tensor([[0.9041,0.0196],[-0.3108,-2.4423],[-0.4821,1.059]])>>>atensor([[ 0.9041,  0.0196],        [-0.3108, -2.4423],        [-0.4821,  1.0590]])>>>b=torch.tensor([[-2.1763,-0.4713],[-0.6986,1.3702]])>>>btensor([[-2.1763, -0.4713],        [-0.6986,  1.3702]])>>>torch.cdist(a,b,p=2)tensor([[3.1193, 2.0959],        [2.7138, 3.8322],        [2.2830, 0.3791]])