TGraphX › Insights › TGraphX vs Knowledge Graph Toolkits: Where the Boundaries Are
← Back to Insights

TGraphX vs Knowledge Graph Toolkits: Where the Boundaries Are

Topic: Knowledge graphs

"Graph learning" and "knowledge graph embedding" are often mixed up, but they are different problem settings. TGraphX covers both, to different depths. This page explains where one ends and the other begins, what TGraphX's knowledge graph module includes, where it stops, and how to combine knowledge graph embeddings with message passing.

An earlier version of this page said that TGraphX had no triple-scoring functions, no negative sampling for knowledge graph embeddings and no (h, r, t) link prediction metrics. All three statements were wrong: tgraphx.kg provides them, as the first example below shows. Examples tested with TGraphX 1.5.1 on CPU; the Python blocks build on each other.

Two Different Problem Settings

Knowledge graph embedding (KGE) Graph neural network (GNN)
Input triples (head, relation, tail) nodes with features, edges
What is learned one representation per entity and relation weights of message passing layers
Training signal observed triples against corrupted ones node, edge or graph labels, or self-supervision
Core operation scoring a triple (TransE, DistMult, RotatE, ...) aggregating messages from neighbours
Typical task predicting missing facts node or graph classification, regression
Unseen entities ID-based models need retraining possible if the model relies on features, not IDs

The boundary is not sharp. Classic KGE models use only IDs, but literal-aware variants also read entity attributes, and relational GNN encoders with a KGE decoder (the R-GCN approach) combine message passing with triple scoring.

What TGraphX Covers on the Knowledge Graph Side

tgraphx.kg includes:

  • a KnowledgeGraph container with optional entity, relation and triple features;
  • six scoring models: TransE, DistMult, RESCAL and SimplE (beta), ComplEx and RotatE (experimental);
  • four negative samplers: uniform, Bernoulli, filtered and typed;
  • filtered head and tail ranking (KGEvaluator: mean rank, MRR, Hits@k);
  • a trainer (KGTrainer) and a one-call helper (tgx.kg_completion);
  • MultimodalKGModel for entity features and KGRGCNModel, an R-GCN encoder with a DistMult decoder (both Experimental);
  • Experimental temporal knowledge graphs, path extraction and rule mining.

The labels come from tgx.api_status() and the module documentation; "beta" does not mean battle-tested.

A Completion Task, End to End

People work for companies, companies are based in cities, and most people live in their employer's city. Some lives_in facts are held out and predicted from the rest.

python
import torch
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx.kg import (KnowledgeGraph, TransEModel, KGTrainer, KGTrainingConfig,
                        KGEvaluator, UniformNegativeSampler)

torch.set_num_threads(1)
gen = torch.Generator().manual_seed(0)

PEOPLE, COMPANIES, CITIES = 60, 6, 3
NUM_ENTITIES = PEOPLE + COMPANIES + CITIES
WORKS_FOR, BASED_IN, LIVES_IN = 0, 1, 2

employer = torch.randint(COMPANIES, (PEOPLE,), generator=gen)
company_city = torch.arange(COMPANIES) % CITIES
home = company_city[employer].clone()                 # usually the employer's city
moved = torch.rand(PEOPLE, generator=gen) < 0.1
home[moved] = torch.randint(CITIES, (int(moved.sum()),), generator=gen)

people = torch.arange(PEOPLE)
companies = PEOPLE + torch.arange(COMPANIES)
cities = PEOPLE + COMPANIES + torch.arange(CITIES)

def facts(heads, relation, tails):
    return torch.stack([heads, torch.full_like(heads, relation), tails], dim=1)

works_for = facts(people, WORKS_FOR, companies[employer])
based_in = facts(companies, BASED_IN, cities[company_city])
lives_in = facts(people, LIVES_IN, cities[home])

order = torch.randperm(PEOPLE, generator=gen)
train = torch.cat([works_for, based_in, lives_in[order[:40]]])
valid, test = lives_in[order[40:50]], lives_in[order[50:]]
kg = KnowledgeGraph(train, num_entities=NUM_ENTITIES, num_relations=3)

def fit_transe(train_triples, dim):
    torch.manual_seed(0)
    model = TransEModel(NUM_ENTITIES, 3, embedding_dim=dim)
    config = KGTrainingConfig(num_epochs=100, batch_size=32, lr=1e-2,
                              loss_type="margin", seed=0)
    sampler = UniformNegativeSampler(NUM_ENTITIES, num_negatives=4)
    KGTrainer(model, config, train_triples, sampler=sampler).train()
    return model

