पाठ 12 / 25
Knowledge Graphs
Entities and relationships as a network.
Triples and traversal
A knowledge graph stores facts as triples: subject, relation, object (Pune, located_in, Maharashtra). Queries traverse relations, including chains (Pune is in Maharashtra, which is in India). Search engines, e-commerce catalogues and enterprise data platforms use knowledge graphs to connect entities; graph databases and query languages (Cypher, SPARQL) support them. Knowledge graphs also ground language-model applications with reliable, structured facts.
Querying a tiny knowledge graph, run
I ran this with plain Python 3 (standard library only), with fixed random seeds where randomness is used. Following located_in edges shows Pune is in Maharashtra and India; Infosys is headquartered in Bengaluru, which is in Karnataka and India; and the cities recorded in Maharashtra are Pune and Mumbai.
triples = [
("Pune", "located_in", "Maharashtra"), ("Maharashtra", "located_in", "India"),
("Mumbai", "located_in", "Maharashtra"), ("Bengaluru", "located_in", "Karnataka"),
("Karnataka", "located_in", "India"), ("Infosys", "headquartered_in", "Bengaluru"),
]
def located_in(place): # follow located_in edges transitively
out, frontier = [], [place]
while frontier:
p = frontier.pop()
for s, rel, o in triples:
if s == p and rel == "located_in":
out.append(o); frontier.append(o)
return out
print("Pune is in:", located_in("Pune"))
hq = next(o for s, r, o in triples if s == "Infosys" and r == "headquartered_in")
print("Infosys HQ city:", hq, "-> which is in", located_in(hq))
print("cities in Maharashtra:", [s for s, r, o in triples if r == "located_in" and o == "Maharashtra"])
Output:
Pune is in: ['Maharashtra', 'India'] Infosys HQ city: Bengaluru -> which is in ['Karnataka', 'India'] cities in Maharashtra: ['Pune', 'Mumbai']
Fix relation names early
Agree on a small vocabulary of relation types; inconsistent names (in, located_in, part_of) make queries miss facts.
त्वरित जाँच: How does a knowledge graph store facts?
- As pixel arrays
- As subject-relation-object triples
- As neural network weights only
- As unstructured paragraphs
Answer
As subject-relation-object triples — Triples make relationships queryable.