A CNN sees a hotel room and says “bedroom”: the two look alike. Add a second branch that reads which objects sit next to which, and one luggage rack turns the answer to hotel.
Pick a room, then pick a reader: the CNN alone, the object graph alone, or both. Then switch off the detector’s view of the rack. Then we build each piece from zero: the CNN branch, the object graph, message passing, attention and fusion.
You need a little Python and what a probability is. We build the rest from zero.
A two-branch design used in indoor scene recognition. The room and its numbers are a toy made for this page. Chapter 10 names one published model and its result.
Illustrative toy: hand-set object votes, a 2-nearest-neighbour graph, two mean message-passing layers, and a whole-image branch that cannot tell the two rooms apart. The same model runs the showcase in Chapter 8.
Chapter 0
See which signal a whole-image CNN throws away, and what a second view must keep
Your scene classifier works well outdoors. A beach looks nothing like a kitchen. Then you test it on indoor photos, and the errors line up in pairs: hotel room as bedroom, bookstore as library, fast-food counter as cafeteria.
Each pair shares its objects. A bedroom and a hotel room both have a bed, a nightstand, a lamp and a window. The classifier is a convolutional neural network (CNN): a network that slides learned filters over the image. It ends with global average pooling (GAP), which averages each feature channel over the whole image. GAP keeps how much of each pattern there is. It drops where the pattern was.
The useful signal sits in what GAP drops. A hotel room has a luggage rack beside the bed and a TV on a dresser, in a tidy matched layout. A home bedroom has a laundry basket and clutter. The difference is co-occurrence (which objects appear together) and arrangement (which object is next to which).
Blue bars are each room’s whole-image descriptor. Teal is its object graph. Switch views and compare the two rooms.
Illustrative: we made up the eight descriptor values per room to show the effect. A real descriptor has 512 values.
In the whole-image view the two rooms match to a cosine similarity of 0.999 (1 means the same direction). In the graph view they differ by two nodes and their edges. A bigger CNN does not fix this. More filters still end in GAP, and GAP still averages away “the rack is next to the bed”.
The fix is a second branch with a different inductive bias (a built-in assumption about what matters). Detect the objects. Make each object a node. Join nearby objects with edges. Run a graph neural network (GNN), a network that works on nodes and edges instead of a pixel grid. Then fuse its answer with the CNN’s.
Failure. Symptom: top-1 accuracy is high overall but low on a few indoor pairs. Measure: print the confusion matrix and sort the off-diagonal cells; the top cells share objects. Fix: add a view that keeps object structure, not a bigger backbone.
Chapter 1
Split the model into a whole-image branch and a graph branch, and count how often both are wrong
The model reads one photo two ways. Branch A, the CNN, makes the whole-image descriptor h: one vector for the whole image’s look. Branch B, a detector plus a GNN, makes the graph descriptor g: one vector for the objects and their relations. A fusion step joins h and g, and a linear layer with softmax names the scene.
| Step | Branch A: CNN | Branch B: detector + GNN |
|---|---|---|
| Input | photo (3, 224, 224) | the same photo |
| Middle | feature map (512, 7, 7) | N objects, a graph |
| Output | h (512,) | g (256,) |
| Fails on | scenes with the same look | scenes with few or missed objects |
Why two branches? They fail on different images. The question is how often both fail on the same image. Call branch A’s accuracy ah and branch B’s ag. If their errors are independent, the share of images where both are wrong is Pboth:
P-both equals one minus a-h, times one minus a-g.
Take each branch’s error rate, 1 minus a-h and 1 minus a-g. Multiply them. The product is P-both. It holds only if the errors are independent.
With made-up numbers: a-h = 0.70 and a-g = 0.65. P-both = 0.30 × 0.35 = 0.105. A perfect referee that always picks the right branch scores 1 − 0.105 = 0.895. Neither branch alone passes 0.70.
Each square is one image. Blue: only the CNN is right. Teal: only the graph is right. Green: both. Red: neither. Drag the accuracies, then make the errors overlap.
Illustrative: 400 images. With independent errors, each branch’s right answers fill a block, so the red corner is the product. “Same hard images” ranks images by difficulty, the same for both branches.
Switch to “same hard images”. Now the red share is the smaller error rate, 30%, and a second branch adds almost nothing. Two copies of one CNN behave like this. We build the graph branch to fail elsewhere; that is why it helps.
Chapter 2
Follow the tensor shapes from photo to h, and watch pooling forget where a pattern was
Branch A turns a photo into one fixed-length vector. The input is a tensor (3, 224, 224): three colour channels, 224 pixels high and wide. A backbone such as ResNet-18 is a stack of convolution blocks. Each block halves the height and width and adds channels.
| Stage of ResNet-18 | Output shape | Stride so far |
|---|---|---|
| input | (3, 224, 224) | 1 |
| conv1 + max pool | (64, 56, 56) | 4 |
| layer2 | (128, 28, 28) | 8 |
| layer3 | (256, 14, 14) | 16 |
| layer4 | (512, 7, 7) | 32 |
The last map has 512 channels. Each channel is a pattern detector, such as “wood grain” or “a vertical edge”. Its 7 by 7 grid says where in the photo that pattern fired. Call the value of channel c at row i and column j Fc,i,j, the grid height H and width W. GAP gives channel c one number, hc:
h-c equals one over H times W, times the sum over i and j of F-c-i-j.
Add every cell F-c-i-j of channel c. Divide by the number of cells, H times W. The result h-c says how much of pattern c is in the photo, anywhere.
With a made-up 3 by 3 channel: rows [0.10, 0.80, 0.20], [0.00, 0.90, 0.30], [0.05, 0.70, 0.15]. The sum is 3.20. H · W = 9. h-c = 3.20 / 9 = 0.356. The bright middle column is gone; only “moderately present” is left.
Tap cells to light them in one 7 by 7 channel. The blue bar is its pooled value h-c. Then move the pattern.
One channel of a toy feature map. Each tap adds 0.5 to a cell, up to 1.
Do this for all 512 channels and branch A is done: (512, 7, 7) becomes h (512,). Ignoring place is right for a whole-image summary: a kitchen is a kitchen with the stove on either side. It is also the blind spot from Chapter 0.
pythonimport torch, torchvision.models as models backbone = torch.nn.Sequential(*list(models.resnet18(weights="DEFAULT").children())[:-2]) fmap = backbone(images) # (B, 3, 224, 224) -> (B, 512, 7, 7) h = fmap.mean(dim=(2, 3)) # GAP -> (B, 512): the whole-image descriptor
Failure. Symptom: you keep the (512, 7, 7) map to “give fusion spatial detail”, and the fused layer has 25,088 inputs and overfits. Measure: the gap between train and test accuracy. Fix: pool in branch A; let branch B carry the structure.
Chapter 3
Turn a detector’s box list into nodes with features and nearest-neighbour edges
Branch B starts with an object detector: a network such as Faster R-CNN, YOLO or DETR. For each object it returns a class, a confidence and a bounding box (the rectangle that holds the object). Each detected object becomes one node of a graph.
A node needs a feature vector, not only a name. It usually joins two parts. The first is the RoI feature (region of interest): the detector’s CNN features pooled inside the box, which say what the object looks like. The second is a box code: centre x, centre y, width and height, scaled to 0 to 1. With a 256-value RoI feature, each node has 256 + 4 = 260 values.
| Tensor | Shape | What it holds |
|---|---|---|
| X | (N, 260) | one row per object: RoI feature and box code |
| A | (N, N) | 1 if objects i and j share an edge, else 0 |
Now the edges. The common rule is k-nearest neighbours (k-NN): join each object to the k objects whose box centres are closest. Then make every edge two-way. With the centres (xi, yi) and (xj, yj), the distance is the straight line between them:
With k = 1, each node keeps its nearest: bed to nightstand, nightstand to bed, lamp to nightstand, window to lamp. Three edges remain, a chain bed–nightstand–lamp–window. With k = 2 the graph has five edges. The window has no close neighbour, and that is information too.
Drag any object. Each one joins its k nearest by centre distance, shown on the edge. Drag the luggage rack next to the bed.
Positions start at the worked example (the rack starts in a far corner). Distances are in the 0 to 100 image units.
Failure. Symptom: you join every object to every other, and the GNN output barely depends on the photo. Measure: the spread of g across scenes shrinks. Fix: keep k small (2 to 4) or use a distance cut-off, so a node hears its real neighbours.
Chapter 4
Run one GNN layer by hand, read the graph out to g, and see why ten layers blur it
A GNN layer does one thing: each node mixes its neighbours’ vectors into its own. After one layer, the bed’s vector knows about the nightstand. After two, it knows the nightstand’s neighbours too. This is message passing.
One layer has two steps. Aggregate: average the neighbours’ vectors into one message. Update: blend the node’s own vector with the message, multiply by a learned matrix, and apply ReLU (replace negatives with 0). Call node i’s vector hi, its set of neighbours N(i) and the learned matrix W. The new vector is h′i:
h-prime-i equals ReLU of W times, h-i plus the mean of h-j over the neighbours of i, all over two.
Average the neighbours’ vectors h-j into a message. Add it to h-i and halve the sum. Multiply by W, clip negatives with ReLU, and you have h-prime-i. Do every node at the same time.
Made-up 2-value features on the Chapter 3 chain: bed [1.0, 0.0], nightstand [0.0, 1.0], lamp [0.5, 0.5]. The nightstand’s neighbours are the bed and the lamp. Message = ([1.0, 0.0] + [0.5, 0.5]) / 2 = [0.75, 0.25]. h-prime = ([0.0, 1.0] + [0.75, 0.25]) / 2 = [0.375, 0.625]. ReLU keeps it. The nightstand now leans toward its company.
After two or three layers, a readout turns all node vectors into one graph vector g. The plain readout is the mean over nodes. With the window at [0.2, 0.2], layer one gives bed [0.5, 0.5], nightstand [0.375, 0.625], lamp [0.3, 0.55], window [0.35, 0.35], and g = [0.381, 0.506]. GAP pools cells; readout pools nodes.
The GCN of Kipf and Welling (2017) adds a self-loop and weights each pair by 1 / √(degreei · degreej). Here the nightstand takes 0.408 of the bed, 0.333 of itself and 0.333 of the lamp: [0.575, 0.5].
Each node’s colour is one value from 0 to 1. Press the button to run one layer. Keep pressing and watch the values meet.
The layer is the equation above with W = 1 and a single value per node. The six start values are illustrative.
The spread falls from 1.00 to 0.67 after three layers and to 0.31 after ten, and it keeps shrinking toward 0. That is over-smoothing: every node averages in the whole graph, and all nodes end with the same vector. An object graph has few nodes, so 2 or 3 layers reach far enough.
Failure. Symptom: accuracy drops as you add layers. Measure: the mean distance between node vectors per layer. Fix: 2 or 3 layers, or a skip connection that keeps h-i.
Chapter 5
Let each node score its neighbours and listen most to the one that matters
The mean treats every neighbour the same. A bed next to a luggage rack and a plain wall gives each half the vote. A graph attention network (GAT), from Veličković et al. (2018), learns a weight for each neighbour instead. The bed can listen mostly to the rack.
The score for a pair is a small learned function. Multiply both vectors by W. Join them end to end, written [W hi ‖ W hj]. Take a dot product with a learned vector a. Pass it through LeakyReLU, which keeps positive values and multiplies negative ones by 0.2. Then a softmax over the neighbours, including i itself, turns the scores into weights αij that add up to 1:
alpha-i-j equals the softmax over j of LeakyReLU of a-transpose times W-h-i joined with W-h-j.
For each neighbour j, join W-h-i and W-h-j, dot with a, and apply LeakyReLU. Softmax the scores over all j. The new vector is the sum of alpha-i-j times W-h-j.
With made-up weights: W is the identity and a = [0.5, 0.5, 1, −1]. For the nightstand [0, 1]: self scores LeakyReLU(0.5 − 1) = −0.1, bed [1, 0] scores 0.5 + 1 = 1.5, lamp [0.5, 0.5] scores 0.5 + 0 = 0.5. Softmax gives alpha = 0.129, 0.637 and 0.234. New vector = 0.637 · [1, 0] + 0.234 · [0.5, 0.5] + 0.129 · [0, 1] = [0.754, 0.246].
The mean over the same three nodes gives [0.5, 0.5]. Attention moved the nightstand most of the way to the bed, because this a rewards neighbours whose first value is large. In training, a learns which neighbours carry the scene signal.
Purple bars are the attention weights alpha. Grey ticks are the plain mean, one third each. Drag the knob from “like me” to “like the bed”.
a = [0.5, 0.5, s, −s] and W is the identity; s = 1 is the worked example. A real GAT learns a and W, and often runs several attention heads side by side.
Failure. Symptom: the GAT is no better than the mean. Measure: plot the alpha values; if they sit near 1 / (degree + 1) for every node, attention learned nothing. Fix: more data per scene, or keep the cheaper mean layer.
Chapter 6
Join the two descriptors by concatenation, then let a gate choose a branch for each image
Now there are two vectors: h from the CNN and g from the GNN. Fusion joins them into one input for the classifier. The plain way is concatenation: write g after h. A 512-value h and a 256-value g make a 768-value vector, written [h ; g]. A linear layer with weights Wc and bias b maps it to one score per scene, the logits. Softmax turns them into probabilities p:
p equals the softmax of W-c times h stacked on g, plus b.
Stack g under h. Multiply by W-c and add b to get one logit per scene. Softmax the logits into p. Each row of W-c learns how much to trust each half.
With made-up values: h = [0.9, 0.1] (looks like a bedroom), g = [0.2, 0.8] (the graph saw a luggage rack). [h ; g] = [0.9, 0.1, 0.2, 0.8]. W-c rows: bedroom [2, 0, −1, −1], hotel [0, 0, 1, 2]. Logits: 1.8 − 0.2 − 0.8 = 0.8 and 0.2 + 1.6 = 1.8. Softmax: 2.23 / 8.28 = 0.27 bedroom, 6.05 / 8.28 = 0.73 hotel.
Without g, the same W-c gives logits 1.8 and 0, so 0.86 bedroom. The graph branch turned a wrong answer into a right one. Concatenation learns one trust level per weight, the same for every photo.
A gate trusts a branch per photo. Make h and g the same length. A small layer reads [h ; g] and outputs the gate value z between 0 and 1. The fused vector f mixes the two:
f equals z times h, plus one minus z times g.
Compute z from both descriptors. Scale h by z and g by 1 minus z. Add them. Near z = 1 the model trusts the CNN; near z = 0 it trusts the graph.
With made-up gate weights w-z = [0, 0, −4, −4] and b-z = 2, the gate reads how much graph signal there is. g = [0.2, 0.8]: 2 − 4 = −2, z = 0.12, f = [0.28, 0.72]. An empty graph, g = [0, 0]: z = 0.88, so f leans on h.
Lean 0 means bedroom, 1 means hotel. “Graph signal” is how much the detector found. Compare the two fusions as you empty the graph.
Illustrative: h = [1 − lean, lean], g = signal · [1 − lean, lean]. Concatenation uses the W-c above; the gated fusion uses the gate above and logits 3 · f.
Failure. Symptom: the gated model beats concatenation on train data and loses on test data. Measure: train and test accuracy for both. Fix: on a small set like MIT Indoor67 (80 training photos per scene), start with concatenation; add the gate only if it wins on held-out data.
Chapter 7
Measure how much one object moves the odds between two look-alike scenes
Indoor scenes are hard for a whole-image CNN. MIT Indoor67 (Quattoni and Torralba, 2009) has 67 indoor classes and 15,620 photos, with 80 training and 20 test photos per class in the standard split. Its classes share walls, floors, lighting and furniture, so their whole-image descriptors sit close together.
What separates a library from a bookstore? Both have books and shelves. A bookstore also has a cash register. A library has study desks. The signal is which objects appear together. That is a graph property, and GAP averages it away.
Put a number on it. Before you look at objects, the belief is the prior odds O: P(bookstore) divided by P(library). Seeing object o multiplies the odds by the likelihood ratio: how much more often o appears in bookstores, P(o | B), than in libraries, P(o | L). The new belief is O′:
O-prime equals O times P of o given B, over P of o given L.
Divide how often o shows up in bookstores by how often it shows up in libraries. Multiply the old odds O by that ratio to get O-prime. To get a probability back, compute O-prime / (1 + O-prime).
With made-up rates: a book is in 95% of both, so its ratio is 1 and the odds stay at 1. A cash register is in 70% of bookstores and 3% of libraries: O-prime = 1 · 0.70 / 0.03 = 23.3, so P(bookstore) = 23.3 / 24.3 = 0.96. A study desk then multiplies by 0.08 / 0.65 = 0.12: odds 2.87, P = 0.74.
The bar is the belief: library on the left, bookstore on the right. Tap objects to detect them. Shared objects barely move it.
Illustrative rates. Multiplying ratios assumes objects appear independently once the scene is known; real objects are not independent, which is why a GNN learns the combination instead.
Outdoors the picture flips. A beach, a forest or a highway is defined by texture and layout, with few countable objects. There the CNN already wins, and the graph is nearly empty. The graph branch helps most where overall look is weakest: indoors, crowded with objects, alike in look.
Failure. Symptom: the two-branch model is worse than the CNN on outdoor classes. Measure: per-class accuracy, split by the mean number of detections per photo. Fix: a gate that mutes g when the graph is empty, as in Chapter 6.
Chapter 8
Place objects and run the whole two-branch model live over four scenes
Every piece now runs together. You place objects in a room. The model builds a 2-nearest-neighbour graph, runs two mean layers from Chapter 4, reads out g, and adds the CNN’s logits from the room-look slider. Four bars show bedroom, hotel room, library and bookstore.
Each object carries a vote: four numbers, one per scene. A bed votes for bedroom and hotel alike. A luggage rack votes hotel. A cash register votes bookstore. Message passing spreads each vote to the object’s neighbours before the readout.
Tap an object to add it, tap again to remove it. Slide the room look. Raise the detector noise to drop and invent objects.
Illustrative toy: hand-set votes, graph logits = 2.5 × the readout, CNN logits that cannot split bedroom from hotel or library from bookstore. Noise drops objects in a fixed order and, above 0.6, invents a cash register.
Three experiments, one per idea:
Then raise the noise. The rack drops out first and the hotel goes back to “bedroom”. Past 0.6 a false cash register appears and pulls a library toward bookstore. Chapter 9 puts numbers on that.
Chapter 9
Price the second branch, and compute how detector recall caps its gain
The graph branch costs a second network. Every frame now runs a backbone and a detector, and you train, store and update both. On a robot with a fixed time budget per frame, that can be too much. One answer: run the graph branch only when the CNN is unsure.
The graph is only as good as the detections. Three failures come from the detector:
Count the first failure. Call the detector’s recall on the deciding object r: the share of photos where it finds that object. Call the model’s accuracy when the object is found a1, and when it is missed a0 (the CNN’s accuracy on this pair). The expected accuracy is acc:
acc equals r times a-one, plus one minus r times a-zero.
On a share r of photos the object is found and you score a-one. On the rest you fall back to a-zero. Weight each by its share and add. The gain over the CNN is r times (a-one minus a-zero).
With made-up accuracies a-one = 0.95 and a-zero = 0.55: r = 0.8 gives 0.76 + 0.11 = 0.87. r = 0.5 gives 0.475 + 0.275 = 0.75. The gain of 0.40 shrinks in step with recall.
The pink line is expected accuracy against recall. The dot is your detector. Add false detections and watch the floor sink below the CNN.
Illustrative: a-one 0.95, a-zero 0.55. When the true object is missed, a false object for the other scene appears with the false rate and drops accuracy to 0.10.
With no false detections the line never drops below the CNN’s 0.55: fusion degrades gracefully. With a false rate of 0.3 and recall 0.5, accuracy falls to 0.68. Below recall 0.25 it drops under the CNN alone: 0.52 at recall 0.2. An unreliable graph with naive fusion can make things worse.
Failure. Symptom: the two-branch model is worse than the CNN on new data. Measure: detector recall and false rate on that data, per object class. Fix: an in-domain detector, a confidence cut-off on detections, and a gate that can mute g.
Chapter 10
Keep the shapes, the numbers, a checklist, the code and the links in one place
A scene is read two ways. The CNN branch pools a feature map into h and sees the overall look. The graph branch turns detected objects into nodes, joins near ones, passes messages and reads out g. Fusion joins h and g, by concatenation or a gate, and a softmax names the scene.
| Term | What it is | Number to keep |
|---|---|---|
| Whole-image descriptor h | GAP over the last feature map | (512, 7, 7) to (512,) in ResNet-18 |
| Node feature | RoI feature plus box code | 256 + 4 = 260 values in our example |
| k-NN edges | each object to its k closest, made two-way | k = 2 to 4 |
| Mean layer | ReLU(W (h-i + mean of neighbours) / 2) | 2 or 3 layers |
| GAT weight | softmax of LeakyReLU(a · [Wh-i, Wh-j]) | LeakyReLU slope 0.2 |
| Concatenation | [h ; g], then linear and softmax | 512 + 256 = 768 inputs |
| Gate | z h + (1 − z) g, z from a sigmoid | z near 1 trusts the CNN |
| Recall bound | r a-one + (1 − r) a-zero | gain scales with r |
| MIT Indoor67 | indoor scene benchmark | 67 classes, 15,620 photos, 80/20 per class |
Song, Wu and Ma, Inter-object Discriminative Graph Modeling for Indoor Scene Recognition (arXiv, 2023), add one graph convolution to a ConvNeXt backbone. Their nodes are feature-map pixels, and their edges are weighted by how well each pair of object labels separates scenes, from a segmentation map with 150 ADE20K classes. On MIT Indoor67 with ConvNeXt-Base (their Table 5), the CNN baseline scores 87.4% and their model 89.3%; with ten-crop testing, 90.4%.
| Approach | How it reads the scene | Best when |
|---|---|---|
| CNN with GAP | overall look only | outdoor, few objects, distinct textures |
| CNN + mean GNN | look plus an equal-weight object graph | indoor, many objects, look-alike classes |
| CNN + GAT | look plus an attention-weighted graph | cluttered rooms where a few objects decide |
| Vision Transformer | attention over image patches, structure learned implicitly | large pretraining data |
pythonimport numpy as np def knn_adjacency(centres, k=2): # centres: (N, 2) d = np.linalg.norm(centres[:, None] - centres[None], axis=-1) A = np.zeros_like(d) for i, row in enumerate(d): A[i, np.argsort(row)[1:k + 1]] = 1 # skip self at position 0 return np.maximum(A, A.T) # (N, N), two-way edges def mean_layer(X, A, W): # X: (N, d), W: (d, d) msg = (A @ X) / np.maximum(A.sum(1, keepdims=True), 1) return np.maximum(((X + msg) / 2) @ W, 0) def classify(fmap, X, centres, W1, W2, Wc, b): h = fmap.mean(axis=(1, 2)) # (512, 7, 7) -> (512,) A = knn_adjacency(centres) g = mean_layer(mean_layer(X, A, W1), A, W2).mean(0) # readout -> (d,) z = Wc @ np.concatenate([h, g]) + b # logits, one per scene e = np.exp(z - z.max()) return e / e.sum() # p, sums to 1
Visual scene classification · RGB-D scene classification · Remote-sensing scene classification · Graph neural networks · CS224W: GNNs 1 · CS224W: a general view of GNNs (GCN, GAT) · CS224W: GNN training · Detection and segmentation · Pooling and aggregation · GNN workbook
Sources: Quattoni and Torralba, “Recognizing Indoor Scenes” (CVPR 2009) for MIT Indoor67; Kipf and Welling, Semi-Supervised Classification with Graph Convolutional Networks (ICLR 2017); Veličković et al., Graph Attention Networks (ICLR 2018); Song, Wu and Ma (arXiv 2311.05919). All rooms, votes and accuracies in the devices are illustrative.
Now press Present or Teach and explain from memory: why GAP cannot tell the rooms apart, one mean layer on the nightstand, how GAT reweights it, and why recall caps the gain. Then go back to the hero, pick the hotel room, and switch off the rack.