python - 使用 Networkx 计算图中的边时出现内存错误

标签 python graph networkx

我最初的目标是使用 Networkx 进行一些结构属性分析(直径、聚类系数等)。然而,我只是简单地尝试计算给定图中存在多少条边,就已经被绊倒了。这个图,可以下载from over here (beware: 126 MB zip file)由 1,632,803 个节点和 30,622,564 条边组成。 请注意,如果您要下载此文件,请务必删除文件顶部的注释(包括#)

我的机器有 8 GB 内存。对于这种大小的图表,我的计划(直径/聚类系数)是否过于雄心勃勃?我希望不会,因为我喜欢networkx,因为它简单而且看起来很完整。但是如果它雄心勃勃,您能否建议我可以用于这项工作的另一个库?

import networkx as nx

graph = nx.Graph()
graph.to_directed()

def create_undirected_graph_from_file(path, graph):
    for line in open(path):
        edges = line.rstrip().split()
        graph.add_edge(edges[0], edges[1])

print(create_undirected_graph_from_file("C:\\Users\\USER\\Desktop\\soc-pokec-relationships.txt", graph).g.number_of_edges())

错误:

Traceback (most recent call last):
  File "C:/Users/USER/PycharmProjects/untitled/main.py", line 12, in <module>
    print(create_undirected_graph_from_file("C:\\Users\\USER\\Desktop\\soc-pokec-relationships.txt", graph).g.number_of_edges())
  File "C:/Users/User/PycharmProjects/untitled/main.py", line 8, in create_undirected_graph_from_file
    edges = line.rstrip().split()
MemoryError

最佳答案

一个潜在的问题是字符串占用大量内存。由于所有边都是整数,因此在创建边之前将它们转换为整数可以受益。您将受益于更快的内部跟踪,并且内存占用更少!具体来说:

def create_undirected_graph_from_file(path, graph):
    for line in open(path):
        a, b = line.rstrip().split()
        graph.add_edge(int(a), int(b))
    return graph

我建议还更改您的 open 以使用上下文并确保文件被打开:

def create_undirected_graph_from_file(path, graph):
    with open(path) as f:
        for line in f:
            a, b = line.rstrip().split()
            graph.add_edge(int(a), int(b))
    return graph

或者神奇的一句台词:

def create_undirected_graph_from_file(path, graph):
    with open(path) as f:
        [graph.add_edge(*(int(point) for point in line.rstrip().split())) for line in f]
    return graph

还有一件事要记住。 Graph.to_directed 返回一个新图表。因此,请确保将 graph 设置为该结果,而不是丢弃结果。

关于python - 使用 Networkx 计算图中的边时出现内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44468676/

相关文章:

python - 使用分组列的邻接矩阵

python - NetworkX - 将多个度量的结果写入 CSV

python - 包含 '#' 时文本操作的惊人输出

algorithm - 在图中,找到连接到一个节点但未连接到另一个节点的所有节点的最快方法是什么?

azure - 在运行 Azure 资源图查询以进行图像漏洞评估时获取 docker 图像标签

haskell - 确保数据的正确性

python - 如何使用 Corpus.slice 添加带有日期的列

python - NLTK 是否实现了 TF-IDF?

python - 在 Python 中使用除法运算符时如何获得十进制值?

python - Pandas read_csv : low_memory and dtype options