Tuesday, November 25, 2025

Louvain for Community detection

Louvain algorithm is a widely used and and well-regarded method for community detection in graphs. The algorithm begins with a singleton partition, where each node belongs to its own community. It then proceeds iteratively through multiple passes, each consisting of two distinct phases.

We will use the Louvain Algorithm in Oracle Graph Server to identify communities in the following Mentoring relationship graph

 

Let's start by generating some sample data:

 

 



create table users (username varchar(10));
create table mentors (mentor varchar(10), mentee varchar(10), weight float);

insert into users values 
  ('a')
  , ('b')
  , ('c')
  , ('d')
  , ('e')
  , ('f')
  , ('g')
  , ('h')
  , ('i')
  , ('j')
  , ('k')
  , ('l')
  , ('m')
  , ('n')

  ;


insert into mentors values 
  ('a', 'b', 0.3)
  , ('a', 'c', 0.4)  
  , ('a', 'd', 0.1)  
  , ('a', 'e', 0.4)    
  , ('b', 'g', 0.5)  
  , ('g', 'f', 0.2)  
  , ('f', 'a', 0.5)  
  , ('f', 'h', 0.2)  
  , ('f', 'i', 0.1)  
  , ('f', 'j', 0.5)        
  , ('f', 'k', 0.9)
  , ('k', 'a', 0.1)        
  , ('k', 'm', 0.2)        
  , ('k', 'n', 0.6)
  , ('k', 'l', 0.3);                 


Next create a PROPERTY GRAPH to reflect the Mentor -> Mentee relationships
CREATE OR REPLACE PROPERTY GRAPH social_network
  VERTEX TABLES (
    users KEY (username) PROPERTIES ARE ALL COLUMNS
  )
  EDGE TABLES ( 
    mentors
      key (mentor, mentee) 
      SOURCE KEY (mentor) REFERENCES users(username)
      DESTINATION KEY(mentee) REFERENCES users(username)
      PROPERTIES ARE ALL COLUMNS
    
);

Now let's run the Louvain algorithm on this Property Graph 

%python-pgx

# Write your code here - e.g.: graph = session.read_graph_with_prgraph = ....
graph = session.read_graph_by_name("SOCIAL_NETWORK", "pg_sql")

weight = graph.get_edge_property(name="WEIGHT")

print(weight)

partition = analyst.louvain(graph, weight,  max_iter=100, nbr_pass=3, tol=0.0001, community='community')

result_set = graph.query_pgql(

    "SELECT x.USERNAME, x.community MATCH (x) ORDER BY x.community DESC")

result_set.print()
print(partition)

session.close()

Output:

EdgeProperty(name: WEIGHT, type: double, graph: SOCIAL_NETWORK)
+--------------------------+
| x.USERNAME | x.community |
+--------------------------+
| i          | 10          |
| j          | 10          |
| k          | 10          |
| l          | 10          |
| m          | 10          |
| n          | 10          |
| f          | 10          |
| h          | 10          |
| a          | 4           |
| c          | 4           |
| d          | 4           |
| e          | 4           |
| b          | 1           |
| g          | 1           |
+--------------------------+

PgxPartition(graph: SOCIAL_NETWORK, components: 14)
 
 
 

No comments:

Post a Comment