transe = fit_transe(kg.triples, dim=32)
evaluator = KGEvaluator(train, valid, test, num_entities=NUM_ENTITIES)
result = evaluator.evaluate(transe, triples=test)

rule = (company_city[employer] == home)[order[50:]].float().mean().item()
print(kg)
print(f"TransE, tail side: MRR {result.filt_mrr_tail:.2f}, Hits@1 {result.filt_hits_tail[1]:.2f}")
print(f"rule 'lives where the employer is': Hits@1 {rule:.2f}")
text
KnowledgeGraph(entities=69, relations=3, triples=106)
TransE, tail side: MRR 0.83, Hits@1 0.80
rule 'lives where the employer is': Hits@1 0.80

On ten test facts this shows that the pieces work, nothing more. It also shows a habit worth keeping: compare with the simplest rule you can write.

Where TGraphX's Knowledge Graph Support Stops

  • Datasets. tgraphx.kg ships synthetic datasets only, with no loader for benchmarks such as FB15k-237 or WN18RR. KnowledgeGraph.load_tsv reads integer IDs only, so it raises ValueError on files with string names, as in the usual copies of those benchmarks. Read the rows yourself and pass the string tuples to KnowledgeGraph.from_triples, which builds entity_to_id and relation_to_id. With separate train, validation and test files, build the two mappings once from all rows and pass them to every call, with num_entities and num_relations; otherwise one name can get different IDs in different splits.
  • Training. KGTrainer trains with sampled negatives (margin, BCE or softplus loss). It has no 1-vs-all training, and although it can record validation metrics, it does not stop early or restore the best epoch.
  • Scale. The evaluator ranks one test triple at a time in a Python loop. Nothing here was tested on large knowledge graphs.
  • Breadth. Six scoring functions. Others you write yourself by subclassing KGScoringModel.
  • Search. run_kg_hpo is a small grid or random search. Its main limitation: each trial draws its own random 80/20 split of the triples you pass, so trials are scored on different holdouts. The other limits are listed under Hyperparameter search in TGraphX vs PyKEEN.
  • Rough edges. KGTrainer needs an explicit sampler for ComplEx, RotatE and SimplE, and cannot train MultimodalKGModel. Do not train KGRGCNModel with it either. With in_dim set it raises ValueError. With the default in_dim=None it runs without an error, but it scores triples from the raw entity embeddings, so message passing is skipped and the R-GCN weights never change. Write the loop yourself: call encode() and pass the result to score_triples(triples, table). KGEvaluator calls score_triples(triples) too, so give it a wrapper that holds the encoded table, such as Frozen in the tensor entity features tutorial.

For benchmark research, a dedicated library is the better tool. PyKEEN is a widely used one; the feature-by-feature view is in TGraphX vs PyKEEN. PyTorch Geometric also ships TransE, DistMult, ComplEx and RotatE in torch_geometric.nn.kge.

What TGraphX Provides for GNN Work

The other side of the boundary is where most of TGraphX sits:

  • node features of image or volume shape, such as [N, C, H, W], in the tensor layers (SAGE, GAT, GIN, convolutional message passing);
  • standard vector layers (GCNConv, GATv2Conv, APPNP);
  • shape and index validation when a Graph is constructed;
  • image-patch and graph builders such as image_to_patches and build_grid_graph;
  • experiment helpers (config-driven runs, report writers, seeding).

Combining the Two

KGE embeddings as node features

A common pipeline: learn entity embeddings from the triples, use them as node features, then train a GNN for a downstream task. Here the task is to predict each person's city. That is exactly what lives_in states, so those facts must be removed both from embedding training and from the message-passing graph:

python
from tgraphx.estimators import EarlyStopping

structure = torch.cat([works_for, based_in])        # lives_in is the label: leave it out
embeddings = fit_transe(structure, dim=16).entity_emb.weight.detach().clone()

forward_edges = torch.stack([structure[:, 0], structure[:, 2]])
edge_index = torch.cat([forward_edges, forward_edges.flip(0)], dim=1)
edge_type = structure[:, 1].repeat(2)

labels = torch.zeros(NUM_ENTITIES, dtype=torch.long)
labels[:PEOPLE] = home
train_mask = torch.zeros(NUM_ENTITIES, dtype=torch.bool)
val_mask, test_mask = train_mask.clone(), train_mask.clone()
train_mask[order[:30]] = True
val_mask[order[30:45]] = True
test_mask[order[45:]] = True

