【问题标题】:Is there a more efficient way to generate a distance matrix in numpy有没有更有效的方法在 numpy 中生成距离矩阵
【发布时间】:2018-06-19 03:42:15
【问题描述】:

我想知道在给定矩阵的 H x W 和起始索引位置的情况下,是否有更直接、更有效的方法来生成距离矩阵。

为简单起见,我们采用一个 3x3 矩阵,其起点为 (0,0)。因此,要生成的距离矩阵为:

[[ 0.          1.          2.        ]
 [ 1.          1.41421356  2.23606798]
 [ 2.          2.23606798  2.82842712]]

索引 (0,1) 距离为 1,而索引 (2,2) 距离为 2.828。

我目前的代码如下:

def get_distances(start, height, width):
        matrix = np.zeros((height, width), dtype=np.float16)
        indexes = [(y, x) for y, row in enumerate(matrix) for x, val in enumerate(row)]
        to_points = np.array(indexes)
        start_point = np.array(start)
        distances = np.linalg.norm(to_points - start_point, ord=2, axis=1.)

    return distances.reshape((height, width))



height = 3
width = 3
start = [0,0]
distance_matrix = get_distances(start, height, width)

我认为这已经很有效了。但是 numpy 总是用一些我通常不会想到的技巧让我感到惊讶,所以我想知道在这种情况下是否存在这样的技巧。谢谢

【问题讨论】:

    标签: python numpy matrix euclidean-distance


    【解决方案1】:

    您可以使用hypot() 和广播:

    import numpy as np
    x = np.arange(3)
    np.hypot(x[None, :], x[:, None])
    

    outer 方法:

    np.hypot.outer(x, x)
    

    结果:

    array([[ 0.        ,  1.        ,  2.        ],
           [ 1.        ,  1.41421356,  2.23606798],
           [ 2.        ,  2.23606798,  2.82842712]])
    

    计算网格上每个点到固定点(x, y)的距离:

    x, y = np.ogrid[0:3, 0:3]
    np.hypot(x - 2, y - 2)
    

    【讨论】:

    • 这很有趣。但是如果我想从(2,2)开始,我该怎么做呢?
    • @user1179317 你想计算网格上每个点到固定点(x, y)的距离吗?
    • 是的,从起点到矩阵中的每个索引/点
    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    相关资源
    最近更新 更多