🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Scene Graph Generation and Compositional Reasoning

Computer VisionCompositional Visual Reasoning and Scene GraphsđŸŸĸ Free Lesson

Scene Graph Generation and Compositional Reasoning

Module: Computer Vision | Difficulty: Premium

Prerequisites

  • !Object detection and region proposals
  • !Graph basics: nodes, edges, adjacency
  • !How classification heads and softmax outputs work

What You'll Learn

  • 1Explain why boxes alone cannot support reasoning
  • 2Generate a scene graph with iterative message passing
  • 3Handle the extreme long tail of visual predicates
  • 4Test compositional generalization with held-out triplets
  • 5Feed a generated graph into question answering

Boxes describe where, graphs describe what is happening

Two people standing near a doorway and two people arguing in a hallway produce nearly identical detections: same classes, similar boxes, comparable confidence. What distinguishes them is the relation between them, and relations are exactly what a detector discards. Scene graphs restore them by representing an image as a set of object nodes joined by labeled, directed edges, each edge a predicate such as riding, holding, next to, or wearing.

Formally the graph is a pair of vertex and edge sets, where each vertex carries a class label and a region, and each edge carries a predicate label. The value of the representation shows up downstream: captioning systems conditioned on a graph produce sentences with correct relational structure instead of unordered noun lists, and question answering systems can resolve queries like which cup is beside the plate by walking edges rather than re-examining pixels.

The hard part is statistical. In standard benchmarks a handful of generic predicates such as on, in, has and near account for the large majority of annotated edges, while the expressive ones — chasing, hugging, repairing — appear a few dozen times each. A model evaluated on micro accuracy will learn to predict on everywhere and score respectably, which is why the field reports triplet recall instead.

Two evaluation protocols and the leakage between them

Predicate classification answers the easiest question: given ground-truth boxes and object labels, what is the relation? Scene graph generation is the real task: given only the image, produce objects and relations jointly. Conditional scene graph generation sits between them, giving ground-truth objects but not predicates. Reporting the middle setting while claiming the first is a recurring source of overstated results.

SettingInputs given to the modelWhat it measuresTypical R@50
Predicate classificationGround-truth boxes and labelsRelation semantics onlyHigh
Scene graph generationImageDetection and relations jointlyModerate
Conditional generationGround-truth objectsRelation reasoning aloneHigh
Zero-shot generationImage, unseen tripletsCompositional transferLow

Recall at K is computed over triplets, meaning subject, predicate and object must all be correct. Because a correct triplet requires three right predictions, scores drop sharply relative to plain detection, and improvements in the object detector propagate directly into the graph score. Any honest comparison holds the detector fixed.

Message passing over object proposals

Once proposals exist, relations become a contextual classification problem. A candidate edge between two regions should not be decided from those regions alone; it should be decided from them plus everything else nearby, because a person holding a cup and a person holding a bat look similar in isolation but differ once the surrounding objects are known. Graph neural networks formalize that intuition by repeatedly aggregating neighbor features into each node.

python
import torch
import torch.nn as nn
import torch.nn.functional as F


