পাঠ ২০ · ৪০-এর মধ্যে · মডিউল ৩

LeNet ও AlexNet

LeNet (1998) and AlexNet (2012) — CNN milestones
৭ মিনিট পড়া মাঝারি · Intermediate PyTorch hands-on

এই পাঠে যা শিখবেন

  • LeNet-5-এর architecture — postal digit থেকে modern OCR
  • AlexNet-এর breakthrough — কী ছিল নতুন
  • ReLU, dropout, data augmentation — কেন একসাথে কাজ করল
  • GPU training-এর গুরুত্ব
  • PyTorch-এ দু'টো architecture implement

১ · LeNet-5 — CNN-এর জন্ম (১৯৯৮)

Yann LeCun ও সহকর্মীরা AT&T Bell Labs-এ — handwritten ZIP code recognition। US Postal Service-এর তখনকার একটি বড় সমস্যা — letter sort করা।

LeNet-5 architecture

Input $32 \times 32$ grayscale → C1 (6@28×28) → S2 (6@14×14) → C3 (16@10×10) → S4 (16@5×5) → C5 (120) → F6 (84) → Output (10)।
Conv kernel: $5 \times 5$, Pool: $2 \times 2$ avg, Activation: tanh/sigmoid।

প্রভাব: ১৯৯০-এর দশকে বহু US ব্যাংকে check digit recognition-এ ব্যবহৃত। ~৬০K parameter — আজকের তুলনায় টিনি, কিন্তু সেই সময়ে বিপ্লবী।

LeNet ছিল সমুদ্রের পানিতে প্রথম পা — শাসিত depth, চেনা water। AlexNet — surfboard নিয়ে বিশাল ঢেউয়ে ঝাঁপ। দু'টো একই সমুদ্র, ১৪ বছরের ব্যবধান, কিন্তু resource ও courage সম্পূর্ণ ভিন্ন স্তরের।

২ · LeNet-5 — PyTorch implementation

Python · PyTorch
import torch.nn as nn

class LeNet5(nn.Module):
    def __init__(self, num_classes=10):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 6, kernel_size=5),     # 32 -> 28
            nn.Tanh(),
            nn.AvgPool2d(2),                     # 28 -> 14
            nn.Conv2d(6, 16, kernel_size=5),     # 14 -> 10
            nn.Tanh(),
            nn.AvgPool2d(2),                     # 10 -> 5
        )
        self.classifier = nn.Sequential(
            nn.Flatten(),
            nn.Linear(16 * 5 * 5, 120),
            nn.Tanh(),
            nn.Linear(120, 84),
            nn.Tanh(),
            nn.Linear(84, num_classes),
        )
    def forward(self, x):
        return self.classifier(self.features(x))

model = LeNet5()
total = sum(p.numel() for p in model.parameters())
print(f"LeNet-5 parameters: {total:,}")
# ~61,706 — modern CNN-এর তুলনায় টিনি

    

৩ · মাঝখানের ১৪ বছর — কী ঘটল না

১৯৯৮ থেকে ২০১২ — CNN নিয়ে গবেষণা চলত, কিন্তু সাধারণভাবে SVM, Random Forest, kernel methods জনপ্রিয়। কারণ:

  • Compute সীমিত — large network train অসম্ভব ছিল।
  • Data কম — ImageNet (২০০৯) আগে large labeled dataset বিরল।
  • Vanishing gradient — sigmoid/tanh deep network-এ ভালো train না।
  • Bias-variance theory — kernel methods বেশি principled মনে হত।

৪ · AlexNet — DL-এর "Big Bang" (২০১২)

Alex Krizhevsky, Ilya Sutskever, Geoffrey Hinton — University of Toronto। ImageNet ILSVRC-2012 challenge-এ — top-5 error ১৬.৪% (আগের best ২৬%)। ১০% improvement — DL revolution শুরু।

AlexNet architecture

