Modularity calculation for weighted graphs in igra

2019-05-10 02:59发布

问题:

I used the fastgreedy algorithm in igraph for my community detection in a weighted, undirected graph. Afterwards I wanted to have a look at the modularity and I got different values for different methods and I am wondering why. I included a short example, which demonstrates my problem:

library(igraph)
d<-matrix(c(1, 0.2, 0.3, 0.9, 0.9,   
            0.2, 1, 0.6, 0.4, 0.5,  
            0.3, 0.6, 1, 0.1, 0.8,  
            0.9, 0.4, 0.1, 1, 0.5,  
            0.9, 0.5, 0.8, 0.5, 1), byrow=T, nrow=5)    

g<-graph.adjacency(d, weighted=T, mode="lower",diag=FALSE, add.colnames=NA)
fc<-fastgreedy.community(g)

fc$modularity[3]
#[1] -0.05011095
modularity(g,membership=cutat(fc,steps=2),weights=get.adjacency(g,attr="weight"))
#[1] 0.07193047

I would expect both of the values to be identical and if I try the same with an unweighted graph, I get the same values.

d2<-round(d,digits=0)
g2<- graph.adjacency(d2, weighted=NULL, mode="lower",diag=FALSE, add.colnames=NA)
fc2<-fastgreedy.community(g2)
plot(fc2,g2)

fc2$modularity[3]
#[1] 0.15625
modularity(g2,membership=cutat(fc2,steps=2))
#[1] 0.15625

Another user had a similar problem, but I have the current version of igraph, so that should not be the problem. Can someone explain to me why there is a difference or is there a problem with my code I don't see?

回答1:

The line

modularity(g,membership=cutat(fc,steps=2),weights=get.adjacency(g,attr="weight"))

is wrong. If you want to pass the weights of edges to modularity(), do it with E(g)$weight:

modularity(g, membership = cutat(fc, steps = 2), weights = E(g)$weight)
# [1] -0.05011095