def compute_modularity(graph, partitions):
m = len(graph.edges())
q = 0
for i, community in enumerate(set(partitions.values())):
nodes = [node for node, comm in partitions.items() if comm == community]
subgraph = graph.subgraph(nodes)
lc = len(subgraph.edges())
dc = sum(graph.degree(node) for node in nodes)
q += lc / m - (dc / (2 * m)) ** 2
return q
def compute_delta_modularity(graph, partitions, current_community, neighbor):
m = len(graph.edges())
lc = sum(
1 for node in graph.neighbors(neighbor)
if partitions[node] == current_community
)
dc = sum(graph.degree(node) for node in graph)
k_i = graph.degree(neighbor)
k_i_in = sum(
graph.degree(node) for node in graph.neighbors(neighbor)
if partitions[node] == current_community
)
delta_modularity = (
2 * lc / m - 2 * k_i * k_i_in / (2 * m * m) -
2 * lc / (2 * m) + 2 * k_i * dc / (2 * m * m)
)
return delta_modularity
# Construire le graphe directement en Python
graph = {
'A': ['B', 'C', 'D'],
'B': ['A', 'E', 'F'],
'C': ['A', 'G', 'H'],
'D': ['A', 'I', 'J'],
'E': ['B'],
'F': ['B'],
'G': ['C'],
'H': ['C'],
'I': ['D'],
'J': ['D']
}
# Exemple d'utilisation de l'algorithme de Louvain
if __name__ == '__main__':
communities = louvain_algorithm(graph)
print(communities)
——————–
Adamou02 – Envoyé depuis le Discord : Culte du code