Algorithm Search⌘K

Algorithmadvanced

DIPRE

Also called dual iterative pattern relation expansion.

Brin's bootstrapping that alternates between finding text patterns around seed pairs and finding new pairs that match the patterns.

Time
O(n c (r + p c)) worst
Space
O(n + o) extra
Where
c = the largest length of a middle or of a matched field; n = the total number of characters of the pages; o = the number of occurrences; p = the number of patterns; r = the number of known pairs
Properties
deterministicnot exactofflineiterative
Origin
Sergey Brin, 1998

DIPRE (Dual Iterative Pattern Relation Expansion) finds pairs that stand in one relation, such as (author, title) for books, in a large set of web pages, starting from a handful of examples. Brin (1998) built it on a duality: if you know many pairs, you can find the patterns in which they are written, and if you know good patterns, you can find many pairs. So the algorithm goes back and forth. It looks up the known pairs in the pages and keeps the text around them, turns groups of similar contexts into patterns, and uses the patterns to read new pairs off the pages. It is a heuristic for relation extraction with almost no labeled data. Its main risk is drift: one bad pattern brings in bad pairs, and these bring in more bad patterns.

In plain words

Start with five books you know, each an author and a title. Search the web for pages where an author and title of yours appear close together, and note the text just before, between and after them, and the web address. When several of these places look the same, for example the title in bold, then the word "by", then the author, and all on the same site, make a pattern from what they share. Use the pattern to read every other author and title written the same way on that site. Add the new books to your list and start again. A pattern is kept only if it is specific enough, so that a very short shared context, which would match almost anything, is not used.

The problem

Input: a set of pages, each a url and a text; a few seed pairs of the relation; a context length mm (Brin used 10 characters); and a threshold tt. Output: a set of pairs of the relation. There is no labeled data beyond the seeds, and no guarantee: a pair is accepted when some accepted pattern finds it.

An occurrence of a pair is a place where both strings appear in a page with at most cc characters between them. It records seven things: the author, the title, the order (whether the author comes first), the url, the mm characters before the first string (the prefix), the text between the two (the middle) and the mm characters after the second (the suffix). A pattern has five parts: the order, a url prefix, a prefix, a middle and a suffix. A page whose url starts with the url prefix matches the pattern where its text holds the prefix, then a field, then the middle, then a field, then the suffix; the two fields are read as the author and the title in the given order.

The specificity of a pattern is the product of the lengths of its middle, url prefix, prefix and suffix. It measures how hard the pattern is to match by chance. A pattern built from nn occurrences is accepted when n>1n > 1 and specificity times nn is above tt.

The algorithm

  1. DIPRE(pages, seeds, m, t)
  2. 1R ← seeds
  3. 2repeat
  4. 3O ← all occurrences of the pairs of R in the pages, with order, url, prefix, middle and suffix
  5. 4group O by (order, middle)
  6. 5for each group G: urlprefix ← longest common prefix of the urls, prefix ← longest common suffix of the prefixes, suffix ← longest common prefix of the suffixes
  7. 6if |G| > 1 and specificity · |G| > t then accept the pattern (order, urlprefix, prefix, middle, suffix)
  8. 7else if the urls of G differ then split G by the next character of the urls after urlprefix, and go to L5 for each part
  9. 8R ← R ∪ all pairs matched by the accepted patterns
  10. 9until R does not grow (or after a fixed number of rounds)
  11. 10return R

Line L7 is how Brin rescues a group whose shared context is too short: a smaller group from one site or one directory has a longer url prefix and often a longer shared prefix and suffix, so its pattern may pass the test. The code adds one guard of its own: a field is 1 to cc characters with no '<', '>' or line break.

Example

The test file uses five small pages. Two lists on www.books.com/sf/ write one book per line as <li><b>Title</b> by Author., and list2 also has the line <li><b>Contents</b> by chapter. before its closing </ul>. Two pages on www.reads.net/a/ write <p>Author: <i>Title</i></p>. A blog page says "I read Dune by Frank Herbert and then Foundation by Isaac Asimov." The seeds are (Isaac Asimov, Foundation) and (Frank Herbert, Dune), with m=10m = 10 and t=100t = 100. Below, \n is a line break.

