Algorithm Search⌘K

Algorithmadvanced

TrustRank

Also called Gyongyi-Garcia-Molina-Pedersen TrustRank.

Propagates trust from a hand-checked seed set of good pages by a biased PageRank, so spam pages get low trust scores.

Time
O(M (n + m) + n log n) worst
Space
O(n) extra
Where
M = the number of rounds of each power iteration; m = the number of links; n = the number of pages
Properties
deterministicdirectediterativenot weighted
Origin
Zoltan Gyongyi, Hector Garcia Molina, Jan Pedersen, 2004

TrustRank is a link analysis algorithm that gives each web page a trust score by spreading trust from a small seed set of pages that a person has checked and found good. Zoltán Gyöngyi, Hector Garcia-Molina and Jan Pedersen published it in 2004 as a defence against link spam. The computation is a personalized PageRank whose jump vector is uniform on the good seeds, with two differences from the usual personalized PageRank: a human oracle picks the seeds from the pages with the highest inverse PageRank, and the trust that reaches a page with no out-link is dropped instead of being sent back, so the scores sum to at most 1. Spam pages get low trust because good pages seldom link to spam.

In plain words

Spam pages try to look important by collecting many links. TrustRank starts from a few pages that a person has checked and found good, such as the home pages of universities or of large companies. Each of these pages gets an equal share of trust. In each round, every page passes most of its trust along its links, in equal parts, and the seed pages get a fresh share again. Good pages seldom link to spam, so trust flows mostly to good pages. Spam pages can link to each other as much as they like, but this makes no new trust. Trust also gets weaker at each link it crosses, so a page far from all seeds gets little. To choose the seeds, the method looks for pages from which many other pages can be reached, and asks a person to check only the best of them.

The problem

The input is a directed graph G=(V,E)G = (V, E) of web pages (or of web sites, as in the paper), with V={0,…,n−1}V = \{0, \ldots, n - 1\} and mm links, an oracle OO that says for a page whether it is good (O(p)=1O(p) = 1) or spam (O(p)=0O(p) = 0), a limit LL on the number of oracle calls, a decay factor αB∈[0,1)\alpha_B \in [0, 1) and a number of rounds MBM_B. Self links are removed and repeated links count once. The output is a trust score t(p)≥0t(p) \ge 0 for each page. Pages are ranked by trust, highest first, and equal scores go to the smaller page number.

The oracle is expensive: in practice it is a person who looks at the page. So the method may call it only LL times, and the rest of the graph is judged by its links alone. The method rests on one assumption, which the paper calls approximate isolation of the good set: good pages seldom link to spam pages, while spam pages may link to good pages. This is a property of the web that the paper observes, not a theorem.

The algorithm

Let ω(q)\omega(q) be the out-degree of page qq. The transition matrix is Tpq=1/ω(q)T_{pq} = 1/\omega(q) if (q,p)∈E(q, p) \in E and 00 otherwise. A column of a page with no out-link is all zero, so TT loses the mass that reaches such a page. Inverse PageRank is PageRank on the graph with every link reversed: the same update as line L6, with the transition matrix of the reversed graph and the uniform vector (1/n,…,1/n)(1/n, \ldots, 1/n) in place of dd. A page with a high inverse PageRank reaches many pages in few steps, which makes it a useful seed.

  1. TRUSTRANK(G, O, L, αB, MB)
  2. 1s ← INVERSE-PAGERANK(G) ▷ seed desirability, αI = 0.85 and MI = 20 rounds
  3. 2σ ← the pages in order of s, highest first, ties to the smaller page
  4. 3d ← 0; for i ← 1 to L: if O(σ(i)) = 1 then d(σ(i)) ← 1
  5. 4d ← d / |d| ▷ |d| is the number of good seeds; fail if 0
  6. 5t ← d
  7. 6repeat MB times: t ← αB · T · t + (1 - αB) · d
  8. 7return t

Lines L1 to L4 choose the seeds and cost LL oracle calls. Lines L5 and L6 are the biased PageRank: the walker follows a random out-link with probability αB\alpha_B and jumps to a random good seed with probability 1−αB1 - \alpha_B. The paper uses αB=0.85\alpha_B = 0.85 and MB=20M_B = 20. As MBM_B grows, tt tends to the fixed point

t∗=αBTt∗+(1−αB)d=(1−αB)∑k≥0αBkTkd.t^* = \alpha_B T t^* + (1 - \alpha_B) d = (1 - \alpha_B) \sum_{k \ge 0} \alpha_B^k T^k d.

