numpy/scipy 从加权边列表构建邻接矩阵 [英] numpy/scipy build adjacency matrix from weighted edgelist
问题描述
我正在读取一个加权的 egdelist/numpy 数组,例如:
I'm reading a weighted egdelist / numpy array like:
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 矩阵作为输入.如何将上一个列表转换为方阵:
where the columns are 'User1','User2','Weight'. I'd like to perform a DFS algorithm with scipy.sparse.csgraph.depth_first_tree
, which requires a N x N matrix as input. How can I convert the previous list into a square matrix as:
0 1 1
1 0 1
0 4 0
在 numpy 或 scipy 中?
within numpy or scipy?
感谢您的帮助.
我一直在使用一个巨大的(1.5 亿个节点)网络,所以我正在寻找一种内存高效的方法来做到这一点.
I've been working with a huge (150 million nodes) network, so I'm looking for a memory efficient way to do that.
推荐答案
您可以使用内存高效的 scipy.sparse 矩阵:
You could use a memory-efficient 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
:
To convert the sparse matrix to a dense numpy array, you could use todense
:
print(coo.todense())
# [[0 1 1]
# [1 0 1]
# [0 4 0]]
这篇关于numpy/scipy 从加权边列表构建邻接矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!