Round 1 finds 5 occurrences. The two on the books.com lists share the middle </b> by and give the url prefix http://www.books.com/sf/list (28 characters), the prefix \n<li><b> (8) and the suffix .\n<li><b> (9). The specificity is 8⋅28⋅8⋅9=161288 \cdot 28 \cdot 8 \cdot 9 = 16128, and 16128⋅2>10016128 \cdot 2 > 100, so the pattern is accepted. The two blog occurrences share the middle by, but their suffixes and then and .\n have no common prefix, so the specificity is 0 and the group is rejected; both are on one url, so it cannot be split. Herbert on reads.net is alone in its group. The pattern finds (Dan Simmons, Hyperion) but not the last book of a list, because its suffix asks for another <li><b> line after the book.

Round 2 has 7 occurrences: Simmons now also appears on reads.net next to Herbert, so the reads.net format gives a second pattern, and the two patterns add (William Gibson, Neuromancer), (Ursula K. Le Guin, The Dispossessed) and (Iain Banks, Excession). Round 3 has 11 occurrences. Gibson is the last line of list1, so the books.com suffix shrinks to .\n<, and the more general pattern now also matches the last line of list2: it adds the false pair (chapter, Contents). Round 4 adds nothing and the loop stops with 7 pairs, one of them wrong. With t=30000t = 30000 instead, the false pair never appears, but the run also stops with only Hyperion beside the seeds: a higher threshold trades recall for precision.

Correctness

DIPRE is a heuristic, so no theorem says that its pairs are true. The proof in proofs/correctness.md shows what can be shown: the longest common prefix of a list is the one of its smallest and largest strings; the pattern step ends, because each split makes strictly smaller groups; each accepted pattern has n>1n > 1 and specificity times n>tn > t; an accepted pattern matches every occurrence it was built from, so a known pair is never lost; and the loop ends, because the set of pairs only grows and there are finitely many substrings. The test file checks the matcher against a search over all ways to cut a text into prefix, field, middle, field and suffix.

Proof: DIPRE: the pattern step ends and gives patterns that match their own occurrences, and the loop endsfull

DIPRE is a heuristic: nothing guarantees that a pair it finds is a true fact, and the example of the page shows a false pair. What can be proved is what each step computes. The line numbers refer to the pseudocode on the page; a page is a pair (url, text), and a field is a string of 1 to max_len characters with no '<', '>' or newline.

Claim 1: the longest common prefix and suffix

The code computes the longest common prefix of a list as the longest common prefix of its smallest and largest strings in lexicographic order. Let PP be the longest common prefix of the smallest string aa and the largest string bb. Every common prefix of the list is a common prefix of aa and bb, so it is no longer than PP. Conversely, take any string ss of the list, so a≤s≤ba \le s \le b. If ss did not start with PP, let kk be the first position where ss and PP differ (or ss ends before ∣P∣|P|). If ss ends first, or sk<Pks_k < P_k, then s<as < a; if sk>Pks_k > P_k, then s>bs > b. Both contradict a≤s≤ba \le s \le b. So PP is a common prefix of the whole list and it is the longest. The longest common suffix is the longest common prefix of the reversed strings. The test file checks both against a search over all candidates.

Claim 2: pattern generation ends, and each kept pattern satisfies the test

Line L4 puts each occurrence into exactly one group, by (order, middle). Line L5 builds one candidate pattern for a group. If the group has fewer than 2 occurrences it is dropped. If specificity times nn is above tt (line L6), the pattern is kept. Otherwise, if all the urls are equal, the group is dropped. Otherwise line L7 splits the group by the character of each url just after the common url prefix UU (or by the end of the url). Since UU is the longest common prefix and the urls are not all equal, at least two urls differ at that position, so the group splits into at least 2 nonempty parts, each smaller than the group. Each part has a longer common url prefix than UU, or it consists of urls that end at ∣U∣|U| and are therefore all equal. So each recursive call has fewer occurrences than its caller, the recursion depth is at most the group size, and the procedure ends. A pattern is returned only from line L6, so every kept pattern was built from at least 2 occurrences and has specificity times n>tn > t. In particular its specificity is positive, so its url prefix, prefix, middle and suffix are all nonempty.