Input $227 \times 227 \times 3$ → 5 conv layer + 3 FC layer → 1000 class softmax।
~৬০M parameter, ৬৫০K neuron। Two GPU split (memory limit)।

Layer breakdown:

  • Conv1: 96 filter, $11 \times 11$, stride 4 → $55 \times 55 \times 96$
  • MaxPool1: $3 \times 3$, stride 2 → $27 \times 27 \times 96$
  • Conv2: 256 filter, $5 \times 5$, padding 2 → $27 \times 27 \times 256$
  • MaxPool2: $3 \times 3$, stride 2 → $13 \times 13 \times 256$
  • Conv3-5: 384, 384, 256 filter, $3 \times 3$
  • FC6, FC7: 4096 → 4096
  • FC8: 1000 (ImageNet classes)

৫ · AlexNet-এর key innovations

  1. ReLU activation: sigmoid/tanh-এর বদলে — gradient saturate করে না, ৬x faster train।
  2. GPU training: দু'টো GTX 580 (3GB each) — model parallel split।
  3. Dropout (0.5): FC layer-এ — overfitting কমাতে।
  4. Data augmentation: random crop, horizontal flip, PCA color shift।
  5. Local Response Normalization: (পরে BN replace করেছে)।
  6. Overlapping pooling: $3 \times 3$, stride 2 — slight overlap।
LeNet-5 (১৯৯৮) vs AlexNet (২০১২) Architecture, scale, এবং era LeNet-5 ~60K params · MNIST · Tanh Conv 5×5, 6 filters AvgPool 2×2 Conv 5×5, 16 filters AvgPool 2×2 FC 120 → FC 84 Output: 10 digits AlexNet ~60M params · ImageNet · ReLU + Dropout + GPU Conv 11×11/4, 96 MaxPool 3×3/2 Conv 5×5, 256 MaxPool 3×3/2 3 × Conv 3×3 (384,384,256) FC 4096 → 4096 (Dropout) Output: 1000 classes একই pattern (Conv-Pool stack + FC) — কিন্তু scale, activation, regularization সম্পূর্ণ ভিন্ন। LeNet-5: USPS digit recognition, CPU train। AlexNet: ImageNet, 6 days দু'টি GPU। ~১,০০০ গুণ বেশি parameter, ~১,০০০ গুণ বেশি data, ~১০x DL revolution।
LeNet-5 (১৯৯৮) ও AlexNet (২০১২) — একই blueprint, ভিন্ন era।

৬ · AlexNet — PyTorch (simplified)

Python · PyTorch
import torch.nn as nn

class AlexNet(nn.Module):
    def __init__(self, num_classes=1000):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 96, 11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(3, stride=2),
            nn.Conv2d(96, 256, 5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(3, stride=2),
            nn.Conv2d(256, 384, 3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 384, 3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, 3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(3, stride=2),
        )
        self.classifier = nn.Sequential(
            nn.Flatten(),
            nn.Dropout(0.5),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes),
        )
    def forward(self, x):
        return self.classifier(self.features(x))

# torchvision থেকে pretrained ও ব্যবহার করা যায়:
# import torchvision.models as models
# alexnet = models.alexnet(weights='IMAGENET1K_V1')

    

৭ · AlexNet-এর historical impact

  • ২০১২: AlexNet — ImageNet winner, error ১৬%।
  • ২০১৩: ZFNet — AlexNet refine।
  • ২০১৪: VGG, GoogLeNet — depth ও sparsity।
  • ২০১৫: ResNet — error ৩.৫৭%, human-level pass।
  • আজ: ConvNet, Transformer, hybrid — সব AlexNet-এর descendant।
Hinton-এর famous quote: "এই network training করার জন্য আমাদের ৬ দিন লাগল দু'টি GPU-তে। আজ একই network ৬ মিনিটে train হবে।" — DL revolution-এর pace।

৮ · ReLU — কেন এত গুরুত্বপূর্ণ ছিল

