CNN + GNN Scene Fusion

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.

Read one room three ways

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

The Bedroom That Was a Hotel Room

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).

Read two rooms two ways

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.

The road

  1. Two views: why two branches that fail on different images beat one.
  2. The CNN branch: from a 224 by 224 photo to the vector h.
  3. Objects to a graph: nodes, features and nearest-neighbour edges.
  4. Message passing: one GNN layer by hand, and the readout to g.
  5. Attention over neighbours: the GAT layer, which weights each neighbour.
  6. Fusion: concatenation, then a gate that trusts one branch per image.
  7. Why indoor: one rare object can move the odds by 23 times.
  8. Showcase: place objects and watch the scene change.
  9. Trade-offs: the detector sets the ceiling.
  10. Field guide: shapes, code, a published result and links.
A CNN with GAP confuses bedrooms with hotel rooms and libraries with bookstores. What do these pairs share, and what is the best fix?

Chapter 1

Two Views That Fail on Different Images

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.

StepBranch A: CNNBranch B: detector + GNN
Inputphoto (3, 224, 224)the same photo
Middlefeature map (512, 7, 7)N objects, a graph
Outputh (512,)g (256,)
Fails onscenes with the same lookscenes 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:

Say it aloud

P-both equals one minus a-h, times one minus a-g.

Pboth
P-both the share of images where both branches are wrong.
ah
a-h the accuracy of the whole-image branch alone, from 0 to 1.
ag
a-g the accuracy of the graph branch alone, from 0 to 1.
1 − a
one minus a that branch’s error rate.
In plain words

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 numbers

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.

Count the images both branches miss

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.

0.70
0.65

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.

Branch A is right 80% of the time and branch B 60%, with independent errors. On what share of images are both wrong?

Chapter 2

The CNN Branch: One Vector for the Whole Room

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-18Output shapeStride 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:

Say it aloud

h-c equals one over H times W, times the sum over i and j of F-c-i-j.

hc
h-c entry c of the whole-image descriptor h; there are 512 entries.
H
H the height of the feature map: 7 cells.
W
W the width of the feature map: 7 cells.
Σi,j
the sum over i and j add one term for every cell, all 49 of them.
Fc,i,j
F-c-i-j how strongly pattern c fired at row i, column j.
In plain words

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 numbers

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.

Move a pattern, keep the same h

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.

The backbone outputs a (512, 7, 7) map. After GAP, what is the shape of h, and what was lost?

Chapter 3

From Detected Objects to a Graph

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.

TensorShapeWhat 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:

dij = √((xi − xj)2 + (yi − yj)2)
bed (20, 70), nightstand (35, 60), lamp (38, 40), window (80, 25), in a 100 by 100 image
bed–nightstand = √(152 + 102) = 18.0 · nightstand–lamp = √(32 + 202) = 20.2
bed–lamp = 35.0 · lamp–window = 44.6 · nightstand–window = 57.0 · bed–window = 75.0

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 objects, watch the edges form

Drag any object. Each one joins its k nearest by centre distance, shown on the edge. Drag the luggage rack next to the bed.

1

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.

In branch B, what is a node, what is an edge, and what is a node’s feature?

Chapter 4

Message Passing: Each Object Hears Its Neighbours

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:

Say it aloud

h-prime-i equals ReLU of W times, h-i plus the mean of h-j over the neighbours of i, all over two.

h′i
h-prime-i node i’s vector after this layer.
ReLU
ReLU keep positive values, set negative values to 0.
W
W a learned square matrix, the same for every node. Here it is the identity, so it changes nothing.
hi
h-i node i’s vector before the layer.
meanj∈N(i) hj
the mean of h-j over the neighbours of i the message: add the vectors of the nodes joined to i, divide by how many there are.
In plain words

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.

With numbers

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].

Pass messages, layer by layer

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.

Node n has two neighbours with vectors [2, 0] and [0, 4]. What message does n receive in a mean-aggregate step?

Chapter 5

Attention Over Neighbours: the GAT Layer

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:

Say it aloud

alpha-i-j equals the softmax over j of LeakyReLU of a-transpose times W-h-i joined with W-h-j.

αij
alpha-i-j how much node i listens to node j; the weights over j add to 1.
softmaxj
the softmax over j raise e to each score, divide by the total over i’s neighbours and i itself.
LeakyReLU
leaky ReLU keep a positive score; multiply a negative score by 0.2.
aT
a-transpose a learned vector, twice as long as W-h; its dot product with the joined pair is the raw score.
W hi
W-h-i the listening node’s vector after the learned matrix W.
W hj
W-h-j the neighbour’s vector after W. The bars ‖ mean “joined end to end”.
In plain words

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 numbers

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.

Tune what the nightstand listens for

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”.

1.0

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.

A node has raw scores 2, 0 and 0 for three neighbours (including itself). What weight does the first one get after the softmax?

Chapter 6

Fusing h and g

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:

Say it aloud

p equals the softmax of W-c times h stacked on g, plus b.

