Exercise: the random walker

Goal

By the end of this exercise you should be able to:

  • compute random-walker probabilities by hand on a chain (voltage drops in proportion to resistance) and for a single free node (a weighted average),
  • predict where the walker puts the boundary, and where it differs from a graph cut on the same weights,
  • recognise the walker’s failure modes: seed position, far regions, no edge, the choice of σ, and fix them with seeds or priors,
  • (math) derive the linear system, the maximum principle, and why the label probabilities sum to 1.

Do the pen-and-paper part first, then the two demos.

Background

Idea What it means
Weights affinities w_{pq} = \exp(-(I_p - I_q)^2/2\sigma^2): large inside regions, small across edges
Random walk from p, step to neighbour q with probability w_{pq}/d_p, d_p = \sum_q w_{pq}
Probability x_p = probability of reaching an object seed before a background seed
Harmonic x_p = \sum_q w_{pq}x_q / d_p at every free node; x = 1 at object seeds, 0 at background seeds
Electrical picture conductance w_{pq}, resistance 1/w_{pq}; x = voltage; on a chain the voltage drops in proportion to resistance
Label the seed label with the largest probability (two labels: x > 0.5)
Linear system L_U\mathbf x_U = -B^\top\mathbf x_M (math layer)
Graph cut (recall) minimum total weight of cut edges between the seeds; on a chain: the weakest edge between them

With the Laplacian L = D - W ordered as marked/unmarked nodes, L = \begin{pmatrix} L_M & B \\ B^\top & L_U\end{pmatrix}, the walker minimises \mathbf x^\top L\mathbf x = \sum_{(p,q)} w_{pq}(x_p - x_q)^2 with \mathbf x_M fixed, which gives L_U\mathbf x_U = -B^\top\mathbf x_M. The same equations describe hitting probabilities (first-step analysis) and voltages (Kirchhoff’s current law). L_U is positive definite when every connected component of the graph contains a seed, so the solution is unique.

By hand

B1. A chain of 5 nodes; node 1 is an object seed (1), node 5 a background seed (0). Edge weights 1, 1, 0.25, 1. (a) Write the resistances and their total. Compute the voltages of nodes 2, 3, 4. (b) Which nodes are labelled object? Between which nodes is the boundary? (c) Where would a graph cut on the same weights cut? Do the two methods agree? (d) Check node 3: is its voltage the weighted average of its neighbours?

B2. One free node joined to an object seed with w = 3 and to two background seeds with w = 1 and w = 1. (a) Compute its probability. (b) Change the two background weights to 2 and 2. (c) Which label does the graph cut choose in (a) and in (b)? (d) Show that with a single free node the two methods always agree.

B3. A chain of 7 nodes, object seed at node 1, background seed at node 7, weights 0.2, 1, 1, 1, 1, 0.25. (a) Compute all voltages. Where does the walker cross 0.5? (b) Where does the graph cut cut, and which nodes does it label object? (c) Which result looks like “the boundary is at the strongest image edge”? Describe the bias of each method in one sentence.

B4. Move a seed. In B3, move the object seed from node 1 to node 3. (a) What are the voltages of nodes 1 and 2 now? (b) Compute the voltages of nodes 4–6. (c) Where do the walker and the graph cut put the boundary now? (d) What does this tell you about where to place seeds?

B5. A 3 \times 3 grid with all weights 1 (4-neighbours); object seed in the top-left corner, background seed in the bottom-right corner. Without solving: which pixels have exactly 0.5? Which pixels are object?

B6. Predict. (a) You double every weight in a graph. What happens to the probabilities? (b) You add the same constant to every grey level. (c) You lower σ from 30 to 5 in an image with noise of standard deviation 10 and object/background contrast 100. What happens to the weights inside regions, and to the result?