Each term of the sum is the trust that arrives along walks of exactly kk links from the seeds, multiplied by αBk\alpha_B^k. The factor αBk\alpha_B^k is the trust dampening of the paper, and the division by ω(q)\omega(q) inside TT is its trust splitting: a page that links to many pages gives each of them a smaller part.

Example

Take seven pages. Pages 0 to 3 are good and pages 4 to 6 form a small link farm. The links are 0→10 \to 1, 1→21 \to 2, 2→02 \to 0, 2→32 \to 3, 3→03 \to 0, 3→43 \to 4, 4→04 \to 0, 4→54 \to 5, 5→45 \to 4, 5→65 \to 6 and 6→46 \to 4. The link 3→43 \to 4 is a good page that points to spam, for example through a comment that a spammer posted. The farm also links back to page 0 to look normal. Every page has an out-link, so no trust leaks.

With L=3L = 3 and 20 rounds of inverse PageRank, the three pages with the highest inverse PageRank are 4, 2 and 1. The oracle rejects page 4 and accepts the other two, so d=(0,12,12,0,0,0,0)d = (0, \tfrac12, \tfrac12, 0, 0, 0, 0). The first round of line L6 gives page 2 the value 0.15⋅12+0.85⋅12=120.15 \cdot \tfrac12 + 0.85 \cdot \tfrac12 = \tfrac12 (page 1 sends its whole trust to page 2), pages 0 and 3 each get 0.85⋅12⋅12=17800.85 \cdot \tfrac12 \cdot \tfrac12 = \tfrac{17}{80} from page 2, and page 1 keeps only its jump share 340\tfrac{3}{40}. The table gives the exact fixed point t∗t^* and, for comparison, the PageRank with a uniform jump vector and the same α=0.85\alpha = 0.85, both to 4 places.

page 0 1 2 3 4 5 6
inverse PageRank (20 rounds) 0.1608 0.1639 0.1676 0.1184 0.1816 0.1348 0.0729
PageRank 0.2108 0.2006 0.1919 0.1030 0.1506 0.0854 0.0577
TrustRank t∗t^* 0.2088 0.2524 0.2896 0.1231 0.0786 0.0334 0.0142

PageRank puts the spam page 4 above the good page 3. TrustRank puts every good page above every spam page, and page 4 keeps about half of its PageRank. The trust sums to exactly 1, as Theorem 4 of the proof file says for a graph with no dangling page in reach. After the 20 rounds of the paper, the sum of the errors is about 0.0001, well inside the bound 2⋅0.8520≈0.0782 \cdot 0.85^{20} \approx 0.078.

Correctness

The file proofs/correctness.md proves five facts. The fixed point t∗t^* exists, is unique and is nonnegative, because ∥αBTx∥1≤αB∥x∥1\lVert \alpha_B T x \rVert_1 \le \alpha_B \lVert x \rVert_1. After MM rounds the sum of the errors is at most αBM∥d−t∗∥1≤2αBM\alpha_B^M \lVert d - t^* \rVert_1 \le 2 \alpha_B^M. A page has positive trust exactly when it can be reached from a seed, and a page at link distance kk from the nearest seed has trust at most αBk\alpha_B^k. The total trust is 1 when no page in reach is dangling, and less than 1 otherwise. A set of pages with no seed holds at most αB/(1−αB)\alpha_B / (1 - \alpha_B) times the trust that links from outside bring into it.

The last fact is the formal side of approximate isolation. With αB=0.85\alpha_B = 0.85, a link farm can hold at most 17/317/3 times the trust that its links from good pages carry in, however many pages it adds. These facts hold for every seed set. Whether the seeds cover the good web well, and whether good pages really avoid linking to spam, are questions that only measurement can answer.

Proof: TrustRank has a unique fixed point, its iteration converges at rate alpha, and trust stays near the seedsfull

Let V={0,…,n−1}V = \{0, \ldots, n-1\} be the pages and EE the links, with self links removed and repeated links counted once. Let ω(q)\omega(q) be the out-degree of qq. The matrix TT has Tpq=1/ω(q)T_{pq} = 1/\omega(q) for each link (q,p)∈E(q, p) \in E and 00 elsewhere. The seed vector dd has d(s)=1/∣S∣d(s) = 1/|S| for each good seed s∈Ss \in S and 00 elsewhere, with S≠∅S \neq \emptyset. Fix α∈[0,1)\alpha \in [0, 1). Line L6 of the algorithm computes t0=dt_0 = d and tk+1=αTtk+(1−α)dt_{k+1} = \alpha T t_k + (1 - \alpha) d. For a vector xx, ∥x∥1=∑p∣xp∣\lVert x \rVert_1 = \sum_p |x_p| and 1⊤x=∑pxp\mathbf{1}^\top x = \sum_p x_p.

