Knowledge graph completion: what does a filtered rank measure?
知识图谱补全
Score missing links, compute raw and filtered ranks, and inspect false negatives and ties.
knowledge-graph-completionThe model did not change, but its rank improved
A model ranks two cities as plausible answers to a query. The test file names the second city as correct, so raw evaluation assigns rank 2. Suppose the first city is also a known correct answer. Removing that competitor changes the target’s filtered rank to 1, without changing a single model parameter.
Knowledge graph completion predicts missing relations or missing endpoints. It is not simply a database query: some desired edges are absent from the input graph. TransE describes raw and filtered endpoint ranking, while Toutanova and Chen study observed and latent features for this task. TransE, PDF 5 Task and evaluation, PDF 2 and 5
The essential distinctions are between unknown and false, training inputs and evaluation metadata, and the prediction score and the protocol used to rank it. Our program exposes each with a tiny, fully inspectable graph.
Start by specifying what may be observed
Let E be a fixed entity roster and R the relation labels. In this transductive setting, training and test edges refer to entities in the roster, but the edge sets are disjoint:
Disjoint edges alone do not prevent every shortcut. A nearly duplicate or inverse relation can reveal the same pair through a different label. Toutanova and Chen discuss removing such relationships in constructing a harder evaluation dataset. The exact data construction and split must accompany any reported comparison. Selected inverse-relation discussion, PDF 8
Training often needs competing triples even when observations are predominantly positive. Replacing one endpoint and excluding known training positives gives a corruption pool:
Its members are training competitors, not verified false statements. An unobserved but correct edge can enter this pool. Our demonstration shows that a held-out positive does so. TransE’s single-endpoint corruption motivates this construction; the explicit removal of training positives is our stated choice. PDF 3
For an inspectable baseline, count two-hop paths with the same relation and add a small tail-frequency term, both derived from training edges only:
This is an authored scoring heuristic. It favors transitive-looking patterns and popular tails; it is not a learned rule or an assertion that every relation is transitive. Toutanova and Chen’s observed-feature method uses direct links and learned weights, so this program does not reproduce their model. PDF 2
For target t and candidate set C, scores are better when larger. Let B count strictly better candidates and T count candidates tied with the target, including the target itself. We define three tie conventions:
These conventions are explicitly defined for this tutorial. A tie of six candidates yields ranks 1, 6 and 3.5. Reciprocal average rank is not the same as averaging the reciprocals of every possible tie position; report the convention used.
Let K contain the known positives permitted by the evaluation protocol. Filter competing known answers, always retaining the current target:
TransE uses positives from the training, validation and test sets for this filtering step. They are evaluation metadata, not permission to add test edges to the scoring graph. Unknown correct alternatives can still remain. PDF 5 For M target queries, define:
MRR rewards earlier ranks; Hits@k tests a cutoff. Neither directly measures factual certainty or the precision of a deployed batch of new edges.
Keep test facts out of the score
The Python 3.12 program uses only the standard library. Its six entity IDs and five training edges are synthetic. The test asks for two missing tails from a. The same score function is evaluated both ways; known positives affect only the candidate filter.
"""Original link-prediction protocol with a declared two-hop/count baseline.
Known positives filter evaluation only; no embedding or benchmark reproduction.
"""
import json
import math
from collections import Counter
def scores(train, head, relation, entities):
edges = set(train)
tails = Counter(t for _, r, t in edges if r == relation)
forward = {}
for h, r, t in edges:
if r == relation:
forward.setdefault(h, set()).add(t)
paths = Counter(t for middle in forward.get(head, ()) for t in forward.get(middle, ()))
return {e: paths[e] + 0.1*tails[e] for e in entities}
def rank(values, target, exclude=frozenset(), tie="realistic"):
if target not in values or any(not math.isfinite(x) for x in values.values()):
raise ValueError("Target and finite scores required")
if tie not in {"optimistic", "pessimistic", "realistic"}:
raise ValueError("Unknown tie convention")
kept = {e: s for e, s in values.items() if e == target or e not in exclude}
best = 1 + sum(s > kept[target] for s in kept.values())
worst = sum(s >= kept[target] for s in kept.values())
return best if tie == "optimistic" else worst if tie == "pessimistic" else (best+worst)/2
def evaluate(train, test, entities, known=None):
train, test = set(train), list(test)
if not test or set(test) & train:
raise ValueError("Need nonempty test disjoint from training")
if len(set(entities)) != len(entities) or any(h not in entities or t not in entities for h, _, t in train | set(test)):
raise ValueError("Entity roster must be unique and cover all triples")
known = set(known) if known is not None else train | set(test)
raw, filtered = [], []
for h, r, t in test:
v = scores(train, h, r, entities)
excluded = {tail for head, rel, tail in known if (head, rel) == (h, r)}
raw.append(rank(v, t))
filtered.append(rank(v, t, excluded))
return dict(raw_ranks=raw, filtered_ranks=filtered,
raw_mrr=sum(1/r for r in raw)/len(raw),
filtered_mrr=sum(1/r for r in filtered)/len(filtered))
def corruptions(triple, entities, training):
h, r, t = triple
return sorted(({(e, r, t) for e in entities} | {(h, r, e) for e in entities}) - set(training) - {triple})
def demo():
entities = list("abcdex")
train = {("a", "r", "b"), ("b", "r", "d"), ("a", "r", "c"),
("c", "r", "e"), ("x", "r", "d")}
test = [("a", "r", "e"), ("a", "r", "d")]
out = evaluate(train, test, entities)
out.update(scores=scores(train, "a", "r", entities),
withheld_positive_can_be_negative=test[0] in corruptions(("a", "r", "b"), entities, train),
all_tied_ranks={m: rank(dict.fromkeys(entities, 0), "a", tie=m)
for m in ["optimistic", "pessimistic", "realistic"]})
return out
if __name__ == "__main__":
print(json.dumps(demo(), indent=2))
The scores for d and e are 1.2 and 1.1. The two held-out targets e,d receive raw ranks 2, 1 and filtered ranks 1, 1. MRR rises from 0.75 to 1.0 solely because the other known answer is excluded. The program also verifies that a withheld positive can occur in a training corruption pool and prints all three all-tied rank conventions.
For each query, constructing the relation index and tail counts scans m training edges. Two-hop enumeration costs the number of visited path combinations, and scoring/ranking scans n candidate entities. Expected time is O(m+p+n), where p counts traversed two-hop combinations; index and counters require O(m+n) space. This implementation repeats that work for each query. A production baseline can cache relation indexes without incorporating held-out facts.
Good ranks depend on the candidate universe
Restricting candidates to an entity type can make a task easier. Replacing the full roster with sampled negatives changes it again. Tail-only evaluation, used by this demo, does not establish head-prediction performance. A real report should specify entity coverage, both endpoint tasks where applicable, negative construction, type restrictions, tie handling and known-positive filters.
The baseline may recommend a popular tail for the wrong head, and a two-hop pattern can be misleading for nontransitive relations. A learned embedding is another option, but it still requires the same protocol discipline. TransE’s small training example is in the next article; relation embeddings examine how score symmetry constrains possible predictions.
Change the protocol, then explain the number
- Does a corrupted triple absent from training necessarily represent a false fact? Answer: No. It may be missing but true. The corruption process creates competitors under incomplete observations.
- Two queries have ranks 2 and 1. What is MRR? Answer: (1/2+1)/2=0.75. If filtering changes both ranks to 1, MRR is 1 although the scores may be identical.
- Six candidates tie. What reciprocal rank does this article’s average-rank convention use? Answer: 1/3.5=2/7. Averaging 1,1/2,…,1/6 would be a different tie policy.
- May the test graph be joined into the training graph before constructing two-hop scores because filtered evaluation knows test positives? Answer: No. The filter may use the declared known-positive set, but scoring features must respect the information available for prediction. Combining them would leak target facts.
Compare models on the same question
TransE supplies a concrete endpoint-ranking protocol, and Toutanova–Chen show why observed features and relation redundancy deserve attention alongside embedding capacity. The numerical example here is original and reproduces neither paper’s benchmark. A useful extension compares the same baseline under full-roster and type-restricted candidates, reporting both the candidate recall ceiling and rank metrics. That comparison isolates protocol changes before attributing an improvement to a more complex model.
Make a prediction, then check
Why can filtered rank improve without a changed model?
Learning objectives
- Keep held-out facts out of feature construction while using declared known positives for evaluation filtering.
- Compute three tie conventions and MRR, and identify why training corruptions can contain true but missing edges.
Prerequisites & connections
Explore related knowledge →References
- Translating Embeddings for Modeling Multi-relational Data
Antoine Bordes; Nicolas Usunier; Alberto Garcia-Durán; Jason Weston; Oksana Yakhnenko · 2013 - Observed versus latent features for knowledge base and text inference
Kristina Toutanova; Danqi Chen · 2015
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF1 identity and PDF2–3/5 text; viewed PDF3. Translation, L1/L2 norm, margin loss, head-or-tail corruption, unit entity constraint and raw/filtered evaluation. Original full-pair deterministic program differs from paper sampling/validation; no benchmark reproduction. Read PDF1 identity, PDF2/4–5 text and selected inverse-relation paragraphs on PDF1/3/8. Distinguishes observed features, training inputs, candidate domains and filtered metrics. Teaching baseline has two-hop counts, not the paper’s trained one-link model. No reported benchmark replicated. 6 paired equations and four explained exercises. Checked training-only two-hop/count features, known-positive filtering, raw/filtered MRR, target retention, three tie conventions and false negatives. Synthetic tail-only baseline; no original-paper model or benchmark reproduction.
- Checked training-only two-hop/count features, known-positive filtering, raw/filtered MRR, target retention, three tie conventions and false negatives. Synthetic tail-only baseline; no original-paper model or benchmark reproduction.
- Four computed SVG variants per topic;14 numeric/geometry tests and36 responsive cases passed. Twelve selected current captures visually checked: seven identical to previously viewed images and five re-viewed final captures; TransE arrow revision retained. Full article acceptance recorded separately.
Source locations checked:
- Translating Embeddings for Modeling Multi-relational Data · Read PDF1 identity and PDF2–3/5 text; viewed PDF3. Translation, L1/L2 norm, margin loss, head-or-tail corruption, unit entity constraint and raw/filtered evaluation. Original full-pair deterministic program differs from paper sampling/validation; no benchmark reproduction.
- Observed versus latent features for knowledge base and text inference · Read PDF1 identity, PDF2/4–5 text and selected inverse-relation paragraphs on PDF1/3/8. Distinguishes observed features, training inputs, candidate domains and filtered metrics. Teaching baseline has two-hop counts, not the paper’s trained one-link model. No reported benchmark replicated.
Related topics