B1. (a) Resistances 1, 1, 4, 1, total 7. The voltage drops by \tfrac17 per unit of resistance: node 2 at 1 - \tfrac17 = \tfrac67 \approx 0.857, node 3 at \tfrac57 \approx 0.714, node 4 at \tfrac57 - \tfrac47 = \tfrac17 \approx 0.143. (b) Nodes 1–3 are object (above 0.5); the boundary is between nodes 3 and 4, in the weak edge (\tfrac47 of the whole drop happens there). (c) The cheapest edge between the seeds is the 0.25 edge between nodes 3 and 4: the same boundary. (d) Node 3: (1 \cdot \tfrac67 + 0.25 \cdot \tfrac17)/(1 + 0.25) = (\tfrac{24}{28} + \tfrac{1}{28})/1.25 = \tfrac{25}{28}/\tfrac54 = \tfrac57. Yes.

B2. (a) x = (3 \cdot 1 + 1 \cdot 0 + 1 \cdot 0)/(3 + 1 + 1) = \tfrac35 = 0.6: object. (b) 3/(3 + 2 + 2) = \tfrac37 \approx 0.43: background. (c) The cut either cuts the object edge (cost 3, node background) or the two background edges (cost 2 in (a), 4 in (b)). (a): 2 < 3, so the node stays with the object; (b): 3 < 4, so it goes to the background. Same labels as the walker. (d) With one free node, x = w_O/(w_O + w_B) where w_O, w_B are its total weights to object and background seeds. x > 0.5 \iff w_O > w_B \iff cutting the background edges is cheaper: the two rules are the same comparison.

B3. (a) Resistances 5, 1, 1, 1, 1, 4, total 13: voltages 1, \tfrac{8}{13}, \tfrac{7}{13}, \tfrac{6}{13}, \tfrac{5}{13}, \tfrac{4}{13}, 0 (0.615, 0.538, 0.462, 0.385, 0.308). The walker crosses 0.5 between nodes 3 and 4, on an edge of weight 1. (b) The cheapest edge between the seeds is the first one (0.2): the cut keeps only node 1 as object. (c) The graph cut puts the boundary at the weakest edge, the strongest image edge; the walker puts it on a strong edge in the middle. The graph cut is biased towards short (cheap) cuts close to a seed; the walker is biased towards the middle in resistance: with two weak edges of similar strength, it divides the drop between them and the 0.5 crossing can fall between them.

B4. (a) Nodes 1 and 2 hang off the seed with no other seed behind them: both at 1. (b) Between node 3 (1 V) and node 7 (0 V): resistances 1, 1, 1, 4, total 7: nodes 4–6 at \tfrac67, \tfrac57, \tfrac47 (0.857, 0.714, 0.571). (c) The walker now crosses 0.5 in the 0.25 edge between nodes 6 and 7. The graph cut also cuts the 0.25 edge (cheapest between the seeds; nodes 1–2 are object at no cost). They agree. (d) The walker’s boundary depends on where the seeds are; seeds placed close to the boundary you want (or strokes along the object) make the result more reliable.

B5. By symmetry (reflection across the anti-diagonal swaps the seeds and turns x into 1 - x), the three anti-diagonal pixels (top-right, centre, bottom-left) have exactly 0.5. The top-left seed and its two neighbours (top-middle and middle-left, both \tfrac23) are object; the others are background (\tfrac13 or 0). The anti-diagonal pixels are a tie.

B6. (a) Nothing: every free node is a weighted average, and scaling all weights does not change any average. (b) Nothing: the weights depend only on differences. (c) Inside regions the noise differences (typically 10\sqrt2 \approx 14) give w = e^{-14^2/50} \approx 0.02 at σ = 5 instead of 0.9 at σ = 30: noise becomes “edges”. The walker is trapped near its seeds and the probability map breaks up into patches; the boundary follows noise.

Math questions

B7. (math) Derive L_U\mathbf x_U = -B^\top\mathbf x_M from E(\mathbf x) = \sum_{(p,q)} w_{pq}(x_p - x_q)^2 with the seeds fixed, and show that row p says x_p is the weighted average of its neighbours.

B8. (math) Let P_p be the probability that a walk from p hits an object seed before a background seed. Show that P satisfies the same equations as the voltages.