Lemma 1 (leaky columns). Column qq of TT sums to 11 if ω(q)>0\omega(q) > 0 and to 00 if ω(q)=0\omega(q) = 0. So ∥Tx∥1≤∥x∥1\lVert T x \rVert_1 \le \lVert x \rVert_1 for every real vector xx, and 1⊤Tx=∑q:ω(q)>0xq\mathbf{1}^\top T x = \sum_{q : \omega(q) > 0} x_q.

Proof. Column qq has the entry 1/ω(q)1/\omega(q) in the ω(q)\omega(q) rows pp with (q,p)∈E(q, p) \in E, and no other nonzero entry. Then ∥Tx∥1=∑p∣∑qTpqxq∣≤∑q∣xq∣∑pTpq≤∥x∥1\lVert T x \rVert_1 = \sum_p \lvert \sum_q T_{pq} x_q \rvert \le \sum_q |x_q| \sum_p T_{pq} \le \lVert x \rVert_1 by the triangle inequality, and 1⊤Tx=∑qxq∑pTpq\mathbf{1}^\top T x = \sum_q x_q \sum_p T_{pq} is the sum over the pages with an out-link. □\square

Theorem 1 (fixed point). The equation t=αTt+(1−α)dt = \alpha T t + (1 - \alpha) d has exactly one solution,

t∗=(1−α)∑k≥0αkTkd,t^* = (1 - \alpha) \sum_{k \ge 0} \alpha^k T^k d,

and t∗≥0t^* \ge 0 entrywise.

Proof. By Lemma 1, ∥αkTkd∥1≤αk\lVert \alpha^k T^k d \rVert_1 \le \alpha^k, so the series converges absolutely. Put t∗t^* into the right side: αTt∗+(1−α)d=(1−α)∑k≥0αk+1Tk+1d+(1−α)d=t∗\alpha T t^* + (1 - \alpha) d = (1 - \alpha) \sum_{k \ge 0} \alpha^{k+1} T^{k+1} d + (1 - \alpha) d = t^*. If tt and uu are two solutions, then t−u=αT(t−u)t - u = \alpha T (t - u), so ∥t−u∥1≤α∥t−u∥1\lVert t - u \rVert_1 \le \alpha \lVert t - u \rVert_1 by Lemma 1, and α<1\alpha < 1 forces t=ut = u. Each term of the series has nonnegative entries, because TT and dd do. □\square

The same argument shows that I−αTI - \alpha T is invertible: if (I−αT)x=0(I - \alpha T) x = 0 then ∥x∥1≤α∥x∥1\lVert x \rVert_1 \le \alpha \lVert x \rVert_1, so x=0x = 0. So the exact solver of the implementation, which solves (I−αT)t=(1−α)d(I - \alpha T) t = (1 - \alpha) d by Gaussian elimination in rational numbers, always finds a pivot and returns t∗t^*.

Theorem 2 (rate). After MM rounds, ∥tM−t∗∥1≤αM∥d−t∗∥1≤2αM\lVert t_M - t^* \rVert_1 \le \alpha^M \lVert d - t^* \rVert_1 \le 2 \alpha^M.

Proof. Subtract the fixed point equation from the update: tk+1−t∗=αT(tk−t∗)t_{k+1} - t^* = \alpha T (t_k - t^*). By Lemma 1 and induction, ∥tM−t∗∥1≤αM∥t0−t∗∥1\lVert t_M - t^* \rVert_1 \le \alpha^M \lVert t_0 - t^* \rVert_1, and t0=dt_0 = d. Both dd and t∗t^* are nonnegative with sums at most 11 (Theorem 4 below), so ∥d−t∗∥1≤1⊤d+1⊤t∗≤2\lVert d - t^* \rVert_1 \le \mathbf{1}^\top d + \mathbf{1}^\top t^* \le 2. □\square

With α=0.85\alpha = 0.85 and M=20M = 20, as in the paper, the bound is 2⋅0.8520≈0.0782 \cdot 0.85^{20} \approx 0.078. This is a worst-case bound on the sum of the errors; the error is often much smaller, but the bound is what the method guarantees.

