首页 > 解决方案 > create an adjacency matrix in python

问题描述

I want to load CSV or text file of signed (weighted) graph and create an adjacency matrix. The CSV file contains three columns named "FromNodeId", "ToNodeId" and "Sign". The code I used is as follows:

G = nx.read_edgelist('soc-sign-epinions.txt', data = [('Sign', int)])
#print(G.edges(data = True))

A = nx.adjacency_matrix(G)
print(A.todense())

I encountered the following error

ValueError: array is too big; `arr.size * arr.dtype.itemsize` is larger than 
the maximum possible size

How can I solve this problem? Please suggest me a way to create the adjacency matrix.

标签: pythonmatrixnetworkx

解决方案


存储大矩阵所需的内存很容易失控,这就是为什么nx.adjacency_matrix(G)返回一个存储效率更高的“稀疏矩阵”(利用许多条目将是 0)。

由于您的图有 131000 个顶点,因此整个邻接矩阵将使用131000^2 * 24 bytes大约 400GB(整数在 python 中占用 24 个字节的内存)。但是,您的图的所有边不到 0.01%,换句话说,它非常稀疏,稀疏矩阵适合您。

为了获得稀疏矩阵,只需使用 A = nx.adjacency_matrix(G)而不调用A.todense()它(这会再次尝试正常存储它)。

有一个内置函数scipy.sparse可以有效地保存和加载稀疏矩阵,请参见此处。例如,要保存稀疏矩阵 A,请使用

scipy.sparse.save_npz('filename.npz', A)

如果使用 txt 或 CSV 对您很重要,则必须手动执行。这可以通过遍历矩阵的每一行并将它们一一写入文件来完成:

for i in range(A.shape[0]): row = A.getrow(i).todense() [write row to file using your preferred method]

这可能需要几分钟才能运行,但应该可以工作(我用相同大小的路径进行了测试)。


推荐阅读