PART 4 โ€ข DEEP & GENERATIVE AI โ€ข LEVEL 18

Computer Vision & Convolutional Neural Networks

Learn how models convert pixels into edges, textures, objects and decisions. Calculate convolutions, trace spatial shapes and build the practical reasoning required for image classification, detection and segmentation.

โฑ๏ธ 360โ€“440 min๐ŸŽฏ Beginner โ†’ Interview Ready๐Ÿงช 2 Computational Labs๐Ÿ’ผ Vision Engineering Focus
3 ร— 3 KERNELEDGEฮฃ patch ร— weight
โ†’
VISION CONTRACTpixels โ†’ local features โ†’ spatial hierarchy โ†’ predictionHout = โŒŠ(H + 2P โˆ’ K) / SโŒ‹ + 1

By the End of This Level, You Can

01Represent grayscale and colour images as numerical tensors.
02Calculate convolution outputs using kernels, padding and stride.
03Trace CNN spatial shapes, parameters and receptive fields.
04Explain pooling, augmentation and transfer learning correctly.
05Distinguish classification, detection and segmentation systems.
06Design and diagnose an end-to-end vision training pipeline.

Six Building Blocks of Visual Learning

A computer does not see an object directly; it receives a structured tensor of measured intensities.

PIXELA measured intensity

A grayscale pixel is one value; an RGB pixel contains three channel values.

KERNELA small reusable filter

The same learned weights slide across locations to detect local visual evidence.

FEATURE MAPA spatial response grid

Each output cell records how strongly one filter matches one receptive region.

CHANNELOne representation plane

Early channels may encode colour or edges; deeper channels encode learned patterns.

RECEPTIVE FIELDInput region affecting a unit

Depth, kernel size and stride determine how much context a feature can use.

HEADTask-specific prediction layer

A head converts learned features into classes, boxes, masks or embeddings.

Images Are Structured Tensors

Unlike a flat table row, an image preserves neighbourhood, direction and scale.

From Scene to Numbers

A digital image samples light on a rectangular grid. In machine learning, a batch is commonly represented as N ร— C ร— H ร— W: number of images, channels, height and width. Libraries may also store images as H ร— W ร— C, so shape awareness is essential.

  • Grayscale: one intensity channel.
  • RGB: red, green and blue channels.
  • Normalization: rescales values or standardizes each channel.
  • Resolution: controls detail, computation and memory.
WORKED INTUITION

A batch of 32 RGB images sized 224ร—224 has shape 32ร—3ร—224ร—224 and contains 4,816,896 scalar values.

AI / PLACEMENT CONNECTION

Always explain channel order and preprocessing when debugging a vision pipeline.

COMMON MISCONCEPTION

Resizing changes the measured signal; it is not merely a display operation.

Convolution: Local Connectivity with Shared Weights

A filter calculates the same local dot product at every valid spatial position.

How a Feature Map Is Calculated

Place the kernel over an image patch, multiply aligned entries, add the products and bias, then move the kernel. Weight sharing makes convolution far more parameter-efficient than connecting every pixel to every output neuron.

Y[i,j] = b + ฮฃu ฮฃv X[i+u,j+v]K[u,v]

  • Kernel size: local field inspected in one operation.
  • Stride: number of pixels moved between outputs.
  • Padding: values added around borders.
  • Dilation: spacing between kernel elements.
WORKED INTUITION

A 5ร—5 input with a 3ร—3 kernel, stride 1 and no padding produces a 3ร—3 feature map.

AI / PLACEMENT CONNECTION

Derive output height and width before writing a CNN architecture.

COMMON MISCONCEPTION

CNN libraries usually implement cross-correlation without flipping the kernel, although the operation is conventionally called convolution.

PREMIUM COMPUTATIONAL VISUALIZER

๐Ÿ”Ž Convolution & Feature-Map Workbench

Run a real two-dimensional convolution. Change the image, kernel, stride and padding; then follow every patch multiplication and compare the complete output map.

CodeBhavya โ€ข Slide, Multiply, Detect
PATCHReady
RAW SUMโ€”
OUTPUTโ€”
MAP SHAPEโ€”

Activation, Pooling and Spatial Hierarchy

CNN blocks progressively transform raw local evidence into useful task features.

Why Convolution Alone Is Not Enough

Convolution is linear. Nonlinear activations allow layered feature composition, while pooling or strided convolution reduces spatial size and increases effective context. Modern networks often preserve more spatial detail early and reduce it deliberately later.

  • ReLU: clips negative responses and introduces nonlinearity.
  • Max pooling: keeps the strongest value in each window.
  • Average pooling: summarizes the regional mean.
  • Global average pooling: converts each final feature map into one number.
WORKED INTUITION

2ร—2 pooling with stride 2 converts a 28ร—28 feature map into 14ร—14.