Theorem 3 (support and dampening). t∗(p)>0t^*(p) > 0 if and only if a directed path leads from some seed to pp (a seed is reached by the empty path). If the shortest such path has kk links, then t∗(p)≤αkt^*(p) \le \alpha^k.

Proof. Expand (Tjd)(p)=∑q0,…,qjd(q0)Tq1q0⋯Tqjqj−1(T^j d)(p) = \sum_{q_0, \ldots, q_j} d(q_0) T_{q_1 q_0} \cdots T_{q_j q_{j-1}} over the sequences with qj=pq_j = p. A term is positive exactly when q0q_0 is a seed and each (qi−1,qi)(q_{i-1}, q_i) is a link, so (Tjd)(p)>0(T^j d)(p) > 0 exactly when a walk of jj links leads from a seed to pp. All terms of the series of Theorem 1 are nonnegative and each (1−α)αj(1 - \alpha)\alpha^j is positive, so t∗(p)>0t^*(p) > 0 exactly when such a walk exists for some jj, that is, when pp is reachable. If no walk shorter than kk links reaches pp, the terms with j<kj < k are 00 at pp, and by Lemma 1 (Tjd)(p)≤1⊤Tjd≤1(T^j d)(p) \le \mathbf{1}^\top T^j d \le 1, so t∗(p)≤(1−α)∑j≥kαj=αkt^*(p) \le (1 - \alpha) \sum_{j \ge k} \alpha^j = \alpha^k. □\square

Theorem 4 (total trust). 1⊤t∗≤1\mathbf{1}^\top t^* \le 1, with equality if and only if no page reachable from the seeds is dangling (has no out-link).

Proof. Let mj=1⊤Tjdm_j = \mathbf{1}^\top T^j d. By Lemma 1, mj+1=mj−∑q:ω(q)=0(Tjd)(q)≤mjm_{j+1} = m_j - \sum_{q : \omega(q) = 0} (T^j d)(q) \le m_j, and m0=1m_0 = 1. So 1⊤t∗=(1−α)∑jαjmj≤1\mathbf{1}^\top t^* = (1 - \alpha) \sum_j \alpha^j m_j \le 1. If no reachable page is dangling, then by the proof of Theorem 3 the vector TjdT^j d is 00 outside the reachable pages, so the subtracted sum is 00, every mj=1m_j = 1, and the total is 11. If a reachable page qq is dangling, then (Tjd)(q)>0(T^j d)(q) > 0 for some jj by Theorem 3, so mj+1<mj≤1m_{j+1} < m_j \le 1, hence mi<1m_i < 1 for all i>ji > j and the total is less than 11. □\square

Theorem 5 (leak into a set). Let U⊆VU \subseteq V contain no seed, and let X=∑(q,p)∈E, q∉U, p∈Ut∗(q)/ω(q)X = \sum_{(q, p) \in E,\ q \notin U,\ p \in U} t^*(q)/\omega(q) be the trust that links from outside bring into UU. Then ∑p∈Ut∗(p)≤α1−αX\sum_{p \in U} t^*(p) \le \frac{\alpha}{1 - \alpha} X.

Proof. For p∈Up \in U, d(p)=0d(p) = 0, so the fixed point equation gives t∗(p)=α∑(q,p)∈Et∗(q)/ω(q)t^*(p) = \alpha \sum_{(q, p) \in E} t^*(q)/\omega(q). Sum over p∈Up \in U and split the links by whether q∈Uq \in U. The links from outside give XX. A page q∈Uq \in U sends t∗(q)/ω(q)t^*(q)/\omega(q) along each of its ω(q)\omega(q) links, so the links inside UU give at most ∑q∈Ut∗(q)\sum_{q \in U} t^*(q). Write tUt_U for this sum. Then tU≤α(X+tU)t_U \le \alpha (X + t_U), so tU≤αX/(1−α)t_U \le \alpha X / (1 - \alpha). □\square

For α=0.85\alpha = 0.85 the factor is 17/3≈5.6717/3 \approx 5.67. A link farm with no link from a reachable page has X=0X = 0 and so no trust (Theorem 3 says the same). A farm that gets links from good pages can hold at most 17/317/3 times the trust that those links carry in, however many pages it has.

Seed selection. Lines L1 to L4 only choose dd: they rank the pages by inverse PageRank (Theorem 1 applies to it with the reversed links and dd uniform), take the first LL pages in that order with ties to the smaller page, and keep those that the oracle calls good. The results above hold for every nonempty seed set, so they do not depend on how good the seed choice is. How well the seeds cover the good part of the web is a measured property; the paper notes that an exact choice of the seeds that reach the most pages is a hard combinatorial problem, and uses inverse PageRank as a heuristic.

