python - 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.
解决方案
存储大矩阵所需的内存很容易失控,这就是为什么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]
这可能需要几分钟才能运行,但应该可以工作(我用相同大小的路径进行了测试)。
推荐阅读
- arrays - 指向数组和二维数组的指针
- go - go install c 共享输出路径
- python - 如何使用 QSqlTableModel 在可编辑的 QTableView 中将值设置为 NULL
- javascript - 打字稿吊装
- c++ - 模板参数中的括号,例如 std::function
- java - Fortify -Denial of Service_Format 字符串
- python - 关于python制作计算器报错的问题
- node.js - 在 node.js 应用程序中呈现页面之前解码 JWT cookie 和密码时出错
- python - 为什么我的 tkinter 盒子永远不会关闭,也不会在我的终端上打印
- extract - 来自 chess.com 的实时统计 chess960?