Semantic segmentation (U-Net, FCN)
3.4.14· AI-ML › Convolutional Neural Networks
Overview
Semantic segmentation ek aisa task hai jisme image ke har pixel ko ek category mein classify kiya jaata hai (jaise road, car, person, sky). Object detection se alag — jo sirf bounding boxes draw karta hai — segmentation ek dense prediction map produce karta hai jisme har pixel ko ek label milta hai.
Key difference: Object detection = "coordinates (x, y, w, h) par ek dog hai." Semantic segmentation = "ye 2,347 pixels dog HAIN."

Core Problem: Classification se Dense Prediction tak
Ye mushkil kyun hai? Standard CNNs jaise VGG/ResNet aggressively downsample karte hain (stride-2 convs, pooling) taaki abstract features ban sakein. Final layer tak, ek 224×224 image 7×7 feature maps ban jaati hai. Humne spatial resolution kho di hai — lekin segmentation ko har pixel classify karne ke liye original resolution wapas chahiye!
Fully Convolutional Networks (FCN)
FCN (Long et al., 2015) pehli aisi architecture thi jisne segmentation ko CNNs ke saath end-to-end tackle kiya.
Architecture Breakdown
Step 1: Encoder (Downsampling)
- Ek pretrained classifier backbone se shuru karo (jaise VGG-16)
- End ke FC layers remove karo
- Ab network ek feature map output karta hai, jaise input ke liye
Ye step kyun? Humein rich semantic features chahiye (kaun se objects present hain). Deep layers high-level abstractions capture karte hain, lekin wo spatially coarse hote hain.
Step 2: Class Scores ke liye 1×1 Convolution
- filters (number of classes) ke saath ek conv apply karo
- Output: score map
Kyun? Har spatial location ko ek class prediction vector milta hai. Ye aise hai jaise har location par ek classifier run ho.
Step 3: Upsampling (Transposed Convolution)
- Spatial size badhane ke liye transposed convolution use karo (ise deconvolution bhi kehte hain, lekin wo ek misnomer hai)
- Example: FCN-32s ek baar mein ×32 upsample karta hai:
Derivation: Regular convolution striding se size ghataata hai. Transposed convolution iska ulta karta hai: ye input values ke beech zeros insert karta hai (stride se input ko dilate karta hai), phir regular convolution apply karta hai. Stride ke saath, input effectively times expand ho jaata hai, phir convolve hota hai.
Transposed conv kyun? Ye ek learnable upsampling hai — network seekhta hai ki best tarike se interpolate kaise karna hai, fixed bilinear upsampling ki jagah.
Skip Connection Innovation
FCN-32s (ek-shot ×32 upsampling) bahut coarse hai. FCN-16s aur FCN-8s skip connections add karte hain:
- FCN-16s: ×32 upsampled map ko pool4 ke features (higher resolution) ke saath fuse karo, phir ×16 upsample karo
- FCN-8s: pool3 ke saath bhi fuse karo, ×8 upsample karo
Kaise? Upsampled deep features ka earlier-layer features ke saath element-wise addition (channel counts match karne ke liye 1×1 conv ke baad).
Ye sequence kyun? Gradual refinement: coarse semantics + medium details + fine details.
U-Net: Medical Imaging Champion
U-Net (Ronneberger et al., 2015) biomedical segmentation ke liye design kiya gaya tha (jaise microscopy mein cell nuclei) jahan training data scarce hoti hai.
Architecture Details
Encoder (Contracting Path):
- Baar baar: 3×3 conv → ReLU → 3×3 conv → ReLU → 2×2 max pool (stride 2)
- Har downsampling feature channels double karta hai (64 → 128 → 256 → 512 → 1024)
- Result: progressively smaller spatial size, richer feature representation
Channels double kyun? Jaise spatial info compress hoti hai, abstract patterns encode karne ke liye zyada feature capacity chahiye.
Bottleneck:
- Sabse low resolution (jaise 572×572 input ke liye 28×28 with 1024 channels)
- Highest semantic abstraction
Decoder (Expansive Path):
- Baar baar: 2×2 transposed conv (stride 2, upsamples) → encoder features ke saath concatenate (skip connection) → 3×3 conv → ReLU → 3×3 conv → ReLU
- Har upsampling feature channels halve karta hai (1024 → 512 → 256 → 128 → 64)
- Final 1×1 conv C classes mein map karta hai
Derivation: Channel axis ke along concatenation dono paths se saari information preserve karta hai. Baad ke convolutions inhe fuse karna seekhte hain. Ye FCN ke addition se alag hai, jo information lose kar sakta hai agar features perfectly aligned na hon.
Add ki jagah concatenate kyun? Medical images mein subtle differences hote hain (cell membranes, small structures). Concatenation network ko choose karne deta hai ki kaun se encoder features use karne hain, bajaaye ek linear combination force karne ke.
Decoder:
- Upsample: 56×56×512, encoder 64×64 ko 56×56 par crop karo, concat → 56×56×1024
- Convs ke baad: 52×52×512
- (Repeat: upsample, crop-concat, conv...)
- Final: 388×388×C
Crop kyun? Original U-Net no padding use karta hai (valid convolutions), isliye encoder feature maps thode bade hote hain. Inhe decoder size match karne ke liye center-crop kiya jaata hai.
Ye step kyun matter karta hai: Medical imaging mein, data augmentation (rotation, flip) heavily use hoti hai. No-padding design original paper ki ek khasiyat thi; modern U-Nets padding use karte hain taaki sizes aligned rahein.
U-Net vs. FCN
| Aspect | FCN | U-Net |
|---|---|---|
| Skip connections | Upsampled + encoder ka addition | Har level par concatenation |
| Symmetry | Asymmetric (classifier backbone) | Symmetric encoder-decoder |
| Use case | Natural images (ImageNet-pretrained) | Medical/small datasets (scratch se train) |
| Output size | Input jaisi | Alag ho sakti hai (original U-Net) ya same (modern) |
Semantic Segmentation Models ko Train Karna
Derivation: Har pixel ek independent classification problem hai. Hum saare pixels pe cross-entropy sum karte hain.
U-Net ke liye class imbalance ke saath (jaise cells 5% pixels hain, background 95%), weighted cross-entropy use karo: jahan (inverse frequency weighting).
Kyun? Weighting ke bina, model saara background predict karke 95% accuracy le sakta hai. Weighting use karne se wo rare classes ki bhi parwah karta hai.
Derivation: Dice coefficient overlap measure karta hai: . minimize karna overlap maximize karta hai.
Ise kyun use karein? Dice, IoU (Intersection over Union) ka ek soft version hai — differentiable aur class imbalance ke liye robust.
Evaluation Metrics
mIoU kyun? Ye false positives (jahan nahi hai wahan class predict karna) aur false negatives (class miss karna) dono ko penalize karta hai. Pixel accuracy misleading ho sakti hai agar classes imbalanced hon.
Ye kyun matter karta hai: Bhale hi humne car ke 80% pixels sahi predict kiye, extra false alarms IoU ko 72.7% tak reduce kar dete hain.
Common Mistakes
Worked Example: 128×128 Image par U-Net Segmentation
Setup: 3 classes (background, cell, membrane). Input: 128×128×3 RGB image.
Encoder:
- Conv1: 3×3 conv (64 filters, padding=same) → 128×128×64 → ReLU → 3×3 conv → 128×128×64 → ReLU
- MaxPool: 2×2 stride 2 → 64×64
- Conv2: 3×3 conv (128 filters) → 64×64×128 → ReLU → 3×3 conv → 128×128 (typo: should be 64×64×128) → ReLU
- MaxPool: 2×2 stride 2 → 32×32×128
- Conv3: 3×3 conv (256 filters) → 32×32×256 → ... → 32×32×256
- MaxPool → 16×16×256
- Conv4: 3×3 conv (512 filters) → 16×16×512
- MaxPool → 8×8×512
Bottleneck:
- Conv5: 3×3 conv (1024 filters) → 8×8×1024
Decoder:
- Upsample: 2×2 transposed conv (stride 2) → 16×16×512
- Conv4 output (16×16×512) ke saath Concatenate karo → 16×16×1024
- 3×3 conv (512 filters) → 16×16×512
- Upsample: 2×2 transposed conv → 32×32×256
- Conv3 ke saath Concat karo → 32×32×512
- 3×3 conv (256 filters) → 32×32×256
- Upsample: 2×2 transposed conv → 64×64×128
- Conv2 ke saath Concat karo → 64×64×256
- 3×3 conv (128 filters) → 64×64×128
- Upsample: 2×2 transposed conv → 128×128×64
- Conv1 ke saath Concat karo → 128×128×128
- 3×3 conv (64 filters) → 128×128×64
Output:
- 1×1 conv (3 classes ke liye 3 filters) → 128×128×3 logits
- Softmax → 128×128 class predictions
Har step kyun?
- Downsampling: Context capture karne ke liye compress karo ("yahan ek cell hai")
- Upsampling: Pixel resolution tak wapas expand karo
- Concatenation: "Ye raha cell ka high-res representation (encoder se), ise upsampled semantic info ke saath fuse karo (decoder se)"
Numerical check: Pehle decoder layer mein, hum 8×8→16×16 upsample karte hain. Stride-2 transposed conv ke saath, formula deta hai: . ✓
Modern Extensions
- Atrous/Dilated Convolutions: DeepLab mein use hote hain. Pooling ki jagah, resolution rakhte hue receptive field expand karne ke liye dilated convs use karo.
- Attention U-Net: Relevant regions par focus karne ke liye skip connections mein attention gates add karo.
- SegFormer: Transformer-based encoder with lightweight MLP decoder. Kai benchmarks par state-of-the-art.
Recall Ek 12-Saal Ke Bacche Ko Samjhao
Socho tum ek picture color kar rahe ho, lekin kisi ke banaye lines ke andar rehne ki bajaye, tumhe khud lines draw karni hain. Picture mein har ek dot (pixel) ko ek color chahiye, aur color depend karta hai ki wo dot kis cheez ka hissa hai: Kya wo sky hai? Ek tree? Ek insaan?
Semantic segmentation computer ko yehi karna sikhana hai. Computer ek photo dekhta hai aur har pixel ko color karta hai — jo kuch bhi wo pehchaanta hai. Ek self-driving car iske liye use karti hai taaki dekh sake "ye pixels road ke hain, ye ek pedestrian ke hain, ye ek parked car ke hain."
U-Net ek aisi magnifying glass ki tarah hai jo dono taraf kaam karti hai: Pehle, ye zoom out karti hai (encoder) taaki samjhe "oh, is area mein ek insaan hai." Phir ye wapas zoom in karti hai (decoder) taaki insaan ke har hisse ko carefully trace kare. Clever part? Wapas zoom in karte waqt, ye yaad rakhti hai ki picture pehle kaisi dikhti thi, taaki chhoti details jaise ungliyan ya baal na kho jaayein. Wo memory hi "skip connection" hai — jaise har zoom level par sticky notes chhod dena.
Connections
- Convolutional Layers: U-Net aur FCN poori tarah conv layers (aur transposed conv) se bane hain
- Pooling Layers: Max pooling encoder mein downsample karta hai; transposed conv decoder mein upsample karta hai
- Residual Networks (ResNet): Modern segmentation VGG ki jagah ResNet backbones use karta hai
- Transfer Learning: FCN typically ImageNet-pretrained encoder use karta hai; U-Net aksar scratch se train karta hai
- Data Augmentation: Medical imaging mein U-Net ke liye critical hai (rotation, elastic deformation)
- Batch Normalization: Modern U-Nets stable training ke liye har conv ke baad BN add karte hain
- Loss Functions: Cross-entropy, Dice loss, Focal loss (hard examples ke liye)
- Object Detection: Segmentation pixel-level masks deta hai vs. bounding boxes
- Attention Mechanisms: Attention U-Net relevant features par focus karne ke liye gates use karta hai
#flashcards/ai-ml
Semantic segmentation kya hai? :: Har pixel ko ek semantic category mein classify karne ka task (jaise road, car, person), ek dense prediction map produce karta hai jahan har pixel ko ek class label milta hai.