页面简介
Uses parallel beam search over Jev's Choice probabilities to classify documents in deep patent, retail product, and biomedical hierarchies.
正文摘录
Many kinds of data are hierarchies: taxonomies, file systems, websites, codebases, org charts, biological ontologies, LLM skills and moderation policies. Hierarchical classification walks a hierarchy from the root to the correct leaf node; that leaf is the final classification. We start at the root, ask a System One Choice question over its children, follow the most probable child, and repeat until we reach a leaf (Greedy Search). Because System One questions can run in parallel, we can also follow several paths at once with Beam Search, so one wrong early choice doesn’t decide the result. At each level, beam search scores every path by the geometric mean of its edge probabilities, product(edge_probabilities) ** (1 / decisions), keeps the best K, and prunes the rest. The geometric mean, unlike the raw product, doesn’t penalize a deep leaf just for taking more decisions. Asking one question per node also helps you observe and test the classifier: Observability identify which nodes your misclassifications occur most in measure the number of times each node and edge is traversed Testability unit test and measure the impact of hierarchy updates on classification performance Hierarchies used in this cookbook CPC 2026.05: patent subject matter, from broad technology sections to narrow inventions. Published by the European Patent Office and the US Patent and Trademark Office. Shopify 2026-02: retail product categories, from store departments to specific product types. From Shopify’s Product Taxonomy (MIT). MeSH 2026: biomedical subjects from broad domains to specific conditions. MeSH is a DAG, so one descriptor can appear under several parents; we give each of its official tree numbers a separate path. Source: U.S. National Library of Medicine. This is the January 2026 build of MeSH 2026 and may not be the most current MeSH data. Attribution and licences for the three are in DATA_LICENSE.md. Methods Greedy search: choose the highest-probability child and discard every alternative. One early mistake cannot be recovered. Beam search: retain K plausible paths and classify every frontier in parallel. When an early choice is close, a clearer decision further down can put the right path back on top. The leaf of the path with the highest geometric-mean probability is the final classification. System One Choice questions: each node asks one Choice question over its children, and the answer’s probabilities become the edge probabilities. The beam’s K questions at each level run in parallel, so beam search takes one round of calls per level, as greedy search does. Formula: path_score = product(edge_probabilities) ** (1 / decisions) used for pruning and comparing paths for hierarchies deeper than about 10 levels, compute it as exp(mean(log(probs))) to avoid floating-point precision loss separation = top_path_score / second_path_score reported only, not used for pruning near 1×, the top two paths are almost tied; the further above 1×, the clearer the winner Setup Run in ColabRuns as published without an API key.Python fileThis page as one .py file, to run locally. Requires Python 3.10 or later. pip install typesafe-sdk ipython 'cooksafe>=0.3.0,<0.4.0' With uv, uv run taxonomy_beam_search.py installs the dependencies for you. The code replays saved answers, so it runs as published without an API key. To change a request, set TYPESAFE_API_KEY; in Colab, add it in the Secrets panel. The first run downloads the three hierarchies (about 28 MB) into datasets/. Numbers below came from jev-1.14.0 on 2026-11-03. Load and visualize the example hierarchies We download a pinned version of each taxonomy, turn it into a tree of direct children, and draw each search as a static SVG. import html import os import shutil import textwrap import urllib.request from collections import defaultdict from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import NamedTuple, TypeAlias from xml.etree import ElementTree from zipfile import ZipFile from cooksafe import JsonCache from IPython.display import Markdown, display from typesafe_sdk import Choice, RetryPolicy, TypeSafeClient Tree: TypeAlias = dict[str, "Tree"] class Report(Markdown): """Markdown that renders in a notebook and prints as plain text from a terminal.""" def __str__(self) -> str: return self.data class Hierarchy(NamedTuple): """One query and a complete hierarchy. :param slug: filename-safe taxonomy name. :param name: display name. :param source_url: hierarchy source. :param node_count: number of loaded hierarchy nodes. :param document: unstructured text classified by Jev. :param expected_leaf: expected final classification. :param tree: nested direct-child menus. """ slug: str name: str source_url: str node_count: int document: str expected_leaf: str tree: Tree EXAMPLES_URL = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/hierarchical_classification" ) CPC_URL = ( "https://www.cooperativepatentclassification.org/sites/default/files/" "cpc/archive/CPCSchemeXML202605.zip" ) SHOPIFY_URL = ( "https://raw.githubusercontent.com/Shopify/product-taxonomy/" "v2026-02/dist/en/categories.txt" ) # NLM updates the current MeSH file in place, so the pinned January 2026 build is hosted. MESH_URL = f"{EXAMPLES_URL}/datasets/mesh_descriptors_2026.zip" MESH_CATEGORIES = { "A": "Anatomy", "B": "Organisms", "C": "Diseases", "D": "Chemicals and Drugs", "E": "Analytical, Diagnostic and Therapeutic Techniques, and Equipment", "F": "Psychiatry and Psychology", "G": "Phenomena and Processes", "H": "Disciplines and Occupations", "I": "Anthropology, Education, Sociology, and Social Phenomena", "J": "Technology, Industry, and Agriculture", "K": "Humanities", "L": "Information Science", "M": "Named Groups", "N": "Health Care", "V": "Publication Characteristics", "Z": "Geographicals", } def _download(url: str, path: Path) -> Path: """Download a pinned dataset once. :param url: pinned dataset URL. :param path: local cache path. :returns: local dataset path. """ if path.exists(): return path path.parent.mkdir(parents=True, exist_ok=True) temporary_path: Path = path.with_suffix(path.suffix + ".tmp") request = urllib.request.Request( url, headers={"User-Agent": "typesafe-taxonomy/1.0"} ) with urllib.request.urlopen(request, timeout=120) as response: with temporary_path.open("wb") as file: shutil.copyfileobj(response, file) temporary_path.replace(path) return path def _insert(tree: Tree, path: tuple[str, ...]) -> None: subtree_value: Tree = tree for label in path: subtree_value = subtree_value.setdefault(label, {}) def _cpc_title(item: ElementTree.Element) -> str: class_title: ElementTree.Element | None = item.find("class-title") if class_title is None: return "" return " ".join(" ".join(class_title.itertext()).split()) def _load_cpc(path: Path) -> tuple[Tree, int]: titles: dict[str, str] = {} levels: dict[str, int] = {} parent_by_symbol: dict[str, str] = {} children_by_symbol: defaultdict[str, list[str]] = defaultdict(list) def visit(item: ElementTree.Element, parent_symbol: str | None) -> None: symbol: str | None = item.findtext("classification-symbol") next_parent: str | None = parent_symbol if symbol: title: str = _cpc_title(item) if title: titles[symbol] = title levels[symbol] = min(levels.get(symbol, 99), int(item.attrib["level"])) if ( parent_symbol and parent_symbol != symbol and symbol not in parent_by_symbol ): parent_by_symbol[symbol] = parent_symbol children_by_symbol[parent_symbol].append(symbol) next_parent = symbol for child in item.findall("classification-item"): visit(child, next_parent) with ZipFile(path) as zip_file: names = sorted( name for name in zip_file.namelist() if name.startswith("cpc-scheme-") and name.endswith(".xml") ) for name in names: root = ElementTree.fromstring(zip_file.read(name)) for item in root.findall("classification-item"): visit(item, None) labels: dict[str, str] = { symbol: f"{symbol} {titles.get(symbol, '')}".strip() for symbol in levels } def build(symbol: str) -> Tree: return { labels[child]: build(child) for child in children_by_symbol.get(symbol, []) } root_symbols: list[str] = sorted( symbol for symbol, level in levels.items() if level == 2 ) tree: Tree = {labels[symbol]: build(symbol) for symbol in root_symbols} return tree, len(labels) def _load_shopify(path: Path) -> tuple[Tree, int]: tree: Tree = {} category_count: int = 0 for line in path.read_text().splitlines(): if not line or line.startswith("#"): continue _, path_text = line.split(" : ", maxsplit=1) category_path: tuple[str, ...] = tuple(path_text.strip().split(" > ")) _insert(tree, category_path) category_count += 1 return tree, category_count def _load_mesh(path: Path) -> tuple[Tree, int]: """Load every official MeSH tree-number path. A descriptor may have multiple tree numbers because MeSH is a DAG. Expanding those positions into paths makes it usable by the tree-oriented beam search. :param path: MeSH descriptor XML ZIP. :returns: expanded tree and position count. """ with ZipFile(path) as zip_file: root: ElementTree.Element = ElementTree.fromstring( zip_file.read("desc2026.xml") ) names_by_tree_number: dict[str, str] = { tree_number.text: descriptor_record.findtext("DescriptorName/String", "") for descriptor_record in root.findall("DescriptorRecord") for tree_number in descriptor_record.findall("TreeNumberList/TreeNumber") if tree_number.text } tree: Tree = {} for tree_number in sorted(names_by_tree_number): parts: list[str] = tree_number.split(".") prefixes: list[str] = [ ".".join(parts[:index]) for index in range(1, len(parts) + 1) ] category_code: str = tree_number[0] category_path: tuple[str, ...] = ( f"{category_code} {MESH_CATEGORIES[category_code]}", *(f"{prefix} {names_by_tree_number[prefix]}" for prefix in prefixes), ) _insert(tree, category_path) position_count: int = len(names_by_tree_number) + len(tree) return tree, position_count def load_hierarchies(data_directory: Path = Path("datasets")) -> tuple[Hierar