Claim 3: a kept pattern matches every occurrence that is consistent with it

Let p=(order,U,A,M,B)p = (\text{order}, U, A, M, B) be a kept pattern and oo an occurrence with the same order and middle MM whose url starts with UU, whose prefix ends with AA and whose suffix starts with BB. Every occurrence that line L5 used to build pp has these properties, because UU, AA and BB are its longest common prefix of the urls, longest common suffix of the prefixes and longest common prefix of the suffixes. Let oo have its first string xx at position ii of its page and its second string yy right after the middle. The prefix of oo is the text just before ii, so AA ends at ii; MM starts at i+∣x∣i + |x|; and BB starts right after yy. The function match_pattern tries every position of AA, then every position of MM that starts 1 to max_len characters later, then every position of BB that starts 1 to max_len characters after the end of MM, so it tries this one when xx and yy have at most max_len characters and reads off xx and yy as the two fields. If xx and yy are fields (true for the pairs of the example and of the tests), the pair of oo is in the output. The test file checks this on random pages, and checks match_pattern itself against a search over all choices of the four cut points.

Claim 4: the loop ends, and the set of pairs only grows

Line L8 adds the matches to the known set and never removes a pair, so the set grows weakly from round to round. Every pair that a pattern finds is two substrings of the pages of length at most max_len, and there are finitely many such pairs. So the set can grow only finitely many times, and the stop test of line L9 (no new pair in a round) is met after a finite number of rounds, even without a round limit. The test file checks that the sizes never go down.

What is not proved

Whether a found pair is a true fact depends on the pages and on tt. In the example of the page, the round that adds "William Gibson, Neuromancer" also makes the pattern of the first site more general, and the next round accepts the false pair "chapter, Contents". Raising tt removes the false pair and also most of the true ones. This trade is a measurement on data, not a theorem.

Complexity

Let nn be the total length of the pages, rr the number of known pairs, pp the number of patterns and cc the bound on the middle and on a field. Count each string comparison and field check as one step, and list the positions of a string in a page with a linear-time string matching method such as Knuth-Morris-Pratt. For each pair, each position of the first string is followed by at most cc candidate positions of the second, so finding occurrences costs O(ncr)O(n c r). For each pattern, each position of its prefix has at most cc positions of the middle and cc of the suffix, so matching costs O(nc2p)O(n c^2 p). Grouping and the common prefixes cost the total length of the occurrences. So one round costs O(nc(r+pc))O(n c (r + p c)), the bound given above, and the space is O(n+o)O(n + o) for the pages and the oo occurrences. Brin ran the occurrence search over 24 million pages; at that size the search over the text, done with an index, is the main cost.

Properties

  • Heuristic: precision depends on the pages and on tt. Brin reports (a measurement) that 19 of 20 books sampled from his final list were real books.
  • Weakly supervised: only the seeds are given. The patterns come from the data.
  • Monotone: pairs are never removed, so an error stays and can spread. This is the drift that the example shows.
  • Site-specific patterns: the url prefix limits a pattern to one site or directory, which is why patterns from web lists can be long and exact.

Brin's run on 24 million pages (a measurement): from 5 seed books, the first round found 199 occurrences, 3 patterns and 4047 pairs; the second found 3972 occurrences, 105 patterns and 9369 pairs; the final round found 9938 occurrences and 346 patterns, for 15257 books. Brin reports that he removed by hand 242 occurrences that involved a false title, "Conclusion".

Variants and improvements

  • Snowball (Agichtein and Gravano 2000) works on plain text with named entity tags, so a pattern requires an organization and a location in the right slots. It represents contexts as term vectors, clusters them, and gives each pattern a confidence from the share of its matches that agree with known pairs; a new pair is kept only if its confidence from all the patterns that found it is high enough.
  • Hearst patterns are hand-written lexical patterns such as "X such as Y" for the is-a relation; DIPRE learns such patterns from seeds instead.
  • The Yarowsky algorithm uses the same bootstrapping idea for word senses: rules label examples and labeled examples make new rules.
  • Distant supervision also needs no hand-labeled sentences, but takes many pairs from a knowledge base at once and trains a classifier, instead of growing a small seed set.