Sigmoid: $\sigma(x) = \frac{1}{1 + e^{-x}}$, derivative $\sigma'(x) \leq 0.25$। Deep network-এ chain rule — gradient $\to 0$ (vanishing)।

ReLU: $f(x) = \max(0, x)$, derivative = $1$ if $x > 0$ else $0$। Gradient flow unimpeded। Deep network train possible।

৯ · Modern descendants

  • VGG: AlexNet-এর uniformity — শুধু $3 \times 3$ conv।
  • ResNet: skip connection — depth scale।
  • Inception: branching — multi-scale parallel।
  • EfficientNet: depth, width, resolution scale।
  • ConvNeXt: modern CNN — Transformer-এর সাথে competitive।
AlexNet আজ production-এ ব্যবহার হয় না। কিন্তু architectural pattern (conv stack → FC → softmax) — আজকের সব CNN-এর foundation। History-র এই landmark বুঝা — modern network-এর "কেন" বুঝার চাবি।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ "AlexNet একদম নতুন idea ছিল না — সব pieces আগেই ছিল। তবে কী combine effort revolution হলো?" — এই perspective কী?

AlexNet — invention নয়, integration। প্রতিটি component আগে ছিল, কিন্তু একসাথে বাঁধা — সেটাই revolution।

প্রতিটি component-এর pre-history:

  • CNN: LeCun ১৯৮৯-৯৮।
  • ReLU: Nair-Hinton (২০১০) — paper-এ ব্যবহৃত।
  • Dropout: Hinton (২০১২ NIPS workshop) — সরাসরি AlexNet paper-এর সাথে।
  • GPU CNN: Cireşan et al. (২০১১) — earlier MNIST।
  • Data augmentation: classical — vision community-এ widely used।

Synergy যা revolutionary করল:

  • ReLU + deep: vanishing gradient solve, depth practical।
  • GPU + parallel: training time কয়েক মাস → ১ সপ্তাহ।
  • Dropout + scale: overfitting control, large network train।
  • ImageNet + scale: large data CNN need।

"Right time, right place":

  • ২০১০: GPU consumer-friendly।
  • ২০০৯: ImageNet release।
  • ২০১১: ReLU paper।
  • ২০১২: পুরো ecosystem ready।

Lesson for innovators:

  • Pure invention rare।
  • Combination ideas powerful।
  • Right timing critical।
  • Engineering effort matter।

Counter-perspective:

  • "Mere combination" understate?
  • Each piece adapted carefully।
  • Hyperparameter tuning extensive।
  • Implementation risk-taking।

Modern parallels:

  • Transformer (২০১৭) — attention আগেই ছিল, scale + Adam + token embedding একসাথে।
  • GPT-3 — Transformer + massive data + compute।
  • ChatGPT — GPT + RLHF + fine-tuning।

What this means:

  • Watch convergence — multiple ideas mature।
  • Engineering matters for breakthrough।
  • Compute ভাল idea unlock।
  • Data scale game-changer।

Bangladesh context:

  • Local idea + global tools — innovation।
  • Bangla NLP — pre-trained model + local data।
  • Agriculture AI — drone + standard CNN।
  • Composition than invention।

Hinton-এর role:

  • Long-term DL believer।
  • Patient research strategy।
  • Right student-collaborator।
  • Persistence pay off।

মূল উপলব্ধি: Innovation more often integration than pure invention। AlexNet — combine ReLU, GPU, Dropout, augmentation, ImageNet। Each piece pre-existed, integration revolution। Bangladesh-এ — local problem + global tools = original solution। Engineering excellence + timing — research success-এর recipe।

প্র ০২ "১৯৯৮ থেকে ২০১২ — DL ১৪ বছর ঘুমিয়ে ছিল?" — এই ধারণা সত্য? CNN research সেই সময়ে কী ঘটছিল?

"AI Winter" narrative অতিরঞ্জিত। CNN research চলছিল, কিন্তু mainstream-এর বাইরে।

