Exercise: pixel classification with a forest

Goal

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

  • compute a pixel’s feature vector from a few simple filters and classify it with a small forest,
  • choose feature families and scales for a given distinction,
  • evaluate a pixel classifier honestly (held-out region, confusion matrix, Dice) and explain why the OOB error is optimistic,
  • handle label imbalance,
  • run the paint – train – look – correct loop in the demo,
  • (math) show that class weights are equivalent to resampling.

Do the pen-and-paper part first, then the demo.

Background

Idea What it means
Feature stack filter responses at several scales σ; one channel per family and scale
Families intensity (smoothed), edges (gradient magnitude), blobs (LoG), ridges (Hessian eigenvalues), texture (structure-tensor eigenvalues)
Training set the painted pixels and their classes
Uncertainty 1 - \max_k P(k): high where the trees disagree
Held-out region a part of the image whose labels are not used for training, only for evaluation
Confusion matrix, Dice from the thresholding day: counts of (true, predicted) pairs; Dice = 2TP/(2TP + FP + FN)
Class weights w_k = n/(K n_k) gives every class the same total weight

With L_\sigma = G_\sigma * I: intensity L_\sigma; edges \|\nabla L_\sigma\|; blobs \sigma^2\nabla^2 L_\sigma; ridges: eigenvalues of \sigma^2 \mathbf H(L_\sigma); texture: eigenvalues of \sigma^2\, G_{\sigma/2} * (\nabla L_\sigma\nabla L_\sigma^\top). In the demo the derivatives are central differences of L_\sigma, at σ = 0.7, 1, 1.6, 3.5, 5 and 10: 42 channels.

By hand

B1. A 5 \times 5 patch; the pixel of interest is the centre (value 90):

\begin{pmatrix} 10 & 12 & 14 & 30 & 60 \\ 12 & 15 & 40 & 80 & 90 \\ 14 & 50 & \mathbf{90} & 95 & 92 \\ 40 & 85 & 96 & 98 & 94 \\ 70 & 92 & 97 & 99 & 96 \end{pmatrix}

  1. Compute three features of the centre pixel: the 3 \times 3 box mean b; the gradient magnitude g from central differences, g_x = (I_{x+1} - I_{x-1})/2 and g_y = (I_{y+1} - I_{y-1})/2 (rows go down); and the 4-neighbour Laplacian $= $ (sum of the 4 neighbours) - 4 \cdot centre.
  2. A forest of three stumps: tree 1: b \le 60 → background, else nucleus; tree 2: g \le 30 → nucleus, else background; tree 3: \ell \le -50 → nucleus, else background. What is P(\text{nucleus}), and the label?
  3. Repeat for the pixel at row 2, column 2 (value 15).
  4. Where does the centre pixel sit, and why do the trees disagree on it?

B2. A user paints 400 background pixels and 20 nucleus pixels. (a) A leaf of a tree holds 8 background and 2 nucleus training pixels. What does it vote for a pixel that lands there? (b) Give two ways to fix the imbalance. With balancing weights, what does the same leaf say? (c) Can balancing make the result worse somewhere?

B3. A held-out 4 \times 4 region, N = nucleus, B = background, rows top to bottom:

truth prediction
N N B B N N N B
N N B B N B B B
N B B B N N B B
B B B B B B B B
  1. Give the confusion matrix (TP, FP, FN, TN with N as positive), the accuracy and the Dice coefficient of N and of B.
  2. The forest’s OOB error on the painted pixels was 0.5 %. Why is it so much lower than the error here?

B4. Which feature family, at which scale, should separate: (a) nuclei (bright, about 30 px across) from background; (b) a thin bright membrane (2 px wide) from the cytoplasm on both sides; (c) a granular region from a smooth region with the same mean brightness; (d) a dim nucleus from slightly brighter background that ramps up across the image?

B5. A forest trained on strokes from image 1 reaches 97 % on a fully annotated region of image 1, and 81 % on image 2. Give two reasons, and what you would paint next.