Complexity

Each round of line L6 reads every link once, so it costs Θ(n+m)\Theta(n + m) time on the word RAM with floating point numbers. Line L1 costs the same for each of its rounds, and line L2 sorts the pages in O(nlog⁡n)O(n \log n). With MM rounds in each of the two iterations, the total time is O(M(n+m)+nlog⁡n)O(M (n + m) + n \log n), plus LL oracle calls. Removing repeated links costs O(n+m)O(n + m) by counting sort on the pairs; the implementation sorts the links instead, in O(mlog⁡m)O(m \log m), so that the sums run in a fixed order. Besides the graph, the method keeps the out-degrees and two vectors of length nn, so the extra space is Θ(n)\Theta(n). The human work, LL checks, is the real cost: the paper evaluated 1,250 sites by hand to get its seeds.

Properties

  • Linear in the seeds. t∗t^* is a linear function of dd, so t∗=∑sd(s) ts∗t^* = \sum_{s} d(s)\, t^*_s, where ts∗t^*_s is the vector for the single seed ss. A new seed can be added without a full new run, if the single-seed vectors are kept.
  • No trust from nothing. A page that no seed reaches has trust exactly 0, so an isolated farm gets nothing, whatever its size or structure.
  • Leaks are allowed. The scores sum to at most 1, and the sum is below 1 when a dangling page is in reach. The paper keeps this leak; it does not send the lost trust back to the seeds.
  • Deterministic. With a fixed oracle and the tie rule of line L2, the output depends only on the graph.

Variants and improvements

  • Other seed choices. Section 5.2 of the paper also tries the pages with the highest PageRank as seed candidates. Inverse PageRank prefers pages from which many pages are reachable, which is closer to the goal of covering the good web.
  • Spam mass. Gyöngyi, Berkhin, Garcia-Molina and Pedersen (2006) compare the PageRank of a page with its biased PageRank from a large set of known good pages. The difference estimates how much of the PageRank comes from spam, which finds spam that low trust alone does not mark.
  • Distrust. Later methods also spread distrust from known spam pages, along the links in reverse, because a page that links to spam is suspect. This uses the same biased PageRank on the reversed graph.
  • Exact solution. For a small graph, the linear system (I−αBT)t=(1−αB)d(I - \alpha_B T) t = (1 - \alpha_B) d gives t∗t^* directly by Gaussian elimination. The test file uses this, in rational numbers, as the reference.

When to use it

Use TrustRank when you can pay for some hundreds of human checks and you need a signal that demotes pages which gain their rank from link farms. It works as one feature among many, next to content features and anchor text. It is a poor tool to label single pages: low trust means only that a page is far from the seeds, which is also true of many good pages in parts of the web that the seeds do not reach.

Pitfalls

  • One bad seed spoils the result. A spam page in the seed set gives trust to its whole farm. The oracle must be a careful human check, and seeds must be pages that stay under the same control over time.
  • The dangling rule changes the numbers. If an implementation sends the trust of dangling pages back to the seeds, or spreads it uniformly, the scores differ from the paper's. Say which rule you use.
  • Twenty rounds are not convergence. The bound after MB=20M_B = 20 rounds is 2⋅0.8520≈0.0782 \cdot 0.85^{20} \approx 0.078 on the sum of the errors. That is enough to rank, but not to compare scores across runs with different MBM_B.
  • Coverage gaps look like spam. Good pages in a region with no seed get trust near 0. Pick seeds from many topics and regions, or combine trust with other signals.
  • Spammers can buy good links. Links from blog comments, wikis and expired domains carry trust into a farm. The leak bound limits the gain from each such link, but it does not stop it.
  • Pages or sites. The paper runs on the graph of web sites, in which a link between two sites counts once. On the page graph, links inside one site add weight that the site owner controls.

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.

trustrank.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trustrank/. The authors are listed in prov/Y8VX0X.jsonl.
"""TrustRank of Gyongyi, Garcia-Molina and Pedersen (VLDB 2004).

Pages are the integers 0 to n - 1. An edge (q, p) is a link from q to p.
Self links are removed and repeated links count once, as in the paper.
The transition matrix is T[p][q] = 1 / out(q) for each link (q, p), so a
page with no out-link passes no trust on and its trust leaks away.
"""

from fractions import Fraction
from typing import Callable, Iterable, Sequence

