【问题标题】:Vectorize compressed sparse matrix from array in Python在 Python 中从数组中向量化压缩的稀疏矩阵
【发布时间】:2014-12-21 03:44:19
【问题描述】:

我正在尝试将图论方法应用于图像处理问题。我想从包含我要绘制的点的数组中生成一个邻接矩阵。我想生成数组中点的完整图。如果我需要绘制数组中有 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 循环的情况下生成相同的数组吗?

【问题讨论】:

    标签: python arrays matrix adjacency-matrix


    【解决方案1】:

    使用函数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)
    

    【讨论】:

    • 那速度非常快。非常感谢。我只后悔我没有足够的声望来投票。再次感谢您。
    猜你喜欢
    • 2015-12-05
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2011-10-02
    • 2020-07-01
    • 1970-01-01
    • 2011-12-02
    相关资源
    最近更新 更多