B1. (a) Box: the 3 \times 3 block 15, 40, 80, 50, 90, 95, 85, 96, 98 sums to 649: b = 72.1. g_x = (95 - 50)/2 = 22.5, g_y = (96 - 40)/2 = 28, g = \sqrt{22.5^2 + 28^2} = 35.9. \ell = 40 + 96 + 50 + 95 - 360 = -79. (b) Tree 1: 72.1 > 60 → N. Tree 2: 35.9 > 30 → B. Tree 3: -79 \le -50 → N. P(\text{N}) = 2/3, label N. (c) Pixel (row 2, column 2) = 15: box over rows 1–3, columns 1–3: 10 + 12 + 14 + 12 + 15 + 40 + 14 + 50 + 90 = 257, b = 28.6; g_x = (40 - 12)/2 = 14, g_y = (50 - 12)/2 = 19, g = 23.6; \ell = 40 + 12 + 50 + 12 - 60 = 54. Votes: B, N, B: P(\text{N}) = 1/3, label B. (d) The centre sits on the edge of a bright object (dark top-left, bright bottom-right): bright on average and brighter than its neighbours, but with a strong gradient. The edge tree reads “boundary” as background, the others “inside”. Boundary pixels are where the votes split and the uncertainty is high.

B2. (a) Majority background: P(\text{nucleus}) = 2/10 = 0.2. (b) Weight each class by 1/n_c (here w = 0.525 and 10.5, ratio 20), or sample the same number of pixels per class (e.g. all 20 nucleus pixels and 20 random background pixels, which throws data away). With the weights: P(\text{N}) = 2 \cdot 10.5/(2 \cdot 10.5 + 8 \cdot 0.525) = 0.83. (c) Yes: background pixels that resemble the 20 nucleus pixels are now called nucleus more often. Balancing trades errors of the small class for errors of the large one; it does not add information.

B3. (a) TP = 4, FP = 2 (row 1 column 3, row 3 column 2), FN = 1 (row 2 column 2), TN = 9. Accuracy 13/16 = 0.8125. Dice N = 8/(8 + 2 + 1) = 0.727; Dice B = 18/(18 + 3) = 0.857. (b) OOB votes are cast on painted pixels, whose neighbours (near copies) were in the bootstrap samples, and which sit where painting was easy. The held-out region contains boundaries, dim objects and other hard pixels that no stroke came near.

B4. (a) Intensity (smoothed) at a medium scale, or blobs (LoG) at σ ≈ 30/(2√2) ≈ 10. (b) Ridges (Hessian eigenvalue) at a small scale, σ ≈ 1: a bright line has a strongly negative eigenvalue across it. (c) Texture (structure tensor) or edges (gradient magnitude) at a small scale: smoothing removes the texture, so intensity at large σ cannot tell them apart. (d) Large-scale intensity to capture the ramp, together with small-scale intensity, so that the tree can compare the pixel with its surroundings; or paint background on both ends of the ramp.

B5. Image 2 may differ in staining, illumination or noise (the features shift), and it may contain structures never painted in image 1. Strokes from image 1 also share its specific neighbourhoods. Paint a few strokes on image 2 where it is wrong or uncertain, retrain on both images, and evaluate on a third, or on an annotated region not used for training.

Math questions

B6. (math) Show that weighting every sample of class k by w_k in the Gini impurity gives exactly the impurity of the data in which each sample of class k is replicated w_k times (for integer w_k), so both choose the same splits. Which weights balance 400 background and 20 nucleus pixels?

B7. (math) A stroke of 200 pixels is so smooth that consecutive pixels have correlation \rho = 0.95 in every feature. Treating the correlation as that of an AR(1) sequence, the effective number of independent samples is about n\frac{1-\rho}{1+\rho}. Compute it, and explain what it means for the OOB error.

B6. In a node with n_k samples of class k, the weighted shares are p_k = w_k n_k/\sum_l w_l n_l. Replicating each sample of class k w_k times gives w_k n_k samples of class k and the same shares. Gini depends only on the shares, and the weighted sizes \sum_l w_l n_l of the children are the sizes of the replicated children, so every split has the same impurity decrease in both settings: the same splits win. Balancing: w_k = n/(K n_k): 420/(2 \cdot 400) = 0.525 and 420/(2 \cdot 20) = 10.5 (any pair with ratio 20 works).

