Chapter 6: Knowledge Graphs — Implementation
A triple store and pattern queries, from scratch
RDFS inference by forward chaining, from scratch
The same graph with rdflib: Turtle and SPARQL
Graph analytics with networkx
Link prediction: TransE against simple rules on a family graph
import itertools
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
# country, capital, continent, main language(s), organisations
COUNTRIES = [
('SaudiArabia', 'Riyadh', 'Asia', ['Arabic'], ['ArabLeague']),
('Egypt', 'Cairo', 'Africa', ['Arabic'], ['ArabLeague', 'AfricanUnion']),
('Tunisia', 'Tunis', 'Africa', ['Arabic'], ['ArabLeague', 'AfricanUnion']),
('Morocco', 'Rabat', 'Africa', ['Arabic', 'Berber'], ['ArabLeague', 'AfricanUnion']),
('Algeria', 'Algiers', 'Africa', ['Arabic', 'Berber'], ['ArabLeague', 'AfricanUnion']),
('Jordan', 'Amman', 'Asia', ['Arabic'], ['ArabLeague']),
('UnitedArabEmirates', 'AbuDhabi', 'Asia', ['Arabic'], ['ArabLeague']),
('Qatar', 'Doha', 'Asia', ['Arabic'], ['ArabLeague']),
('France', 'Paris', 'Europe', ['French'], ['EuropeanUnion']),
('Belgium', 'Brussels', 'Europe', ['Dutch', 'French', 'German'], ['EuropeanUnion']),
('Germany', 'Berlin', 'Europe', ['German'], ['EuropeanUnion']),
('Austria', 'Vienna', 'Europe', ['German'], ['EuropeanUnion']),
('Italy', 'Rome', 'Europe', ['Italian'], ['EuropeanUnion']),
('Spain', 'Madrid', 'Europe', ['Spanish'], ['EuropeanUnion']),
('Portugal', 'Lisbon', 'Europe', ['Portuguese'], ['EuropeanUnion']),
('Brazil', 'Brasilia', 'SouthAmerica', ['Portuguese'], []),
('Argentina', 'BuenosAires', 'SouthAmerica', ['Spanish'], []),
('Colombia', 'Bogota', 'SouthAmerica', ['Spanish'], []),
('Canada', 'Ottawa', 'NorthAmerica', ['English', 'French'], []),
('Japan', 'Tokyo', 'Asia', ['Japanese'], []),
('Kenya', 'Nairobi', 'Africa', ['Swahili', 'English'], ['AfricanUnion']),
('Nigeria', 'Abuja', 'Africa', ['English'], ['AfricanUnion']),
('Australia', 'Canberra', 'Oceania', ['English'], []),
]
facts = set()
for country, capital, continent, languages, orgs in COUNTRIES:
facts |= {(capital, 'capitalOf', country), (capital, 'locatedIn', country), (country, 'locatedIn', continent)}
facts |= {(country, 'language', l) for l in languages} | {(country, 'memberOf', o) for o in orgs}
print(len(facts), 'facts, for example', sorted(facts)[:3])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.
class TripleStore:
def __init__(self, triples=()):
self.triples = set()
self.by_s, self.by_p, self.by_o = defaultdict(set), defaultdict(set), defaultdict(set)
for t in triples:
self.add(t)
def add(self, t):
if t not in self.triples:
self.triples.add(t)
self.by_s[t[0]].add(t); self.by_p[t[1]].add(t); self.by_o[t[2]].add(t)
return True
return False
def match(self, s=None, p=None, o=None):
candidates = [self.by_s[s] if s else None, self.by_p[p] if p else None, self.by_o[o] if o else None]
candidates = [c for c in candidates if c is not None]
if not candidates:
return set(self.triples)
return set.intersection(*sorted(candidates, key=len))
kg = TripleStore(facts)
print('Arabic-speaking:', sorted(s for s, _, _ in kg.match(p='language', o='Arabic')))
print('about Belgium :', sorted((p, o) for _, p, o in kg.match(s='Belgium')))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.
def is_var(x):
return isinstance(x, str) and x.startswith('?')
def query(store, patterns, binding=None):
binding = binding or {}
if not patterns:
return [binding]
s, p, o = (binding.get(x, x) if is_var(x) else x for x in patterns[0])
results = []
for ts, tp, to in store.match(None if is_var(s) else s, None if is_var(p) else p, None if is_var(o) else o):
new, ok = dict(binding), True
for var, val in ((s, ts), (p, tp), (o, to)):
if is_var(var):
if new.get(var, val) != val: ok = False
new[var] = val
if ok:
results += query(store, patterns[1:], new)
return results
answers = query(kg, [('?capital', 'capitalOf', '?country'), ('?country', 'language', 'Arabic'), ('?country', 'locatedIn', 'Africa')])
print('capitals of Arabic-speaking African countries:', sorted((a['?capital'], a['?country']) for a in answers))
two_langs = query(kg, [('?c', 'language', '?l1'), ('?c', 'language', '?l2'), ('?c', 'memberOf', 'EuropeanUnion')])
print('EU countries with more than one main language:', sorted({a['?c'] for a in two_langs if a['?l1'] < a['?l2']}))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).
SCHEMA = {('Capital', 'subClassOf', 'City'), ('City', 'subClassOf', 'Place'), ('Country', 'subClassOf', 'Place'),
('Continent', 'subClassOf', 'Place'),
('capitalOf', 'domain', 'Capital'), ('capitalOf', 'range', 'Country'),
('language', 'domain', 'Country'), ('language', 'range', 'Language'),
('memberOf', 'range', 'Organisation')}
TRANSITIVE = {'locatedIn'}
def infer(store, schema):
for t in schema:
store.add(t)
rounds = 0
while True:
rounds += 1
new = set()
for a, _, b in store.match(p='subClassOf'): # transitivity of subClassOf
new |= {(a, 'subClassOf', c) for _, _, c in store.match(s=b, p='subClassOf')}
for x, _, c in store.match(p='type'): # type inheritance
new |= {(x, 'type', d) for _, _, d in store.match(s=c, p='subClassOf')}
for prop, _, c in store.match(p='domain'): # domain
new |= {(x, 'type', c) for x, _, _ in store.match(p=prop)}
for prop, _, c in store.match(p='range'): # range
new |= {(y, 'type', c) for _, _, y in store.match(p=prop)}
for prop in TRANSITIVE: # transitive properties
for x, _, y in store.match(p=prop):
new |= {(x, prop, z) for _, _, z in store.match(s=y, p=prop)}
added = sum(store.add(t) for t in new)
if added == 0:
return rounds
before = len(kg.triples)
rounds = infer(kg, SCHEMA)
print(f'{before} triples -> {len(kg.triples)} after {rounds} rounds of inference')
print('Riyadh is a:', sorted(o for _, _, o in kg.match(s='Riyadh', p='type')))
print('Riyadh is located in:', sorted(o for _, _, o in kg.match(s='Riyadh', p='locatedIn')))
print('places in Africa:', len(query(kg, [('?x', 'locatedIn', 'Africa')])))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.
import re
from rdflib import Graph, Namespace, Literal, RDF, RDFS
EX = Namespace('http://example.org/')
g = Graph(); g.bind('ex', EX)
for s, p, o in facts:
g.add((EX[s], EX[p], EX[o]))
for country, capital, continent, languages, orgs in COUNTRIES:
g.add((EX[country], RDF.type, EX.Country)); g.add((EX[capital], RDF.type, EX.Capital))
for name in (country, capital):
g.add((EX[name], RDFS.label, Literal(re.sub(r'(?<!^)(?=[A-Z])', ' ', name), lang='en')))
print(len(g), 'triples. A sample in Turtle:\n')
print('\n'.join(g.serialize(format='turtle').split('\n')[:18]))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 .
def sparql(q):
rows = [[str(v).replace('http://example.org/', '') if v is not None else '—' for v in row] for row in g.query(q)]
return rows
PREFIX = 'PREFIX ex: <http://example.org/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> '
print('1. Capitals of Arabic-speaking countries in Africa:')
print(sparql(PREFIX + 'SELECT ?capital ?country WHERE { ?capital ex:capitalOf ?country . ?country ex:language ex:Arabic ; ex:locatedIn ex:Africa . } ORDER BY ?capital'))
print('\n2. Languages by number of countries (GROUP BY, COUNT):')
print(sparql(PREFIX + 'SELECT ?lang (COUNT(?c) AS ?n) WHERE { ?c ex:language ?lang } GROUP BY ?lang ORDER BY DESC(?n) LIMIT 5'))
print('\n3. African countries and, if any, a membership other than the African Union (OPTIONAL, FILTER):')
print(sparql(PREFIX + '''SELECT ?c ?org WHERE { ?c ex:locatedIn ex:Africa ; a ex:Country .
OPTIONAL { ?c ex:memberOf ?org FILTER(?org != ex:AfricanUnion) } } ORDER BY ?c'''))
print('\n4. Capitals whose English label contains "Abu" or "Buenos" (FILTER with a regular expression):')
print(sparql(PREFIX + 'SELECT ?x ?label WHERE { ?x a ex:Capital ; rdfs:label ?label FILTER(regex(?label, "Abu|Buenos")) }'))
print('\n5. Capitals located, through one or more steps, in Europe (property path locatedIn+):')
print(sorted(r[0] for r in sparql(PREFIX + 'SELECT ?x WHERE { ?x a ex:Capital ; ex:locatedIn+ ex:Europe }')))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.
import networkx as nx
G = nx.Graph()
for s, p, o in facts:
G.add_edge(s, o, label=p)
def show_path(a, b):
path = nx.shortest_path(G, a, b)
print(f'{a} to {b}: ' + path[0] + ''.join(f' —[{G.edges[x, y]["label"]}]— {y}' for x, y in zip(path, path[1:])))
show_path('Riyadh', 'Tunis')
show_path('Ottawa', 'Paris')
rank = nx.pagerank(G)
print('most central entities:', [(n, round(v, 3)) for n, v in sorted(rank.items(), key=lambda kv: -kv[1])[:6]])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)]
5. Link Prediction: Embeddings and Rules¶
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.
import torch
from torch import nn
def make_family_kg(n_families=40, seed=0):
rng = np.random.default_rng(seed)
triples, count = set(), itertools.count(1)
new = lambda: f'p{next(count)}'
for _ in range(n_families):
g1, g2 = new(), new()
triples |= {(g1, 'spouseOf', g2), (g2, 'spouseOf', g1)}
kids = [new() for _ in range(rng.integers(2, 4))]
for k in kids:
for g in (g1, g2): triples |= {(g, 'parentOf', k), (k, 'childOf', g)}
triples |= {(a, 'siblingOf', b) for a in kids for b in kids if a != b}
for k in kids:
spouse = new(); triples |= {(k, 'spouseOf', spouse), (spouse, 'spouseOf', k)}
grandkids = [new() for _ in range(rng.integers(1, 4))]
for gk in grandkids:
for p in (k, spouse): triples |= {(p, 'parentOf', gk), (gk, 'childOf', p)}
triples |= {(g, 'grandparentOf', gk) for g in (g1, g2)}
triples |= {(a, 'siblingOf', b) for a in grandkids for b in grandkids if a != b}
return sorted(triples)
family = make_family_kg()
entities = sorted({x for s, _, o in family for x in (s, o)}); relations = sorted({p for _, p, _ in family})
E, R = {e: i for i, e in enumerate(entities)}, {r: i for i, r in enumerate(relations)}
data = np.array([(E[s], R[p], E[o]) for s, p, o in family])
perm = np.random.default_rng(1).permutation(len(data)); n_test = len(data) // 10
test, train = data[perm[:n_test]], data[perm[n_test:]]
all_tails = defaultdict(set)
for s, p, o in data: all_tails[(s, p)].add(o)
print(f'{len(family)} triples, {len(entities)} people; {len(train)} for training, {len(test)} hidden for testing')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.
class TransE(nn.Module):
def __init__(self, n_entities, n_relations, dim=50):
super().__init__()
self.ent, self.rel = nn.Embedding(n_entities, dim), nn.Embedding(n_relations, dim)
bound = 6 / dim ** 0.5
nn.init.uniform_(self.ent.weight, -bound, bound); nn.init.uniform_(self.rel.weight, -bound, bound)
def score(self, h, r, t):
return -(self.ent(h) + self.rel(r) - self.ent(t)).norm(p=1, dim=-1) # -||h + r - t||
torch.manual_seed(0)
model = TransE(len(entities), len(relations))
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
train_t = torch.tensor(train)
for epoch in range(300):
with torch.no_grad():
model.ent.weight.data /= model.ent.weight.data.norm(dim=1, keepdim=True)
for batch in train_t[torch.randperm(len(train_t))].split(256):
h, r, t = batch.T
random_entity = torch.randint(0, len(entities), (len(batch),))
corrupt_head = torch.rand(len(batch)) < 0.5
h_neg, t_neg = torch.where(corrupt_head, random_entity, h), torch.where(corrupt_head, t, random_entity)
loss = torch.relu(1.0 - model.score(h, r, t) + model.score(h_neg, r, t_neg)).mean()
opt.zero_grad(); loss.backward(); opt.step()
def rank_of(scores, s, p, o):
"""Filtered rank: other true answers do not count against the right one."""
scores = scores.copy()
scores[[x for x in all_tails[(s, p)] if x != o]] = -np.inf
return 1 + int((scores > scores[o]).sum())
def transe_ranks(rows):
with torch.no_grad():
everyone = torch.arange(len(entities))
return np.array([rank_of(model.score(torch.full_like(everyone, s), torch.full_like(everyone, p), everyone).numpy(), s, p, o) for s, p, o in rows])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.
train_set = {(entities[s], relations[p], entities[o]) for s, p, o in train}
out_edges = defaultdict(set)
for s, p, o in train_set: out_edges[(s, p)].add(o)
def rule_candidates(s, p):
votes = defaultdict(int)
def vote(xs):
for x in xs: votes[x] += 1
if p == 'childOf':
vote([x for x in entities if s in out_edges[(x, 'parentOf')]])
if p == 'parentOf':
vote({k for sp in out_edges[(s, 'spouseOf')] for k in out_edges[(sp, 'parentOf')]}) # my spouse's children
vote([x for x in entities if s in out_edges[(x, 'childOf')]])
if p in ('spouseOf', 'siblingOf'):
vote([x for x in entities if s in out_edges[(x, p)]])
if p == 'siblingOf':
vote({k for par in out_edges[(s, 'childOf')] for k in out_edges[(par, 'parentOf')]} - {s})
if p == 'grandparentOf':
vote({g for c in out_edges[(s, 'parentOf')] for g in out_edges[(c, 'parentOf')]})
return votes
def rule_ranks(rows, seed=0):
rng = np.random.default_rng(seed)
ranks = []
for s, p, o in rows:
votes = rule_candidates(entities[s], relations[p])
scores = np.array([votes.get(e, 0) for e in entities], float) + rng.random(len(entities)) * 1e-3
ranks.append(rank_of(scores, s, p, o))
return np.array(ranks)
def summary(ranks):
return f'Hits@1 {np.mean(ranks == 1):.2f} Hits@10 {np.mean(ranks <= 10):.2f} MRR {np.mean(1 / ranks):.2f}'
print(f'{"relation":14} {"n":>3} TransE rules')
for rel in relations:
rows = test[test[:, 1] == R[rel]]
print(f'{rel:14} {len(rows):3d} {summary(transe_ranks(rows))} {summary(rule_ranks(rows))}')
print(f'{"all":14} {len(test):3d} {summary(transe_ranks(test))} {summary(rule_ranks(test))}')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 and , then 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¶
| Section | Result |
|---|---|
| 1 | a triple store with three indexes and a backtracking matcher answers graph-pattern queries |
| 2 | forward chaining with five RDFS/OWL rules more than doubles the stated facts |
| 3 | rdflib loads the same graph; SPARQL with joins, GROUP BY, OPTIONAL, FILTER and property paths |
| 4 | networkx finds connecting paths and central entities |
| 5 | TransE ranks well but struggles with symmetric relations; rules are exact where they apply |