class EdgeUpdate(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.mlp = nn.Sequential(
            nn.Linear(dim * 3, dim), nn.ReLU(inplace=True),
            nn.Linear(dim, dim),
        )

    def forward(self, h_sub, h_obj, h_union):
        return self.mlp(torch.cat([h_sub, h_obj, h_union], dim=-1))


class GraphReasoner(nn.Module):
    """Two rounds of message passing, then predicate classification."""

    def __init__(self, num_predicates, dim=256, rounds=2):
        super().__init__()
        self.rounds = rounds
        self.edge_update = EdgeUpdate(dim)
        self.node_update = nn.GRUCell(dim, dim)
        self.classifier = nn.Sequential(
            nn.Linear(dim * 3, dim), nn.ReLU(inplace=True),
            nn.Dropout(0.3), nn.Linear(dim, num_predicates),
        )

    def forward(self, nodes, edges, union_feats):
        h = nodes
        e = union_feats
        for _ in range(self.rounds):
            msg = self.edge_update(h[edges[:, 0]], h[edges[:, 1]], e)
            agg = torch.zeros_like(h)
            agg.index_add_(0, edges[:, 1], msg)      # into object nodes
            agg.index_add_(0, edges[:, 0], msg)      # into subject nodes
            h = self.node_update(agg, h)
            e = self.edge_update(h[edges[:, 0]], h[edges[:, 1]], e)
        feats = torch.cat([h[edges[:, 0]], h[edges[:, 1]], e], dim=-1)
        return self.classifier(feats)


model = GraphReasoner(num_predicates=51)
logits = model(object_feats, edge_index, union_feats)
loss = F.cross_entropy(logits, predicate_labels)

Two design details matter in practice. Updating both endpoints keeps subject features informed about their objects, which resolves asymmetric predicates such as above versus below. Recomputing edge features after each round lets a relation change once its context has changed, which is how the model moves from a plausible guess to a considered one.

Dealing with a predicate distribution that refuses to balance

The long tail cannot be wished away with class weights alone. Effective strategies combine three ideas: resampling so rare predicates appear more often during training, focal loss so confidently predicted common predicates stop dominating the gradient, and embedding-based classifiers that share statistical strength between related predicates. Predicate embeddings are particularly useful because they let a model trained on riding transfer some signal to chasing, which share visual structure even when their labels never co-occur.

Thresholding is equally important at inference. Predicting a predicate for every candidate edge fills the graph with noise, and downstream reasoners compound that noise. A learned per-edge confidence threshold, calibrated on validation data, consistently beats accepting a fixed number of edges per subject.

The horse-riding-person problem

Compositional generalization is the property that separates a graph model from a lookup table. If training contains person riding horse but never horse riding person, a model that memorized joint triplet statistics will confidently predict the first and never the second, even though both are visually well defined. Held-out triplet evaluation measures exactly this: split the predicate-object combinations so some appear only at test time.

Two approaches help. Structural decompositions that score subject and object identities separately from the predicate keep the predicate head independent of specific object pairs, which preserves the ability to recombine. Data augmentation that rewires existing graphs — swapping objects between edges while keeping predicates that remain physically plausible — manufactures novel combinations at almost no labeling cost. Neither fully solves the problem, but both measurably close the gap between seen and unseen triplet recall.

From graphs to answers

A generated graph becomes useful the moment something queries it. The example below builds a graph from detections, then answers relational questions by pattern matching over edges rather than by asking a language model to reinterpret pixels.

python
from collections import defaultdict


class SceneGraph:
    def __init__(self):
        self.nodes = {}                      # id -> class name
        self.edges = defaultdict(list)       # subj -> [(pred, obj)]

    def add_object(self, node_id, label, box):
        self.nodes[node_id] = {"label": label, "box": box}

    def add_relation(self, subj, pred, obj):
        self.edges[subj].append((pred, obj))

    def ask(self, subject, predicate):
        out = []
        for sid, rels in self.edges.items():
            if self.nodes[sid]["label"] != subject:
                continue
            for pred, oid in rels:
                if pred == predicate:
                    out.append(self.nodes[oid]["label"])
        return out or ["nothing found"]

    def path(self, start_label, hops):
        frontier = [n for n, v in self.nodes.items()
                    if v["label"] == start_label]
        for pred, direction in hops:
            nxt = []
            for nid in frontier:
                for p, oid in self.edges[nid]:
                    if p == pred:
                        nxt.append(oid)
                for sid, rels in self.edges.items():
                    for p, oid in rels:
                        if oid == nid and p == pred:
                            nxt.append(sid)
            frontier = nxt
        return [self.nodes[n]["label"] for n in frontier]


g = SceneGraph()
g.add_object(0, "person", (40, 60, 120, 300))
g.add_object(1, "cup", (200, 240, 250, 280))
g.add_object(2, "table", (150, 260, 400, 400))
g.add_relation(0, "holding", 1)
g.add_relation(1, "on", 2)

print(g.ask("person", "holding"))       # ['cup']
print(g.path("person", [("holding", 0), ("on", 0)]))  # ['table']

Where generated graphs still fail

Three failure modes account for most production disappointments. Occlusion breaks edge prediction silently: a hand behind a cup still produces a plausible holding edge with high confidence, and nothing in the loss function tells the model that visibility matters. Viewpoint-dependent predicates such as left of are defined in image coordinates, so the same physical scene yields different labels when the camera moves, which quietly poisons any video application that assumes temporal consistency.

Second, graphs inherit every error from the detector. A missed object deletes all of its edges, and no amount of message passing restores them, which means graph quality is bounded below by detector recall in a way that is easy to forget when reading relation papers. Third, annotation is subjective for exactly the predicates people care about: annotators disagree about wearing versus holding in cluttered scenes, and the label noise concentrates in the rare tail classes that the model most needs.

The mitigation is task-specific. For captioning, prune to the five or six most salient edges so a single annotation error cannot rewrite the sentence. For robotic planning, attach a visibility and distance score to each edge and refuse to act on edges whose evidence is thin. For video, add a temporal consistency term that encourages the same relation to persist unless the pixels clearly changed.

This is deliberately symbolic. Hybrid systems that combine symbolic traversal with learned embeddings get the best of both: exact, auditable answers for well-formed queries, and graceful degradation when language becomes vague or the graph is incomplete.

Common Mistakes

Reporting predicate classification accuracy as scene graph generation performance

Fix: State the evaluation setting explicitly and report triplet recall for the image-only setting

Building the relation head on boxes alone and ignoring surrounding context

Fix: Include union-box features and at least one round of message passing over neighboring nodes

Accepting a predicate for every candidate edge

Fix: Calibrate a confidence threshold on validation data so the graph stays sparse enough to reason over

Evaluating only on triplets seen during training

Fix: Hold out object-predicate combinations and report seen versus unseen recall separately

Best Practices

  • Freeze the object detector when comparing relation modules so gains are attributable
  • Report micro and macro predicate accuracy alongside triplet recall to expose tail behaviour
  • Use union-region features, since relations live in the space between boxes rather than inside them
  • Keep graph construction differentiable end to end when compute allows, otherwise pipeline errors dominate
  • Publish the predicate frequency histogram with any graph result so readers can judge imbalance

Interview Questions

Q1: Why is triplet recall the right metric for scene graphs?

A relation prediction is only correct when subject, predicate and object all match. Reporting predicate accuracy alone hides errors in object detection and lets a model look strong while producing unusable graphs.

Q2: What is compositional generalization and how do you test for it?

It is the ability to interpret combinations of known objects and predicates that never appeared together in training. Test it by splitting triplets so some object-predicate pairs are test-only, then measuring recall on that held-out set.

Q3: Why do graph reasoners recompute edge features after message passing?

Because a relation's correct label often depends on what its endpoints learned from their own neighbors. Updating edges after node aggregation lets the classifier see the revised context instead of the original isolated pair.

Q4: How would you use a scene graph for visual question answering?

Parse the question into a small graph pattern, traverse the generated scene graph to bind variables, and read off the answer. Unmatched queries fall back to an end-to-end model, which keeps the symbolic path precise without making it brittle.

Key Takeaways

  • Scene graphs turn detections into statements by adding labeled, directed relations between objects
  • Triplet recall is the honest metric, because object, predicate and object must all be correct
  • Message passing with union-region features is the standard way to inject relational context
  • The predicate long tail demands resampling, focal loss and embedding-based classifiers together
  • Held-out triplet evaluation reveals models that memorize rather than compose
  • Graphs feed captioning and question answering through traversal, which stays auditable
  • Thresholding edges prevents noisy graphs from poisoning every downstream consumer
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Computer Vision Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement