我最初的目标是使用 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 返回一个新图。因此,请确保将图形设置为此结果,而不是丢弃结果。
