Dependency trees to DGL graphs

Hello,

Do you have any example on how to convert dependency trees (from spacy or stanford corenlp) into DGL graphs that can serve as input to your TreeLSTM model?

Thanks in advance!

We don’t have the dataset in DGL currently. Welcome contribution! I guess if you could first convert it to networkx graph, then it can be converted to DGLGraph easily.

nlp = spacy.load("en_core_web_sm")    
doc = nlp(u'The last reply to this topic was 10 months ago.')

Load spacy’s dependency tree into a networkx graph

edges = []
for token in doc:
    for child in token.children:
        edges.append(('{0}'.format(token.lower_),
                      '{0}'.format(child.lower_)))

visualize the dependency tree in google colab

spacy.displacy.render(doc, style='dep', jupyter=True)

convert networkx graph to dgl graph

graph = nx.Graph(edges)
g = dgl.DGLGraph()
g.from_networkx(graph)

function to visualize the graph created

def plot_tree(g):
    pos = nx.nx_agraph.graphviz_layout(g, prog='dot')
    nx.draw(g, pos, with_labels=False, node_size=10,
            node_color=[[.5, .5, .5]], arrowsize=4)
    plt.show()

Visualize dgl graph as a networkx graph

plot_tree(g.to_networkx())

2 Likes

I have written a python script to create a DGL graph object using a spacy dependency parser, unlike the above answers it doesn’t require the networkx package.

2 Likes