代码运行时的内存问题(Python,Networkx)
我写了一段代码,用来生成一个有379613734条边的图。
但是因为内存的问题,代码没能完成。当处理到6200万行的时候,它占用了大约97%的服务器内存。所以我只好把它杀掉了。
你有什么办法解决这个问题吗?
我的代码是这样的:
import os, sys
import time
import networkx as nx
G = nx.Graph()
ptime = time.time()
j = 1
for line in open("./US_Health_Links.txt", 'r'):
#for line in open("./test_network.txt", 'r'):
follower = line.strip().split()[0]
followee = line.strip().split()[1]
G.add_edge(follower, followee)
if j%1000000 == 0:
print j*1.0/1000000, "million lines done", time.time() - ptime
ptime = time.time()
j += 1
DG = G.to_directed()
# P = nx.path_graph(DG)
Nn_G = G.number_of_nodes()
N_CC = nx.number_connected_components(G)
LCC = nx.connected_component_subgraphs(G)[0]
n_LCC = LCC.nodes()
Nn_LCC = LCC.number_of_nodes()
inDegree = DG.in_degree()
outDegree = DG.out_degree()
Density = nx.density(G)
# Diameter = nx.diameter(G)
# Centrality = nx.betweenness_centrality(PDG, normalized=True, weighted_edges=False)
# Clustering = nx.average_clustering(G)
print "number of nodes in G\t" + str(Nn_G) + '\n' + "number of CC in G\t" + str(N_CC) + '\n' + "number of nodes in LCC\t" + str(Nn_LCC) + '\n' + "Density of G\t" + str(Density) + '\n'
# sys.exit()
# j += 1
边的数据是这样的:
1000 1001
1000245 1020191
1000 10267352
1000653 10957902
1000 11039092
1000 1118691
10346 11882
1000 1228281
1000 1247041
1000 12965332
121340 13027572
1000 13075072
1000 13183162
1000 13250162
1214 13326292
1000 13452672
1000 13844892
1000 14061830
12340 1406481
1000 14134703
1000 14216951
1000 14254402
12134 14258044
1000 14270791
1000 14278978
12134 14313332
1000 14392970
1000 14441172
1000 14497568
1000 14502775
1000 14595635
1000 14620544
1000 14632615
10234 14680596
1000 14956164
10230 14998341
112000 15132211
1000 15145450
100 15285998
1000 15288974
1000 15300187
1000 1532061
1000 15326300
最后,有没有人有分析Twitter链接数据的经验?对我来说,处理一个有向图并计算节点的平均入度和出度实在太难了。有什么帮助或建议吗?
2 个回答
6
这里有一些建议:
你可以用整数来给节点命名,而不是用字符串:这样会比问题中提到的用字符串的方法节省内存:
follower, followee = map(int, line.split())
实际上,整数占用的内存远远少于多个数字的字符串。
让程序继续运行,即使内存满了,因为你的操作系统会自动开始进行交换:你大约有3亿个节点,我想这些节点可能会占用几GB的内存;即使你的电脑开始交换,它也可能能够处理这么多节点(特别是使用整数命名节点后节省的内存)。
7
首先,你可以考虑一下是否可以简单地增加一些内存(RAM)。你可以估算一下内存的使用情况,要么根据你已有的数据进行计算,要么读取不同大小的数据样本来测量性能是如何变化的。增加几GB的内存花费不高,但可能会为你节省很多时间和麻烦。
其次,想想你是否真的需要构建整个图形。例如,你可以通过遍历文件来确定顶点的数量和它们的度数——这样你只需要在内存中保留一行数据和一些计数,这样占用的内存会比整个图形小得多。知道了度数后,在寻找最大的连通分量时,你可以省略掉度数为1的顶点,然后再对省略的节点进行修正。你是在做数据分析,而不是实现某种通用算法:先了解数据的一些简单特征,这样才能进行更复杂的分析。