১৯৯৮-২০১২ research highlights:

  • ২০০৩: Behnke — neural abstraction pyramid।
  • ২০০৬: Hinton DBN (Deep Belief Network) — pre-training দিয়ে deep network।
  • ২০০৭: Bengio — deep autoencoder।
  • ২০১০: Cireşan — GPU CNN MNIST।
  • ২০১১: Cireşan — German traffic sign superhuman।

Why it was "quiet":

  • SVM/kernel methods — rigorous theory।
  • Conference review — neural net "old"।
  • Compute cost prohibitive।
  • Data scarcity small benchmark।

SVM golden age (২০০০-২০১০):

  • Kernel methods theoretical elegance।
  • Convex optimization — guaranteed solution।
  • SIFT + Bag of Words + SVM — vision standard।
  • Random Forest — strong baseline।

The believers:

  • Hinton, LeCun, Bengio — "Canadian Mafia"।
  • Schmidhuber — LSTM (১৯৯৭)।
  • Long-term commitment pay off।
  • Patient capital essential।

What enabled the revolution:

  • GPU compute: NVIDIA CUDA (২০০৭)।
  • ImageNet (২০০৯): Fei-Fei Li 1M labeled images।
  • Theoretical: better optimizer, regularization।
  • Software: Theano, Caffe।

The tipping point:

  • ২০১২ AlexNet — undeniable proof।
  • Industry attention sudden।
  • Funding flow।
  • Research focus shift।

Hindsight bias:

  • "Obviously DL would win" — post-hoc।
  • ২০১১-এ majority bet against।
  • Cireşan-এর work largely ignored।
  • Persistence rare commodity।

Lessons:

  • "Out of fashion" research valuable।
  • Critical mass moment unpredictable।
  • Compute progress shape feasibility।
  • Data scale game-changer।

What's "asleep" now?

  • Symbolic AI / logic systems।
  • Capsule networks।
  • Spiking neural networks।
  • Some architecture variants।

Could have been earlier:

  • If GPU adopted earlier — possibly ২০০৮।
  • If ImageNet earlier — ২০০৬ possible।
  • Single bottleneck shift — timing change।

Bangladesh tech parallel:

  • Currently "AI winter" — early stage।
  • Early adopters reaping benefit।
  • Long-term commitment essential।
  • Patience + persistence + compute access।

মূল উপলব্ধি: "AI Winter" narrative simplistic। Research চলছিল, mainstream attention লেগেছিল না। Compute + data + persistence — DL revolution। Bangladesh-এ — patient capital + early commitment + global tool adoption = local breakthrough। History-র lesson — out-of-fashion field-এও opportunity।

প্র ০৩ আজকের era-তে LeNet বা AlexNet train করা trivial। তবু এই historical model বুঝা DL student-এর জন্য গুরুত্বপূর্ণ — কেন?

Modern DL practitioner — কেন LeNet/AlexNet পড়বেন? Multiple reasons—pedagogical, historical, methodological।

Pedagogical value:

  • Simple architecture: Conv-Pool-FC pattern স্পষ্ট।
  • Tractable size: entire network manually trace।
  • Clean ideas: minimal complications।
  • Foundation building: modern architecture understanding।

Historical context:

  • "Why 3x3 conv standard?" — VGG history।
  • "Why ReLU?" — AlexNet decision।
  • "Why batch normalization?" — training instability।
  • Each improvement specific problem solve।

Methodological lessons:

  • Empirical approach — try, measure, iterate।
  • Engineering matters — implementation detail।
  • Compute drives design।
  • Data scale matters।

What modern practitioners miss:

  • Stand on shoulders ignored।
  • Why decision made forgotten।
  • Hyperparameters magic numbers।
  • Architecture choices arbitrary।

What you learn from training LeNet:

  • End-to-end pipeline।
  • Forward + backward verification।
  • Activation function impact।
  • Pooling effect।

