【问题标题】:numpy/scipy build adjacency matrix from weighted edgelistnumpy/scipy 从加权边缘列表构建邻接矩阵
【发布时间】:2018-05-23 15:24:15
【问题描述】:

我正在读取一个加权 egdelist / numpy 数组,例如:

0 1 1
0 2 1
1 2 1
1 0 1
2 1 4

其中的列是“User1”、“User2”、“Weight”。我想使用scipy.sparse.csgraph.depth_first_tree 执行 DFS 算法,它需要一个 N x N 矩阵作为输入。如何将上一个列表转换为方阵:

0 1 1
1 0 1
0 4 0

在 numpy 或 scipy 中?

感谢您的帮助。

编辑:

我一直在使用一个巨大的(1.5 亿节点)网络,所以我正在寻找一种内存高效的方法来做到这一点。

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    您可以使用节省内存的scipy.sparse matrix

    import numpy as np
    import scipy.sparse as sparse
    
    arr = np.array([[0, 1, 1],
                    [0, 2, 1],
                    [1, 2, 1],
                    [1, 0, 1],
                    [2, 1, 4]])
    shape = tuple(arr.max(axis=0)[:2]+1)
    coo = sparse.coo_matrix((arr[:, 2], (arr[:, 0], arr[:, 1])), shape=shape,
                            dtype=arr.dtype)
    
    print(repr(coo))
    # <3x3 sparse matrix of type '<type 'numpy.int64'>'
    #   with 5 stored elements in COOrdinate format>
    

    要将稀疏矩阵转换为密集的 numpy 数组,您可以使用todense

    print(coo.todense())
    # [[0 1 1]
    #  [1 0 1]
    #  [0 4 0]]
    

    【讨论】:

    • 谢谢!一切都很顺利,直到todense():它使脚本内存不足。但是您的解决方案非常快且内存消耗低!
    【解决方案2】:

    尝试以下方法:

    import numpy as np
    import scipy.sparse as sps
    
    A = np.array([[0, 1, 1],[0, 2, 1],[1, 2, 1],[1, 0, 1],[2, 1, 4]])
    i, j, weight = A[:,0], A[:,1], A[:,2]
    # find the dimension of the square matrix
    dim =  max(len(set(i)), len(set(j)))
    
    B = sps.lil_matrix((dim, dim))
    for i,j,w in zip(i,j,weight):
        B[i,j] = w
    
    print B.todense()
    >>>
    [[ 0.  1.  1.]
     [ 1.  0.  1.]
     [ 0.  4.  0.]]
    

    【讨论】:

    • 感谢您的提示!我认为 numpy 和/或 scipy 中有一些内置函数可以做到这一点......
    • 我认为没有。您可能需要考虑使用 networkx 来创建和操作图表。
    • 我试过了,但问题是网络很大:大约有 1.5 亿个节点。 NetworkX 因其尺寸而崩溃。您的脚本很好,但是在构建 B 矩阵时会出现 MemoryError 。 :-(
    • 如果用稀疏矩阵替换 B 会怎样?
    • 你的意思是初始化一个稀疏的B矩阵吗?代码现在在这里崩溃:B = np.zeros((dim, dim))。但是我在具有 200 GB RAM 的机器上运行脚本,我认为 np.array 对内存的依赖较少......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2014-09-04
    • 2019-09-07
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多