Table of Contents
Shortcuts

# torch.cdist

torch.cdist(x1, x2, p=2.0, compute_mode='use_mm_for_euclid_dist_if_necessary')

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

  Parameters:

    - x1 (Tensor) – input tensor of shape B×P×M B \times P \times M B×P×M.

    - x2 (Tensor) – input tensor of shape B×R×M B \times R \times M B×R×M.

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

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

  Return type:

    Tensor

  If x1 has shape B×P×M B \times P \times M B×P×M and x2 has shape B×R×M B \times R \times M B×R×M then the output will have shape B×P×R B \times P \times R B×P×R.

  This function is equivalent to scipy.spatial.distance.cdist(input,’minkowski’, p=p) if p∈(0,∞)p \in (0, \infty)p∈(0,∞). When p=0 p = 0 p=0 it is equivalent to scipy.spatial.distance.cdist(input, ‘hamming’) * M. When p=∞p = \infty p=∞, the closest scipy function is scipy.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]])
      >>> a
      tensor([[ 0.9041,  0.0196],
              [-0.3108, -2.4423],
              [-0.4821,  1.0590]])
      >>> b = torch.tensor([[-2.1763, -0.4713], [-0.6986,  1.3702]])
      >>> b
      tensor([[-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]])

## Docs

Access comprehensive developer documentation for PyTorch

View Docs

## Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

## Resources

Find development resources and get your questions answered

View Resources

To analyze traffic and optimize your experience, we serve cookies on this site. By clicking or navigating, you agree to allow our usage of cookies. As the current maintainers of this site, Facebook’s Cookies Policy applies. Learn more, including about available controls: Cookies Policy.