B9. (math) Prove the maximum principle on a connected graph: a function that is harmonic at every free node attains its maximum and minimum at seeds. Conclude 0 \le x_p \le 1.

B10. (math) With K labels, show that the K solutions \mathbf x^1, \dots, \mathbf x^K (one per label) sum to the all-ones vector at every node.

B11. (math) Show that L_U is singular if and only if some connected component of the graph contains no seed. What does that mean for the segmentation?

B7. E = \mathbf x^\top L\mathbf x with L = D - W. Splitting into marked and unmarked blocks, E = \mathbf x_M^\top L_M\mathbf x_M + 2\mathbf x_U^\top B^\top\mathbf x_M + \mathbf x_U^\top L_U\mathbf x_U. \nabla_{\mathbf x_U}E = 2B^\top\mathbf x_M + 2L_U\mathbf x_U = 0. Row p of L_U has d_p on the diagonal and -w_{pq} for free neighbours; row p of B^\top has -w_{pq} for marked neighbours. So d_p x_p - \sum_{q\,\text{free}} w_{pq}x_q = \sum_{q\,\text{marked}} w_{pq}x_q, i.e. x_p = \sum_q w_{pq}x_q/d_p. E is a convex quadratic, so the stationary point is the minimum.

B8. For a free node, condition on the first step: the walk goes to q with probability w_{pq}/d_p and from there succeeds with probability P_q (the walk has no memory). So P_p = \sum_q (w_{pq}/d_p)P_q. At an object seed the walk has already succeeded (P = 1), at a background seed failed (P = 0). These are the equations of B7 with the same boundary values; with a unique solution (B11), P = x.

B9. Let m = \max_p x_p and suppose it is attained at a free node p. x_p is a weighted average (positive weights) of its neighbours, all \le m; it equals m only if all neighbours equal m. Repeating from each neighbour, every node reachable from p through free nodes has value m, and since the graph is connected and contains seeds, some seed adjacent to this set has value m too. So the maximum is attained at a seed; likewise the minimum. Seeds are 0 or 1, hence 0 \le x_p \le 1.

B10. Write the K systems as L_U X = -B^\top M, where column k of M is 1 at seeds of label k and 0 elsewhere. Every seed has exactly one label, so M\mathbf 1 = \mathbf 1_M. Then \mathbf y = X\mathbf 1 solves L_U\mathbf y = -B^\top\mathbf 1_M. The constant vector also solves it: L\mathbf 1 = 0 gives B^\top\mathbf 1_M + L_U\mathbf 1_U = 0. By uniqueness X\mathbf 1 = \mathbf 1.

B11. \mathbf x_U^\top L_U\mathbf x_U = \sum_{(p,q)} w_{pq}(x_p - x_q)^2 with x = 0 on the seeds (edges to seeds contribute w_{pq}x_p^2). It is zero only if \mathbf x is constant on each connected component and zero on every component that contains a seed. So a non-zero \mathbf x_U with zero energy (a null vector) exists exactly when some component has no seed: put a constant there. Then L_U is singular: the walker’s value on that component is undetermined (a walk from there never reaches any seed). Every separate piece of the image needs a seed.

Explore: the random walker on a chain

Nodes in a row joined by edges of conductance w (thickness; numbers above). Click a node to cycle it between free, object seed (orange, value 1) and background seed (blue, value 0); click an edge and set its w with the slider. The bars show the voltages (= probabilities), the dashed line 0.5, the orange tick where the voltages cross 0.5, and the numbers below the edges each edge’s share of the total voltage drop. averaging sweep lets every free node take the weighted mean of its neighbours once (from left to right), solve shows the exact answer, walkers releases 200 random walks from the selected node (green ring), and the check box marks the minimum graph cut on the same weights.

W1. Preset by hand (a): compare the bars with B1. What share of the drop does the weak edge take? Turn on the minimum graph cut.