AI / PLACEMENT CONNECTION

Discuss the trade-off between invariance, computation and localization detail.

COMMON MISCONCEPTION

Pooling is not automatically beneficial; excessive downsampling destroys small-object information.

CNN Shapes, Parameters and Receptive Fields

Architecture quality depends on tracking both representation size and contextual reach.

Three Calculations for Every Layer

For each convolution, calculate output shape, trainable parameters and receptive field. A standard convolution with Cin input channels, Cout filters and a Kร—K kernel contains (KยฒCin + 1)Cout parameters when each filter has a bias.

  • Output size: depends on input, padding, dilation, kernel and stride.
  • Parameters: depend on channels and kernelโ€”not image width and height.
  • Receptive field: grows across stacked operations.
  • Activation memory: often dominates training memory for large batches.
WORKED INTUITION

A 3ร—3 convolution from 3 to 32 channels has (3ร—3ร—3+1)ร—32 = 896 parameters.

AI / PLACEMENT CONNECTION

Shape and parameter-count questions are common screening and interview tasks.

COMMON MISCONCEPTION

More parameters do not necessarily mean a larger receptive field.

CNN ENGINEERING LABORATORY

๐Ÿ—๏ธ CNN Shape, Parameter & Receptive-Field Laboratory

Propagate a real image tensor through a selected architecture. Inspect output dimensions, parameter counts, activation size and receptive field at every layer.

CodeBhavya โ€ข Shape Before Training
LAYERInput
OUTPUTโ€”
TOTAL PARAMETERS0
RECEPTIVE FIELD1 ร— 1
ACTIVATION MEMORYโ€”

Augmentation and Transfer Learning

Good vision performance depends as much on data and initialization as architecture.

Learn the Right Invariances

Augmentation generates plausible training variations such as crops, flips, colour shifts or rotations. Transformations must preserve the label and update boxes or masks consistently. Transfer learning starts from features learned on a larger source dataset and adapts them to the target problem.

  • Feature extraction: freeze the backbone and train a new task head.
  • Fine-tuning: update some or all pretrained layers using a smaller learning rate.
  • Domain shift: source and target images may have different visual statistics.
  • Leakage safety: split related patients, videos or objects before augmentation.
WORKED INTUITION

A horizontal flip is valid for many animals but may be invalid for text or asymmetric medical anatomy.

AI / PLACEMENT CONNECTION

Explain when to freeze, partially unfreeze and fully fine-tune a pretrained model.

COMMON MISCONCEPTION

More augmentation is not always better; unrealistic transformations teach the wrong invariances.

Classification, Detection and Segmentation

The output representation and evaluation metric must match the visual task.

Three Different Prediction Contracts

  • Classification: one or more labels for the complete image.
  • Object detection: class scores and bounding boxes for multiple objects.
  • Semantic segmentation: a class prediction for every pixel.
  • Instance segmentation: separate masks for individual object instances.

Accuracy may suit balanced classification, while detection often uses intersection-over-union and mean average precision. Segmentation commonly uses IoU or Dice score because foreground pixels can be rare.

WORKED INTUITION

A box with intersection 40 and union 100 has IoU 0.40, which may fail a 0.50 matching threshold.

AI / PLACEMENT CONNECTION

Choose metrics by task and error cost rather than using accuracy everywhere.

COMMON MISCONCEPTION

Image classification cannot localize an object simply because the correct class was predicted.

Training and Diagnosing Vision Models

A reliable pipeline preserves the same image contract from training to deployment.

Practical PyTorch Pattern

model.train()
for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad()
    logits = model(images)
    loss = criterion(logits, labels)
    loss.backward()
    optimizer.step()

Monitor class-wise errors, confusion matrices, data quality, calibration and robustness to lighting, blur, crop and domain shift. Visual inspection of failures is essential because aggregate metrics can hide systematic problems.

WORKED INTUITION

If training augmentation normalizes with one mean and deployment uses another, the model receives a shifted input distribution.

AI / PLACEMENT CONNECTION

Describe the complete preprocessing-to-deployment contract in project interviews.

COMMON MISCONCEPTION

High validation accuracy does not prove robustness if validation images share near-duplicates with training.

๐Ÿ‘๏ธ Computer Vision Pipeline โ€” Visual Flow

Preserve the spatial reasoning chain from pixels to a validated task decision.

1Define image contract

Set size, channels and normalization.

โ†’
2Extract local features

Convolve, activate and downsample.

โ†’
3Build hierarchy

Grow channels and receptive field.

โ†’
4Predict task output

Classify, localize or segment.

โ†’
5Evaluate visually

Measure errors and inspect failures.

PROGRAM TRACING โ€ข TRUE FOUR-LOOP EXECUTION