B7. 200 \cdot 0.05/1.95 \approx 5.1: the stroke is worth about 5 independent pixels, not 200. The bootstrap and the OOB estimate count 200; nearly every OOB pixel has near copies in the bag, so OOB measures the error on near copies of training pixels, and is far too optimistic.

Explore

Left: the image with the painted labels. Choose a label and paint with the mouse (brush sets the size; erase, undo, clear). The forest retrains when you lift the mouse (untick train after each stroke to train only with train). Middle: the result: segmentation (colour = most probable class), probability of a chosen class, uncertainty (1 - \max P), one feature channel (step through all of them), or the ground truth (test image only). Right: presets, the classifier (random forest or single tree) and its settings, the feature families and scales used, balance classes, and hold out the right part (the strokes right of the yellow line are not used for training; the region is evaluated). The readout lists the painted (and used) pixels per class, the OOB accuracy on the painted pixels, and on the test image the accuracy, Dice per class and the confusion matrix against the ground truth (rows: truth; columns: prediction; in % of the pixels of the whole image or the held-out region).

The test image: background (illumination rising to the right), smooth nuclei (some dim) and granular cells that are as bright as the nuclei but textured. The micrograph has no ground truth.

E1. Preset two strokes (one nucleus stroke, one background stroke). How many pixels are painted? Accuracy and Dice of the nucleus class? What happens to the granular cells, and why can the forest not do otherwise? Paint one stroke of granular cell across a granular cell and watch the result.

E2. Preset intensity only (strokes for all three classes, only the intensity channels): accuracy, Dice of nucleus and granular cell, and the share of granular-cell pixels called nucleus. Then preset full stack (all 42 channels): the same numbers. Use the features view to find a channel in which the granular cells differ clearly from the nuclei.

E3. Preset small scales only (σ ≤ 1.6). Accuracy and Dice compared with the full stack? Look at the segmentation: where are the extra errors?

E4. Preset only bright nuclei painted. Compare the nucleus row of the confusion matrix (how much of the image is nucleus called background?) with the full stack preset. Look at the dim nuclei in the segmentation. Then paint a short nucleus stroke on one dim nucleus.

E5. Preset huge background strokes. How many pixels per class are painted, and how many are used (the training set is capped at 4000)? Read the nucleus row of the confusion matrix and the Dice of the nucleus. Tick balance classes: what changes in the nucleus row, in the background row and in the accuracy?

E6. Preset OOB vs held-out region (strokes on both sides; those right of the yellow line are held out). Compare the OOB accuracy, the accuracy on the painted pixels in the held-out region, and the accuracy against the ground truth in that region. Which number would you report? Untick hold out the right part: what does the accuracy in the right part (now trained on) become?

E7. Preset uncertainty: where to paint (no granular stroke). Where is the uncertainty high? Is it high on the granular cells? Paint where the map tells you to, and then where the truth view tells you to.

E8. Switch the classifier to single tree on the full stack preset. Accuracy and Dice compared with the forest? Look at the segmentation of the granular cells.

E9. Preset micrograph: nucleus (nucleus and background strokes). Describe the result: where is it wrong? Then preset micrograph: + cytoplasm. Which parts of the cell become cytoplasm? Where would you paint next?

E1. 220 background and 116 nucleus pixels. Accuracy 87.4 %, Dice nucleus 0.57. The granular cells are classified as nucleus (8.5 % of all pixels: the granular row of the confusion matrix is 0.4 / 8.5 / 0.0): the forest only knows two classes and granular cells are bright like nuclei. A classifier can only output classes it was shown. A granular stroke adds the class; with the base strokes (E2) its Dice reaches 0.86.

E2. Intensity only (6 channels): accuracy 91.3 %, Dice nucleus 0.65, granular 0.68; 3.8 % of the image is granular cell called nucleus (granular row 0.0 / 3.8 / 5.1). Full stack (42 channels): 96.3 %, Dice nucleus 0.85, granular 0.86; granular row 0.1 / 0.0 / 8.7. Channels that separate them: the gradient or the structure-tensor eigenvalue μ1 at small σ (σ = 0.7–1.6): bright speckle inside the granular cells, nearly flat inside the nuclei.

E3. Small scales only (21 channels): 94.8 % (full stack 96.3 %), Dice nucleus 0.78 (0.85), granular 0.83 (0.86). The extra errors: an orange speckle of “nucleus” in the brighter background on the right (0.9 % of the image, against 0.2 %), and more nucleus pixels called granular (2.2 % against 1.6 %). Without the large scales a pixel only knows its immediate surroundings: a bright background pixel on the right looks like a dim nucleus pixel, and the forest cannot see that it lies far from any object.

E4. Only bright nuclei: nucleus row 1.2 / 6.4 / 2.0, i.e. 1.2 % of the image is nucleus called background (full stack: 0.7 %); Dice nucleus 0.80 (0.85). Parts of the dim nuclei (16 % of their interior, against 2 % with a dim stroke) become background: they are darker than anything painted as nucleus. One stroke on a dim nucleus brings them back.

E5. Painted: 4772 background, 37 nucleus, 45 granular; used (capped, same fraction per class): 3959, 30, 42. Without balancing: nucleus row 4.1 / 3.5 / 2.0 (more nucleus pixels called background than found), Dice nucleus 0.53, accuracy 92.6 %. Balanced: nucleus row 3.3 / 3.9 / 2.4, Dice 0.58; but the background row changes from 81.6 / 0.0 / 0.0 to 79.1 / 0.0 / 2.5, and the accuracy drops to 91.8 %. Balancing helps the small classes and costs the large one; the real cure is better strokes for the small classes.

E6. OOB accuracy 100.0 %; painted pixels in the held-out region 99.8 % right (650 pixels); full ground truth in the region 95.9 %. Report the last one: OOB is fooled by neighbouring pixels, and the painted pixels in the region are easy ones (stroke centres). Trained on all strokes: the accuracy in the right part rises to 96.9 %, but that number is no longer an independent test.

E7. High uncertainty on the rims of all objects and on the background in the right part of the image, which is brighter than any painted background (the background strokes are on the left). Not on the granular cells: they are classified confidently as nucleus (8.4 % of the image is granular cell called nucleus). The uncertainty map shows where the classes it knows meet, not what it has never seen. Paint background on the right; for the granular cells you need the truth (or your eyes) to add a class.

E8. Single tree: accuracy 94.6 %, Dice nucleus 0.78, granular 0.74 (forest: 96.3 %, 0.85, 0.86). Every granular cell gets a thick nucleus-coloured rim: 3.5 % of the image is granular cell called nucleus. One tree uses only a few channels (mean depth 3) and draws one hard boundary in them; the forest averages many trees that use different channels and gets the rims right.

E9. With nucleus and background only: the nucleus is found, but so is much of the cytoplasm and other dark material (it is neither the light background nor anything else the forest knows). With the cytoplasm strokes, the cytoplasm around the nucleus and the cell processes become cytoplasm; the nucleus is mostly nucleus, with its lower part and its envelope partly called cytoplasm. Paint nucleus in the lower part of the nucleus and cytoplasm or background where the result is uncertain (the uncertainty view).

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 randomforest/src/pixelclass/exercise.rs.

A random forest is ready in the download (the forest of the forest unit, with class weights), and so is Gaussian smoothing, gaussian(img, σ). The code writes a pixel as (x, y) = (column, row): the centre of the patch in B1 is (2, 2).

C1. pixel_features(img, x, y): the three features of B1, with the edge pixel copied outside the image:

b = the mean of the 3 × 3 neighbourhood
g = sqrt(gx² + gy²),   gx = (I(x+1, y) − I(x−1, y)) / 2,   gy = (I(x, y+1) − I(x, y−1)) / 2
l = I(x+1, y) + I(x−1, y) + I(x, y+1) + I(x, y−1) − 4 · I(x, y)

The checks are B1 (a) and (c).

C2. feature_stack(img, sigmas): three channels per scale:

for every σ:
    L = the image smoothed with a Gaussian of scale σ
    channel: L                                   # intensity
    channel: g of C1, computed on L, at every pixel     # edges
    channel: σ² · l of C1, computed on L          # blobs (Laplacian of Gaussian)

The checks: on a flat image the edge and blob channels are 0; at a bright spot the blob channel is negative.

C3. class_weights(counts): w_k = n / (K\, n_k); weighted_shares(counts, weights): the class shares of a leaf when every pixel of class k counts w_k times. The check is B2: weights 0.525 and 10.5, and the leaf with 8 B and 2 N says P(\text{N}) = 0.83 instead of 0.2.

C4. confusion(truth, predicted, n_classes): m[t][p] = the number of pixels of true class t predicted as p; dice(m, k) = 2\,TP / (2\,TP + FP + FN) for class k, with TP = m[k][k], FP the rest of column k and FN the rest of row k. The check is B3.

Then cargo run -p randomforest -- pixelclass and open the pictures in out/pixelclass/. The test image (input.png, 256 \times 256) has a background that gets brighter to the right, smooth nuclei, and granular cells about as bright as the nuclei; truth.png shows the classes (green = nucleus, magenta = granular cell). The program “paints” strokes on the left half only (strokes.png): through three nuclei, three granular cells and the background. It trains a forest (50 trees) on the painted pixels with the stack at σ = 0.7, 1.6, 3.5 and 8 (12 channels), classifies every pixel, and scores the result against the truth on the left half and on the held-out right half. It repeats this with balanced class weights, with the intensity channels only, and with the small scales only. For each run it writes the segmentation, the nucleus probability and the uncertainty (1 - \max_k P).

C5. Compare the OOB accuracy with the accuracy and the Dice coefficients on the right half. Which number would you report, and why is the OOB number so high?

C6. What do the edge and blob channels add? Compare the full stack with the intensity channels only, for the granular cells. Then compare with the small scales only: which does better on the right half, and why could that be?

C7. Look at full-stack-uncertainty.png and full-stack-segmentation.png. Where is the forest uncertain, and where would you paint next?

The model solution is randomforest/src/pixelclass/solution.rs in the download.

C5. Painted: 1119 background, 144 nucleus and 138 granular-cell pixels. The OOB accuracy is 99.4 %, but on the held-out right half only 94.1 % of the pixels are right, with Dice 0.75 for the nuclei and 0.58 for the granular cells (left half: 97.7 %, 0.77, 0.82). Report the held-out numbers. The OOB votes are cast on painted pixels, whose neighbours (near copies) were in the trees’ samples, and which sit in the middle of objects and of the background, where painting was easy (Trap 1).

C6. With the intensity channels only (4 channels) the right half drops to 90.3 %, Dice 0.47 (nuclei) and 0.29 (granular): smoothed brightness cannot tell a speckled cell from a smooth nucleus of the same brightness, while the gradient at small σ can (as in demo question E2). The small scales only (σ ≤ 1.6, 6 channels) do slightly better than the full stack on the right half (95.1 %, Dice 0.77 and 0.63). The large-scale intensity channels see mostly the illumination, which on the right half is brighter than anything that was painted: the forest has learned “bright surroundings” from the left half, and that does not carry over. (Balancing the classes changes little here: 94.2 %, Dice 0.74 and 0.62.)

C7. The uncertainty is high on the rims of all objects, where the classes meet (the forest often calls the rim of a nucleus “granular”: the edge gives a strong gradient, as the speckle does), and on the brightest background at the right edge of the image, which looks like nothing painted; there the segmentation has scattered granular-cell pixels. Paint background on the right, and a nucleus and a granular cell on the right half, then retrain.

Where this leads

The forest on a hand-made stack is the strong baseline from a few strokes. The SVM day plugs a support-vector machine into the same demo, where feature standardisation and by-stroke cross-validation become essential. The neural-networks day replaces the hand-made stack by filters that a network learns itself (U-Net), at the price of many more labels. The evaluation day measures segmentations object by object and makes the “split by image” rule precise (leakage). The Gaussian mixtures day models each class instead of drawing a boundary, and can do without labels.