Chapter 6 — Lab: Knowledge Graphs
Lab Overview¶
| Exercise | Topic | Points |
|---|---|---|
| 1 | From a table to triples | 10 |
| 2 | Matching triple patterns | 15 |
| 3 | Queries with variables | 20 |
| 4 | Schema inference | 20 |
| 5 | SPARQL with rdflib | 15 |
| 6 | Scoring and evaluating embeddings | 20 |
| Challenge | Mining a rule and its confidence | +10 |
Complete the code where you see # TODO, then run the check cell under it. In Colab, first run !pip install rdflib.
import itertools
from collections import defaultdict
import numpy as np
def check(name, test):
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
# A small university, as a table: one row per course
COURSES = [
{'code': 'CS101', 'title': 'Programming 1', 'teacher': 'Amal', 'dept': 'CS', 'prereq': None},
{'code': 'CS102', 'title': 'Programming 2', 'teacher': 'Amal', 'dept': 'CS', 'prereq': 'CS101'},
{'code': 'CS201', 'title': 'Data Structures', 'teacher': 'Omar', 'dept': 'CS', 'prereq': 'CS102'},
{'code': 'CS301', 'title': 'Algorithms', 'teacher': 'Omar', 'dept': 'CS', 'prereq': 'CS201'},
{'code': 'CS340', 'title': 'Artificial Intelligence', 'teacher': 'Sara', 'dept': 'CS', 'prereq': 'CS301'},
{'code': 'MA101', 'title': 'Calculus', 'teacher': 'Yusuf', 'dept': 'MATH', 'prereq': None},
{'code': 'MA201', 'title': 'Probability', 'teacher': 'Yusuf', 'dept': 'MATH', 'prereq': 'MA101'},
]
print('Setup complete.')Exercise 1: From a Table to Triples (10 points)¶
Complete table_to_triples(rows, key, columns): each row becomes an entity named by its key column; each of the other listed columns becomes a predicate, with the cell as object. Skip empty cells (None): under the open-world assumption, a missing value is not a fact.
def table_to_triples(rows, key, columns):
raise NotImplementedError # TODOKG = table_to_triples(COURSES, 'code', ['title', 'teacher', 'dept', 'prereq'])
check('Ex 1: 26 triples (two courses have no prerequisite)', lambda: len(KG) == 26)
check('Ex 1: a sample triple', lambda: ('CS301', 'prereq', 'CS201') in KG and ('CS101', 'prereq', None) not in KG)Exercise 2: Matching Triple Patterns (15 points)¶
Complete match(triples, s=None, p=None, o=None), returning the set of triples that agree with every argument that is not None.
def match(triples, s=None, p=None, o=None):
raise NotImplementedError # TODOcheck("Ex 2: Amal's courses", lambda: {t[0] for t in match(KG, p='teacher', o='Amal')} == {'CS101', 'CS102'})
check('Ex 2: everything about CS340', lambda: len(match(KG, s='CS340')) == 4)
check('Ex 2: no arguments returns everything', lambda: match(KG) == KG)Exercise 3: Queries with Variables (20 points)¶
Complete query(triples, patterns). Each pattern is a triple in which strings starting with ? are variables. Return the list of all bindings (dicts from variable to value) that satisfy every pattern at once. Hint: recursion: match the first pattern with the variables already bound replaced by their values, extend the binding, and solve the remaining patterns.
def query(triples, patterns, binding=None):
raise NotImplementedError # TODOcheck('Ex 3: courses taught by the teacher of CS201', lambda: sorted(b['?c'] for b in query(KG, [('CS201', 'teacher', '?t'), ('?c', 'teacher', '?t')])) == ['CS201', 'CS301'])
check('Ex 3: two steps: the prerequisite of the prerequisite of CS340', lambda: [b['?y'] for b in query(KG, [('CS340', 'prereq', '?x'), ('?x', 'prereq', '?y')])] == ['CS201'])
check('Ex 3: a variable used twice must agree', lambda: query({('a', 'likes', 'a'), ('a', 'likes', 'b')}, [('?x', 'likes', '?x')]) == [{'?x': 'a'}])Exercise 4: Schema Inference (20 points)¶
Complete infer(triples, schema), returning a new set with all the triples that follow from the rules below, applied repeatedly until nothing new appears:
(A, 'subClassOf', B)and(B, 'subClassOf', C)give(A, 'subClassOf', C)(x, 'type', A)and(A, 'subClassOf', B)give(x, 'type', B)(p, 'domain', A)and(x, p, y)give(x, 'type', A)(p, 'range', A)and(x, p, y)give(y, 'type', A)(p, 'transitive', True)and(x, p, y),(y, p, z)give(x, p, z)
SCHEMA = {('Course', 'subClassOf', 'Activity'), ('Activity', 'subClassOf', 'Thing'), ('Teacher', 'subClassOf', 'Person'),
('Person', 'subClassOf', 'Thing'), ('teacher', 'domain', 'Course'), ('teacher', 'range', 'Teacher'),
('prereq', 'domain', 'Course'), ('prereq', 'range', 'Course'), ('prereq', 'transitive', True)}
def infer(triples, schema):
raise NotImplementedError # TODOdef _inf():
return infer(KG, SCHEMA)
check('Ex 4: Amal is a Teacher, a Person and a Thing', lambda: {o for s, p, o in _inf() if s == 'Amal' and p == 'type'} == {'Teacher', 'Person', 'Thing'})
check('Ex 4: CS340 now requires, directly or not, all four earlier CS courses', lambda: {o for s, p, o in _inf() if s == 'CS340' and p == 'prereq'} == {'CS101', 'CS102', 'CS201', 'CS301'})
check('Ex 4: the input set is not modified', lambda: (_inf(), len(KG) == 26)[1])Question. MA101 has no prerequisite in the data. Under the open-world assumption, may the system conclude “MA101 has no prerequisite”? What would a university database (closed world) conclude?
Your answer:
Exercise 5: SPARQL with rdflib (15 points)¶
The courses are loaded into an rdflib graph below (prefix ex:). Write the three queries as strings.
from rdflib import Graph, Namespace, Literal
EX = Namespace('http://example.org/')
g = Graph()
for s, p, o in KG:
g.add((EX[s], EX[p], Literal(o) if p == 'title' else EX[o]))
def run(q):
return sorted(tuple(str(v).replace('http://example.org/', '') for v in row) for row in g.query('PREFIX ex: <http://example.org/> ' + q))
Q1 = 'TODO' # every MATH course
Q2 = 'TODO' # each teacher with their number of courses (GROUP BY)
Q3 = 'TODO' # every prerequisite of CS340, at any depth (a property path)check('Ex 5, Q1', lambda: run(Q1) == [('MA101',), ('MA201',)])
check('Ex 5, Q2', lambda: run(Q2) == [('Amal', '2'), ('Omar', '2'), ('Sara', '1'), ('Yusuf', '2')])
check('Ex 5, Q3', lambda: run(Q3) == [('CS101',), ('CS102',), ('CS201',), ('CS301',)])Exercise 6: Scoring and Evaluating Embeddings (20 points)¶
Complete:
transe_score(h, r, t): for NumPy vectors;rank(scores, true_index): 1 + the number of candidates with a strictly higher score than the true one;hits_and_mrr(ranks, k): the pair (fraction of ranks , mean of ).
def transe_score(h, r, t):
raise NotImplementedError # TODO
def rank(scores, true_index):
raise NotImplementedError # TODO
def hits_and_mrr(ranks, k=10):
raise NotImplementedError # TODOEMB = {'Paris': np.array([1, 2.]), 'France': np.array([2, 3.]), 'Berlin': np.array([4, 1.]), 'Germany': np.array([5, 2.]),
'Rome': np.array([2, -1.]), 'Italy': np.array([3, 0.1])}
CAPITAL_OF = np.array([1, 1.])
countries = ['France', 'Germany', 'Italy']
check('Ex 6: a perfect triple scores 0', lambda: transe_score(EMB['Paris'], CAPITAL_OF, EMB['France']) == 0)
check("Ex 6: the chapter example: Rome's country ranks Italy first", lambda: rank([transe_score(EMB['Rome'], CAPITAL_OF, EMB[c]) for c in countries], 2) == 1)
check('Ex 6: Hits@1 and MRR of ranks 1, 2, 4', lambda: np.allclose(hits_and_mrr([1, 2, 4], k=1), (1 / 3, (1 + 0.5 + 0.25) / 3)))Question. TransE gives each relation one vector. Why does this fail for a symmetric relation such as siblingOf? (Write the two equations.)
Your answer:
Challenge: Mining a Rule (+10 points)¶
A path rule is judged by its support (how many pairs the body produces that are also facts) and its confidence (support divided by the number of pairs the body produces). Complete rule_confidence(triples, r1, r2, r3) returning (support, confidence).
def rule_confidence(triples, r1, r2, r3):
raise NotImplementedError # TODOFAMILY = {('Ali', 'parentOf', 'Hana'), ('Hana', 'parentOf', 'Rami'), ('Hana', 'parentOf', 'Lina'), ('Ali', 'grandparentOf', 'Rami'),
('Ali', 'grandparentOf', 'Lina'), ('Mona', 'parentOf', 'Hana'), ('Mona', 'grandparentOf', 'Rami')}
check('Challenge: parentOf ∘ parentOf ⇒ grandparentOf has support 3, confidence 3/4', lambda: rule_confidence(FAMILY, 'parentOf', 'parentOf', 'grandparentOf') == (3, 0.75))
check('Challenge: a nonsense rule has confidence 0', lambda: rule_confidence(FAMILY, 'grandparentOf', 'parentOf', 'parentOf')[1] == 0.0)The confidence is below 1 only because the fact Mona grandparentOf Lina is missing: the rule proposes exactly that fact. This is how rule mining completes knowledge graphs.
Lab Report¶
Submit this notebook with every check cell showing ✅ and your answers to the two questions.