Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 6: Knowledge Graphs — Implementation

Open in Colab
  1. A triple store and pattern queries, from scratch

  2. RDFS inference by forward chaining, from scratch

  3. The same graph with rdflib: Turtle and SPARQL

  4. Graph analytics with networkx

  5. Link prediction: TransE against simple rules on a family graph

119 facts, for example [('AbuDhabi', 'capitalOf', 'UnitedArabEmirates'), ('AbuDhabi', 'locatedIn', 'UnitedArabEmirates'), ('Abuja', 'capitalOf', 'Nigeria')]

1. A Triple Store from Scratch

Three indexes (by subject, by predicate, by object) let us find the matches of a pattern quickly. None is a wildcard.

Arabic-speaking: ['Algeria', 'Egypt', 'Jordan', 'Morocco', 'Qatar', 'SaudiArabia', 'Tunisia', 'UnitedArabEmirates']
about Belgium  : [('language', 'Dutch'), ('language', 'French'), ('language', 'German'), ('locatedIn', 'Europe'), ('memberOf', 'EuropeanUnion')]

Basic graph patterns

A query is a list of triple patterns in which strings starting with ? are variables. query finds all bindings that satisfy every pattern, by backtracking: match the first pattern, substitute its bindings into the rest, recurse.

capitals of Arabic-speaking African countries: [('Algiers', 'Algeria'), ('Cairo', 'Egypt'), ('Rabat', 'Morocco'), ('Tunis', 'Tunisia')]
EU countries with more than one main language: ['Belgium']

2. RDFS Inference by Forward Chaining

The schema of Section 6.3, plus a rule for transitive locatedIn (an OWL feature). Each rule produces new triples from existing ones; we apply all rules until no new triple appears (a fixpoint).

119 triples -> 281 after 3 rounds of inference
Riyadh is a: ['Capital', 'City', 'Place']
Riyadh is located in: ['Asia', 'SaudiArabia']
places in Africa: 12

Nobody wrote that Riyadh is a place, or that it is in Asia: the reasoner derived it.

3. rdflib: Turtle and SPARQL

rdflib is a standard Python library for RDF. We load the same facts, with IRIs, and an English label for each entity.

211 triples. A sample in Turtle:

@prefix ex: <http://example.org/> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

ex:AbuDhabi a ex:Capital ;
    rdfs:label "Abu Dhabi"@en ;
    ex:capitalOf ex:UnitedArabEmirates ;
    ex:locatedIn ex:UnitedArabEmirates .

ex:Abuja a ex:Capital ;
    rdfs:label "Abuja"@en ;
    ex:capitalOf ex:Nigeria ;
    ex:locatedIn ex:Nigeria .

ex:Algiers a ex:Capital ;
    rdfs:label "Algiers"@en ;
    ex:capitalOf ex:Algeria ;
    ex:locatedIn ex:Algeria .

1. Capitals of Arabic-speaking countries in Africa:
[['Algiers', 'Algeria'], ['Cairo', 'Egypt'], ['Rabat', 'Morocco'], ['Tunis', 'Tunisia']]

2. Languages by number of countries (GROUP BY, COUNT):
[['Arabic', '8'], ['English', '4'], ['Spanish', '3'], ['French', '3'], ['German', '3']]

3. African countries and, if any, a membership other than the African Union (OPTIONAL, FILTER):
[['Algeria', 'ArabLeague'], ['Egypt', 'ArabLeague'], ['Kenya', '—'], ['Morocco', 'ArabLeague'], ['Nigeria', '—'], ['Tunisia', 'ArabLeague']]

4. Capitals whose English label contains "Abu" or "Buenos" (FILTER with a regular expression):
[['AbuDhabi', 'Abu Dhabi'], ['BuenosAires', 'Buenos Aires'], ['Abuja', 'Abuja']]