Number = float | Fraction


def clean_links(n: int, edges: Iterable[tuple[int, int]]) -> list[tuple[int, int]]:
    """Distinct links (q, p) with q != p, sorted."""
    arcs = set()
    for q, p in edges:
        if not (0 <= q < n and 0 <= p < n):
            raise ValueError("page out of range")
        if q != p:
            arcs.add((q, p))
    return sorted(arcs)


def biased_pagerank(n: int, edges: Iterable[tuple[int, int]], d: Sequence[Number], alpha: Number = 0.85, rounds: int = 20) -> list[Number]:
    """Start from t = d and apply t <- alpha T t + (1 - alpha) d for the given number of rounds.

    Works with floats, or exactly with Fraction values of alpha and d.
    """
    arcs = clean_links(n, edges)
    out = [0] * n
    for q, _ in arcs:
        out[q] += 1
    t = list(d)  # @line L5
    for _ in range(rounds):  # @line L6
        new = [(1 - alpha) * d[p] for p in range(n)]
        for q, p in arcs:
            new[p] += alpha * t[q] / out[q]
        t = new
    return t


def inverse_pagerank(n: int, edges: Iterable[tuple[int, int]], alpha: Number = 0.85, rounds: int = 20) -> list[Number]:
    """PageRank on the graph with every link reversed, with the uniform jump vector."""
    rev = [(p, q) for q, p in clean_links(n, edges)]
    one = Fraction(1, n) if isinstance(alpha, Fraction) else 1.0 / n
    return biased_pagerank(n, rev, [one] * n, alpha, rounds)


def select_seeds(scores: Sequence[Number], oracle: Callable[[int], bool], limit: int) -> list[int]:
    """The pages among the top `limit` by score (ties: smaller page first) that the oracle calls good."""
    order = sorted(range(len(scores)), key=lambda p: (-scores[p], p))  # @line L2
    return [p for p in order[:limit] if oracle(p)]  # @line L3


def seed_vector(n: int, seeds: Sequence[int], exact: bool = False) -> list[Number]:
    """The vector d with d(p) = 1 / |seeds| on each seed and 0 elsewhere."""
    if not seeds:
        raise ValueError("no good seed page")
    w: Number = Fraction(1, len(seeds)) if exact else 1.0 / len(seeds)  # @line L4
    zero: Number = Fraction(0) if exact else 0.0
    d = [zero] * n
    for s in seeds:
        d[s] = w
    return d


def trustrank(n: int, edges: Sequence[tuple[int, int]], oracle: Callable[[int], bool], limit: int, alpha: float = 0.85, rounds: int = 20, seed_alpha: float = 0.85, seed_rounds: int = 20) -> tuple[list[float], list[int]]:
    """Return (trust scores, good seeds) as in Figure 5 of the paper."""
    s = inverse_pagerank(n, edges, seed_alpha, seed_rounds)  # @line L1
    seeds = select_seeds(s, oracle, limit)
    d = seed_vector(n, seeds)
    return biased_pagerank(n, edges, d, alpha, rounds), seeds  # @line L7


def _solve(a: list[list[Fraction]], b: list[Fraction]) -> list[Fraction]:
    """Solve a x = b exactly by Gaussian elimination with Fraction entries."""
    n = len(b)
    m = [row[:] + [b[i]] for i, row in enumerate(a)]
    for c in range(n):
        piv = next(r for r in range(c, n) if m[r][c] != 0)
        m[c], m[piv] = m[piv], m[c]
        for r in range(n):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                m[r] = [x - f * y for x, y in zip(m[r], m[c])]
    return [m[i][n] / m[i][i] for i in range(n)]


def trustrank_exact(n: int, edges: Iterable[tuple[int, int]], seeds: Sequence[int], alpha: Fraction = Fraction(17, 20)) -> list[Fraction]:
    """The fixed point t = alpha T t + (1 - alpha) d, from (I - alpha T) t = (1 - alpha) d."""
    arcs = clean_links(n, edges)
    out = [0] * n
    for q, _ in arcs:
        out[q] += 1
    a = [[Fraction(int(i == j)) for j in range(n)] for i in range(n)]
    for q, p in arcs:
        a[p][q] -= alpha / out[q]
    d = seed_vector(n, seeds, exact=True)
    return _solve(a, [(1 - alpha) * x for x in d])
test_trustrank.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trustrank/. The authors are listed in prov/Y8VX0X.jsonl.

import random
from fractions import Fraction

import pytest