p
p one probability per scene; they add to 1.
softmax
softmax raise e to each logit, divide by the total.
Wc
W-c the classifier weights: one row per scene, one column per fused value. For 67 scenes, 67 by 768.
h
h the whole-image descriptor from the CNN branch.
g
g the graph descriptor from the GNN branch. The semicolon means “stack g under h”.
b
b one bias per scene. Zero in the example.
In plain words

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 numbers

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:

Say it aloud

f equals z times h, plus one minus z times g.

f
f the fused vector the classifier reads.
z
z the gate: sigma of w-z dot [h ; g] plus b-z, where sigma squeezes any number into 0 to 1.
h
h the whole-image descriptor; it gets weight z.
g
g the graph descriptor; it gets weight 1 minus z.
In plain words

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 numbers

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.

Mix the two branches

Lean 0 means bedroom, 1 means hotel. “Graph signal” is how much the detector found. Compare the two fusions as you empty the graph.

0.10
0.80
1.00

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.

h = [1, 0] and g = [0, 1, 1]. What vector does concatenation pass to the classifier?

Chapter 7

Why It Helps Indoor Scenes Most

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′:

Say it aloud

O-prime equals O times P of o given B, over P of o given L.

O′
O-prime the odds of bookstore against library after you see the object.
O
O the odds before; 1 means a 50/50 tie.
P(o | B)
P of o given B the share of bookstore photos that contain object o.
P(o | L)
P of o given L the share of library photos that contain object o.
In plain words

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 numbers

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.

Detect objects, move the odds

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.

Why does the graph branch help indoor benchmarks more than outdoor ones?

Chapter 8

Showcase: Build the Room, Watch the Scene Change

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.

Place objects, read the scene

Tap an object to add it, tap again to remove it. Slide the room look. Raise the detector noise to drop and invent objects.

beds
0.00

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:

  1. The tie. Bed and nightstand only, room look at bedroom. Fused: bedroom 55%, hotel 45%. The CNN leans a little; the graph cannot break the tie.
  2. One object flips it. Add the luggage rack. Graph logits go from 2.0 and 2.0 to 1.0 and 2.83. Fused: hotel 83%.
  3. Library to bookstore. Clear the room, slide the room look to books, add books and a study desk: library 94%. Add a cash register: bookstore 52%, library 46%.

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

Trade-offs: The Detector Sets the Ceiling

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:

  1. Missed detection. The rack is not found, so the graph never says hotel.
  2. False detection. An invented object adds a node that misleads the messages.
  3. Domain shift. COCO, a common detector training set, has 80 classes; a study carrel or a fume hood is not one of them. The graph is empty where you need it.

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:

Say it aloud

acc equals r times a-one, plus one minus r times a-zero.

acc
acc the expected accuracy on photos that need the deciding object.
r
r the detector’s recall on that object, from 0 to 1.
a1
a-one the accuracy when the object is found.
a0
a-zero the accuracy when it is missed: the CNN’s accuracy.
In plain words

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 numbers

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.

Set the detector’s quality

The pink line is expected accuracy against recall. The dot is your detector. Add false detections and watch the floor sink below the CNN.

0.80
0.00

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.

The CNN is right 60% of the time on a pair; with the deciding object found the model is right 90%. Detector recall is 0.5. What is the expected accuracy?

Chapter 10

Field Guide

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.

Terms and numbers

TermWhat it isNumber to keep
Whole-image descriptor hGAP over the last feature map(512, 7, 7) to (512,) in ResNet-18
Node featureRoI feature plus box code256 + 4 = 260 values in our example
k-NN edgeseach object to its k closest, made two-wayk = 2 to 4
Mean layerReLU(W (h-i + mean of neighbours) / 2)2 or 3 layers
GAT weightsoftmax of LeakyReLU(a · [Wh-i, Wh-j])LeakyReLU slope 0.2
Concatenation[h ; g], then linear and softmax512 + 256 = 768 inputs
Gatez h + (1 − z) g, z from a sigmoidz near 1 trusts the CNN
Recall boundr a-one + (1 − r) a-zerogain scales with r
MIT Indoor67indoor scene benchmark67 classes, 15,620 photos, 80/20 per class

One published result

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%.

ApproachHow it reads the sceneBest when
CNN with GAPoverall look onlyoutdoor, few objects, distinct textures
CNN + mean GNNlook plus an equal-weight object graphindoor, many objects, look-alike classes
CNN + GATlook plus an attention-weighted graphcluttered rooms where a few objects decide
Vision Transformerattention over image patches, structure learned implicitlylarge pretraining data

Checklist

  1. Print the confusion matrix first. Add a graph branch only if the top confusions share objects.
  2. Check detector recall on the deciding objects, on your own photos.
  3. Build k-NN edges with k from 2 to 4 and make them two-way.
  4. Use 2 or 3 message-passing layers. Watch for over-smoothing.
  5. Start with concatenation. Add a gate only if it wins on held-out data.
  6. Report per-class accuracy, split by the number of detections per photo.

The core in code

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

Keep going

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.

The takeaway. GAP knows what a room looks like and forgets what sits next to what. The object graph keeps exactly that, and fusion lets the model use whichever view sees clearly on each photo.

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.

CNN + GNN Scene Fusion
Back to Visual Scene Classification · Back to Gleams