Practical exercise:

  • Train LeNet MNIST — 99% achievable।
  • Modify activation: tanh → ReLU → see effect।
  • Add BN — convergence speed measure।
  • Add dropout — generalization test।

Pre-trained AlexNet:

import torchvision.models as models
alexnet = models.alexnet(weights='IMAGENET1K_V1')
# 60M params, 1000 ImageNet classes
# Transfer learning starting point

Modern relevance:

  • Transfer learning baseline।
  • Edge device deployment (small)।
  • Benchmarking — sanity check।
  • Educational standard।

Skills developed:

  • Architecture design।
  • Hyperparameter tuning।
  • Training dynamics — empirical observation।
  • Debugging skill।

Modern equivalents:

  • LeNet → MobileNet / EfficientNet small।
  • AlexNet → ResNet / EfficientNet medium।
  • Architecture progression understanding।

What NOT to do:

  • Use AlexNet production (replaced)।
  • Skip training experiment (limit understanding)।
  • Memorize architecture (understand logic)।
  • Ignore failure modes।

Bangladesh educational value:

  • Resource-constrained — small model train।
  • Local dataset experiment।
  • Bangla MNIST equivalent — Ekush, BanglaLekha।
  • Hands-on confidence building।

Career trajectory:

  • Foundation strong → modern architecture understand।
  • Research direction inform।
  • Production debugging easier।
  • Cross-architecture insights।

মূল উপলব্ধি: Historical CNN — student-এর foundational textbook। Architecture clarity, methodology lesson, debugging skill। Modern model massive কিন্তু principle same। Bangladesh-এ — local dataset + classical architecture practical learning। "Stand on shoulders" — past understand করেই future build। DL pedagogy-র backbone।

প্র ০৪ Bangladesh-এ Bangla handwritten digit recognition (Ekush dataset) — LeNet-style model train করতে কী strategy অনুসরণ করবেন?

Practical Bangladesh project — Bangla digit recognition। LeNet-style CNN ভাল starting point।

Dataset selection:

  • Ekush: 0-9 Bangla, ~30K samples।
  • BanglaLekha-Isolated: 50 character classes।
  • NumtaDB: 85K Bangla digit।
  • CMATERdb 3.1.1: 6K+ digit।

Bangla digit unique challenges:

  • Visually similar: ০, ৫ confuse।
  • Curvature complex: ৩, ৬।
  • Writing style variation high।
  • 10 classes (০-৯)।

Architecture - Bangla LeNet:

class BanglaLeNet(nn.Module):
    def __init__(self, num_classes=10):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 32, 5, padding=2),
            nn.BatchNorm2d(32),  # not in original
            nn.ReLU(inplace=True),  # not tanh
            nn.MaxPool2d(2),

            nn.Conv2d(32, 64, 5, padding=2),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2),

            nn.Conv2d(64, 128, 3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(inplace=True),
            nn.AdaptiveAvgPool2d(1),
        )
        self.classifier = nn.Sequential(
            nn.Flatten(),
            nn.Dropout(0.3),
            nn.Linear(128, 64),
            nn.ReLU(inplace=True),
            nn.Linear(64, num_classes),
        )

Modernizations:

  • BatchNorm — training stability।
  • ReLU — vanishing gradient avoid।
  • GAP — parameter কম।
  • Dropout — overfitting।

Training pipeline:

transform = transforms.Compose([
    transforms.Resize((32, 32)),
    transforms.RandomRotation(15),
    transforms.RandomAffine(0,
        translate=(0.1, 0.1)),
    transforms.ColorJitter(0.3),
    transforms.ToTensor(),
    transforms.Normalize((0.5,), (0.5,)),
])

# Loss + optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(
    model.parameters(),
    lr=1e-3,
    weight_decay=1e-4,
)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
    optimizer, T_max=50
)

Augmentation strategy:

  • Rotation: ±15°।
  • Translation: 10%।
  • Color jitter: brightness, contrast।
  • Random erasing: noise robustness।

