pythongraphnetworkxpytorch-geometricgraph-neural-network

Convert multirelational graphs to bipartite graphs with networkx


I have a multi-relational graph G (subject s and object o nodes connected with an edge having a predicate label p), made with networkx.DiGraph. Is there a way to easily and elegantly create its bipartite graph by replacing each labeled edge (s, p, o) with two unlabeled edges {(s,p),(p,o)}? This operation is also called Levi transformation (Levi, 1942) and is aimed to treat each entity and relation equally.

Current graph construction example:

amr_graph = networkx.DiGraph()

for node_id, node_string in amr.nodes.items():
   amr_graph.add_node(node_id, name=node_string)

for subj, pred, obj in amr.edges:
   amr_graph.add_edge(subj, obj, key=pred)

Solution

  • Just create the new edges as you see fit:

    import random
    import networkx as nx
    
    s=[random.randint(0,2) for i in range(10)]
    o=[random.randint(3,5) for i in range(10)]
    p=[random.randint(6,8) for i in range(10)]
    
    G = nx.DiGraph()
    H = nx.DiGraph()
    F = nx.DiGraph()
    
    #split while constructing the orgiginal graph
    for subj, pred, obj in zip(s,p,o):
        G.add_edge(subj, obj, key= pred)
    
        H.add_edge(subj, pred, key = obj)
        H.add_edge(pred, obj, key= subj)
                   
    #use existing graph to split edges              
    for subj, obj, d in G.edges(data=True):
        pred = d['key']
    
        F.add_edge(subj, pred, key = obj)
        F.add_edge(pred, obj, key= subj)