繁体   English   中英

来自加权边缘列表的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亿个节点)合作,因此我正在寻找一种高效的内存存储方式。

您可以使用内存有效的scipy.sparse矩阵

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

尝试如下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM