Algorithm Search⌘K

Algorithmadvanced

Focused crawling

Also called topical crawling.

Orders the crawl frontier by a classifier score of page relevance to a topic, so the crawler fetches on-topic pages first.

Time
O((S + m) log(S + m)) expected
Space
O(S + m) extra
Where
S = the number of seeds; k = the budget of pages; m = the number of links on the fetched pages
Properties
deterministiciterative
Origin
Soumen Chakrabarti, Martin van den Berg, Byron Dom, 1999

Focused crawling is a way to run a web crawler so that it fetches pages about one topic first and spends little of its budget on the rest of the web. A classifier gives each fetched page a relevance score, and the URL frontier is ordered so that the links of relevant pages are fetched before the links of irrelevant ones. Soumen Chakrabarti, Martin van den Berg and Byron Dom gave the method its name in 1999. The core is a best-first search over the web graph, in which the priority of a URL is the relevance of the pages that link to it. That the method finds more relevant pages for the same budget is a measured property, not a theorem: it holds when relevant pages tend to link to each other and the classifier is good.

In plain words

A general crawler follows every link it finds, so it wanders all over the web. A focused crawler is for one subject, such as cycling. Each time it downloads a page, a program decides how much the page is about cycling. Links on a page that is about cycling are probably worth following soon, because pages on a subject tend to link to other pages on the same subject. Links on a page about something else can wait. So the crawler keeps its list of links to visit sorted by how good the page was where it found each link, and always visits the best one next. In a strict form, it does not follow the links of pages that are off the subject at all. The crawler is judged by the share of downloaded pages that are on the subject.

The problem

The input is a set SS of seed URLs, a fetch operation that returns the out-links out(u)\mathrm{out}(u) of a page uu, a relevance function R(u)∈[0,1]R(u) \in [0, 1] computed from the fetched page, and a budget of kk fetches. The task is to choose which kk pages to fetch, one at a time, so that many of them are relevant. The crawler sees the web graph only through the pages it has fetched. The usual measure is the harvest rate, the fraction of fetched pages that are relevant. Since the true relevance is unknown, experiments estimate it with the classifier itself or with human judgments.

The algorithm

The priority of an unfetched page vv is 1 if it is a seed, and else the largest R(u)R(u) over fetched pages uu that link to vv. This is the soft focus rule. With hard focus and threshold θ\theta, the links of a page uu are followed only if R(u)≥θR(u) \ge \theta. The frontier is a max-heap of pairs (priority, URL), ties to the smaller URL. When a priority rises, a new entry is pushed and the old one is skipped later (lazy deletion).

  1. FOCUSED-CRAWL(S, R, k, θ) ▷ θ = none for soft focus
  2. 1for each seed s: prio(s) ← 1; push (1, s) on the max-heap
  3. 2D ← ∅; order ← empty list
  4. 3while the heap is not empty and |order| < k:
  5. 4(p, u) ← EXTRACT-MAX(heap) ▷ ties to the smaller u
  6. 5if u ∈ D or p < prio(u) then continue ▷ a stale entry
  7. 6fetch u; add u to D and to order; r ← R(u)
  8. 7if θ ≠ none and r < θ then continue ▷ hard focus: do not follow the links
  9. 8for each v ∈ out(u) with v ∉ D:
  10. 9if v has no priority or r > prio(v):
  11. 10prio(v) ← r; push (r, v)
  12. 11return order

The relevance function in the implementation is a two-class multinomial naive Bayes classifier trained on example pages, which returns the probability that a page is on the topic. Any score in [0,1][0, 1] works, such as the output of logistic regression.

Chakrabarti, van den Berg and Dom used a hierarchical classifier over a topic taxonomy in which the user marks some classes as good. In their soft focus rule, the relevance of a page is the total probability of the good classes. In their hard focus rule, the crawler finds the most likely leaf class of the page and follows its links only if that class or one of its ancestors is good. The threshold rule of line L7 is a simple form of this.

Example

Take eight pages with the links a → b, c; b → d, e; c → f, g; f → h, and the scores below. The seed is a, and a page counts as on the topic when its score is at least 0.5.

page a b c d e f g h
R 0.9 0.1 0.8 0.2 0.1 0.9 0.3 0.7

With soft focus:

step fetch R new priorities
1 a 0.9 b: 0.9, c: 0.9
2 b (tie with c, smaller id) 0.1 d: 0.1, e: 0.1
3 c 0.8 f: 0.8, g: 0.8
4 f (tie with g) 0.9 h: 0.9
5 h 0.7
6 g 0.3
7, 8 d, e

The fetch order is a, b, c, f, h, g, d, e. Breadth-first search fetches a, b, c, d, e, f, g, h. With a budget of 5 pages, the focused crawler gets the four on-topic pages a, c, f and h, and breadth-first search gets only a and c. With hard focus and θ=0.5\theta = 0.5, the links of b are never followed, so d and e are never found, and the crawl is a, b, c, f, h, g.

On larger graphs the effect is measured. The test file plants a graph of 1000 pages, 20% of them on the topic, with 6 links per page. Each link goes with probability 0.6 to a random page of the class of its page and otherwise to a random page of the whole graph, so a link of an on-topic page reaches an on-topic page with probability about 0.6+0.4⋅0.2=0.680.6 + 0.4 \cdot 0.2 = 0.68. A naive Bayes classifier trained on other pages of the same model labels about 1.5% of the pages wrongly. With 3 on-topic seeds and a budget of 200 pages, over ten fixed seeds of the generator, the harvest rate of the focused crawler is between 0.58 and 0.635 (mean 0.600), and that of breadth-first search is between 0.275 and 0.48 (mean 0.406). When all links go to random pages of the whole graph, both stay near the base rate of 20% (means 0.2175 and 0.203).

Correctness

The file proofs/correctness.md proves that the crawler follows its rule. The invariant is that for every discovered unfetched page vv, prio(v)(v) is the largest score of an expanded fetched page that links to vv (or 1 for a seed), the heap holds the entry (prio(v)(v), vv), and every other entry of vv has a smaller key. A stale entry thus never hides a page, so each step fetches the discovered page of largest priority, ties to the smaller id. The test file checks this against a brute-force rule that recomputes all priorities at each step. It also follows that each page is fetched once and only pages reachable from the seeds are fetched, and that with soft focus and no budget limit every reachable page is fetched.

Nothing in the proof says that the crawl finds relevant pages. That depends on the web, through the tendency of pages to link to pages on the same topic, and on the quality of RR.

Proof: The best-first focused crawler fetches the page of largest priority at each stepfull

The input is a directed graph given by the out-links out(u)\mathrm{out}(u) of each page, a set SS of seeds, a relevance score R(u)∈[0,1]R(u) \in [0, 1], a budget k≥0k \ge 0, and, for hard focus, a threshold θ\theta. Page ids are totally ordered. The line numbers are those of the pseudocode on the page. This file proves what the crawler does. It does not prove that the crawler finds more relevant pages than another order: that is a measured property of the web and of the classifier.

Call a fetched page uu expanded if its links are followed: always for soft focus, and when R(u)≥θR(u) \ge \theta for hard focus. For a set DD of fetched pages, the priority of a page v∉Dv \notin D is

πD(v)=max⁡({1:v∈S}∪{R(u):u∈D expanded, v∈out(u)}),\pi_D(v) = \max\left(\{1 : v \in S\} \cup \{R(u) : u \in D \text{ expanded},\ v \in \mathrm{out}(u)\}\right),

defined when the set is not empty, that is, when vv is a seed or has a link from an expanded page of DD. These vv are the discovered pages.

Lemma 1 (invariant). Let DD be the set fetched so far. At each test of line L3:

  1. The keys of prio are the pages that are seeds or are linked from an expanded page of DD (fetched or not), and for each discovered v∉Dv \notin D, prio(v)=πD(v)\mathrm{prio}(v) = \pi_D(v).
  2. For each discovered v∉Dv \notin D, the heap holds the entry (prio(v),v)(\mathrm{prio}(v), v).
  3. Every other heap entry (p,v)(p, v) has v∈Dv \in D or p<prio(v)p < \mathrm{prio}(v).

Proof. After line L1 no page is fetched, prio is 1 on the seeds, and the heap holds (1,s)(1, s) for each seed once. So the claims hold.

Suppose they hold and lines L4 to L10 run. If line L5 skips the entry (p,u)(p, u), then u∈Du \in D or p<prio(u)p < \mathrm{prio}(u), so by claim 2 the entry is not the one that claim 2 needs, and removing it keeps all three claims. Else u∉Du \notin D and p=prio(u)p = \mathrm{prio}(u); line L6 fetches uu, and DD grows to D′=D∪{u}D' = D \cup \{u\}. The entry for uu is gone, and u∈D′u \in D', so claims 2 and 3 do not speak of uu any more. If uu is not expanded (line L7), then πD′(v)=πD(v)\pi_{D'}(v) = \pi_D(v) for all v∉D′v \notin D', and nothing else changes. If uu is expanded, then for v∈out(u)v \in \mathrm{out}(u) with v∉D′v \notin D', πD′(v)=max⁡(πD(v),R(u))\pi_{D'}(v) = \max(\pi_D(v), R(u)), or R(u)R(u) if vv was not discovered. Lines L9 and L10 set prio(v)(v) to exactly this value, and push a new entry when it changes. The old entry of vv now has a key less than prio(v)(v), which meets claim 3. Priorities of other pages do not change. □\square

Theorem 2 (the rule of choice). The jj-th page that the crawler fetches is the discovered page v∉Dv \notin D with the largest πD(v)\pi_D(v), ties to the smallest id, where DD is the set of the first j−1j - 1 fetched pages. The crawler stops when it has fetched kk pages or no discovered page is left.

Proof. The heap returns the entry with the largest key, ties to the smallest id. By claims 2 and 3 of Lemma 1, the entries with v∉Dv \notin D and key prio(v)(v) are exactly one for each discovered unfetched page, and every other entry is skipped at line L5. A stale entry (p,v)(p, v) with v∉Dv \notin D has p<prio(v)p < \mathrm{prio}(v), and the current entry of vv is also in the heap, so a stale entry never hides a page. The first entry that passes line L5 therefore belongs to the page described. When the heap is empty, no discovered page is unfetched. □\square

Corollary 3. Each page is fetched at most once, and only pages reachable from SS are fetched. With soft focus and kk at least the number of reachable pages, every page reachable from SS is fetched. With hard focus, each fetched page that is not a seed has a link from a fetched page uu with R(u)≥θR(u) \ge \theta.

Proof. Line L5 rejects pages of DD. A discovered page is a seed or has a link from a fetched page, so by induction it is reachable. With soft focus every fetched page is expanded; if a reachable page were never fetched, the first such page on a path from a seed would have a fetched predecessor and so be discovered, against Theorem 2. For hard focus, a non-seed page is discovered only through an expanded page. □\square

Lazy deletion is what keeps the update of line L10 cheap. A heap with a decrease-key operation and a map from pages to heap positions gives the same order.

Cost. Line L1 pushes ∣S∣|S| entries. Each expanded page uu pushes at most ∣out(u)∣|\mathrm{out}(u)| entries. So the heap gets at most ∣S∣+m′|S| + m' entries in total, where m′m' is the number of links of the fetched pages, and each push and pop costs O(log⁡(∣S∣+m′))O(\log(|S| + m')). With hash tables for prio and DD, the crawl costs O((∣S∣+m′)log⁡(∣S∣+m′))O((|S| + m') \log(|S| + m')) expected time and O(∣S∣+m′)O(|S| + m') space, plus kk fetches and kk calls of RR, which in practice cost far more than the heap.

Measured, not proved. The crawl reaches more relevant pages early only if relevant pages tend to link to relevant pages and if RR is a good classifier. The test file plants such a graph: 1000 pages, 20% on topic, 6 links per page, each link going with probability 0.6 to a random page of the class of its page and otherwise to a random page of the whole graph (so a link of an on-topic page stays on the topic with probability about 0.6+0.4⋅0.2=0.680.6 + 0.4 \cdot 0.2 = 0.68), and a naive Bayes classifier trained on separate pages. On ten fixed seeds and a budget of 200, the share of on-topic pages among the fetched pages is between 0.58 and 0.635 for the focused crawler and between 0.275 and 0.48 for breadth-first search. When all links go to random pages of the whole graph (probability 0 in place of 0.6, so a link of an on-topic page stays on the topic with probability about 0.2), the same run gives a mean of 0.2175 for the focused crawler and 0.203 for breadth-first search, close to the 20% base rate.

Complexity

The heap gets one entry per seed and at most one per link of an expanded page, so at most S+mS + m entries, where mm is the number of links on the fetched pages. Each push and pop costs O(log⁡(S+m))O(\log(S + m)), and the hash tables for prio and DD cost O(1)O(1) expected per lookup. So the crawl costs O((S+m)log⁡(S+m))O((S + m) \log(S + m)) expected time and O(S+m)O(S + m) extra space, plus kk fetches and kk calls of the classifier. In a real crawler the fetches and the classifier dominate by far.

Properties

  • Deterministic. With a fixed RR and the tie rule, the order is fixed.
  • Greedy and local. The priority of a URL uses only the pages already fetched. A good page behind an off-topic page gets a low priority, and with hard focus it is never found.
  • The link of a good page is not always good. Soft focus gives every link of a relevant page the same high priority, so the off-topic pages that relevant pages link to are fetched early too. This puts a ceiling on the harvest rate, as in the planted graph above.
  • Not polite by itself. The algorithm orders URLs only. A real crawler puts the priorities into a two-stage frontier that also enforces a gap per host.

Variants and improvements

  • Fish search and shark search. Before the 1999 paper, De Bra and Post's fish search and the shark search of Hersovici and others ordered links by a text match of the page, and shark search also used the anchor text of each link. See anchor text indexing for why the anchor text is a good clue.
  • Distillation. Chakrabarti, van den Berg and Dom also ran a distiller, a form of HITS on the fetched pages, to find hub pages that link to many relevant pages, and raised the priority of the links of the hubs.
  • Link scores from the anchor and the URL. Later crawlers score each link and not only its page, from the anchor text, the words near the link, and the URL. Chakrabarti, Punera and Subramanyam trained a second classifier, an apprentice, on the links that led to relevant pages.
  • Context graphs. Diligenti and others learned how many links away from a relevant page a page usually is, and ordered the frontier by this estimated distance.
  • Learning crawlers. Reinforcement learning crawlers estimate the value of a link as the number of relevant pages that it leads to in the future, not just the relevance of its page.
  • Global ordering. Cho, Garcia-Molina and Page ordered the frontier of a general crawler by backlink counts or an estimate of PageRank, which is the same best-first scheme with a different priority.

When to use it

Use a focused crawler when you need pages on one subject and cannot or will not crawl the whole web, for example to build a topic search engine or a corpus for a domain. It needs a classifier with good accuracy on the topic and seeds inside the topic. If the topic is spread over unrelated sites with few links between them, start from many seeds or use a search engine to find more.

Pitfalls

  • Tunnelling. Relevant pages can sit behind one or two off-topic pages, such as a university home page that leads to a lab page. Hard focus never gets there, and soft focus gets there late. A tolerance for a few off-topic steps helps.
  • A drifting classifier. A classifier trained on a few examples can rate pages with common words too high, and the crawl drifts away from the topic. Check samples of the fetched pages by hand.
  • Measuring with the same classifier. A harvest rate computed with the classifier that steers the crawl rewards the crawler for agreeing with itself. Use held-out judgments or a second classifier.
  • Ties. With coarse scores, many URLs tie, and the tie rule then decides much of the order. State it.
  • The benefit is not a guarantee. On a graph without topical clustering, the focused crawler does no better than breadth-first search.

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.

focused_crawling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/focused-crawling/. The authors are listed in prov/CT80NW.jsonl.
"""A best-first focused crawler in the style of Chakrabarti, van den Berg and Dom (1999).

The crawler fetches pages from a frontier ordered by priority. The
priority of an unfetched URL is the largest relevance of a fetched page
that links to it (soft focus). With hard focus, the links of a page are
followed only when its relevance is at least a threshold. Seeds have
priority 1. Ties go to the smaller URL. The heap uses lazy deletion: an
entry whose priority is no longer the current one is skipped.

A small multinomial naive Bayes classifier gives a relevance score in [0, 1].
"""

import heapq
import math
from collections import Counter
from typing import Callable, Hashable, Iterable, Optional


def focused_crawl(links: Callable[[Hashable], Iterable[Hashable]], seeds: Iterable[Hashable], relevance: Callable[[Hashable], float], budget: int, hard: Optional[float] = None) -> list[Hashable]:
    """Return the fetched URLs in the order of fetching, at most `budget` of them.

    links(u) gives the out-links of page u (the fetch). relevance(u) is in [0, 1].
    hard is None for soft focus, or the threshold for hard focus.
    """
    prio: dict = {}
    heap: list = []
    for s in seeds:  # @line L1
        if s not in prio:
            prio[s] = 1.0
            heapq.heappush(heap, (-1.0, s))
    fetched: set = set()  # @line L2
    order: list = []
    while heap and len(order) < budget:  # @line L3
        p, u = heapq.heappop(heap)  # @line L4
        if u in fetched or -p < prio[u]:  # @line L5
            continue
        out = list(links(u))  # @line L6
        fetched.add(u)
        order.append(u)
        r = relevance(u)
        if hard is not None and r < hard:  # @line L7
            continue
        for v in out:  # @line L8
            if v in fetched:
                continue
            if v not in prio or r > prio[v]:  # @line L9
                prio[v] = r  # @line L10
                heapq.heappush(heap, (-r, v))
    return order  # @line L11


def harvest_rate(order: list, relevant: Callable[[Hashable], bool]) -> float:
    """The fraction of fetched pages that are relevant."""
    if not order:
        return 0.0
    return sum(1 for u in order if relevant(u)) / len(order)


class NaiveBayes:
    """Multinomial naive Bayes for two classes (1 = on topic), with add-one smoothing."""

    def __init__(self, docs: list[list[str]], labels: list[int]) -> None:
        if set(labels) != {0, 1}:
            raise ValueError("need examples of both classes")
        self.count = [Counter(), Counter()]
        ndocs = [0, 0]
        for d, y in zip(docs, labels):
            self.count[y].update(d)
            ndocs[y] += 1
        self.vocab = set(self.count[0]) | set(self.count[1])
        self.total = [sum(c.values()) for c in self.count]
        self.prior = [math.log(n / len(docs)) for n in ndocs]

    def log_score(self, doc: list[str], y: int) -> float:
        v = len(self.vocab)
        s = self.prior[y]
        for w in doc:
            if w in self.vocab:  # words never seen in training are ignored
                s += math.log((self.count[y][w] + 1) / (self.total[y] + v))
        return s

    def prob(self, doc: list[str]) -> float:
        """P(on topic | doc) under the model."""
        d = self.log_score(doc, 0) - self.log_score(doc, 1)
        if d > 0:
            e = math.exp(-d)
            return e / (1.0 + e)
        return 1.0 / (1.0 + math.exp(d))
test_focused_crawling.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/focused-crawling/. The authors are listed in prov/CT80NW.jsonl.

import math
import random
from collections import deque

import pytest

from focused_crawling import NaiveBayes, focused_crawl, harvest_rate

TOPIC = ["t%d" % i for i in range(20)]
OTHER = ["g%d" % i for i in range(60)]


def text(rng: random.Random, on: bool, length: int = 30) -> list[str]:
    share = 0.3 if on else 0.03
    return [rng.choice(TOPIC) if rng.random() < share else rng.choice(OTHER) for _ in range(length)]


def planted(rng: random.Random, n: int, share: float, out: int, stay: float):
    """A web graph in which on-topic pages cluster: a link stays inside the class of its page with probability `stay`."""
    label = [rng.random() < share for _ in range(n)]
    group = {True: [u for u in range(n) if label[u]], False: [u for u in range(n) if not label[u]]}
    graph = {}
    for u in range(n):
        graph[u] = [rng.choice(group[label[u]]) if rng.random() < stay else rng.randrange(n) for _ in range(out)]
    words = [text(rng, label[u]) for u in range(n)]
    return graph, label, words


def classifier(rng: random.Random) -> NaiveBayes:
    labels = [i % 2 for i in range(200)]
    return NaiveBayes([text(rng, y == 1) for y in labels], labels)


def bfs_crawl(graph, seeds, budget):
    seen, queue, order = set(seeds), deque(seeds), []
    while queue and len(order) < budget:
        u = queue.popleft()
        order.append(u)
        for v in graph[u]:
            if v not in seen:
                seen.add(v)
                queue.append(v)
    return order


def reference(graph, seeds, rel, budget, hard):
    """Pick the next page by brute force: the unfetched page with the largest priority, ties to the smaller id."""
    order: list = []
    while len(order) < budget:
        prio = {s: 1.0 for s in seeds}
        for u in order:
            if hard is None or rel(u) >= hard:
                for v in graph[u]:
                    prio[v] = max(prio.get(v, -1.0), rel(u))
        cand = [(-p, v) for v, p in prio.items() if v not in order]
        if not cand:
            break
        order.append(min(cand)[1])
    return order


def reachable(graph, seeds):
    seen, stack = set(seeds), list(seeds)
    while stack:
        for v in graph[stack.pop()]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return seen


def setup(seed: int, n: int = 1000):
    rng = random.Random(seed)
    graph, label, words = planted(rng, n, share=0.2, out=6, stay=0.6)
    nb = classifier(rng)
    score = [nb.prob(w) for w in words]
    seeds = rng.sample([u for u in range(n) if label[u]], 3)
    return graph, label, score, seeds


def test_order_matches_brute_force() -> None:
    for seed in range(30):
        rng = random.Random(seed)
        n = rng.randrange(1, 40)
        graph = {u: [rng.randrange(n) for _ in range(rng.randrange(0, 4))] for u in range(n)}
        # Few distinct scores, so ties occur and the tie rule is tested.
        score = [rng.choice([0.0, 0.25, 0.5, 0.75, 1.0]) for _ in range(n)]
        seeds = rng.sample(range(n), rng.randrange(1, min(n, 3) + 1))
        budget = rng.randrange(1, n + 2)
        for hard in (None, 0.5):
            got = focused_crawl(graph.__getitem__, seeds, score.__getitem__, budget, hard)
            assert got == reference(graph, seeds, score.__getitem__, budget, hard)


def test_each_page_once_and_reachable() -> None:
    graph, label, score, seeds = setup(7)
    order = focused_crawl(graph.__getitem__, seeds, score.__getitem__, 10**9)
    assert len(order) == len(set(order))
    # Soft focus follows every link, so with no budget it fetches all reachable pages.
    assert set(order) == reachable(graph, seeds)
    hard = focused_crawl(graph.__getitem__, seeds, score.__getitem__, 10**9, hard=0.5)
    assert len(hard) == len(set(hard)) and set(hard) <= reachable(graph, seeds)


def test_hard_focus_follows_only_relevant_pages() -> None:
    graph, label, score, seeds = setup(8)
    order = focused_crawl(graph.__getitem__, seeds, score.__getitem__, 300, hard=0.5)
    # Every fetched page that is not a seed is linked from a fetched page with score at least 0.5.
    fetched = set(order)
    for v in order:
        if v not in seeds:
            assert any(v in graph[u] and score[u] >= 0.5 for u in fetched)


def test_budget_and_empty() -> None:
    graph = {0: [1, 2], 1: [], 2: []}
    assert focused_crawl(graph.__getitem__, [0], lambda u: 0.5, 2) == [0, 1]
    assert focused_crawl(graph.__getitem__, [], lambda u: 0.5, 5) == []
    assert focused_crawl(graph.__getitem__, [0], lambda u: 0.5, 0) == []


def test_small_example() -> None:
    # The example of the page: soft focus goes into the on-topic branch first.
    graph = {"a": ["b", "c"], "b": ["d", "e"], "c": ["f", "g"], "d": [], "e": [], "f": ["h"], "g": [], "h": []}
    score = {"a": 0.9, "b": 0.1, "c": 0.8, "d": 0.2, "e": 0.1, "f": 0.9, "g": 0.3, "h": 0.7}
    assert focused_crawl(graph.__getitem__, ["a"], score.__getitem__, 8) == ["a", "b", "c", "f", "h", "g", "d", "e"]
    assert focused_crawl(graph.__getitem__, ["a"], score.__getitem__, 8, hard=0.5) == ["a", "b", "c", "f", "h", "g"]
    assert bfs_crawl(graph, ["a"], 8) == ["a", "b", "c", "d", "e", "f", "g", "h"]


def test_harvest_rate_is_higher_than_bfs_on_planted_graphs() -> None:
    # A measured effect on these fixed seeds, not a theorem.
    focus, base = [], []
    for seed in range(10):
        graph, label, score, seeds = setup(100 + seed)
        on = label.__getitem__
        focus.append(harvest_rate(focused_crawl(graph.__getitem__, seeds, score.__getitem__, 200), on))
        base.append(harvest_rate(bfs_crawl(graph, seeds, 200), on))
    assert all(f > b for f, b in zip(focus, base))
    assert sum(focus) / 10 > sum(base) / 10 + 0.15


def test_naive_bayes_matches_direct_formula() -> None:
    nb = NaiveBayes([["a", "a", "b"], ["b", "c"]], [1, 0])
    # P(1) ∝ 1/2 · (2 + 1)/(3 + 3) and P(0) ∝ 1/2 · (0 + 1)/(2 + 3), so P(1 | "a") = 5/7.
    assert math.isclose(nb.prob(["a"]), 5 / 7)
    assert math.isclose(nb.prob(["zzz"]), 1 / 2)
    for d in (["a"] * 2000, ["c"] * 2000):
        assert 0.0 <= nb.prob(d) <= 1.0
    with pytest.raises(ValueError):
        NaiveBayes([["a"]], [1])

History

Early topical crawlers include the fish search of De Bra and Post in 1994 and the shark search of Hersovici and others in 1998. In 1998, Cho, Garcia-Molina and Page studied how to order a crawl frontier by importance, including the similarity of a page to a query. Chakrabarti, van den Berg and Dom presented focused crawling at the WWW8 conference in 1999, with a taxonomy classifier, the soft and hard focus rules, and a distiller for hubs. In their experiments, the focused crawler kept finding relevant pages over long crawls, while an unfocused crawler from the same seeds soon moved away from the topic. Menczer, Pant and Srinivasan compared best-first and adaptive topical crawlers in 2004, and found that best-first crawlers are strong baselines.

References

  1. Soumen Chakrabarti, Martin van den Berg and Byron Dom, Focused crawling: a new approach to topic-specific Web resource discovery, Computer Networks 31(11-16), 1999 (Proceedings of the Eighth International World Wide Web Conference), the description of the classifier, the soft and hard focus rules, the distiller, and the experiments that measure the harvest rate against an unfocused crawler
  2. Junghoo Cho, Hector Garcia-Molina and Lawrence Page, Efficient crawling through URL ordering, Computer Networks 30(1-7), 161-172, 1998 (Proceedings of the Seventh International World Wide Web Conference), the ordering metrics for the frontier, including the similarity of a page to a driving query, and the experiments on the Stanford web
  3. Filippo Menczer, Gautam Pant and Padmini Srinivasan, Topical web crawlers: evaluating adaptive algorithms, ACM Transactions on Internet Technology 4(4), 2004, the comparison of best-first, breadth-first and adaptive topical crawlers, and the harvest rate and target recall measures
  4. Christopher Olston and Marc Najork, Web crawling, Foundations and Trends in Information Retrieval 4(3), 175-246, 2010, the section on scoped crawling, which covers topical crawlers

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.expected
  • 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
  • a scene preset for the example