5. Capitals located, through one or more steps, in Europe (property path locatedIn+):
['Berlin', 'Brussels', 'Lisbon', 'Madrid', 'Paris', 'Rome', 'Vienna']

Query 3 shows the open world: countries without a second membership still appear, with “—” where OPTIONAL found nothing. Query 5 needs no inferred facts: the property path follows locatedIn twice (capital → country → continent) at query time.

4. Graph Analytics

Treating the graph as a network: the shortest connection between two entities, and the most central nodes.

Riyadh to Tunis: Riyadh —[capitalOf]— SaudiArabia —[language]— Arabic —[language]— Tunisia —[capitalOf]— Tunis
Ottawa to Paris: Ottawa —[capitalOf]— Canada —[language]— French —[language]— France —[locatedIn]— Paris
most central entities: [('Europe', 0.033), ('EuropeanUnion', 0.033), ('Arabic', 0.032), ('ArabLeague', 0.032), ('Belgium', 0.03), ('Morocco', 0.025)]

Facts about countries are few and irregular. To study link prediction we use a synthetic family graph, where we know the truth: 40 families over three generations with the relations parentOf, childOf, spouseOf, siblingOf and grandparentOf. We hide 10% of the triples and try to predict them back.

2428 triples, 496 people; 2186 for training, 242 hidden for testing

TransE

Entities and relations get 50-dimensional vectors. Training: margin loss against triples whose head or tail is replaced by a random entity; entity vectors are kept at length 1.

Rules mined from the training graph

The rule baseline uses compositions that hold in families, checked against the training triples only: childOf is the inverse of parentOf; spouseOf and siblingOf are symmetric; grandparentOf is parentOf followed by parentOf; siblings share a parent. A candidate gets one point per rule that proposes it; ties are broken at random.

relation         n   TransE                                 rules
childOf         66   Hits@1 0.12   Hits@10 0.89   MRR 0.40   Hits@1 0.88   Hits@10 0.88   MRR 0.88
grandparentOf   45   Hits@1 0.36   Hits@10 0.84   MRR 0.52   Hits@1 0.82   Hits@10 0.82   MRR 0.82
parentOf        62   Hits@1 0.19   Hits@10 0.89   MRR 0.43   Hits@1 0.95   Hits@10 0.95   MRR 0.95
siblingOf       44   Hits@1 0.00   Hits@10 0.98   MRR 0.34   Hits@1 1.00   Hits@10 1.00   MRR 1.00
spouseOf        25   Hits@1 0.00   Hits@10 0.88   MRR 0.33   Hits@1 1.00   Hits@10 1.00   MRR 1.00
all            242   Hits@1 0.15   Hits@10 0.90   MRR 0.41   Hits@1 0.92   Hits@10 0.92   MRR 0.92

What the numbers say.

  • TransE puts the right answer in its top 10 about 90% of the time, but first only rarely. For the symmetric relations it is never first: if h+r≈t\mathbf{h} + \mathbf{r} \approx \mathbf{t} and t+r≈h\mathbf{t} + \mathbf{r} \approx \mathbf{h}, then r≈0\mathbf{r} \approx \mathbf{0} and siblings, spouses and the person themself all look alike. This is the known limit of TransE; models such as RotatE were designed to fix it.

  • The rules are almost perfect where the needed facts survived in the training graph, because family relations really are compositions. But someone had to know (or mine) the rules, and they fail completely when a needed fact is missing.

  • On real knowledge graphs, which are noisy and whose regularities are only partly known, the two approaches are combined: rules where they are reliable, embeddings to rank everything else.

Summary

SectionResult
1a triple store with three indexes and a backtracking matcher answers graph-pattern queries
2forward chaining with five RDFS/OWL rules more than doubles the stated facts
3rdflib loads the same graph; SPARQL with joins, GROUP BY, OPTIONAL, FILTER and property paths
4networkx finds connecting paths and central entities
5TransE ranks well but struggles with symmetric relations; rules are exact where they apply