from trustrank import biased_pagerank, clean_links, inverse_pagerank, seed_vector, select_seeds, trustrank, trustrank_exact

ALPHA = Fraction(17, 20)

# The example graph of the page: good pages 0 to 3, spam pages 4 to 6.
N = 7
E = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 0), (3, 4), (4, 5), (5, 6), (6, 4), (5, 4), (4, 0)]
GOOD = {0, 1, 2, 3}


def random_graph(rng: random.Random, n: int) -> list[tuple[int, int]]:
    return [(q, p) for q in range(n) for p in range(n) if rng.random() < 0.3]


def reachable(n: int, edges: list[tuple[int, int]], start: list[int]) -> set[int]:
    adj: dict[int, list[int]] = {}
    for q, p in clean_links(n, edges):
        adj.setdefault(q, []).append(p)
    seen, stack = set(start), list(start)
    while stack:
        q = stack.pop()
        for p in adj.get(q, []):
            if p not in seen:
                seen.add(p)
                stack.append(p)
    return seen


def test_example() -> None:
    inv = inverse_pagerank(N, E)
    assert sorted(range(N), key=lambda p: (-inv[p], p))[:3] == [4, 2, 1]
    t, seeds = trustrank(N, E, lambda p: p in GOOD, 3)
    assert seeds == [2, 1]
    exact = trustrank_exact(N, E, seeds)
    want = [0.2088, 0.2524, 0.2896, 0.1231, 0.0786, 0.0334, 0.0142]
    assert all(abs(float(x) - w) < 5e-5 for x, w in zip(exact, want))
    assert sum(exact) == 1
    assert sum(abs(a - float(b)) for a, b in zip(t, exact)) <= 2 * 0.85**20
    # Every good page has more trust than every spam page.
    assert min(exact[p] for p in GOOD) > max(exact[p] for p in range(N) if p not in GOOD)


def test_example_rounds_exact() -> None:
    d = seed_vector(N, [2, 1], exact=True)
    t1 = biased_pagerank(N, E, d, ALPHA, 1)
    assert t1 == [Fraction(17, 80), Fraction(3, 40), Fraction(1, 2), Fraction(17, 80), 0, 0, 0]


def test_fixed_point_is_exact() -> None:
    rng = random.Random(7)
    for _ in range(40):
        n = rng.randrange(1, 8)
        edges = random_graph(rng, n)
        seeds = sorted(rng.sample(range(n), rng.randrange(1, n + 1)))
        t = trustrank_exact(n, edges, seeds)
        d = seed_vector(n, seeds, exact=True)
        # t = alpha T t + (1 - alpha) d holds exactly.
        arcs = clean_links(n, edges)
        out = [0] * n
        for q, _ in arcs:
            out[q] += 1
        rhs = [(1 - ALPHA) * d[p] for p in range(n)]
        for q, p in arcs:
            rhs[p] += ALPHA * t[q] / out[q]
        assert rhs == t


def test_iteration_error_bound() -> None:
    # The L1 error after M rounds is at most alpha^M times |d - t*|, which is at most 2 alpha^M.
    rng = random.Random(11)
    for _ in range(40):
        n = rng.randrange(1, 9)
        edges = random_graph(rng, n)
        seeds = sorted(rng.sample(range(n), rng.randrange(1, n + 1)))
        exact = [float(x) for x in trustrank_exact(n, edges, seeds)]
        d = seed_vector(n, seeds)
        for m in (0, 1, 5, 20, 200):
            t = biased_pagerank(n, edges, d, 0.85, m)
            err = sum(abs(a - b) for a, b in zip(t, exact))
            assert err <= 2 * 0.85**m + 1e-12
        assert err <= 1e-9


def test_unreachable_pages_get_zero_and_trust_leaks() -> None:
    rng = random.Random(3)
    for _ in range(60):
        n = rng.randrange(1, 9)
        edges = random_graph(rng, n)
        seeds = sorted(rng.sample(range(n), rng.randrange(1, n + 1)))
        t = trustrank_exact(n, edges, seeds)
        reach = reachable(n, edges, seeds)
        assert all((t[p] > 0) == (p in reach) for p in range(n))
        out = {q for q, _ in clean_links(n, edges)}
        dangling_in_reach = any(p not in out for p in reach)
        assert (sum(t) < 1) == dangling_in_reach
        assert sum(t) <= 1


