翻篇收录说明
翻篇网页快照

Knowledge graph entity alignment - TypeSafe

https://docs.typesafe.ai/cookbooks/entity_alignment

最近抓取:2026-12-03 20:34:59(北京时间)

最近内容变化:2026-12-03 20:34:59(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Route candidate record pairs from two sources to a merge recommendation, manual review, or no link, using one Score question. Three Noul questions check individual fields. The worked example uses 450 album pairs from Wikidata and MusicBrainz.

正文摘录

When data from two sources is combined, the same person, product, place, or work often appears on both sides, described differently on each. Entity alignment decides which record on one side describes the same entity as a record on the other. In a knowledge graph, each entity has facts and links to other entities. Comparing every record with every other is slow, so a cheap first step usually picks out pairs worth a closer look, such as records with similar names. Each of those candidate pairs then needs a decision, which we make here. A wrong merge combines facts and links from different entities. Undoing it means working out where each fact came from. A missed match leaves a duplicate. Pairs that need review get a third outcome: send them to a curator, a person who decides by hand. Jev makes this decision with a Score question: you describe one level per outcome, and the answer is a score along those levels. Here the levels are leave unlinked, send for review, and recommend a merge (assert sameAs). On 450 album pairs from two public music catalogs, we got 57 merge recommendations, 79 pairs for review, and 314 left unlinked. The dataset records 48 of the 57 recommended merges as matches. Setup Run in ColabRuns as published without an API key.Python fileThis page as one .py file, to run locally.Open in playgroundEdit one request and run it live. Needs a TypeSafe account. To run it on your own machine instead: pip install matplotlib ipython 'cooksafe>=0.3.0,<0.4.0' With uv, uv run entity_alignment.py installs the dependencies for you. The code downloads the published answers into entity_alignment_cache.json, so it runs as published without an API key; to run live, set DOWNLOAD_CACHE = False and delete that file. To change a request, set TYPESAFE_API_KEY; in Colab, add it in the Secrets panel. Numbers below came from jev-1.14.0 on 2026-10-16. import json import os import urllib.request from concurrent.futures import ThreadPoolExecutor from pathlib import Path import matplotlib.pyplot as plt from cooksafe import JsonCache, make_playground_link from IPython.display import Markdown, display from typesafe_sdk import Noul, Score, TypeSafeClient TYPESAFE_MODEL = "jev-1.14.0" # the page's model; "jev-latest" runs the newest, live MAX_WORKERS = 6 # small pool to stay under your organization's rate limits # The keys this cookbook uses. In Colab, keys saved in the Secrets panel are copied in here. KEYS = ["TYPESAFE_API_KEY"] try: from google.colab import userdata except ImportError: # not in Colab userdata = None for key in KEYS: if userdata is not None and key not in os.environ: try: os.environ[key] = userdata.get(key) except (userdata.SecretNotFoundError, userdata.NotebookAccessError): pass # not saved, or this notebook may not read it client = TypeSafeClient( api_key=os.environ.get( "TYPESAFE_API_KEY", "cache-only" ), # keyless kernels replay the cache base_url=os.environ.get("TYPESAFE_ENDPOINT"), timeout=120.0, ) See all 34 lines EXAMPLES_URL = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/entity_alignment" ) def download(name: str) -> Path: """Fetch one of this cookbook's files from typesafe-public-examples unless it is on disk.""" path = Path(name) if not path.exists(): urllib.request.urlretrieve(f"{EXAMPLES_URL}/{name}", path) return path CACHE = Path("entity_alignment_cache.json") # True fills CACHE with the published answers, so the run makes no requests. To run # live, set it to False and delete CACHE; a CACHE already on disk is never overwritten. DOWNLOAD_CACHE = True if DOWNLOAD_CACHE: download(CACHE.name) json_cache = JsonCache(CACHE) Load the candidate pairs The pairs in candidate_pairs.json come from two public music catalogs, Wikidata and MusicBrainz. Both release this data under CC0, which puts it in the public domain. In each pair, entity_a is an album record from Wikidata and entity_b is a release from MusicBrainz. Each entity has four fields: title, artist, year, and label. DATA_LICENSE.md credits both sources. Each pair also has known_same_as. It is true when a Wikidata editor linked the album to the MusicBrainz release group that the release belongs to. Wikidata is a knowledge graph, and that link is an entity alignment link. The 70 pairs marked true are called known matches here. In the other 380, the Wikidata album links to a different MusicBrainz entry. Nobody checked each pair by hand. The text is left exactly as the catalogs publish it, with no cleanup: mixed casing and alphabet systems, straight and curly apostrophes, and placeholders such as [no label]. A missing value is -. We send one request per pair, so the number of requests depends on the number of candidate pairs, not the size of either catalog. DATA = Path("candidate_pairs.json") DATA_URL = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/entity_alignment/candidate_pairs.json" ) if not DATA.exists(): urllib.request.urlretrieve(DATA_URL, DATA) PAIRS = json.loads(DATA.read_text(encoding="utf-8")) BY_ID = {pair["id"]: pair for pair in PAIRS} print(f"{len(PAIRS)} candidate pairs. The first one, as the model will see it:") print(json.dumps({k: PAIRS[0][k] for k in ("entity_a", "entity_b")}, indent=2)) 450 candidate pairs. The first one, as the model will see it: { "entity_a": { "title": "My Refuge", "artist": "Alessandra Samadello", "year": "2003", "label": "-" }, "entity_b": { "title": "My Refuge", "artist": "Kent Henry", "year": "1989", "label": "Hosanna! Music" } } Ask one Score question and three Noul questions per candidate pair The decision is a Score question because a Score attaches a written description to each outcome in LEVELS, including the uncertain middle one, and keeps the three outcomes in order. A Noul question could reach the middle outcome only indirectly, by thresholding its output. A Choice question would lose the order of the three outcomes. Put both entities into one state, as entity_a and entity_b, so each question is about the pair. All four questions go in one request. Title, artist, and label each get a Noul question to indicate where the records disagree. We round the score to the nearest level in route(). Write the level descriptions before looking at the scores; the cut points follow from rounding rather than being fitted to this dataset. The middle level’s wording decides which pairs reach a curator instead of being merged or left unlinked, so it names the cases that need one: a reissue, a compilation, a special or live edition, or a title that could refer to either album. The merge recommendation is called assert sameAs: a recommendation to record that the two entities are the same thing. That label is all route() returns; applying it to a graph is a separate step. There is no Noul question for the year, but the year is in the state. For a year check, compare the two years in code and allow for a missing -. The label question needs a rule, because catalogs disagree about which company to name. We count a shortened name or a regional branch as the same label (Columbia Records and Columbia, EMI and EMI Music Brasil). An imprint is a brand name a record company releases under. We count an imprint and its parent company as different labels (RCA Victor and BMG), because sharing a parent company does not establish that two albums are the same. To use this on another kind of data, swap in your own pairs and rewrite QUESTIONS and LEVELS. The only other code that knows about albums is show(), which prints a pair and names its fields. LEVELS = [ "They describe two different albums.", "They describe closely related albums that may or may not be the same one: " "a reissue, a compilation, a special or live edition, or a title that could " "plausibly refer to either.", "They describe one and the same album.", ] OUTCOME = {0: "leave unlinked", 1: "curator queue", 2: "assert sameAs"} QUESTIONS = { "link_state": Score( instructions="How do the two entity descriptions relate as albums?", criteria=LEVELS, ), "same_title": Noul( instructions="Do the two entities give the same album title? Differences in " "casing, punctuation, or writing system (a title and its romanisation) do not " "make two titles different.", ), "same_artist": Noul( instructions="Do the two entities credit the same artist? A name written in " "another script or word order, or a credit that adds collaborators to the same " "lead artist, is the same artist.", ), "same_label": Noul( instructions="Do the two entities name the same record label? A shortened name " "or a regional branch of a label is the same label; an imprint and its parent " "company are different labels. A label of '-' or '[no label]' is not recorded.", ), } @json_cache def score(state_json: str, questions_json: str, model: str) -> dict: """One request about one candidate pair -> the score plus the three noul answers.""" questions = json.loads(questions_json) response = client.system_one( state=json.loads(state_json), questions=questions, model=model, ) link = response.answers["link_state"] return { "score": link.score, "probabilities": link.probabilities, "confidence": link.confidence, "properties": { k: response.answers[k].noul for k in questions if k != "link_state" }, } def score_pair(pair: dict) -> dict: state = {"entity_a": pair["entity_a"], "entity_b": pair["entity_b"]} questions = {k: q.model_dump(mode="json", exclude_none=True) for k, q in QUESTIONS.items()} return score(json.dumps(state), json.dumps(questions), model=TYPESAFE_MODEL) def route(score_value: float) -> str: """The whole decision rule: the nearest level names the outcome.""" return OUTCOME[min(int(score_value + 0.5), len(LEVELS) - 1)] def show(pair_id: str) -> None: pair = BY_ID[pair_id] result = score_pair(pair) print( f"{pair_id} score {result['score']:.2f} confidence {result['confidence']:.2f}" f" -> {route(result['score'])}" ) for side in ("entity_a", "entity_b"): e = pair[side] print( f" {e['title'][: