[英]How can I vectorize (and speed up) this recursive graph search function in R?
我在R中編寫了一個遞歸函數,用於查找有向圖的路徑st的所有路徑(無循環)。 我使用此頁面作為模型: 在有向樹(igraph)中從一個節點到另一個節點的所有可能路徑,並且它輸出正確的結果,但是速度很慢。 小圖沒什么大不了的。 對於大圖,這是一個問題。
我是R的新手,但已閱讀它在避免循環和使用向量化時的性能明顯更好。 我正在努力解決問題,希望您能提供幫助。 我的代碼:
findAllPaths <- function(graph,start,end) {
return(fastFindPaths(graph, start, end))
}
fastFindPaths <- function(graph, from, to, path) {
if(missing(path)) path <- c()
path <- cbind(path, from)
if (from == to) return(path)
paths <- c()
adjList <- get.adjlist(graph, mode="out")[[from]]
for (child in adjList) {
if (!child %in% path) {
childPaths <- fastFindPaths(graph, child, to, path)
for (childPath in childPaths) paths <- c(paths, childPath)
}
}
return(paths)
}
那么,這是矢量化的候選人嗎? 我怎樣才能加快速度? 您還會給其他學習R的技巧嗎?
謝謝!
igraph的開發版本具有get.all.simple.paths()
函數,您可以從此處獲取: http : get.all.simple.paths()
。
我使用Tamas的建議不調用get.adjlist()
,而是使用neighbors()
,這提供了不錯的速度提高。 但是,真正有助於提高性能的是,通過在每個起始節點的子節點上調用fastFindPaths()
並匯總結果來並行化搜索。 我目前在Windows計算機上,因此使用了clusterApply()
函數。 盡管我可能會泛化代碼以檢查Sys.info()[1]
,如果不是Windows,則使用mclapply()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.