def test_dampening_and_leak_bound() -> None:
    # A page at link distance k from the seeds has trust at most alpha^k. A set S with no
    # seed holds at most alpha / (1 - alpha) times the trust that its in-links bring from outside.
    rng = random.Random(5)
    for _ in range(60):
        n = rng.randrange(2, 9)
        edges = random_graph(rng, n)
        seeds = sorted(rng.sample(range(n), rng.randrange(1, n)))
        t = trustrank_exact(n, edges, seeds)
        arcs = clean_links(n, edges)
        dist = {s: 0 for s in seeds}
        layer = list(seeds)
        while layer:
            nxt = []
            for q, p in arcs:
                if q in layer and p not in dist:
                    dist[p] = dist[q] + 1
                    nxt.append(p)
            layer = nxt
        for p, k in dist.items():
            assert t[p] <= ALPHA**k
        out = [0] * n
        for q, _ in arcs:
            out[q] += 1
        rest = [p for p in range(n) if p not in seeds]
        s = set(rng.sample(rest, rng.randrange(1, len(rest) + 1)))
        inflow = sum(t[q] / out[q] for q, p in arcs if p in s and q not in s)
        assert sum(t[p] for p in s) <= ALPHA / (1 - ALPHA) * inflow


def test_isolated_spam_farm_gets_no_trust() -> None:
    # A farm of k pages that all point to a target and back, with no link from a good page.
    for k in (1, 5, 30):
        n = 3 + 1 + k
        edges = [(0, 1), (1, 2), (2, 0), (3, 0)]
        edges += [(3, 4 + i) for i in range(k)] + [(4 + i, 3) for i in range(k)]
        t = trustrank_exact(n, edges, [0])
        assert all(t[p] == 0 for p in range(3, n))
        assert t[0] + t[1] + t[2] == 1


def test_links_are_cleaned() -> None:
    assert clean_links(3, [(0, 1), (0, 1), (1, 1), (2, 0)]) == [(0, 1), (2, 0)]
    with pytest.raises(ValueError):
        clean_links(2, [(0, 2)])
    a = trustrank_exact(3, [(0, 1), (0, 1), (1, 1), (1, 2), (2, 0)], [0])
    b = trustrank_exact(3, [(0, 1), (1, 2), (2, 0)], [0])
    assert a == b


def test_seed_selection() -> None:
    assert select_seeds([0.5, 0.5, 0.9, 0.1], lambda p: p != 2, 3) == [0, 1]
    assert select_seeds([0.5, 0.5, 0.9, 0.1], lambda p: True, 0) == []
    with pytest.raises(ValueError):
        trustrank(N, E, lambda p: False, 3)


def test_inverse_pagerank_is_pagerank_of_reversed_graph() -> None:
    rev = [(p, q) for q, p in E]
    assert inverse_pagerank(N, E, ALPHA, 6) == biased_pagerank(N, rev, [Fraction(1, N)] * N, ALPHA, 6)

History

Gyöngyi, Garcia-Molina and Pedersen presented TrustRank at the VLDB conference in 2004; the work was done at Stanford University and Yahoo!. They tested it on a graph of 31,003,946 web sites that the AltaVista search engine had crawled in August 2003. To get seeds, they ran inverse PageRank, kept the top 25,000 sites, checked by hand the first 1,250 of those that major web directories listed, and kept 178 of them as good seeds. They then judged a sample of sites from each range of scores, and reported that the high trust ranges held fewer spam sites than the high PageRank ranges. These results are measurements on that one graph and one sample.

References

  1. Zoltan Gyongyi, Hector Garcia-Molina and Jan Pedersen, Combating Web spam with TrustRank, Proceedings of the 30th International Conference on Very Large Data Bases (VLDB 2004), 576-587, Section 4.2 (trust dampening and trust splitting), Section 4.3 and Figure 5 (the algorithm with alpha_B = 0.85 and M_B = 20), Section 5.1 (inverse PageRank for seed selection) and Section 6 (the AltaVista experiments)
  2. Taher H. Haveliwala, Topic-sensitive PageRank, Proceedings of the 11th International World Wide Web Conference (WWW 2002), 517-526, the PageRank vector biased toward a chosen set of pages by its jump vector, which is the computation that TrustRank runs with the good seeds
  3. Zoltan Gyongyi, Pavel Berkhin, Hector Garcia-Molina and Jan Pedersen, Link spam detection based on mass estimation, Proceedings of the 32nd International Conference on Very Large Data Bases (VLDB 2006), the definition of spam mass, the part of the PageRank of a page that comes from spam pages, estimated with a biased PageRank on a good core

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