LeNet — প্রথম CNN
এই পাঠে যা শিখবেন
- LeNet-এর historical context
- LeNet-5-এর layer-by-layer architecture
- কেন LeNet revolutionary ছিল
- PyTorch-এ LeNet implementation ও MNIST training
১ · Historical context — ১৯৮৯-১৯৯৮
১৯৮০-র দশকে — Backpropagation reinvent (Rumelhart 1986)। ১৯৮৯-এ LeCun প্রথম CNN paper — handwritten ZIP code recognition AT&T Bell Labs-এ। ১৯৯৮-এ LeNet-5 published — current name।
সমস্যা: US Postal Service ও bank-এ প্রতিদিন লক্ষ লক্ষ চেক ও envelope-এ handwritten digit। Manual entry expensive ও error-prone।
সময়ের অন্য approach: SVM, K-NN, decision tree — hand-crafted feature-এর উপর। Maximum 95% accuracy।
LeCun bet করেছিলেন — feature-ও শেখা যায়, hand-design করতে হয় না। Convolution + pooling + backprop combo দিয়ে। ১৯৯৮-এ এটি heretical idea ছিল।
২ · LeNet-5 architecture
Input: 32×32 grayscale digit (MNIST-এ 28×28 padded to 32×32)।
- C1 — Conv: 6 filters, 5×5 kernel → output 28×28×6।
- S2 — Subsampling: 2×2 average pool → 14×14×6।
- C3 — Conv: 16 filters, 5×5 → 10×10×16। (LeCun-এর সংযোগ pattern অদ্ভুত — কিছু output শুধু কিছু input channel দেখে)।
- S4 — Subsampling: 2×2 average pool → 5×5×16।
- C5 — Conv (FC-equivalent): 120 filters, 5×5 → 1×1×120।
- F6 — FC: 84 neurons।
- Output: 10 RBF units (digit 0-9)।
Total parameters: ~60,000।
Activation: tanh (sigmoid এর variant)। ReLU তখন invent হয়নি।
৩ · কেন এই specific design?
- 5×5 kernel: এই size-এ digit-এর local feature (curve, line) ধরা যায়।
- Average pool: Max pool সেই সময় common ছিল না। Subsampling = "average + scaling"।
- Channel ক্রমশ বাড়া (1→6→16→120): বিচিত্র feature শেখা।
- Spatial ক্রমশ কমা (32→14→10→5→1): abstract representation।
- Two FC layer-এ end: classification head।
৪ · Training challenge ১৯৯৮-এ
- Hardware: SGI workstation, 100 MHz CPU। Modern GPU-র billionth।
- Memory: 16 MB RAM common। Batch ছোট।
- Training time: ৩ দিন MNIST-এ।
- Library: custom C — PyTorch/TensorFlow নেই।
- Initialization: Xavier/He invent হয়নি — heuristic।
৫ · LeNet ও MNIST
MNIST = Modified NIST। LeCun ১৯৯৪-এ assemble। 60,000 training + 10,000 test handwritten digit (0-9), 28×28 grayscale।
- LeNet-5 — 0.8% error rate (১৯৯৮)।
- আজ — modern CNN 0.2% error।
- "Hello world" of CV — every CNN tutorial শুরু এতে।
৬ · PyTorch-এ LeNet implementation
import torch
import torch.nn as nn
class LeNet5(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
# original — tanh activation
self.features = nn.Sequential(
nn.Conv2d(1, 6, kernel_size=5), nn.Tanh(),
nn.AvgPool2d(2),
nn.Conv2d(6, 16, kernel_size=5), nn.Tanh(),
nn.AvgPool2d(2),
nn.Conv2d(16, 120, kernel_size=5), nn.Tanh(), # C5 fully spatial
)
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(120, 84), nn.Tanh(),
nn.Linear(84, num_classes),
)
def forward(self, x):
return self.classifier(self.features(x))
model = LeNet5()
x = torch.randn(8, 1, 32, 32)
y = model(x)
print("Output:", y.shape) # (8, 10)
print("Parameters:", sum(p.numel() for p in model.parameters()))
৭ · LeNet-এর legacy
- Banking: NCR, AT&T-এর OCR — LeNet-derived।
- USPS: ZIP code reading automation।
- Academic seed: AlexNet (২০১২) — directly LeNet-এর scaled-up version।
- Pedagogical: "Hello CNN" — every textbook।
৮ · LeNet থেকে modern CNN — কী বদলায়
- Activation: tanh → ReLU।
- Pool: avg → max।
- Init: heuristic → Xavier/He।
- Optimizer: SGD → Adam।
- BatchNorm: add।
- Dropout: add।
- Depth: 7 layer → 100+।
- Data: 60K → 14M (ImageNet)।
৯ · LeNet-এর আজও practical use
- Educational baseline: CNN শেখা শুরু।
- Embedded device: 60K parameters — microcontroller-এ চলে।
- Quick prototype: ছোট dataset (digit, signature)।
- OCR-light: simple character recognition।
ভাবনার প্রশ্ন
প্র ০১ LeNet ১৯৯৮-এ MNIST-এ 99%। কিন্তু ২০১২ পর্যন্ত (AlexNet) CNN dominant হলো না কেন? "DL winter"-এর কারণ?
এটি AI history-র সবচেয়ে instructive case study। ১৪ বছরের delay-এর কারণ প্রযুক্তি, data, ও mindset।
Hardware bottleneck:
- ১৯৯৮: 100 MHz CPU, 16 MB RAM। MNIST training ৩ দিন।
- ImageNet (১.৪M images) — তখনকার hardware-এ অসম্ভব।
- GPU general-purpose computing ২০০৭ (CUDA)।
- ২০১২ AlexNet — দু'টি GTX 580 GPU-তে train, ৫-৬ দিন।
Data scarcity:
- ImageNet ২০০৯-এ start, ২০১২-এ mature (Fei-Fei Li-র vision)।
- Before — কয়েক হাজার labeled image সর্বোচ্চ।
- Big data + crowdsourcing era CNN-এর অপেক্ষায় ছিল।
Algorithmic gaps:
- ReLU: ২০১০ (Nair & Hinton) — vanishing gradient solved।
- Dropout: ২০১২ (Hinton et al.) — overfitting tamed।
- Xavier init: ২০১০।
- Backprop optimizers: Adam ২০১৪।
- Together — deeper network train possible।
Community skepticism (DL winter):
- Symbolic AI camp NN-কে "dead end" বলত।
- SVM theoretically backed — kernel method dominant ১৯৯৫-২০১০।
- NeurIPS-এ deep network paper reject হতো।
- LeCun, Hinton, Bengio — "lonely crusaders"।
২০১২-র turning point:
- AlexNet — ImageNet 2012 top-5 error: 26% → 15%।
- 10 percentage point gap unprecedented।
- CV community stunned — within months pivot to CNN।
- Industry investment, GPU vendors interest।
Lessons:
- Algorithm ≠ adoption। Three things needed: algorithm + compute + data।
- Visionary research (LeCun) এর timing important।
- Failure-to-scale ≠ failure-of-idea।
- Today's "stuck" research — tomorrow's revolution।
Modern parallel:
- Transformer ২০১৭ — first NLP-এ। Vision ২০২০-এ।
- Diffusion model ২০১৫ — ২০২২-এ Stable Diffusion।
- Idea inception → public adoption — typically 5-10 years।
মূল উপলব্ধি: Research timeline non-linear। LeCun-এর persistence ১৪ বছর — যা CV-কে বদলে দিয়েছে। Researcher-দের long-term vision-এর শক্তি।
প্র ০২ LeNet-এ C3 layer-এ অদ্ভুত connection pattern (some output channel connected to subset of input channels)। আজকের CNN-এ এটি নেই কেন?
LeNet-এর এই detail প্রায়ই tutorial-এ skip। Historical artifact কিন্তু philosophical implication আছে।
LeNet C3 connection:
- S2 output: 6 channel। C3 output: 16 filter।
- Standard "fully connected" conv: 16 × 6 = 96 connection।
- LeCun: কিছু output শুধু 3 input channel দেখে, কিছু 4, কিছু 6।
- Total connection ≈ 60% of full।
কেন এই sparse pattern?
- Compute saving: ১৯৯৮-এ resource scarce। Sparsity 40% reduce।
- Symmetry breaking: different filter ভিন্ন combination শিখে — diversify feature।
- Inductive bias: hierarchical — "low-level → mid-level"-এ specific selection।
আজকের CNN-এ কী?
- Standard conv = fully connected across channels (every output uses every input)।
- GPU optimized for dense matmul — sparsity overhead-এর সাথে speedup না।
- Modern "sparsity" ভিন্ন নামে: group convolution।
Group convolution:
- Input channels-কে $g$ group-এ ভাগ। প্রতিটি group আলাদা filter।
- Group=1 = standard conv। Group=$C$ = depthwise conv।
- AlexNet — 2-group (২ GPU-এ split — engineering reason, not theoretical)।
- ResNeXt — 32 group, accuracy gain।
- MobileNet — depthwise separable। 8x cheap।
- ShuffleNet — group + channel shuffle।
Sparsity philosophy:
- "All connection necessary" assumption — চ্যালেঞ্জ।
- Lottery ticket hypothesis (Frankle & Carbin, 2019): trained network-এর 90% weight prune করেও same accuracy possible।
- LeCun-এর intuition ১৯৯৮-এ — sparsity productive।
আধুনিক sparse CNN:
- Pruning post-training: 50-90% weight zero।
- NAS (Neural Architecture Search) — sparse pattern auto-discover।
- Mixture-of-Experts — selective activation।
মূল উপলব্ধি: "অপ্রয়োজনীয়" historical detail অনেক সময় profound idea-এর precursor। LeNet-এর hand-crafted sparsity আজকের efficient architecture-এর দিকে route।
প্র ০৩ LeNet-এ tanh, AlexNet-এ ReLU। ReLU এত সরল ($\max(0,x)$) — কেন এর introduction এত revolutionary?
ReLU history-এ প্রায়ই trivial মনে হয়। Actually — DL renaissance-এর 3-4 key enabler-এর একটি।
tanh-এর সমস্যা:
- Vanishing gradient: tanh-এর derivative max 1, saturated region-এ ~0।
- Deep network-এ — chain rule-এ gradient layer-wise multiply → exponentially shrink।
- 10-layer network-এ first layer-এর gradient nearly zero — train করতে পারে না।
- 1990s-এ এই কারণে network 5-7 layer-এ সীমাবদ্ধ ছিল।
ReLU-র breakthrough:
- Active region-এ derivative = 1। Saturation নেই (positive side-এ)।
- Gradient deep network-এ stable propagate।
- Sparse activation — many neuron 0, fewer active। Information bottleneck-এর moderate।
Mathematical comparison:
- $\tanh'(x) = 1 - \tanh^2(x) \le 1$, often << 1।
- $\text{ReLU}'(x) = 1$ if $x>0$ else $0$।
- Sigmoid $\sigma'(x) = \sigma(x)(1-\sigma(x)) \le 0.25$।
Computational cost:
- tanh: exp() — expensive in hardware।
- ReLU: comparison + select — single instruction।
- Backward pass — branch-free, vectorizable।
- GPU-এ 5-10x speedup।
Biological inspiration:
- Neuron firing — typically positive only (excitatory)।
- Sparse activation — neuroscience-এর observation।
- "Half-wave rectification" in sensory systems।
ReLU-র সমস্যা:
- Dying ReLU: neuron stuck at 0 forever (negative bias)।
- Not zero-centered: bias activation drift।
- Unbounded: activation explosion possible।
Variants:
- Leaky ReLU: $\max(0.01x, x)$ — dying ReLU avoid।
- PReLU: learnable slope।
- ELU: exponential negative tail।
- GELU: Gaussian probability — Transformer default।
- Swish/SiLU: $x \cdot \sigma(x)$ — EfficientNet, modern CNN।
Adoption timeline:
- ২০০০ — Hahnloser et al। গভীর paper।
- ২০১০ — Nair & Hinton। RBM context-এ।
- ২০১২ — AlexNet popularize।
- আজ — DL-এর default।
মূল উপলব্ধি: Simple trick → big effect। ReLU = "conceptual minimal viable activation"। AI breakthroughs প্রায়ই এমন simple swap।
প্র ০৪ আজ ২০২৬-এ একটি Bangla হাতে-লেখা সংখ্যা চেনার system বানাতে — LeNet, ResNet, বা ViT-tiny কোনটা বাছবেন? Considerations?
এটি real-world Bangladesh edu-tech problem। JSC, SSC, exam OMR — handwriting recognition দরকার।
Task profile:
- Bangla digits 0-9 (০-৯) recognize।
- Handwriting variability — student-ভেদে বিরাট।
- Deploy on basic Android phone বা scanner server।
- Realtime expectation।
Option 1 — LeNet:
- ✅ ~60K params — extremely lightweight।
- ✅ Microsecond inference — embedded device OK।
- ✅ MNIST-style task-এ 95-98% accuracy।
- ❌ Bangla digit MNIST-এর তুলনায় বেশি diverse — accuracy ceiling।
- Verdict: pilot study বা low-resource device-এ ভাল।
Option 2 — ResNet-18:
- ✅ 11M params, ImageNet-pretrained।
- ✅ Transfer learning থেকে ভাল accuracy (99%+)।
- ✅ PyTorch, TF-এ ready-made।
- ❌ Mobile-এ inference 50-100ms — borderline realtime।
- Verdict: server-side OK, edge device challenge।
Option 3 — ViT-tiny:
- ✅ 5M params, recent SOTA।
- ✅ Bigger pretrained model (DINO, MAE) থেকে fine-tune।
- ❌ Patch attention — small image (28×28) reflect awkward।
- ❌ Pretrain large image, downstream small — accuracy mid।
- ❌ Slower than ResNet-18 typically।
- Verdict: overkill for digit task।
Bangla-specific considerations:
- Dataset size: NumtaDB, BanglaLekha — ~50K labeled digits। Small for transformer।
- Style diversity: Bangladesh + India + Bengali speakers — variety।
- Conjuncts: digits straightforward, কিন্তু character recognition different beast।
Recommended approach:
- Baseline: LeNet-modified (ReLU, BN, dropout)। Quick benchmark।
- Production: MobileNetV3-small ImageNet pretrained — transfer learn।
- Server with budget: ResNet-18।
- Augmentation aggressive: rotation ±15°, slight elastic, noise, thickness variation।
- Confidence threshold: low confidence → manual review।
Architecture selection rule:
- Task complexity ↑ → architecture complexity ↑।
- Single-class digit recognition → LeNet/MobileNet sufficient।
- Full Bangla character (50+ class) → ResNet/EfficientNet।
- Sentence-level OCR → Transformer (TrOCR)।
Local context:
- Bornom OCR (Bengali initiative) — ResNet-based।
- Bangladesh Election Commission — printed digit OK।
- Educational tech (10 Minute School) — mobile-first।
মূল উপলব্ধি: "Latest architecture" নয় — task-fit architecture। Bangladesh-এর constraint-এ pragmatic choice often LeNet-spirit। MobileNet, EfficientNet — LeNet-এর grand-children।
অনুশীলন
-
Param count: LeNet-এ C1 (1→6 ch, 5×5) layer-এ মোট parameter (bias সহ)?
$1 \times 6 \times 5 \times 5 + 6 = 156$।
-
Modernize: LeNet-এ tanh → ReLU, AvgPool → MaxPool। 28×28 input থেকে শুরু (32 padding না)। PyTorch।
nn.Conv2d(1, 6, 5, padding=2), # padding 2 যাতে output 28 nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(6, 16, 5), nn.ReLU(), nn.MaxPool2d(2), # ... continue -
ভাবুন: LeNet-এ FC layer (84 → 10) parameter count = 850। শুধু এই layer remove করলে কী effect? কেন এই tiny layer matter?
FC2 — final classifier। Remove করলে 120 → 10 directly। সামান্য parameter কম, কিন্তু classification capacity-ও কম। 84-D intermediate representation feature mix-এর জায়গা — abstract feature compose।
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ১১ · AlexNet ও ImageNet পরবর্তী পাঠ ২০১২-র CV revolution।
- পাঠ ০৯ · CNN recap আগের পাঠ CNN-এর foundation।
- পাঠ ১৪ · ResNet এগিয়ে CNN-এর modern peak।
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।