numpy/scipy 从加权边列表构建邻接矩阵

numpy/scipy build adjacency matrix from weighted edgelist

我正在读取加权 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 亿个节点)网络,所以我正在寻找一种内存高效的方法来做到这一点。

尝试如下操作:

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.]]

您可以使用节省内存的 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]]