When to use it

Use DIPRE, or one of its descendants, when you want a large set of pairs of one relation from many semi-structured pages, you can name a few examples, and you can check a sample of the output by hand. It works best on lists and tables made by templates. For relations written in free prose, Snowball-style methods with entity tags, distant supervision or a trained classifier work better.

Pitfalls

  • Drift: one general pattern can bring in a whole class of wrong pairs, which then make new patterns. Check samples after each round, and keep tt high.
  • Too long contexts: the suffix or prefix can capture parts of the next line, so a pattern misses the last item of a list, as in the example. More rounds usually fix this, but they also make patterns more general.
  • Name variants: "I. Asimov" and "Isaac Asimov" count as different pairs. Normalize the strings before counting.
  • Duplicate pages: mirrors of one page make one context look common. Remove duplicates before grouping.
  • Many-to-many relations: an author has many books, so the pairs give no simple consistency test; Snowball's confidence works best when one side determines the other, as for an organization and its headquarters.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dipre.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dipre/. The authors are listed in prov/RKXK3C.jsonl.

"""DIPRE, Dual Iterative Pattern Relation Expansion (Brin 1998), on a small set of pages.

A page is a pair (url, text). A relation pair is (author, title). The loop:

- find_occurrences: every place where both strings of a known pair appear close
  together on a page, with the order, the url, m characters before (prefix),
  the text between (middle) and m characters after (suffix);
- generate_patterns: group the occurrences by order and middle; a group gives the
  pattern (order, urlprefix, prefix, middle, suffix), where urlprefix is the
  longest common prefix of the urls, prefix the longest common suffix of the
  prefixes and suffix the longest common prefix of the suffixes; the pattern is
  kept if n > 1 and specificity * n > t, else the group is split by the next
  character of the urls and each part is tried again;
- match_pattern: all pairs that the pattern finds on pages whose url starts with
  urlprefix;
- dipre: repeat until no new pair is found or the round limit is reached.

As a simple guard on what a pattern may extract, a field (the author or the
title in a match) is any string of 1 to max_len characters with no '<', '>'
or newline.
"""

from bisect import bisect_left, bisect_right
from collections import defaultdict, namedtuple
from typing import Dict, Iterable, List, Sequence, Set, Tuple

Occurrence = namedtuple("Occurrence", "author title order url prefix middle suffix")
Pattern = namedtuple("Pattern", "order urlprefix prefix middle suffix")
Page = Tuple[str, str]
Pair = Tuple[str, str]

FORBIDDEN = set("<>\n")


def lcp(strings: Sequence[str]) -> str:
    """Longest common prefix of a non-empty list of strings."""
    first, last = min(strings), max(strings)
    k = 0
    while k < len(first) and first[k] == last[k]:
        k += 1
    return first[:k]


def lcs(strings: Sequence[str]) -> str:
    """Longest common suffix of a non-empty list of strings."""
    return lcp([s[::-1] for s in strings])[::-1]


def find_all(text: str, s: str) -> List[int]:
    out, i = [], text.find(s)
    while i >= 0:
        out.append(i)
        i = text.find(s, i + 1)
    return out


def window(positions: List[int], lo: int, hi: int) -> List[int]:
    """The sorted positions p with lo <= p <= hi."""
    return positions[bisect_left(positions, lo):bisect_right(positions, hi)]


def find_occurrences(pages: Iterable[Page], pairs: Iterable[Pair], m: int = 10,
                     max_middle: int = 40) -> List[Occurrence]:
    """All occurrences of the pairs: the first string, then 1 to max_middle characters, then the second.
    order is True when the author comes first."""
    out = []
    pairs = sorted(pairs)
    for url, text in pages:
        for author, title in pairs:
            for order, first, second in ((True, author, title), (False, title, author)):
                seconds = find_all(text, second)
                for i in find_all(text, first):  # @line L3
                    a = i + len(first)
                    for j in window(seconds, a + 1, a + max_middle):
                        out.append(Occurrence(author, title, order, url, text[max(0, i - m):i],
                                              text[a:j], text[j + len(second):j + len(second) + m]))
    return out


