我在 3.0GB CSV 文件中有 2.92M 数据点,我需要循环遍历它两次以创建一个我想加载到 NetworkX 的图形。按照目前的速度,我需要几天才能生成这个图表。我怎样才能加快速度?
similarity = 8
graph = {}
topic_pages = {}
CSV.foreach("topic_page_node_and_edge.csv") do |row|
topic_pages[row[0]] = row[1..-1]
end
CSV.open("generate_graph.csv", "wb") do |csv|
i = 0
topic_pages.each do |row|
i+=1
row = row.flatten
topic_pages_attributes = row[1..-1]
graph[row[0]] = []
topic_pages.to_a[i..-1].each do |row2|
row2 = row2.flatten
topic_pages_attributes2 = row2[1..-1]
num_matching_attributes = (topic_pages_attributes2 & topic_pages_attributes).count
if num_matching_attributes >= similarity or num_matching_attributes == topic_pages_attributes2.count or num_matching_attributes == topic_pages_attributes.count
graph[row[0]].push(row2[0])
end
end
csv << [row[0], graph[row[0]]].flatten
end
end
最佳答案
漂亮的代码,例如
(topic_pages_attributes2 & topic_pages_attributes).count
可能会成为运行时的主要因素,可以通过使用更传统的代码轻松减少。
这会大大缩短算法的运行时间。
您有大约 3 个 Mio 文档。从你的总数据量来看,他们可能平均不到 100 个主题?您的成对比较方法需要 3mio^2 次比较,这对您造成了伤害。如果每个更流行的主题仅用于 30.000 个文档,您可能只计算 30k^2 * 主题数。假设您有 100 个此类非常受欢迎的主题(稀有主题无关紧要),这将是 100 倍的加速。
其中一些数字可能过于乐观——例如,根本没有考虑 IO,如果您的问题是 I/O 限制,使用 C/Java 可能没有多大帮助。可能有一些非常受欢迎的主题可能会受到 C 中讨论的方法的影响。对于 D),您需要 O(n log n) 时间来排序数据;但是有非常好的实现可用。但这绝对是您应该做的简化。这些文档还将在您的最终数据中形成完全连接的派系,这也可能会损害其他分析。
关于python - 加快从 292 万个数据点创建图表的速度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25818246/