W2. Preset walkers estimate the voltage: how many of the 200 walks from node 3 reach the object seed? Select node 2 and node 4 (click once) and press walkers again. How close are the estimates to the voltages, and how close should they be?

W3. Preset averaging converges (the chain of B3, free nodes start at 0.5). Press averaging sweep repeatedly. After how many sweeps is the largest change below 0.001? Are the values then correct to two decimals?

W4. Presets two weak edges and move a seed inwards: check B3 and B4. Then, in two weak edges, change the 0.2 edge to 1. Where are the walker’s crossing and the min cut now?

W5. Preset weights from an intensity profile (grey levels under the nodes, σ = 20). Which edge takes most of the drop, and why? Lower σ to 5: what changes?

W1. Voltages 1, 0.857, 0.714, 0.143, 0. The drops are 14%, 14%, 57%, 14%: the weak edge (resistance 4 of 7) takes 4/7. The min cut is the same 0.25 edge (3–4), and the orange tick lies in it.

W2. 149 of 200 from node 3: 0.745 against the voltage 0.714. From node 2: 167 (0.835 against 0.857); from node 4: 23 (0.115 against 0.143). With 200 walks the standard error is \sqrt{p(1-p)/200} \approx 0.03, and all three estimates are within about one standard error.

W3. The largest change falls below 0.001 after 24 sweeps; the values are then 0.624, 0.548, 0.471, 0.393, 0.314 against the exact 0.615, 0.538, 0.462, 0.385, 0.308: still about 0.01 too high. Averaging converges, but slowly (the weak 0.2 edge passes information slowly). This is why real solvers use conjugate gradients rather than plain averaging.

W4. As in B3 and B4: crossing between nodes 3 and 4 and min cut at edge 1–2; with the seed at node 3, both in edge 6–7. With the 0.2 edge set to 1: resistances 1, 1, 1, 1, 1, 4 (total 9), voltages 1, 0.889, 0.778, 0.667, 0.556, 0.444, 0: the crossing moves to edge 5–6 (still a strong edge), the min cut to the 0.25 edge 6–7.

W5. Weights 0.98, 0.995, 0.516, 0.989, 0.995, 0.026, 0.98, 0.995: the jump from 46 to 100 (54 grey levels) gives w = 0.026, resistance 38 of a total of about 47, so about 83% of the drop. The smaller jump (23) takes about 4%. Voltages 1, 0.978, 0.956, 0.915, 0.893, 0.871, 0.044, 0.022, 0: the boundary is at the large jump, where the min cut is too. At σ = 5 both jumps get the smallest weight the demo allows (0.001, resistance 1000), the wiggles of 2–4 grey levels still have weights 0.7–0.9: the two jumps share the drop equally, and nodes 4–6 sit at about 0.5. The walker can no longer tell which jump is the real edge: undecided.

Explore: painting seeds

A 128 \times 128 image: synthetic scenes (objects: a bright disc with a thin arm touching a second disc with a weak boundary; gap: two halves of a field separated by a dark wall with a 3-pixel gap; ramp: two brightnesses joined by a smooth ramp) or the micrograph. Paint seeds with the mouse (object, background, an optional third label). The right panel shows p(object) (red 1, white 0.5, blue 0), all labels as colours, or the uncertainty 1 - \max p. Click it to probe a pixel: its probability and 30 random walks from it. The system is solved by conjugate gradients a little at a time, and restarted from the previous solution after each stroke: the readout shows the iterations and the residual.

R1. Preset two clicks. The object seed is in the upper disc only, yet the lower disc is also labelled object (3378 object pixels). Why? Add one background stroke in the lower disc and explain the change.

R2. Preset three labels: look at all labels and uncertainty. Where is the walker unsure, and why there?

R3. Preset weak boundary: the walker bridges the gap. Probe the gap. Where does the boundary pass through the gap? What would a single object seed close to the gap do?

R4. Preset seeds far away: fading to 0.5. What is the probability in the middle of the image? Paint a longer object stroke down the left side: what happens to the map?