def specificity(p: Pattern) -> int:
    return len(p.middle) * len(p.urlprefix) * len(p.prefix) * len(p.suffix)


def _gen_one(group: List[Occurrence], t: int) -> List[Pattern]:
    if len(group) < 2:
        return []
    urls = [o.url for o in group]
    p = Pattern(group[0].order, lcp(urls), lcs([o.prefix for o in group]),  # @line L5
                group[0].middle, lcp([o.suffix for o in group]))
    if specificity(p) * len(group) > t:  # @line L6
        return [p]
    if len(set(urls)) == 1:
        return []
    k = len(p.urlprefix)
    parts: Dict[str, List[Occurrence]] = defaultdict(list)
    for o in group:  # @line L7
        parts[o.url[k:k + 1]].append(o)
    out = []
    for key in sorted(parts):
        out.extend(_gen_one(parts[key], t))
    return out


def generate_patterns(occs: Iterable[Occurrence], t: int) -> List[Pattern]:
    groups: Dict[Tuple[bool, str], List[Occurrence]] = defaultdict(list)
    for o in occs:  # @line L4
        groups[(o.order, o.middle)].append(o)
    out: Set[Pattern] = set()
    for key in sorted(groups):
        out.update(_gen_one(groups[key], t))
    return sorted(out)


def _field_ok(s: str, max_len: int) -> bool:
    return 1 <= len(s) <= max_len and not (set(s) & FORBIDDEN)


def match_pattern(p: Pattern, pages: Iterable[Page], max_len: int = 40) -> Set[Pair]:
    """All (author, title) pairs found by the pattern: prefix X middle Y suffix, url starting with urlprefix."""
    found = set()
    for url, text in pages:
        if not url.startswith(p.urlprefix):
            continue
        mids = find_all(text, p.middle)
        sufs = find_all(text, p.suffix)
        for i in find_all(text, p.prefix):
            x0 = i + len(p.prefix)
            for k in window(mids, x0 + 1, x0 + max_len):
                x = text[x0:k]
                if not _field_ok(x, max_len):
                    continue
                y0 = k + len(p.middle)
                for l in window(sufs, y0 + 1, y0 + max_len):
                    y = text[y0:l]
                    if _field_ok(y, max_len):
                        found.add((x, y) if p.order else (y, x))
    return found


def dipre(pages: Sequence[Page], seeds: Iterable[Pair], t: int, m: int = 10, rounds: int = 5,
          max_middle: int = 40, max_len: int = 40):
    """Run the loop. Return the final set of pairs and, per round, (occurrences, patterns, pairs)."""
    known: Set[Pair] = set(seeds)  # @line L1
    stats = []
    for _ in range(rounds):  # @line L2
        occs = find_occurrences(pages, known, m, max_middle)
        pats = generate_patterns(occs, t)
        new = set(known)
        for p in pats:  # @line L8
            new |= match_pattern(p, pages, max_len)
        stats.append((len(occs), len(pats), len(new)))
        if new == known:  # @line L9
            break
        known = new
    return known, stats  # @line L10
test_dipre.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dipre/. The authors are listed in prov/RKXK3C.jsonl.

import random

from dipre import (FORBIDDEN, Occurrence, Pattern, dipre, find_occurrences, generate_patterns, lcp, lcs,
                   match_pattern, specificity)

