pythonpytorch

Piecewise curve segment lengths from Pytorch


Most examples of pdist (or cdist) seems to be between two tensors. If I have a piecewise curve defined as follows:

line=torch.tensor([(-104.6400,0.0000),(-104.6400,0.1500),(-103.5500,0.5140),(-98.1000,1.0775),(-92.6500,1.4553)])

what I have coded to get the segment lenghts is

pdist = torch.nn.PairwiseDistance(p=2)

i=0
for point in line:
   if i>0:
      print(f"{i}: {pdist(previous_point,point)}")
   previous_point = point
   i += 1

Is this the best way or is there a more pytorchic way of doing it?


Solution

  • You don't need the loop. You can just do:

    import torch
    
    line = torch.tensor(
        [
            (-104.6400, 0.0000),
            (-104.6400, 0.1500),
            (-103.5500, 0.5140),
            (-98.1000,1.0775),
            (-92.6500,1.4553),
        ]
    )
    
    pdist = torch.nn.PairwiseDistance(p=2)
    
    distances = pdist(line[:-1], line[1:])
    
    print(distances)
    tensor([0.1500, 1.1492, 5.4791, 5.4631])