Algorithmadvanced
SALSA
Also called stochastic approach for link-structure analysis.
Scores hubs and authorities of a query subgraph by two random walks on its bipartite hub-authority graph; the scores reduce to degrees weighted by component size.
- Solves
- Link-analysis ranking
- Time
- O(n + m) worst
- Space
- O(n + m) extra
- Where
- m = the number of links among them; n = the number of pages in the base set
- Model
- Word RAM
- Properties
- deterministicdirectediterativenot weighted
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ronny Lempel, Shlomo Moran, 2000
SALSA (the stochastic approach for link-structure analysis) is a link analysis algorithm that gives each page of a small query graph a hub score and an authority score, as the stationary distributions of two random walks on the bipartite graph of hubs and authorities. Ronny Lempel and Shlomo Moran introduced it in 2000 as a stochastic form of HITS. Their analysis shows that the scores need no iteration at all: inside each connected component, the authority score of a page is proportional to its in-degree, and the component as a whole gets a weight proportional to its number of authorities. Because each vote is divided by the degrees, a tightly knit block of pages cannot take all the weight, as it does in HITS.
In plain words
Search engines first collect a small set of pages about a query, with the pages that link to them and the pages they link to. Some pages are good lists of links (hubs) and some are good sources (authorities). SALSA imagines a walker who stands on a source page, goes back along a random link to a page that points to it, and then forward along a random link of that list. The fraction of time the walker spends on a page is its authority score. A second walker does the same with the roles of lists and sources swapped. When all the pages are joined together, the time spent on a source turns out to depend only on how many pages point to it. When the graph falls into separate parts, each part gets a share that depends on its size.
The problem
The input is the base set of a query: a directed graph on pages with links, built as for HITS from a root set of pages that match the query, plus the pages that link to the root set and the pages that the root set links to. Self links are removed and repeated links count once. Write and for the degrees. The hub side is and the authority side is ; a page can be on both sides. The bipartite graph has an edge between hub and authority for each link .
The authority chain on moves from authority to a random hub that links to , then to a random authority that links to:
The hub chain on is the same with the roles swapped: . The output is the authority vector and the hub vector , where and are the uniform distributions on and . In matrix form, with the adjacency matrix with each row divided by its sum and the adjacency matrix with each column divided by its sum, is the part of on the authority rows and columns, and is the part of on the hub rows and columns. HITS uses and with no division.
The algorithm
The closed form of Lempel and Moran turns the definition into a count. Let have components with authority sets , hub sets and links.
SALSA(G) ▷ G = (V, E), the base set of a query- 1
E ← E without self links and repeated links - 2
H ← {q : out(q) > 0}; A ← {p : in(p) > 0} - 3
label the connected components of the undirected bipartite graph G̃ - 4
for each component c: count |H_c|, |A_c| and m_c = |E_c| - 5
for each p ∈ A in component c: a(p) ← (|A_c| / |A|) · in(p) / m_c - 6
for each q ∈ H in component c: h(q) ← (|H_c| / |H|) · out(q) / m_c - 7
return h, a
Pages ranked by (or by ) go highest first, with ties to the smaller page number. The definition can also be run as written, by power iteration of the two chains from the uniform start. Each step costs : spread the mass of each authority over the hubs that link to it, then the mass of each hub over its links. The test file runs both and checks that they agree.
Example
Take twelve pages. Hubs 0 to 3 each link to authorities 9 and 10, hubs 4 to 8 each link to authority 11, and hub 0 also links to 11. So , and , and is connected through hub 0. From authority 11 the walker goes back to one of its six hubs; only hub 0 can send it to 9 or 10, so and . From authority 9, and . The stationary vector is
As a check, . The hub scores are : for hub 0, for hubs 1 to 3 and for hubs 4 to 8. HITS, normalized to sum 1, gives the authorities about , and : it ranks the block 9 and 10 above page 11, although more pages link to 11.
Now remove the link . The graph splits into the block (four hubs, two authorities, eight links) and the star (five hubs, one authority, five links). Theorem 2 of the proof file gives and , and every hub gets . HITS gives , and : the dominant eigenvalue of belongs to the block (8 against 5), so the star gets nothing. This is the tightly knit community (TKC) effect that Lempel and Moran describe.
Correctness
The file proofs/correctness.md proves the closed form. Each row of sums to 1. The chain is reversible with weights , because is a sum over the common hubs of , which is symmetric in and . So is stationary. Two authorities can reach each other exactly when they lie in the same component of , and every state has a positive self loop, so on a connected the chain is irreducible and aperiodic: its stationary distribution is unique, and power iteration converges to it from any start. On a general the chain splits into one block per component, the uniform start puts mass on block , and the block keeps it. This gives line L5, and the hub case gives line L6.
Proof: SALSA scores are the in-degrees and out-degrees, weighted by component sizefull
Let be the set of links of the base set after self links and repeated links are removed, and let . Write and for the in-degree and out-degree. The hub side is and the authority side is . The bipartite graph has a node for each , a node for each , and an undirected edge for each link . A page in both sets gives two different nodes.
The authority chain moves from an authority to a uniformly random hub with , and then to a uniformly random authority with . Its transition matrix is
The hub chain moves from a hub along a random out-link to and then back along a random in-link of to a hub : .
SALSA defines the authority scores as , where is the uniform distribution on , and the hub scores in the same way with and the uniform distribution on . The lemmas below show that the limits exist and give them in closed form. We prove the authority case; the hub case is the same proof with the roles of in and out swapped.
Lemma 1 (stochastic). Each row of sums to .
Proof. . The inner sum has terms equal to , so it is . The outer sum has terms equal to .
Lemma 2 (reversible). For all authorities and , .
Proof. Both sides equal , which is symmetric in and .
Lemma 3 (components). if and only if some hub links to both and . Two authorities and can reach each other in the chain if and only if and are in the same connected component of . Each .
Proof. The first claim holds because every term of the sum is positive. A path in alternates between hub nodes and authority nodes, so a path from to is a sequence of authorities in which each consecutive pair shares a hub, which is a path of positive steps of the chain; the converse reads the same sequence backwards. Every authority has some hub with , and the term for in is positive.
Let the components of be , with authority sets , hub sets and link sets , so . Each link lies in exactly one component, because its two ends are joined by an edge.
Theorem 1 (connected case). If is connected, the authority chain has the unique stationary distribution , and .
Proof. is a distribution, because the in-degrees sum to . By Lemma 2, , using Lemma 1 in the last step. So is stationary. By Lemma 3 the chain is irreducible and each state has a self loop, so it is aperiodic. A finite irreducible chain has exactly one stationary distribution, and a finite irreducible aperiodic chain converges to it from every start (the convergence theorem for finite Markov chains).
Theorem 2 (general case). For each authority in component ,
and for each hub in component , .
Proof. By Lemma 3, when and lie in different components, so is block diagonal with one block for each component, and each block is a stochastic matrix by Lemma 1. Then restricted to equals , where is uniform on : the start puts mass on the block, spread evenly, and the block never sends mass out. Component is a connected bipartite graph on its own, so Theorem 1 applied to it gives .
This is Proposition 2 of Lempel and Moran in the unweighted case. The weight comes from the uniform start. With another start the limit gives the component other weights, while the scores inside a component stay proportional to in-degree. This is why SALSA fixes the start.
Theorem 3 (the implementation). The function salsa returns these limits.
Proof. Line L1 builds . Line L2 builds and from the degrees. Line L3 labels the nodes of by a graph search from each node that is not yet labelled; a search labels exactly the nodes that are connected to its start, so two nodes get the same label if and only if they are in the same component. Line L4 counts, for each label, the hubs, the authorities and the links, a link being counted at its hub. Lines L5 and L6 then evaluate the formulas of Theorem 2.
Cost. Removing repeated links costs expected time with a hash set. Building the adjacency lists, the search and the counts cost , and lines L5 and L6 cost . So SALSA costs besides the duplicate removal, with no iteration. The implementation sorts the links once to fix their order, which adds .
Complexity
Repeated links can be removed in worst-case time by two passes of counting sort on the pairs, or in expected time with a hash set. The degrees, the graph search for the components and the counts take , and lines L5 and L6 take . So SALSA costs time on the word RAM and extra space for the bipartite graph, with no iteration. Power iteration of the chains costs for each step, and the number of steps depends on the second eigenvalue of each block, which can be close to 1. The closed form avoids that cost. The implementation sorts the links once to fix their order, which adds . The real cost of query-time link analysis is building the base set, which needs the links into and out of each root page.
Properties
- In-degree inside a component. On a connected , SALSA ranks authorities exactly as the in-degree does, and hubs exactly as the out-degree does. Borodin, Roberts, Rosenthal and Tsaparas make the same point in their comparison of link analysis rankings.
- Component weights. Across components, the score is the in-degree share inside the component times the share of authorities in the component. A page in a small component can beat a page with a larger in-degree in a big one, and the other way round.
- Weighted links. With link weights, Lempel and Moran's result uses the weighted in-degree, the sum of the weights of the links into a page.
- Stable against dense blocks. Because each step divides by and , a dense block gets weight in proportion to its links and its authorities, not by the size of its largest eigenvalue as in HITS.
- Deterministic and exact. The closed form uses only integer counts, so the scores are exact rational numbers.
Variants and improvements
- Weighted SALSA. Give each link a weight, for example lower for links between pages of the same site, and replace the degrees by the sums of the weights.
- SALSA on the global graph. The same chains can run on the whole web graph instead of a query graph; on a connected graph this is in-degree ranking, which is easy to spam with a link farm.
- Random walks with restart. Adding a jump to a random page, as in PageRank, makes the chain irreducible on any graph, at the cost of the closed form.
- Other bipartite graphs. The same two walks can run on any bipartite graph, for example users and the items they chose. The closed form shows that, without a restart, they rank items by popularity inside each component.
When to use it
Use SALSA when you want a query-dependent link score that rewards pages many hubs point to, without the instability of HITS on graphs with a dominant dense block. Know that, on a connected base set, you get in-degree ranking, so compute it as a count. If the base set has several components, the component weights carry the extra information. For a global, query-independent score, PageRank or TrustRank is the usual choice.
Pitfalls
- Iterating when a count is enough. The closed form is exact and linear in the input. Power iteration can take many steps when the second eigenvalue is near 1, and still gives only an approximation.
- Mixing the two sides. A page that is both a hub and an authority is two nodes of . Merging them changes the components and the scores.
- Forgetting the start. The component weights come from the uniform start. A different start, or normalizing each component on its own, gives other scores for pages in different components.
- Repeated links and self links. If they are kept, the degrees and the components change. State the rule, and remove both as HITS implementations do.
- Ties. In-degrees are small integers, so many pages tie. Break ties by a fixed rule, here the smaller page number.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/salsa-algorithm/. The authors are listed in prov/XD0VVF.jsonl.
"""SALSA of Lempel and Moran (WWW9 2000, ACM TOIS 2001), unweighted.
Pages are the integers 0 to n - 1 and an edge (q, p) is a link from q to p.
Self links are removed and repeated links count once. A page with an
out-link is a hub, a page with an in-link is an authority, and a page can
be both. The scores are the stationary distributions of two Markov chains
on the bipartite graph of hubs and authorities, started from the uniform
distribution on each side.
"""
from fractions import Fraction
from typing import Iterable
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 degrees(n: int, arcs: list[tuple[int, int]]) -> tuple[list[int], list[int]]:
out, inn = [0] * n, [0] * n
for q, p in arcs:
out[q] += 1
inn[p] += 1
return out, inn
def salsa(n: int, edges: Iterable[tuple[int, int]], exact: bool = False) -> tuple[list[Number], list[Number]]:
"""Return (hub scores, authority scores) by the closed form of Lempel and Moran.
A page that is not a hub has hub score 0, and one that is not an authority
has authority score 0. With exact=True the scores are Fractions.
"""
arcs = clean_links(n, edges) # @line L1
out, inn = degrees(n, arcs)
hubs = [q for q in range(n) if out[q] > 0] # @line L2
auths = [p for p in range(n) if inn[p] > 0]
# The bipartite graph has 2n sides: hub q is node q and authority p is node n + p.
adj: list[list[int]] = [[] for _ in range(2 * n)]
for q, p in arcs:
adj[q].append(n + p)
adj[n + p].append(q)
label = [-1] * (2 * n) # @line L3
for start in range(2 * n):
if label[start] >= 0 or not adj[start]:
continue
label[start] = start
stack = [start]
while stack:
u = stack.pop()
for w in adj[u]:
if label[w] < 0:
label[w] = start
stack.append(w)
nh: dict[int, int] = {} # @line L4
na: dict[int, int] = {}
ne: dict[int, int] = {}
for q in hubs:
nh[label[q]] = nh.get(label[q], 0) + 1
for p in auths:
na[label[n + p]] = na.get(label[n + p], 0) + 1
for q, _ in arcs:
ne[label[q]] = ne.get(label[q], 0) + 1
def find(x: int) -> int:
return label[x]
def frac(a: int, b: int) -> Number:
return Fraction(a, b) if exact else a / b
zero: Number = Fraction(0) if exact else 0.0
a: list[Number] = [zero] * n
h: list[Number] = [zero] * n
for p in auths: # @line L5
c = find(n + p)
a[p] = frac(na[c] * inn[p], len(auths) * ne[c])
for q in hubs: # @line L6
c = find(q)
h[q] = frac(nh[c] * out[q], len(hubs) * ne[c])
return h, a # @line L7
def authority_step(n: int, arcs: list[tuple[int, int]], x: list[Number]) -> list[Number]:
"""One step of the authority chain: back to a random hub that links to the page, then forward on a random link of that hub."""
out, inn = degrees(n, arcs)
y = [x[0] * 0 for _ in range(n)]
for q, p in arcs:
y[q] += x[p] / inn[p]
z = [x[0] * 0 for _ in range(n)]
for q, p in arcs:
z[p] += y[q] / out[q]
return z
def hub_step(n: int, arcs: list[tuple[int, int]], x: list[Number]) -> list[Number]:
"""One step of the hub chain: forward on a random link, then back to a random hub that links to that authority."""
out, inn = degrees(n, arcs)
y = [x[0] * 0 for _ in range(n)]
for q, p in arcs:
y[p] += x[q] / out[q]
z = [x[0] * 0 for _ in range(n)]
for q, p in arcs:
z[q] += y[p] / inn[p]
return z
def salsa_power(n: int, edges: Iterable[tuple[int, int]], tol: float = 1e-13, max_rounds: int = 100000) -> tuple[list[float], list[float], int]:
"""The definition: run both chains from the uniform start until no score moves by more than tol.
Returns (hub scores, authority scores, rounds used).
"""
arcs = clean_links(n, edges)
out, inn = degrees(n, arcs)
hubs = [q for q in range(n) if out[q] > 0]
auths = [p for p in range(n) if inn[p] > 0]
a = [1.0 / len(auths) if inn[p] else 0.0 for p in range(n)] if auths else [0.0] * n
h = [1.0 / len(hubs) if out[q] else 0.0 for q in range(n)] if hubs else [0.0] * n
for r in range(1, max_rounds + 1):
a2, h2 = authority_step(n, arcs, a), hub_step(n, arcs, h)
moved = max([abs(u - v) for u, v in zip(a, a2)] + [abs(u - v) for u, v in zip(h, h2)])
a, h = a2, h2
if moved <= tol:
return h, a, r
raise RuntimeError("no convergence")
def authority_matrix(n: int, edges: Iterable[tuple[int, int]]) -> dict[tuple[int, int], Fraction]:
"""The exact transition probabilities P_A(i, j) of the authority chain, for authorities i and j."""
arcs = clean_links(n, edges)
out, inn = degrees(n, arcs)
by_hub: dict[int, list[int]] = {}
for q, p in arcs:
by_hub.setdefault(q, []).append(p)
pa: dict[tuple[int, int], Fraction] = {}
for q, ps in by_hub.items():
for i in ps:
for j in ps:
pa[(i, j)] = pa.get((i, j), Fraction(0)) + Fraction(1, inn[i] * out[q])
return pa
test_salsa_algorithm.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/salsa-algorithm/. The authors are listed in prov/XD0VVF.jsonl.
import random
from fractions import Fraction
import pytest
from salsa_algorithm import authority_matrix, authority_step, clean_links, hub_step, salsa, salsa_power
# The example of the page: hubs 0 to 3 link to authorities 9 and 10, hubs 4 to 8 link to 11, and 0 also links to 11.
BLOCK = [(q, p) for q in range(4) for p in (9, 10)]
STAR = [(q, 11) for q in range(4, 9)]
CONNECTED = BLOCK + STAR + [(0, 11)]
def random_graph(rng: random.Random, n: int, prob: float) -> list[tuple[int, int]]:
return [(q, p) for q in range(n) for p in range(n) if q != p and rng.random() < prob]
def components(n: int, arcs: list[tuple[int, int]]) -> list[set[int]]:
"""Authority sets of the connected components of the bipartite graph, by a plain search."""
adj: dict[tuple[str, int], set[tuple[str, int]]] = {}
for q, p in arcs:
adj.setdefault(("h", q), set()).add(("a", p))
adj.setdefault(("a", p), set()).add(("h", q))
seen: set[tuple[str, int]] = set()
comps = []
for v in sorted(adj):
if v in seen:
continue
stack, comp = [v], set()
seen.add(v)
while stack:
u = stack.pop()
if u[0] == "a":
comp.add(u[1])
for w in adj[u]:
if w not in seen:
seen.add(w)
stack.append(w)
comps.append(comp)
return comps
def stationary(pa: dict[tuple[int, int], Fraction], nodes: list[int]) -> list[Fraction]:
"""Solve pi P = pi with sum(pi) = 1 exactly, by Gaussian elimination."""
k = len(nodes)
rows = [[(pa.get((nodes[i], nodes[j]), Fraction(0)) - (1 if i == j else 0)) for i in range(k)] + [Fraction(0)] for j in range(k)]
rows[-1] = [Fraction(1)] * k + [Fraction(1)]
for c in range(k):
piv = next(r for r in range(c, k) if rows[r][c] != 0)
rows[c], rows[piv] = rows[piv], rows[c]
for r in range(k):
if r != c and rows[r][c] != 0:
f = rows[r][c] / rows[c][c]
rows[r] = [x - f * y for x, y in zip(rows[r], rows[c])]
return [rows[i][k] / rows[i][i] for i in range(k)]
def test_example_connected() -> None:
h, a = salsa(12, CONNECTED, exact=True)
assert [a[p] for p in (9, 10, 11)] == [Fraction(2, 7), Fraction(2, 7), Fraction(3, 7)]
assert h[0] == Fraction(3, 14) and h[1] == h[2] == h[3] == Fraction(1, 7)
assert all(h[q] == Fraction(1, 14) for q in range(4, 9))
hp, ap, _ = salsa_power(12, CONNECTED)
assert all(abs(float(x) - y) < 1e-9 for x, y in zip(a + h, ap + hp))
def test_example_two_components() -> None:
h, a = salsa(12, BLOCK + STAR, exact=True)
assert [a[p] for p in (9, 10, 11)] == [Fraction(1, 3)] * 3
assert all(h[q] == Fraction(1, 9) for q in range(9))
def test_closed_form_matches_power_iteration() -> None:
rng = random.Random(2)
for _ in range(80):
n = rng.randrange(1, 10)
edges = random_graph(rng, n, rng.choice([0.15, 0.3, 0.6]))
h, a = salsa(n, edges)
hp, ap, _ = salsa_power(n, edges)
assert all(abs(x - y) < 1e-9 for x, y in zip(h + a, hp + ap))
def test_closed_form_is_exactly_stationary() -> None:
rng = random.Random(4)
for _ in range(80):
n = rng.randrange(1, 10)
edges = random_graph(rng, n, 0.3)
arcs = clean_links(n, edges)
h, a = salsa(n, edges, exact=True)
assert authority_step(n, arcs, a) == a
assert hub_step(n, arcs, h) == h
if arcs:
assert sum(a) == 1 and sum(h) == 1
def test_connected_component_gives_in_degree() -> None:
# On a connected bipartite graph the unique stationary distribution of P_A is in(p) / m.
rng = random.Random(9)
done = 0
while done < 30:
n = rng.randrange(2, 9)
arcs = clean_links(n, random_graph(rng, n, 0.45))
comps = components(n, arcs)
if len(comps) != 1:
continue
done += 1
auths = sorted(comps[0])
pa = authority_matrix(n, arcs)
for i in auths:
assert sum(pa.get((i, j), Fraction(0)) for j in auths) == 1
assert pa[(i, i)] > 0
pi = stationary(pa, auths)
inn = {p: sum(1 for _, x in arcs if x == p) for p in auths}
assert pi == [Fraction(inn[p], len(arcs)) for p in auths]
_, a = salsa(n, arcs, exact=True)
assert [a[p] for p in auths] == pi
def test_component_mass_is_preserved() -> None:
rng = random.Random(6)
for _ in range(40):
n = rng.randrange(2, 10)
arcs = clean_links(n, random_graph(rng, n, 0.2))
auths = sorted({p for _, p in arcs})
if not auths:
continue
x = [Fraction(1, len(auths)) if p in auths else Fraction(0) for p in range(n)]
for _ in range(3):
x = authority_step(n, arcs, x)
_, a = salsa(n, arcs, exact=True)
for comp in components(n, arcs):
share = Fraction(len(comp), len(auths))
assert sum(x[p] for p in comp) == share
assert sum(a[p] for p in comp) == share
def test_links_are_cleaned_and_empty_graph() -> None:
assert clean_links(3, [(0, 1), (0, 1), (2, 2)]) == [(0, 1)]
assert salsa(3, [(0, 1), (0, 1), (2, 2)], exact=True) == salsa(3, [(0, 1)], exact=True)
assert salsa(3, [], exact=True) == ([0, 0, 0], [0, 0, 0])
with pytest.raises(ValueError):
salsa(2, [(0, 5)])
History
Lempel and Moran presented SALSA at the Ninth International World Wide Web Conference (WWW9) in Amsterdam in 2000, under the title "The stochastic approach for link-structure analysis (SALSA) and the TKC effect", and published the full version in ACM Transactions on Information Systems in 2001. They designed it as a random walk version of Kleinberg's hubs and authorities. Their main analytic result is that the stationary distributions reduce to weighted degrees, scaled by the sizes of the components. Borodin, Roberts, Rosenthal and Tsaparas later placed SALSA among the link analysis ranking algorithms and compared it with HITS and in-degree ranking in theory and experiments.
References
- R. Lempel and S. Moran, SALSA, the stochastic approach for link-structure analysis, ACM Transactions on Information Systems 19(2), 131-160 (2001), the two Markov chains on the bipartite hub and authority graph, the proposition that an irreducible authority chain has a stationary distribution proportional to the weighted in-degree, the proposition for several components with a uniform start, and the TKC effect of HITS; this journal version is the one the page relies on
- R. Lempel and S. Moran, The stochastic approach for link-structure analysis (SALSA) and the TKC effect, Computer Networks 33(1-6), 387-401 (2000), Proceedings of the 9th International World Wide Web Conference (WWW9), the conference version, with the definition of the chains, the analysis of their stationary distributions and the examples of the TKC effect
- Allan Borodin, Gareth O. Roberts, Jeffrey S. Rosenthal and Panayiotis Tsaparas, Link analysis ranking, algorithms, theory, and experiments, ACM Transactions on Internet Technology 5(1), 231-297 (2005), the section on SALSA (on a connected graph it ranks authorities by in-degree) and the comparison of InDegree, HITS and SALSA
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XD0VVF Edit this page History Report an error Markdown