Ensemble approach:

  • Multiple seeds train।
  • Test-time augmentation।
  • Vote/average prediction।
  • ~99.5% achievable।

Common mistakes Bangla:

  • Imbalanced class — some digit rare।
  • Font variation underrepresented।
  • Background noise — paper texture।
  • Skew not corrected।

Evaluation strategy:

  • Stratified k-fold।
  • Confusion matrix — common error pair।
  • Per-class accuracy।
  • Real-world test (handwritten samples)।

Comparison baseline:

  • Plain LeNet — 95%।
  • LeNet + BN + Dropout — 97%।
  • Modern CNN (ResNet-18) — 99%।
  • Ensemble — 99.5%।

Deployment:

  • Mobile app — quantized model।
  • OCR pipeline integration।
  • Real-time digit detection।
  • Bangla form processing।

Use cases:

  • Bank check Bangla amount।
  • Government form digitize।
  • Educational app — handwriting practice।
  • NID number recognize।

Extension to multi-digit:

  • Sliding window detect।
  • Connectionist Temporal Classification।
  • CRNN architecture।
  • Sequence prediction।

Bangla character recognition (full):

  • ~50 base character + conjunct।
  • Modifier vowel।
  • Hierarchical recognition।
  • BanglaLekha 50 class — strong starting।

মূল উপলব্ধি: Bangla digit recognition — practical Bangladesh project। LeNet-style modernized — strong baseline। Augmentation + BN + dropout — accuracy boost। Ensemble + TTA — production quality। Local dataset (Ekush, NumtaDB) accessible। Mobile deployment — quantization। Bangla OCR pipeline — multiple Bangladesh use case। Classical CNN today's relevant tool।

অনুশীলন

  1. Parameter count: AlexNet-এর FC6 ($256 \times 6 \times 6 \to 4096$) — কত weight + bias?

    Weight: $9216 \times 4096 = 37{,}748{,}736$। Bias: $4096$। Total: ~$3.78 \times 10^7$. AlexNet-এর সবচেয়ে বড় layer।

  2. Modernize LeNet: LeNet-5-এর tanh — ReLU দিয়ে replace করুন এবং BN যোগ করুন।
    class LeNetModern(nn.Module):
        def __init__(self, n=10):
            super().__init__()
            self.features = nn.Sequential(
                nn.Conv2d(1, 6, 5),
                nn.BatchNorm2d(6),
                nn.ReLU(inplace=True),
                nn.MaxPool2d(2),
                nn.Conv2d(6, 16, 5),
                nn.BatchNorm2d(16),
                nn.ReLU(inplace=True),
                nn.MaxPool2d(2),
            )
            self.head = nn.Sequential(
                nn.Flatten(),
                nn.Linear(16*5*5, 120), nn.ReLU(),
                nn.Linear(120, 84),     nn.ReLU(),
                nn.Linear(84, n),
            )
  3. Pre-trained AlexNet: torchvision থেকে load করে, একটি ছবিতে inference।
    import torchvision.models as models
    import torchvision.transforms as T
    from PIL import Image
    
    alexnet = models.alexnet(weights='IMAGENET1K_V1').eval()
    preprocess = T.Compose([
        T.Resize(256), T.CenterCrop(224),
        T.ToTensor(),
        T.Normalize([0.485, 0.456, 0.406],
                    [0.229, 0.224, 0.225]),
    ])
    img = Image.open('cat.jpg').convert('RGB')
    x = preprocess(img).unsqueeze(0)
    with torch.no_grad():
        pred = alexnet(x).argmax(1).item()
    print("Class index:", pred)

আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ

কোড রানার কাজ না করলে? ব্রাউজারে কাজ না করলে Google Colab ব্যবহার করুন — Google-এর ফ্রি অনলাইন Python পরিবেশ, শুধু Gmail অ্যাকাউন্ট লাগে।
পূর্ববর্তী পাঠ
পাঠ ১৯ · Receptive Field