CNN পুনরাবৃত্তি — DL থেকে
এই পাঠে যা শিখবেন
- CNN-এর তিনটি মূল layer
- Receptive field, parameter sharing
- Hierarchical feature learning
- PyTorch-এ ছোট CNN লেখা
১ · কেন CNN, MLP নয়?
Fully connected MLP — প্রতিটি input pixel প্রতিটি neuron-এর সাথে connected. 224×224×3 ছবিতে প্রথম hidden layer 1000 neuron-এ — 150M parameter. অসম্ভব train.
CNN-এর তিনটি smart constraint:
- Local connectivity: প্রতি neuron শুধু ছোট patch দেখে (3×3, 5×5).
- Weight sharing: একই kernel পুরো ছবিতে slide.
- Translation equivariance: object position বদলালেও feature unchanged.
CNN = "ছবির 2D spatial structure-কে respect করা MLP". Local pattern discover, hierarchical compose, parameter share — এই তিনটি ideas-এ ImageNet-এ revolution.
২ · Conv layer
Conv layer-এ একটি লexpand learnable kernel ছবিতে slide করে। প্রতিটি কাজ:
$$\text{out}[c, x, y] = \sum_{c', i, j} K[c, c', i, j] \cdot \text{in}[c', x+i, y+j] + b[c]$$
- $c$: output channel (filter index).
- $c'$: input channel.
- $(i, j)$: kernel-এর internal coordinate.
Parameter: $C_{\text{in}} \times C_{\text{out}} \times K \times K + C_{\text{out}}$ (bias).
৩ · Pooling layer
Spatial dimension কমায় — feature map-এর উচ্চতা/প্রস্থ অর্ধেক করে।
- Max pool: window-এ সর্বোচ্চ value. Sharp feature preserve.
- Avg pool: গড়। Smooth.
- Global pool: পুরো feature map → এক value per channel. CNN classifier-এর শেষে।
Pooling-এর তিন ভূমিকা:
- Computational reduction: পরের layer-এ কম pixel.
- Translation invariance: ছোট shift-এ output unchanged.
- Receptive field বৃদ্ধি: পরের layer ছবির বড় portion দেখে।
৪ · Activation: ReLU
Conv-এর পরে non-linearity:
$$\text{ReLU}(x) = \max(0, x)$$
ReLU sparse activation — অনেক neuron 0, কিছু active. Sigmoid/tanh-এর চেয়ে gradient stable, training fast.
৫ · Receptive field
একটি deep neuron ছবির কোন region "দেখে" সেটাই receptive field.
- প্রথম 3×3 conv → RF 3.
- আরেকটি 3×3 → RF 5.
- 2×2 max pool (stride 2) → RF doubled.
- VGG-16-এর শেষ conv layer → RF প্রায় 200.
Sufficient RF — object recognize করতে পুরো object দেখা চাই।
৬ · Hierarchical feature
CNN-এর প্রতিটি layer ভিন্ন abstraction level-এ feature শেখে। Zeiler & Fergus (২০১৪) visualization:
- Layer 1: oriented edges, color blobs (Gabor-like).
- Layer 2: corners, junctions, texture patches.
- Layer 3: textures, simple object parts (wheel, eye).
- Layer 4-5: object parts, dog face, car shape.
- Layer 6+ (FC): whole object, scene category.
৭ · PyTorch-এ ছোট CNN
import torch
import torch.nn as nn
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(64, 128, 3, padding=1),nn.ReLU(), nn.MaxPool2d(2),
)
self.classifier = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Flatten(),
nn.Linear(128, num_classes),
)
def forward(self, x):
return self.classifier(self.features(x))
# 32×32 input batch
model = SmallCNN(10)
x = torch.randn(8, 3, 32, 32)
y = model(x)
print("Output:", y.shape) # (8, 10)
# Parameter count
n_params = sum(p.numel() for p in model.parameters())
print(f"Total parameters: {n_params:,}")
৮ · Translation equivariance vs invariance
- Equivariance: input shift হলে output same shift. Conv layer এই প্রপার্টি দেয়।
- Invariance: input shift-এ output unchanged. Pooling + final FC মিলে এই achieve.
Detection-এ equivariance চাই (where object), classification-এ invariance চাই (what object).
৯ · CNN-এর সীমাবদ্ধতা
- Rotation: CNN rotation-invariant না। Augmentation দিয়ে শেখানো হয়।
- Scale: partial — pyramid বা multi-scale চাই।
- Long-range dependency: deep stacks দরকার — Transformer-এ better.
- Reasoning: "এই কুকুর ঐ মানুষের সাথে দৌড়াচ্ছে" — pure CNN পারে না।
ভাবনার প্রশ্ন
প্র ০১ CNN-এ Conv-Pool-Conv-Pool pattern — পুরো ছবিকে কয়েক step-এ ছোট করে। এই "downsampling" কেন না বাঁচিয়ে আরো aggressive করি না?
এটি architecture design-এর মৌলিক trade-off. Spatial resolution vs feature abstraction.
কেন downsampling:
- Compute: পরের layer-এ কম pixel — fast.
- Receptive field: downsample হলে effective RF বড় হয়।
- Memory: activation tensor ছোট — GPU-তে fit.
- Invariance: ছোট shift-এ output unchanged.
কেন aggressive downsample বিপজ্জনক:
- Detail loss: small object আগেই হারায়।
- Localization: detection/segmentation-এ পিক্সেল-precision চাই।
- Information bottleneck: শুরুতেই compress — recovery অসম্ভব।
Empirical sweet spot:
- ৫ stage সাধারণ — 224 → 7×7 (32x reduction).
- প্রতি stage 2x downsample.
- VGG, ResNet, EfficientNet — সবাই follow.
Detection/segmentation-এ ভিন্ন:
- FPN (Feature Pyramid): multi-scale feature combine.
- U-Net: encoder downsample, decoder upsample, skip connection.
- HRNet: all stage-এ high resolution maintain.
- DeepLab: dilated convolution — RF বাড়ায় without downsample.
Aggressive alternative:
- Patch embedding (ViT) — শুরুতেই 16x downsample.
- Convnext — 4x downsample stem.
- Trade-off — image-level task-এ OK, dense task-এ struggle.
Stride choice:
- Stride 2 conv = pool replacement. Modern arch (ResNet) এটি choose.
- Pool deterministic, conv learnable — trade-off.
মূল উপলব্ধি: Architecture = task-dependent design choice. Classification-এ aggressive downsample OK, dense prediction-এ careful.
প্র ০২ 1×1 convolution — pixel-এ pixel একই থাকে, kernel size 1. এটা কী কাজ করে? পুরোপুরি অপ্রয়োজনীয় মনে হয় কিন্তু GoogLeNet, ResNet সর্বত্র ব্যবহার!
1×1 conv — first impression-এ unnecessary, কিন্তু modern CNN-এর secret weapon. Network-in-Network (Lin et al., 2013) introduce করেন।
1×1 conv আসলে কী করে?
- Spatial dimension touch করে না — শুধু channel mix করে।
- Per-pixel-এ একটি linear transformation across channels.
- Effectively — 1×1 spatial × $C_{\text{in}} \to C_{\text{out}}$ matrix multiply.
কাজ ১ — Channel reduction (bottleneck):
- 256 channels → 64 channels (1×1 conv) → 256 channels.
- Computation 16x কম (256² vs 256·64+64²+64·256).
- ResNet bottleneck design.
কাজ ২ — Non-linearity injection:
- 1×1 conv + ReLU = per-pixel MLP.
- Network-in-Network: spatial conv-এর সাথে non-linear feature mix.
কাজ ৩ — Cross-channel feature integration:
- Different channel-এর pattern combine করে নতুন composite feature.
- 3×3 conv — spatial; 1×1 conv — channel.
কাজ ৪ — Inception block-এ:
- 3×3 ও 5×5 conv-এর আগে dimensionality reduce.
- না হলে — 5×5 conv 256→256 channels = 1.6M parameters.
- 1×1 64→256 + 5×5 64→64 = অনেক কম।
কাজ ৫ — Pointwise mixing (MobileNet):
- Depthwise conv (per-channel spatial) + pointwise (1×1 cross-channel).
- Standard conv-এর চেয়ে 8-9x cheap.
- Mobile-friendly architecture-এর key.
কাজ ৬ — Output projection:
- Segmentation network-এর শেষ — feature map → class logits.
- 1×1 conv = "final classifier per pixel".
Mathematical equivalence:
- 1×1 conv across channels = matrix multiply.
- Per-pixel fully connected layer.
- Just FC, but applied at every spatial location with weight sharing.
মূল উপলব্ধি: "1×1 conv trivial মনে হয়" — actually CNN modular architecture-এর key building block. ResNet, GoogLeNet, MobileNet — সব এতে দাঁড়িয়ে।
প্র ০৩ Batch normalization কী করে এবং কেন এত effective? যদি not BN, কী complications?
BN (Ioffe & Szegedy, 2015) — modern DL-এর সবচেয়ে impactful contribution-এর একটি।
BN-এর সূত্র:
$$\hat{x} = \frac{x - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}, \quad y = \gamma \hat{x} + \beta$$
- $\mu_B, \sigma_B$ — batch-এর mean, std (per channel).
- $\gamma, \beta$ — learnable parameter (scale, shift).
- Inference-এ — training-এর running statistics use.
কেন কাজ করে — original claim:
- "Internal covariate shift" reduction — layer-এ input distribution stable.
- Training fast, higher learning rate possible.
আধুনিক understanding:
- Santurkar et al. (2018) — covariate shift theory wrong.
- আসল কাজ: loss landscape smooth — gradient stable.
- Lipschitz constant ছোট — large step safe.
Practical benefits:
- Training fast: 10x larger learning rate.
- Less sensitive to init: Xavier/He init optional.
- Regularization: small noise — dropout-এর মতো।
- Deeper networks: 100+ layer train possible.
BN ছাড়া complication:
- Vanishing/exploding gradient.
- Careful learning rate tuning.
- Activation scale layer-ভেদে drift.
- Deep network train অসম্ভব।
BN-এর সমস্যা:
- Small batch (1-8): statistics noisy. Detection-এ অপ্রিয়।
- Variable batch size inference: running stats inaccurate.
- Sequential data (RNN, Transformer): batch dimension awkward.
Alternatives:
- LayerNorm: Transformer default — feature-wise normalize.
- GroupNorm: Wu & He (2018) — channel-grouped. Detection-এ standard.
- InstanceNorm: per-image normalize — style transfer-এ।
- WeightNorm: weight reparameterize.
BN ও CNN-এর marriage:
- ResNet-এ BN essential — without BN deep ResNet train hard.
- EfficientNet, ConvNeXt — BN/GN/LN-এর combination.
- Modern conv block: Conv → BN → ReLU.
মূল উপলব্ধি: BN modern DL-এর "invisible" foundation. Without it — deep network training a struggle.
প্র ০৪ Vision Transformer (ViT) attention-based, CNN convolution-based. এদের মধ্যে কোনটা future, নাকি hybrid?
এটি ২০২৩-পরবর্তী CV community-র প্রধান বিতর্ক। Verdict — hybrid winning.
CNN-এর strength:
- Inductive bias: locality + translation equivariance — natural image-এ অভিজ্ঞতা।
- Data efficiency: ছোট dataset-এও কাজ করে।
- Hardware optimized: conv kernel CUDA-এ extremely fast.
- Hierarchical: multi-scale natural.
ViT-এর strength:
- Long-range attention: ছবির এক প্রান্ত থেকে অন্য প্রান্ত direct connection.
- Scale: বড় data-এ CNN-কে ছাড়িয়ে যায়।
- Universal: NLP-র সাথে architecture share — multimodal সহজ।
- Less inductive bias: data থেকেই pattern শিখে।
Crossover findings:
- ViT — ১M+ images চাই; ImageNet-এ scratch থেকে CNN champion.
- JFT-300M (Google internal) — ViT ResNet ছাড়িয়ে যায়।
- ConvNeXt (2022) — modern training tricks দিয়ে CNN ViT-কে match করে।
Hybrid architectures:
- Swin Transformer: local attention windows — CNN-like locality.
- CoAtNet: conv + attention combined.
- MobileViT: mobile-friendly hybrid.
- EfficientFormer: CNN early, attention late.
Task-specific:
- Image classification: ConvNeXt, MaxViT competitive.
- Detection: DETR (transformer) — mainstream YOLO (CNN) থেকে accuracy ভাল কিন্তু slow.
- Segmentation: Mask2Former, SAM — transformer dominant.
- Generation: Diffusion U-Net (CNN) → DiT (transformer) — transition হচ্ছে।
Compute trade-off:
- ViT-Large: 300M params, 60 GFLOPs.
- ResNet-152: 60M params, 11 GFLOPs.
- 5x cheaper, often comparable accuracy with proper tricks.
Bangladesh context:
- Limited GPU access — CNN preferred.
- Mobile deployment — MobileNet/EfficientNet champion.
- Small dataset (Bangla-specific) — CNN train possible.
Future prediction:
- 2030-এ — pure CNN বা pure ViT rare হবে।
- Hybrid + foundation model finetune dominant.
- Conv → patch attention → conv hybrid common.
মূল উপলব্ধি: Architecture wars-এ "winner" ভুল frame. Tool-এর diversity grow করছে — engineer-এর fluency in both essential.
অনুশীলন
-
Param count: একটি conv layer 3×3, in_channels=64, out_channels=128 — মোট parameter (bias সহ)?
$3 \times 3 \times 64 \times 128 + 128 = 73{,}856$।
-
Receptive field: পরপর তিনটি 3×3 conv (stride 1) — receptive field কত?
RF = $3 + (3-1) + (3-1) = 7$। তিনটি 3×3 conv ≈ একটি 7×7 conv-এর RF — কিন্তু parameter অনেক কম।
-
ভাবুন: Pooling-এর বদলে stride-2 conv কেন modern arch-এ বেশি use হচ্ছে?
Stride-2 conv learnable — pool fixed. Conv-এ network নিজে decide করতে পারে কোন detail বাদ দেবে। Empirically — slightly better accuracy.
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ১০ · LeNet — প্রথম CNN পরবর্তী পাঠ CNN-এর জন্ম — LeCun ১৯৯৮।
- পাঠ ০৮ · Image augmentation আগের পাঠ Module 1-এর শেষ।
- পাঠ ১৪ · ResNet এগিয়ে Modern CNN-এর backbone.
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।