g = tgx.Graph(node_features=embeddings, edge_index=edge_index, edge_labels=edge_type,
              node_labels=labels, train_mask=train_mask, val_mask=val_mask,
              test_mask=test_mask)

def test_accuracy(features, seed):
    """Two-layer GCN on fixed node features, early stopping on validation loss."""
    torch.manual_seed(seed)
    net = torch.nn.ModuleList([tgx.GCNConv(16, 16), tgx.GCNConv(16, CITIES)])

    def logits():
        return net[1](F.relu(net[0](features, g.edge_index)), g.edge_index)

    optimizer = torch.optim.Adam(net.parameters(), lr=1e-2)
    stopper, best_state = EarlyStopping(patience=20, mode="min"), None
    for epoch in range(200):
        optimizer.zero_grad()
        F.cross_entropy(logits()[g.train_mask], g.y[g.train_mask]).backward()
        optimizer.step()
        with torch.no_grad():
            val_loss = F.cross_entropy(logits()[g.val_mask], g.y[g.val_mask]).item()
        stop = stopper.step(val_loss)
        if stopper.counter == 0:
            best_state = {k: v.clone() for k, v in net.state_dict().items()}
        if stop:
            break
    net.load_state_dict(best_state)
    with torch.no_grad():
        return (logits().argmax(1) == g.y)[g.test_mask].float().mean().item()

def random_ids(seed):
    """ID-only baseline: one random vector per entity, nothing learned from triples."""
    return torch.randn(NUM_ENTITIES, 16, generator=torch.Generator().manual_seed(1000 + seed))

kge_runs = torch.tensor([test_accuracy(g.node_features, s) for s in range(10)])
id_runs = torch.tensor([test_accuracy(random_ids(s), s) for s in range(10)])
majority = torch.bincount(g.y[g.train_mask]).argmax()
for name, acc in [("GNN on KGE features", kge_runs), ("GNN on random vectors", id_runs)]:
    print(f"{name + ':':23s}mean {acc.mean():.2f}, range {acc.min():.2f} to {acc.max():.2f}")
print(f"majority class:        {(g.y[g.test_mask] == majority).float().mean().item():.2f}")
print(f"employer-city rule:    {(company_city[employer] == home)[order[45:]].float().mean().item():.2f}")
text
GNN on KGE features:   mean 0.87, range 0.87 to 0.87
GNN on random vectors: mean 0.72, range 0.53 to 0.87
majority class:        0.27
employer-city rule:    0.87

All of this is one data seed with 15 test people, so one person is worth about 0.07 of accuracy. The ten runs vary only the GNN initialisation and, for the baseline, the random vectors.

The random-vector run is the one to read first. It is far above the majority class, so message passing over works_for and based_in recovers much of the two-step pattern (person, company, city) without any embedding training; only the gap between the first two rows is what the KGE features add here. The KGE version matches the hand-written rule on this data seed. In a repeat of the comparison on 25 data seeds (not shown, one training run each), it tied the rule on 14, scored below it on 11 and never beat it, so on average it is behind the rule; against the random vectors it was ahead on 19, level on 4 and behind on 2. Note also that GCNConv ignores relation types; they are kept in edge_labels so that a relational layer can use them.

A relational encoder with a KGE decoder

Instead of two stages, you can train a relation-aware GNN and a triple scorer together. KGRGCNModel provides an R-GCN encoder and a DistMult decoder for this, to be trained with your own loop (see the rough edges above); the knowledge graph tutorial with tensor entity features walks through it, including entity classification.

Leakage checklist for hybrids

  • Train embeddings and build the message-passing graph from training triples only.
  • Remove any relation that states, or is derived from, the label you are predicting.
  • Split nodes or triples before adding inverse relations.
  • Compare with an ID-only baseline and with a simple rule.

When to Use Each

  • Entities are just IDs and you want missing facts: a KGE model. tgraphx.kg is reasonable for prototypes and teaching; use a dedicated KGE library for benchmarks and large graphs.
  • Nodes carry features and you want classification or regression: a GNN, with TGraphX or another GNN library.
  • Typed relations and entity features: a relational encoder with a KGE decoder, or a multimodal KGE model. Check that it beats the ID-only version.
  • An ordinary untyped graph and link prediction: a GNN encoder with an edge scorer, or neighbourhood heuristics; no KGE machinery is needed.

A Note on "Knowledge Graph" Terminology

The term is used loosely. It can mean a formal knowledge base with typed relations, a large graph that happens to come from a knowledge source, or any labelled graph. The name does not decide the tool. Ask what you need to predict, whether relations are typed, and whether entities have usable features.

Related Guides