Trace a 2D Convolution from First Principles

Follow every output row, output column, kernel row and kernel column. The cursor returns through all four loops exactly as Python calculates the feature map.

Vision Logic Before Framework Calls

Use these procedure maps for revision, coding and interviews.

2D CONVOLUTION
  1. Validate input, kernel, padding and stride.
  2. Pad the spatial borders when required.
  3. Move across each output row and column.
  4. Multiply and sum every aligned patch value.
  5. Add bias and apply the chosen activation.
CNN SHAPE TRACING
  1. Record input channels, height and width.
  2. Apply the convolution output formula.
  3. Update channels to the filter count.
  4. Accumulate parameters and receptive field.
  5. Repeat before flattening or pooling globally.
TRANSFER LEARNING
  1. Load compatible pretrained weights.
  2. Replace the source prediction head.
  3. Train the new head as a baseline.
  4. Unfreeze selected deeper backbone blocks.
  5. Fine-tune carefully and validate domain shift.
VISION ERROR ANALYSIS
  1. Separate errors by class and confidence.
  2. Inspect blur, lighting, crop and background.
  3. Check labels, duplicates and grouped splits.
  4. Measure task-aligned metrics and calibration.
  5. Change data or model using observed evidence.

๐Ÿ’ป Computer Vision Challenges

Attempt each program independently. Workspaces, hints and model programs remain collapsed initially.

0 / 5Solved independently0 / 500Best score

Test Your Computer Vision Reasoning

Select one answer per question. Results show your choice, the correct answer and a clear explanation.

Not checked yet

Diagnose Vision Systems Like an ML Engineer

Use visible evidence and task metrics before changing the network.

SHAPE MISMATCH?

Check channel order, resize, padding, stride, flatten size and label shape.

TRAIN HIGH, VALIDATION LOW?

Inspect duplicates, split grouping, augmentation realism, capacity and domain shift.

SMALL OBJECTS MISSED?

Review resolution, early downsampling, receptive-field scale and detection anchors or feature pyramids.

ONE CLASS DOMINATES?

Inspect class counts, sampling, loss weighting, precision, recall and class-specific errors.

BACKGROUND SHORTCUT?

Use saliency and counterexamples to test whether contextโ€”not the objectโ€”drives predictions.

DEPLOYMENT DROP?

Verify colour space, normalization, resize policy, camera distribution and model mode.

CodeBhavya interview pattern:Define tensor contract โ†’ Calculate shapes โ†’ Explain local feature extraction โ†’ Choose backbone and head โ†’ Match loss and metric โ†’ Control augmentation โ†’ Validate grouped splits โ†’ Inspect errors โ†’ Optimize inference.

๐ŸŽค Computer Vision & CNNs โ€” Interview Questions

Answer aloud before selecting Show Answer for each explanation.

A CNN Learns a Spatial Evidence Hierarchy

1Measure

Represent pixels correctly.

โ†’
2Detect

Match reusable local filters.

โ†’
3Compose

Build deeper visual features.

โ†’
4Predict

Produce classes, boxes or masks.

โ†’
5Verify

Measure and inspect failures.

Computer vision becomes understandable when every pixel transform, spatial shape, receptive field, prediction target and evaluation decision can be explained.

Eight Practical Computer-Vision Habits

01

Display images after all preprocessing to verify colour, range and geometry.

02

Calculate every tensor shape before starting a long training run.

03

Split grouped sources before augmentation to prevent near-duplicate leakage.

04

Begin with transfer learning and a simple head when target data is limited.

05

Use only label-preserving augmentations appropriate to the domain.

06

Inspect class-wise errors and representative false positives and negatives.

07

Profile latency, memory and model size on the actual deployment device.

08

Save preprocessing, class mapping and thresholds with the model checkpoint.

Strengthen Computer-Vision Reasoning

Calculate intermediate values and defend every design decision.

  1. 01

    Represent a 3ร—3 grayscale image as a tensor.

  2. 02

    Calculate one 2ร—2 convolution output by hand.

  3. 03

    Calculate output size for multiple padding and stride settings.

  4. 04

    Count parameters in a 3-to-32 channel convolution.

  5. 05

    Apply ReLU and 2ร—2 max pooling to a feature map.

  6. 06

    Trace receptive field through three convolution blocks.

  7. 07

    Compare flattening and global average pooling.

  8. 08

    Design valid augmentation for a medical-image dataset.

  9. 09

    Explain feature extraction versus fine-tuning.

  10. 10

    Calculate IoU for two bounding boxes.

  11. 11

    Compare semantic and instance segmentation.

  12. 12

    Diagnose a background-shortcut failure.

  13. 13

    Write a complete PyTorch image-classification loop.

  14. 14

    Design a deployment test for blur, lighting and resolution shift.