R5. Presets no edge between two brightnesses and … priors fix it. Where does the 0.5 boundary cross the middle row in each case (the true split is at x = 64)? Then raise λ to 1: what do you see, and what is the risk?

R6. Preset σ too small. Count the object pixels and CG iterations; then set σ = 20. Explain both changes.

R7. Preset micrograph. Which parts of the cell are uncertain? Add background strokes on the cytoplasm until the nucleus is segmented cleanly. How many strokes did you need?

R1. The two discs (grey levels 180 and 160, noise 10) touch along a boundary of only 20 grey levels, which at σ = 20 is a strong link (w = e^{-400/800} \approx 0.6). With no seed inside it, the lower disc is reached through the upper disc far more easily than through its sharp boundary to the background, so walks from it end on the object seed. A background stroke in the lower disc gives it its own seed: it becomes background, and the boundary moves to the narrow waist where the discs touch.

R2. In the contact zone between the two discs: the probabilities blend from orange to green over several pixels (the boundary is weak and both seeds pull). Also, weakly, in the background far from the two small background seeds. The upper disc, the lower disc and the arm are otherwise certain.

R3. The probability at the centre of the gap is 0.514: the boundary passes through the gap in a short line, continuing the wall. With seeds on both sides the walker closes the gap; with the object stroke far from the gap and noise, the boundary may bulge slightly into the other side (compare the ws-msf unit). A single object click right next to the gap pulls the boundary through the gap onto the far side: seed position matters.

R4. About 0.48 at the centre (64, 64), and the probability falls steeply only near the two corner seeds. A long stroke down the left side gives many more paths to the object seed: the map turns redder on the left half and the 0.5 contour moves towards the middle of the image, now more decisively.

R5. Without priors the boundary crosses the middle row between x = 45 and 46: well left of the true split, because the walker only sees seed geometry on a smooth ramp. With priors (λ = 0.05) it crosses between x = 63 and 64: on the true split. At λ = 1 the boundary is sharp and still correct here, but the result approaches thresholding with the seed histograms: an object-coloured region anywhere in the image would become object even without a seed.

R6. At σ = 5: 8447 object pixels and about 3060 iterations; at σ = 20: 3377 object pixels and about 710 iterations. At σ = 5 noise differences (noise 18) are already “edges”: the walker is trapped in patches near its seeds and large parts of the background end up closer (in resistance) to the object seed. The contrast of the weights also makes the system badly conditioned, so CG needs many more steps.

R7. The cytoplasm between the nucleus and the image border is uncertain (pale): it is far from the strokes and its texture gives many weak links. Two or three background strokes on the cytoplasm around the nucleus (left, right, below) are usually enough for the 0.5 contour to follow the nuclear envelope everywhere.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in graphseg/src/random_walker/exercise.rs. Seeds are a label image: 0 = free pixel, 1 = object seed, 2 = background seed (3, 4, … for more labels). A chain is a one-row image. The exercises number the nodes from 1, the code from 0.

C1. chain_voltages(weights, seeds): the voltages of a chain, the way B1 and B3 compute them by hand:

for every pair of consecutive seeds a < b (voltages Va, Vb):
    R = Σ of 1/w over the edges from a to b                 # total resistance
    r = 0
    for i = a .. b−1:
        V[i] = Va + (Vb − Va) · r / R;   r = r + 1/w[i]
before the first seed and after the last one: V = that seed's voltage

The checks are B1(a), B3(a) and B4.

C2. edge_weights(img, σ): the contrast weight w = \exp(-(I_p - I_q)^2/2\sigma^2) of every edge to the right neighbour and to the one below. Grey values are between 0 and 1 here, so \sigma = 0.08 is about 20 grey levels of 255.

C3. averaging_sweep(x, seeds, weights): every free pixel, row by row, takes the weighted mean of its neighbours; returns the largest change:

for every free pixel p, row by row:
    x_p = Σ_q w_pq x_q / Σ_q w_pq            # the values already updated in this sweep

The check repeats it until nothing changes on the 3 \times 3 grid of B5.

