通过使用igraph(R)组合入射顶点的属性来创建边缘属性 [英] Creating edge attributes by combining attributes of incident vertices using igraph (R)
问题描述
对于图形中的每个边,我想添加一个数字属性(权重),它是入射顶点的属性(概率)的乘积.我可以通过遍历边缘来做到这一点;即:
For each edge in a graph I would like to add an numeric attribute (weight) that is the product of an attribute (probability) of the incident vertices. I can do it by looping over the edges; that is:
for (i in E(G)) {
ind <- V(G)[inc(i)]
p <- get.vertex.attribute(G, name = "prob", index=ind)
E(G)[i]$weight <- prod(p)
}
但是,这对于我的图来说很慢(| V |〜= 20,000和| E |〜= 200,000).有没有更快的方法来执行此操作?
However, this is qute slow for my graph (|V| ~= 20,000 and |E| ~= 200,000). Is there a faster way to do this operation?
推荐答案
这可能是最快的解决方案.关键是矢量化.
Here is probably the fastest solution. The key is to vectorize.
library(igraph)
G <- graph.full(45)
set.seed(1)
V(G)$prob <- pnorm(vcount(G))
## Original solution
system.time(
for (i in E(G)) {
ind <- V(G)[inc(i)]
p <- get.vertex.attribute(G, name = "prob", index=ind)
E(G)[i]$wt.1 <- prod(p)
}
)
#> user system elapsed
#> 1.776 0.011 1.787
## sapply solution
system.time(
E(G)$wt.2 <- sapply(E(G), function(e) prod(V(G)[inc(e)]$prob))
)
#> user system elapsed
#> 1.275 0.003 1.279
## vectorized solution
system.time({
el <- get.edgelist(G)
E(G)$wt.3 <- V(G)[el[, 1]]$prob * V(G)[el[, 2]]$prob
})
#> user system elapsed
#> 0.003 0.000 0.003
## are they the same?
identical(E(G)$wt.1, E(G)$wt.2)
#> [1] TRUE
identical(E(G)$wt.1, E(G)$wt.3)
#> [1] TRUE
矢量化解决方案的速度似乎快了500倍,尽管需要更多更好的测量来更精确地进行评估.
The vectorized solution seems to be about 500 times faster, although more and better measurements would be needed to evaluate this more precisely.
这篇关于通过使用igraph(R)组合入射顶点的属性来创建边缘属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!