Semantic segmentation
Quick answer
Semantic segmentation assigns a class to every pixel, rather than a single label to an image. A model commonly returns class logits with shape N,C,H,W; the target has integer class IDs with shape N,H,W. Examples are static Python snippets tested locally on CPU; Torchvision is required for selected examples. ByteMind execution is unverified.
Per-class mask overlap
from fractions import Fractiony=[1,1,0,255]; p=[1,0,1,1]tp=sum(a==b==1 for a,b in zip(y,p) if a!=255)fp=sum(a!=1 and b==1 for a,b in zip(y,p) if a!=255)fn=sum(a==1 and b!=1 for a,b in zip(y,p) if a!=255)print(Fraction(tp,tp+fp+fn),Fraction(2*tp,2*tp+fp+fn))Expected output (locally tested): 1/3 1/2. Ignored pixel is excluded from all counts.
How it works
For mutually exclusive classes use cross-entropy over channels; argmax over C gives the predicted class map. Do not apply softmax before PyTorch CrossEntropyLoss. Compute per-class intersection and union from prediction and target masks, ignoring pixels explicitly marked void (e.g., 255). IoU=TP/(TP+FP+FN); Dice=2TP/(2TP+FP+FN). Pool counts across images before division for dataset-level class IoU. Macro mIoU averages defined class IoUs equally; report whether background is included and exclude zero-union classes under this teaching policy. Pixel accuracy can be dominated by background. Resize categorical masks with nearest-neighbor interpolation; image interpolation can use bilinear. Joint geometric augmentation must preserve alignment.
Pixel classification from logits
import torchlogits=torch.tensor([[[[3.,0.]],[[0.,3.]]]])y=torch.tensor([[[0,1]]])print(logits.argmax(dim=1).tolist())print(round(torch.nn.functional.cross_entropy(logits,y).item(),6))Expected output (locally tested): [[[0, 1]]] 0.048587. Argmax uses the class axis; cross-entropy consumes raw logits.
Common mistakes
Do not bilinearly interpolate integer labels or treat ignored pixels as background. Avoid averaging per-image IoUs while describing pooled dataset IoU. Empty union is not automatically perfect.
Practice and next steps
Compute IoU and Dice for one false positive and one false negative. Check that ignored pixels do not contribute to the confusion counts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Semantic segmentation — knowledge check
Apply semantic segmentation to small examples and debugging scenarios.
For N,C,H,W logits, argmax along which axis?
What interpolation preserves integer mask classes?
IoU with TP=2, FP=1,FN=1?
What is a zero-union class under this policy?
Why can pixel accuracy mislead?