在Python中从数组中矢量化压缩的稀疏矩阵

时间:2014-12-21 03:44:20

标签: python arrays matrix adjacency-matrix

我正在尝试将图论方法应用于图像处理问题。我想从包含我想要绘制的点的数组生成一个邻接矩阵。我想生成一个完整的数组中的点图。如果我需要在数组中有N个点,我需要一个NxN矩阵。权重应该是点之间的距离,所以这是我的代码:

''' vertexarray is an array where the points that are to be 
    included in the complete graph are True and all others False.'''

import numpy as np
def array_to_complete_graph(vertexarray):

    vertcoords = np.transpose(np.where(vertexarray == True))

    cg_array = np.eye(len(vertcoords))

    for idx, vals in enumerate(vertcoords):
        x_val_1, y_val_1 = vals
        for jdx, wals in enumerate(vertcoords):
            x_diff = wals[0] - vals[0]
            y_diff = wals[1] - vals[1]
            cg_array[idx,jdx] = np.sqrt(x_diff**2 + y_diff**2)
    return cg_array

当然,这是有效的,但我的问题是:是否可以在没有嵌套for循环的情况下生成相同的数组?

1 个答案:

答案 0 :(得分:0)

使用函数scipy.spatial.distance.cdist()

import numpy as np

def array_to_complete_graph(vertexarray):

    vertcoords = np.transpose(np.where(vertexarray == True))

    cg_array = np.eye(len(vertcoords))

    for idx, vals in enumerate(vertcoords):
        x_val_1, y_val_1 = vals
        for jdx, wals in enumerate(vertcoords):
            x_diff = wals[0] - vals[0]
            y_diff = wals[1] - vals[1]
            cg_array[idx,jdx] = np.sqrt(x_diff**2 + y_diff**2)
    return cg_array

arr = np.random.rand(10, 20) > 0.75

from scipy.spatial.distance import cdist
y, x = np.where(arr)
p = np.c_[x, y]
dist = cdist(p, p)
np.allclose(array_to_complete_graph(arr), dist)