Graph Learning for NLP: Text-to-Graph Pipelines
Language models process text as sequences. But language is also relational: words modify other words, sentences mention shared entities, documents cite each other. Representing text as a graph gives a model a different set of inductive biases: message passing can connect two words or entities that are far apart in the sequence but close in the graph.
This article builds dependency graphs and entity co-occurrence graphs as TGraphX Graph objects, turns text into node features, and trains a GNN that classifies one graph per document. It ends with what such a model can and cannot do compared with sequence models.
Examples tested with TGraphX 1.5.1 on CPU.
Why Represent Text as a Graph
Three common graph representations motivate the approach differently:
Dependency parse graphs represent a sentence's syntax. Each token is a node and edges encode grammatical dependencies (subject, object, modifier). For tasks such as relation extraction, where the relationship between two entities depends on the syntactic path between them, traversing that path is natural for a GNN.
Entity co-occurrence graphs connect entities (people, organizations, places) that appear in the same sentence. They can be built per document, as here, or over a whole collection to show which entities are discussed together.
Document graphs (TextRank-style) use sentences as nodes and connect sentences that share vocabulary or are semantically similar. TextRank (Mihalcea and Tarau, 2004) is a classic graph method for extractive summarization.
If you only need sentence-window and similarity edges, start with the minimal article-to-graph pipeline.
Prerequisites
- TGraphX (
pip install tgraphx) - For real text: a parser and entity recognizer (for example spaCy) and a text encoder (for example sentence-transformers). TGraphX does not include either.
- Basic familiarity with PyTorch tensors
Parsing and encoding happen outside TGraphX. The graph construction below takes their output (token lists, head indices, entity lists), so you can run and test it without any NLP model. To keep the examples self-contained, a small character-trigram hashing encoder stands in for a real encoder.
Building a Dependency Parse Graph
Each token is a node. A parser gives every token the index of its head; the root points to itself.
import zlib
import torch
import torch.nn as nn
import torch.nn.functional as F
from tgraphx import Graph
class HashingEncoder:
"""Stand-in text encoder: hashed character trigrams. Not a semantic model."""
def __init__(self, dim=64):
self.dim = dim
def encode(self, texts):
out = torch.zeros(len(texts), self.dim)
for row, text in enumerate(texts):
padded = f"#{text.lower()}#"
for i in range(len(padded) - 2):
out[row, zlib.crc32(padded[i:i + 3].encode()) % self.dim] += 1.0
return F.normalize(out, dim=1)
def encode_texts(texts, encoder):
# works with encoders returning NumPy arrays or tensors
return torch.as_tensor(encoder.encode(texts), dtype=torch.float)
def dependency_graph(tokens, heads, encoder):
"""heads[i] is the index of token i's head; the root has heads[i] == i."""
child = [i for i, h in enumerate(heads) if h != i]
parent = [heads[i] for i in child]
edge_index = torch.tensor([child + parent, parent + child], dtype=torch.long) # both directions
return Graph(node_features=encode_texts(tokens, encoder), edge_index=edge_index)
encoder = HashingEncoder(dim=64)
tokens = ["The", "researchers", "published", "their", "findings", "."]
heads = [1, 2, 2, 4, 2, 2] # "published" is the root
g = dependency_graph(tokens, heads, encoder)
print(g.num_nodes, g.num_edges, g.feature_shape) # 6 10 (64,)
Adding both directions lets information flow up and down the tree, but it discards which end was the head. If direction or dependency labels matter, use a relational layer with one relation per edge type. RGCNConv takes a dictionary of edge indices:
from tgraphx.layers.rgcn import RGCNConv
child = torch.tensor([i for i, h in enumerate(heads) if h != i])
parent = torch.tensor([heads[i] for i in child.tolist()])
by_relation = {0: torch.stack([child, parent]), # child -> head
1: torch.stack([parent, child])} # head -> child
conv = RGCNConv(64, 32, num_relations=2)
print(conv(g.node_features, by_relation, num_nodes=g.num_nodes).shape) # torch.Size([6, 32])
Building an Entity Co-Occurrence Graph
Here the input is the recognizer's output: one list of entity strings per sentence. Entities in the same sentence are connected.
from collections import Counter
from itertools import combinations
def cooccurrence_graph(sentence_entities, encoder, min_count=1, label=None):
entities = sorted({e for sentence in sentence_entities for e in sentence})
if not entities:
entities = ["<no entity>"] # keep one node so batching stays aligned
index = {e: i for i, e in enumerate(entities)}
counts = Counter()
for sentence in sentence_entities:
for a, b in combinations(sorted(set(sentence)), 2): # set(): no self-loops
counts[(index[a], index[b])] += 1
pairs = [pair for pair, c in counts.items() if c >= min_count]
edge_index = torch.tensor(pairs, dtype=torch.long).reshape(-1, 2).t()
edge_index = torch.cat([edge_index, edge_index.flip(0)], dim=1) # undirected
graph_label = None if label is None else torch.tensor(label)
graph = Graph(node_features=encode_texts(entities, encoder), edge_index=edge_index,
graph_label=graph_label)
return graph, entities # entities[i] names node i
doc = [["ada park", "globex", "london"], ["globex", "initech"], []]
graph, names = cooccurrence_graph(doc, encoder)
print(names) # ['ada park', 'globex', 'initech', 'london']
print(graph.edge_index.shape) # torch.Size([2, 8])
empty_graph, empty_names = cooccurrence_graph([[]], encoder)
print(empty_graph.num_nodes, empty_graph.num_edges) # 1 0
Two details matter. A document with no co-occurrences gets an empty [2, 0] edge index, not a made-up edge. A document with no entities gets a placeholder node, because TGraphX's pooling functions infer the number of graphs from the batch vector: a graph with zero nodes at the end of a batch would get no output row, and predictions would no longer line up with labels.
A min_count above 1 removes one-off pairs. This is usually only sensible for large collections; in a short document it can remove every edge.
Using a Real Parser and Encoder
With spaCy and sentence-transformers installed, the wiring looks like this. It is not executed as part of this article because it needs downloaded models.
import spacy
from sentence_transformers import SentenceTransformer
nlp = spacy.load("en_core_web_sm") # python -m spacy download en_core_web_sm
text_encoder = SentenceTransformer("all-MiniLM-L6-v2") # 384-dimensional embeddings
parsed = nlp("The researchers published their findings.")
g_real = dependency_graph([t.text for t in parsed], [t.head.i for t in parsed], text_encoder)
parsed = nlp("Ada Park joined Globex in London. Globex later bought Initech.")
entities = [[ent.text.lower() for ent in sent.ents] for sent in parsed.sents]
graph_real, names_real = cooccurrence_graph(entities, text_encoder)
Node features matter a lot. Randomly initialized features say nothing about the text. Note that encoding each token on its own, as above, loses its context. For contextual token features, run a transformer over the whole sentence and pool its subword vectors back to the parser's tokens. For large corpora, encode once, save the tensors, and load them during training.
A Complete Text Classification Pipeline
The corpus below is a toy: two topics with different entity vocabularies plus a few shared entities. It exists to check the plumbing end to end, not to show model quality.
GATv2Conv(in_dim, out_dim, num_heads) works on vector features [N, D]. Its out_dim is the total width across heads, so the second layer's input size is hidden_dim, not hidden_dim * num_heads.
import random
from tgraphx import GATv2Conv, GraphDataLoader, GraphDataset, global_mean_pool
TOPICS = {0: ["acme corp", "globex", "initech", "ada park", "tim lee", "silicon valley"],
1: ["amazon river", "andes", "peru", "maria silva", "rainforest", "kofi mensah"]}
SHARED = ["london", "united nations", "university"]
rng = random.Random(0)
def toy_document(label):
return [rng.sample(TOPICS[label], 2) + rng.sample(SHARED, 1) for _ in range(rng.randint(1, 4))]
dataset = [cooccurrence_graph(toy_document(i % 2), encoder, label=i % 2)[0] for i in range(200)]
train_set, test_set = dataset[:150], dataset[150:] # split by document
class TextGraphClassifier(nn.Module):
def __init__(self, in_dim, hidden_dim, num_classes, num_heads=4):
super().__init__()
self.gat1 = GATv2Conv(in_dim, hidden_dim, num_heads=num_heads)
self.gat2 = GATv2Conv(hidden_dim, hidden_dim, num_heads=num_heads)
self.classifier = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim // 2), nn.ReLU(), nn.Dropout(0.3),
nn.Linear(hidden_dim // 2, num_classes),
)
def forward(self, x, edge_index, batch):
x = F.elu(self.gat1(x, edge_index))
x = F.elu(self.gat2(x, edge_index))
return self.classifier(global_mean_pool(x, batch)) # one row per document
torch.manual_seed(0)
model = TextGraphClassifier(in_dim=64, hidden_dim=64, num_classes=2)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
train_loader = GraphDataLoader(GraphDataset(train_set), batch_size=16, shuffle=True)
test_loader = GraphDataLoader(GraphDataset(test_set), batch_size=16)
for epoch in range(10):
model.train()
for batch in train_loader: # yields GraphBatch objects
optimizer.zero_grad()
logits = model(batch.node_features, batch.edge_index, batch.batch)
loss = F.cross_entropy(logits, batch.graph_labels)
loss.backward()
optimizer.step()
model.eval()
correct = 0
with torch.no_grad():
for batch in test_loader:
logits = model(batch.node_features, batch.edge_index, batch.batch)
correct += int((logits.argmax(1) == batch.graph_labels).sum())
print(f"test accuracy on the toy corpus: {correct / len(test_set):.2f}")
On this toy corpus the entity vocabularies give the answer away, so a high accuracy means only that graphs, labels and pooling are wired correctly. For a real task, add a validation split, compare against a text-only baseline, and report both.
To see which entities influenced one prediction, gradient saliency works on a single document graph:
from tgraphx.explain import node_feature_saliency
graph, names = cooccurrence_graph([["globex", "ada park", "london"], ["initech", "globex"]], encoder)
saliency = node_feature_saliency(model, graph, target=0).sum(dim=1) # one score per node
for name, score in sorted(zip(names, saliency.tolist()), key=lambda p: -p[1]):
print(f"{name:12s} {score:.4f}")
Saliency shows local sensitivity of the class score to a node's features. It is not proof that an entity caused the decision.
Graph Construction Choices and Their Effects
Sliding-window co-occurrence connects words that appear within a fixed window (for example 3 words). It is cheap and captures local context, but long documents give large graphs.
Semantic similarity edges connect sentences or entities with similar embeddings. They can link distant parts of a document, but a naive implementation compares all pairs, which is O(N²) for N nodes.
Dependency edges give sparse graphs tied to syntax. They suit sentence-level tasks and need a parser.
Citation or hyperlink edges use link structure that exists outside the text. When your corpus has them (scientific papers, Wikipedia), they can carry information the text alone does not.
There is no single best choice. It depends on the task, the documents and the preprocessing budget.
Limitations vs Sequence Models
Transformers are pretrained at large scale. BERT, for example, was pretrained on about 3.3 billion words from BooksCorpus and English Wikipedia (Devlin et al., 2019). A GNN trained from scratch on your graphs sees only your data. Using transformer embeddings as node features narrows this gap but does not turn the GNN into a language model.
Graph construction loses information. Once text becomes a graph, word order is gone unless you encode it. "Not good" and "good" can end up looking alike.
Transductive or inductive depends on the construction. Corpus-level graphs, such as TextGCN's word-document graph (Yao et al., 2019), put test documents into the training graph and are normally used transductively. The per-document graphs in this article are inductive: a new document gets its own graph and a forward pass.
Extraction errors compound at the edge level. An edge needs both of its endpoints. If an entity recognizer has 85% precision and 80% recall, and errors were independent, only about 72% of co-occurrence edges would be correct (0.85²) and about 64% of true edges would be found (0.8²). Real errors are not independent, but node errors always propagate to edges.
Parsers are language-specific. Multilingual settings need a parser per language.
Text graphs are most promising when there is relational structure beyond the token sequence, such as citations, hyperlinks or reply trees, and you want to combine it with the content. Whether a GNN helps there is an empirical question: measure it against a text-only baseline.
Connecting to TGraphX Modules
Once text is a Graph, other parts of the library apply:
tgraphx.miningfor structural analysis of entity graphs. Its community detection offers label propagation and spectral clustering; these group nodes (entities), not documents.tgraphx.mining.link_predictionfor scoring unconnected entity pairs. These scores suggest candidate associations, not typed relations.tgraphx.explainfor saliency and edge attribution, as above.tgraphx.CSVLoggerplus thetgraphx-dashboardcommand to review metrics you log.
For the mining tools, see the graph mining overview. For scoring entity pairs, see the link prediction scoring functions guide.
Frequently Asked Questions
Can I use TGraphX for knowledge graph completion from text? Partly. Completion needs typed triples, so you first need relation extraction; co-occurrence edges are not typed relations. tgraphx.kg provides embedding models and ranking, and precomputed text vectors can be used as entity features. See the knowledge graph embedding tutorial.
How do I handle documents of very different lengths? Graph sizes may differ within a GraphBatch; pooling produces one vector per graph. Mean pooling hides document length, so add it as a feature if it matters.
Should I use a GNN or BERT for text classification? Start with a fine-tuned transformer or even a bag-of-words baseline. Add a graph model when you have structure those baselines cannot see.
What node feature dimension should I use? Match your encoder, for example 384 for all-MiniLM-L6-v2 or 768 for BERT-base. The first GNN layer maps it to your hidden size.
References
- Mihalcea, R. and Tarau, P. (2004). TextRank: bringing order into text. EMNLP.
- Devlin, J., Chang, M.-W., Lee, K. and Toutanova, K. (2019). BERT: pre-training of deep bidirectional transformers for language understanding. NAACL.
- Yao, L., Mao, C. and Luo, Y. (2019). Graph convolutional networks for text classification. AAAI.