【问题标题】:Calculate pairwise distance of multiple trajectories using numpy使用 numpy 计算多条轨迹的成对距离
【发布时间】:2020-02-21 15:25:58
【问题描述】:

给定任意数量的 3D 轨迹,每个轨迹有 N 个点(时间步长),我想计算给定时间步长的每个点之间的距离。

假设我们将查看时间步长 3,并有四个轨迹 t_0 ... t_3。轨迹 0 的第三个时间步长的点为 t_0(3)。我想计算距离如下:

d_0 = norm(t_0(3) - t_1(3))
d_1 = norm(t_1(3) - t_2(3))
d_2 = norm(t_2(3) - t_3(3)) 
d_3 = norm(t_3(3) - t_0(3))

如您所见,其中有一种循环行为(最后一个计算到第一个的距离),但这并不是绝对必要的。

我知道如何编写一些 for 循环并计算我想要的。我正在寻找的是一个概念,或者可能是 numpy(或 np 函数的组合)中的一个实现,它可以仅使用右轴和其他 numpy 魔法来执行此逻辑。

这里是一些示例轨迹

import numpy as np

TIMESTEP_COUNT = 70
origin = np.array([0, 0, 0])

run1_direction = np.array([1, 0, 0]) / np.linalg.norm([1, 0 ,0])
run2_direction = np.array([0, 1, 0]) / np.linalg.norm([0, 1, 0])
run3_direction = np.array([0, 0, 1]) / np.linalg.norm([0, 0, 1])
run4_direction = np.array([1, 1, 0]) / np.linalg.norm([1, 1, 0])

run1_trajectory = [origin]
run2_trajectory = [origin]
run3_trajectory = [origin]
run4_trajectory = [origin]

for t in range(TIMESTEP_COUNT - 1):
    run1_trajectory.append(run1_trajectory[-1] + run1_direction)
    run2_trajectory.append(run2_trajectory[-1] + run2_direction)
    run3_trajectory.append(run3_trajectory[-1] + run3_direction)
    run4_trajectory.append(run4_trajectory[-1] + run4_direction)

run1_trajectory = np.array(run1_trajectory)
run2_trajectory = np.array(run2_trajectory)
run3_trajectory = np.array(run3_trajectory)
run4_trajectory = np.array(run4_trajectory)

... 结果如下图:

提前谢谢你!!

编辑: 我的问题与下面建议的答案不同,因为我不想计算完整的距离矩阵。我的算法应该只适用于连续运行之间的距离。

【问题讨论】:

  • 那么runX_trajectory 是您需要计算距离的数组吗?
  • 这能回答你的问题吗? calculating distance between two numpy arrays
  • 也许你应该包含你的 for 循环实现来说明你想要做什么。看起来你想做 - np.linalg.norm(run1_trajectory-run2_trajectory, axis=1)scipy.spatial.distance.cdist(run1_trajectory,run2_trajectory)[:,1]
  • 或者...w=scipy.spatial.distance.cdist(run1_trajectory,run2_trajectory); print(w.diagonal()[:10])

标签: python numpy


【解决方案1】:

我认为你可以将它们垂直堆叠得到一个形状4 x n_timesteps的数组,然后使用np.roll在每个时间步做差异,即:

r = np.vstack([t0,t1,t2,t3])
r - np.roll(r,shift=-1,axis=0)

数字示例:

t0,t1,t2,t3 = np.random.randint(1,10, 5), np.random.randint(1,10, 5), np.random.randint(1,10, 5), np.random.randint(1,10, 5)
r = np.vstack([t0,t1,t2,t3])
r
array([[1, 7, 7, 6, 2],
       [9, 1, 2, 3, 6],
       [1, 1, 6, 8, 1],
       [2, 9, 5, 9, 3]])

r - np.roll(r,shift=-1,axis=0)
array([[-8,  6,  5,  3, -4],
       [ 8,  0, -4, -5,  5],
       [-1, -8,  1, -1, -2],
       [ 1,  2, -2,  3,  1]])

【讨论】:

    猜你喜欢
    • 2017-01-15
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 2013-09-02
    • 1970-01-01
    • 2015-02-25
    相关资源
    最近更新 更多