# The example of the page.
PAGES = [
    ("http://www.books.com/sf/list1",
     "<ul>\n<li><b>Foundation</b> by Isaac Asimov.\n<li><b>Neuromancer</b> by William Gibson.\n</ul>\n"),
    ("http://www.books.com/sf/list2",
     "<ul>\n<li><b>Hyperion</b> by Dan Simmons.\n<li><b>Dune</b> by Frank Herbert.\n"
     "<li><b>Contents</b> by chapter.\n</ul>\n"),
    ("http://www.reads.net/a/1",
     "<p>Dan Simmons: <i>Hyperion</i></p>\n<p>Ursula K. Le Guin: <i>The Dispossessed</i></p>\n<hr>\n"),
    ("http://www.reads.net/a/2",
     "<p>William Gibson: <i>Neuromancer</i></p>\n<p>Frank Herbert: <i>Dune</i></p>\n"
     "<p>Iain Banks: <i>Excession</i></p>\n<hr>\n"),
    ("http://www.blog.org/day7", "I read Dune by Frank Herbert and then Foundation by Isaac Asimov.\n"),
]
SEEDS = {("Isaac Asimov", "Foundation"), ("Frank Herbert", "Dune")}
BOOKS = {("Dan Simmons", "Hyperion"), ("William Gibson", "Neuromancer"),
         ("Ursula K. Le Guin", "The Dispossessed"), ("Iain Banks", "Excession")}
JUNK = ("chapter", "Contents")


def test_lcp_lcs_against_brute_force():
    rng = random.Random(1)
    for _ in range(300):
        strs = ["".join(rng.choice("ab") for _ in range(rng.randint(0, 5))) for _ in range(rng.randint(1, 4))]
        best = max((s[:k] for s in strs for k in range(len(s) + 1) if all(x.startswith(s[:k]) for x in strs)),
                   key=len, default="")
        assert lcp(strs) == best
        best = max((s[k:] for s in strs for k in range(len(s) + 1) if all(x.endswith(s[k:]) for x in strs)),
                   key=len, default="")
        assert lcs(strs) == best


def test_first_round_of_the_page_example():
    occs = find_occurrences(PAGES, SEEDS)
    assert len(occs) == 5
    asimov = [o for o in occs if o.author == "Isaac Asimov" and o.url.endswith("list1")][0]
    assert asimov == Occurrence("Isaac Asimov", "Foundation", False, "http://www.books.com/sf/list1",
                                "l>\n<li><b>", "</b> by ", ".\n<li><b>N")
    pats = generate_patterns(occs, 100)
    p = Pattern(False, "http://www.books.com/sf/list", "\n<li><b>", "</b> by ", ".\n<li><b>")
    assert pats == [p]
    assert specificity(p) == 28 * 8 * 8 * 9 == 16128
    # The blog group (middle " by ") has suffixes " and then " and ".\n", so its suffix is empty.
    assert match_pattern(p, PAGES) == {("Isaac Asimov", "Foundation"), ("Dan Simmons", "Hyperion"),
                                       ("Frank Herbert", "Dune")}


def test_full_run_finds_books_and_drifts():
    found, stats = dipre(PAGES, SEEDS, t=100)
    assert stats == [(5, 1, 3), (7, 2, 6), (11, 2, 7), (12, 2, 7)]
    assert found == SEEDS | BOOKS | {JUNK}


def test_higher_threshold_trades_recall_for_precision():
    found, stats = dipre(PAGES, SEEDS, t=30000)
    assert JUNK not in found
    assert found == SEEDS | {("Dan Simmons", "Hyperion")}


def occ(url, prefix, suffix):
    return Occurrence("A", "T", False, url, prefix, " by ", suffix)


def test_split_by_url_prefix():
    group = [occ("http://a.com/1", "<td>", "</td>"), occ("http://a.com/2", "<td>", "</td>"),
             occ("http://b.com/1", "<li>", "<br>"), occ("http://b.com/2", "<li>", "<br>")]
    # Whole group: urlprefix "http://", prefix ">", suffix "<": specificity 7 * 1 * 4 * 1 = 28, 28 * 4 = 112.
    assert generate_patterns(group, 111) == [Pattern(False, "http://", ">", " by ", "<")]
    a = Pattern(False, "http://a.com/", "<td>", " by ", "</td>")  # 13 * 4 * 4 * 5 = 1040, times 2
    b = Pattern(False, "http://b.com/", "<li>", " by ", "<br>")  # 13 * 4 * 4 * 4 = 832, times 2
    assert generate_patterns(group, 200) == sorted([a, b])
    assert generate_patterns(group, 2000) == [a]
    assert generate_patterns(group, 3000) == []
    assert generate_patterns(group[:1], 0) == []  # one occurrence is never enough