C4. random_walker(seeds, weights, label, tol, max_iterations): the exact probabilities, by conjugate gradients on the system L_U\mathbf x_U = \mathbf b (the lecture’s math slide). First apply_lu(v, seeds, weights) (C4a): multiplying by L_U needs no matrix; for a free pixel, (L_U\mathbf v)_p = d_p v_p - \sum_{q \text{ free}} w_{pq} v_q, with d_p the sum of all its weights, and 0 at the seeds. Then random_walker (C4b), with the right side b_p = \sum_{q \text{ seed}} w_{pq}\,x_q, what the seeds pull with:

x = 0,  r = b,  p = r                         # images, 0 at the seeds
repeat until r·r is small enough:
    q = L_U p
    α = (r·r) / (p·q)
    x = x + α p,   r_new = r − α q
    p = r_new + (r_new·r_new) / (r·r) · p,   r = r_new

The checks are B5, B1 as a one-row image, B2(a) (3/5), and three labels whose probabilities sum to 1 at every pixel.

C5. walk_estimate(seeds, weights, label, start, walks, rng): release random walks from start, each step to neighbour q with probability w_{pq}/d_p, until a seed; return the fraction that ends at a seed of label. The check is 4000 walks from node 3 of B1.

Then cargo run -p graphseg -- random-walker and open the pictures in out/random-walker/. The program repeats the chains, segments the micrograph (at half size) from one object stroke in the nucleus and background strokes on three borders, solves a flat image with seeds in two corners, and segments synthetic nuclei with one seed per nucleus.

C6. The program runs averaging sweeps on the chain of B3, from 0.5 at the free nodes, until the largest change is below 0.001. How many sweeps does it take, and how close are the values to the exact ones of C1? Compare with demo question W3.

C7. Open cell-seeds.png (0.5 contour in yellow) and cell-probability.png. Where does the contour follow the nuclear envelope, and where not? How many CG iterations were needed? Compare the two probed probabilities with the 200 walks: are the differences what you expect?

C8. Read the probabilities along the diagonal of the flat image. Where does the probability change fastest? Which failure mode of the lecture is this? In nuclei-walker.png, what fraction of the pixels got their true label, and why does it work so well there?

The model solution is graphseg/src/random_walker/solution.rs in the download.

C6. 24 sweeps; the values are then 0.624, 0.548, 0.471, 0.393, 0.314 against the exact 0.615, 0.538, 0.462, 0.385, 0.308 of C1: about 0.01 too high, although every sweep changed them by less than 0.001. The same numbers as in W3. A small change per sweep does not mean a small error: averaging converges slowly, which is why the walker is solved by conjugate gradients.

C7. The yellow contour follows the nuclear envelope on the left, top and right. At the bottom it leaves the envelope and takes in a piece of the darker cytoplasm below the nucleus, which is far from all background strokes. Conjugate gradients needed 530 iterations (relative residual 10^{-5}); 2997 pixels are object. Probes: 0.647 against 0.650 from 200 walks, and 0.345 against 0.325. With 200 walks the standard error is \sqrt{p(1-p)/200} \approx 0.034: both estimates are within one standard error.

C8. 1.00, 0.89, 0.80, 0.71, 0.61, 0.50, 0.38, 0.27, 0.16, 0.11, 0.00: the steepest change is right next to the two seeds (from 1 to 0.89 in one pixel, and from 0.11 to 0 in the last), and in between the probability falls slowly through 0.5 in the middle. Only the geometry decides: “far from all seeds”. The nuclei: 99.4 % of the pixels get their true label. Every nucleus has its own seed and a strong edge all round (bright nuclei on a dark background), so each walk is trapped where it starts.

Where this leads

The random walker solves one linear system on the pixel graph. The next unit uses the same graph differently: with dissimilarities and spanning trees, segmentation becomes a greedy grouping (single linkage, Felzenszwalb–Huttenlocher). In the watershed as a spanning forest unit, the walker, the graph cut and the watershed run side by side on the same seeds.