def field_ok(s, max_len):
    return 1 <= len(s) <= max_len and all(c not in FORBIDDEN for c in s)


def brute_match(p, pages, max_len):
    found = set()
    for url, text in pages:
        if url[:len(p.urlprefix)] != p.urlprefix:
            continue
        n = len(text)
        for a in range(n + 1):
            if text[:a][len(text[:a]) - len(p.prefix):] != p.prefix or a < len(p.prefix):
                continue
            for b in range(a, n + 1):
                if text[b:b + len(p.middle)] != p.middle:
                    continue
                c = b + len(p.middle)
                for d in range(c, n + 1):
                    if text[d:d + len(p.suffix)] == p.suffix:
                        x, y = text[a:b], text[c:d]
                        if field_ok(x, max_len) and field_ok(y, max_len):
                            found.add((x, y) if p.order else (y, x))
    return found


def rand_str(rng, alpha, lo, hi):
    return "".join(rng.choice(alpha) for _ in range(rng.randint(lo, hi)))


def test_match_against_brute_force():
    rng = random.Random(2)
    for _ in range(300):
        pages = [("u" + rand_str(rng, "xy", 0, 2), rand_str(rng, "ab<c", 0, 14)) for _ in range(2)]
        p = Pattern(rng.random() < 0.5, rand_str(rng, "uxy", 0, 2), rand_str(rng, "ab<", 0, 2),
                    rand_str(rng, "ac", 1, 2), rand_str(rng, "b<", 0, 2))
        max_len = rng.randint(1, 5)
        assert match_pattern(p, pages, max_len) == brute_match(p, pages, max_len)


def test_patterns_match_their_own_occurrences():
    rng = random.Random(3)
    for _ in range(200):
        words = [rand_str(rng, "ab", 1, 3) for _ in range(4)]
        pages = []
        for k in range(3):
            text = "".join(rng.choice(words + ["<", "c", "cc", " "]) for _ in range(12))
            pages.append(("u/" + "xy"[k % 2] + str(k), text))
        pairs = {(rng.choice(words), rng.choice(words)) for _ in range(3)}
        occs = find_occurrences(pages, pairs, m=4, max_middle=6)
        for p in generate_patterns(occs, rng.randint(0, 50)):
            support = [o for o in occs if o.order == p.order and o.middle == p.middle
                       and o.url.startswith(p.urlprefix) and o.prefix.endswith(p.prefix)
                       and o.suffix.startswith(p.suffix)]
            assert len(support) >= 2 and specificity(p) > 0
            got = match_pattern(p, pages, max_len=40)
            for o in support:
                assert (o.author, o.title) in got


def test_loop_stops_and_only_grows():
    rng = random.Random(4)
    for _ in range(50):
        words = [rand_str(rng, "ab", 2, 3) for _ in range(5)]
        pages = [("u/" + str(k), "".join(rng.choice(words + ["<", " by ", ":"]) for _ in range(15)))
                 for k in range(3)]
        seeds = {(words[0], words[1])}
        found, stats = dipre(pages, seeds, t=5, m=3, rounds=6, max_middle=5, max_len=6)
        assert seeds <= found
        sizes = [s[2] for s in stats]
        assert sizes == sorted(sizes)

History

Hearst (1992) had shown that a few lexical patterns find many is-a pairs in text. Brin (1998) turned the idea around: let the data find the patterns from a few pairs, and use the web as the text. The name stresses the duality of patterns and relations. Snowball (Agichtein and Gravano 2000) extended the idea to plain text with entity tags and confidence scores, and later open information extraction systems and distant supervision grew from the same aim of extraction with little labeled data.

References

  1. Sergey Brin, Extracting patterns and relations from the World Wide Web, WebDB 1998, Lecture Notes in Computer Science 1590, Springer, 1999, pages 172 to 183, the definitions of occurrences and patterns, the pattern generation with specificity and url splitting, and the experiment on author and title pairs
  2. Agichtein and Gravano 2000, the confidence of patterns and of tuples and the use of named entity tags

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example