Deep Learning for Computer Vision
Deep Learning for Computer Vision with TensorFlow
This note set covers core concepts in deep learning for computer vision, including image classification, object detection, and image generation using tools like TensorFlow, Hugging Face, ONNX, Weights & Biases, and others.
Tensors and Variables
Tensors are the fundamental data structure in TensorFlow. A tensor is a multi-dimensional array with a uniform data type (e.g., float32, int64, bool, string). The number of dimensions is called the rank, and each dimension has a specific size.
0D tensor (scalar): A single number.
1D tensor (vector): An array of numbers.
2D tensor (matrix): A table of numbers.
3D/4D tensors: Commonly used for batches of images (batch, height, width, channels).
Creating tensors:
tf.constant(value, dtype=…)for fixed values.tf.convert_to_tensor(numpy_array)from NumPy arrays.tf.ones(shape),tf.zeros(shape),tf.eye(N),tf.fill(shape, value)for patterned tensors.Random tensors:
tf.random.normal(shape, mean=0.0, stddev=1.0)andtf.random.uniform(shape, minval, maxval).
Indexing and slicing follow Python conventions: tensor[0:2], tensor[:, 1], and ellipsis (…) for multiple dimensions.
Math operations include tf.math.abs, tf.add, tf.multiply, tf.math.reduce_sum, tf.math.argmax. Broadcasting automatically expands dimensions when performing operations on tensors of different shapes. Matrix multiplication is done with tf.linalg.matmul and transposing with tf.transpose. Batch matrix multiplication allows multiplying batches of matrices.
Ragged tensors (tf.ragged.constant) store non-rectangular data (variable-length sequences). Sparse tensors (tf.sparse.SparseTensor) efficiently represent data with many zeros. String tensors hold text.
TensorFlow Variables (tf.Variable) are mutable tensors whose values change during training. Methods like .assign(), .assign_add(), and .assign_sub() update them.
A tensor is a multi-dimensional array with a uniform data type, and a
tf.Variableis a tensor that can be updated via assignment operations.
Building a Linear Regression Model (Car Price Prediction)
This project introduces regression tasks. The goal is to predict a car’s price from features like horsepower, year, and kilometers. The machine learning lifecycle includes: define task, source data, prepare data, build model, train/optimize, measure performance, validate/test, and take corrective measures.
Data Preparation
Data is read from a CSV with Pandas. Numeric features are normalized using tf.keras.layers.Normalization. This layer can either accept precomputed mean/variance or learn them via .adapt(X).
Model Building
Models are created with tf.keras.Sequential. A typical architecture:
model = tf.keras.Sequential([
normalization_layer,
tf.keras.layers.Dense(units=1)
])The Dense layer implements Y=W⋅X+B, where W is weight and B is bias.
Error Management (Loss Functions)
Mean Squared Error (MSE): MSE=n1∑i=1n(yi−y^i)2. Heavily penalizes outliers.
Mean Absolute Error (MAE): MAE=n1∑i=1n∣yi−y^i∣. More robust to outliers.
Huber Loss: Combines MSE and MAE, quadratic for small errors and linear for large errors.
Training & Optimization
Stochastic Gradient Descent (SGD) updates weights: w=w−η⋅∂w∂L, where η is the learning rate. Adam is a popular adaptive optimizer that adjusts learning rates per parameter.
The learning rate is critical: too small → slow convergence; too large → divergence.
Performance Measurement
Root Mean Square Error (RMSE) is common: RMSE=MSE.
Validation & Testing
Data is split into training (~80%), validation (10%), and test (10%) sets. Validation is used during training to monitor unseen data; the test set is used only for final evaluation.
Corrective Measures
Underfitting (high loss on all sets) is addressed by:
Making the model more complex (more hidden layers, more neurons).
Adding activation functions like ReLU, sigmoid, or tanh.
Using batch normalization.
TensorFlow Data API (tf.data.Dataset) provides efficient data loading with shuffling, batching, and prefetching.
The learning rate must be chosen carefully: too small causes slow training, too large can cause divergence.
Malaria Diagnosis with CNNs
This project performs binary image classification (parasitized vs. uninfected blood cells) using a Convolutional Neural Network (CNN).
Image Data Representation
Images are tensors of shape (height, width, channels). Pixel values represent RGB intensities.
Data Loading & Preprocessing
The Malaria dataset is loaded from tensorflow_datasets. Images are resized to a fixed size (e.g., 224×224) and normalized by dividing by 255.
Convolutional Neural Network Building Blocks
Convolutional Layer: Uses a small kernel (filter) sliding over the input to produce a feature map. Key parameters: kernel size, stride, and padding (
validorsame). Convolutions are far more efficient than fully connected layers for images.Activation Function: ReLU (f(x)=max(0,x)) introduces non-linearity.
Batch Normalization: Normalizes the output of a layer, stabilizing and accelerating training.
Pooling Layer: Reduces spatial dimensions (e.g., Max Pooling, Average Pooling).
Flatten Layer: Converts multi-dimensional feature maps into a 1D vector for the final dense layers.
Loss Function
Binary Cross-Entropy is used for binary classification: −n1∑i[yilog(y^i)+(1−yi)log(1−y^i)].
Performance Metrics
Accuracy is common, but precision, recall, and F1-score are more important when class imbalances exist or when the cost of false negatives/positives is high.
Precision: TP+FPTP
Recall: TP+FNTP
F1-score: 2⋅precision+recallprecision⋅recall
Saving and Loading Models
Models and weights can be saved to disk (e.g., Google Drive) using model.save() and reloaded with tf.keras.models.load_model().
Advanced Model Building Techniques
Model Creation APIs
Sequential API: Linear stack of layers – simple and common.
Functional API: Allows complex topologies: multiple inputs/outputs, shared layers, skip connections.
Model Subclassing: Subclass
tf.keras.Modeland define the forward pass incall()– maximum flexibility.Custom Layers: Subclass
tf.keras.layers.Layerto define custom operations.
Custom Training Loops
Instead of model.fit(), a loop can be built from scratch using tf.GradientTape:
with tf.GradientTape() as tape:
predictions = model(x)
loss = loss_fn(y, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))This gives fine-grained control.
Graph vs. Eager Mode
Eager Mode: Operations execute immediately – good for debugging.
Graph Mode: TensorFlow builds a computational graph for faster execution and portability. The
@tf.functiondecorator converts a Python function into a graph.
Callbacks
Callbacks are functions called during training to automate tasks:
tf.keras.callbacks.History: Records events into a History object.Custom Callbacks: Subclass
tf.keras.callbacks.Callback.Early Stopping: Stops training when a monitored metric (e.g., validation loss) stops improving.
ModelCheckpoint: Saves model weights or the whole model at intervals, often when a metric improves.
LearningRateScheduler: Adjusts learning rate according to a schedule.
ReduceLROnPlateau: Reduces learning rate when a metric stagnates.
TensorBoard Callback: Logs data for visualization in TensorBoard.
TensorBoard
A visualization tool for tracking experiments, viewing graphs, profiling performance, and tuning hyperparameters. Launched with %tensorboard --logdir logs.
Mixed Sample Data Augmentation
Mixup: Creates new samples by weighted combination of two images and their labels: x~=λxi+(1−λ)xj, y~=λyi+(1−λ)yj.
CutMix: Cuts a patch from one image and pastes it onto another, adjusting labels proportionally.
Weights & Biases (W&B)
An MLOps platform for experiment tracking, hyperparameter sweeps, and collaboration. Integrates with Keras via a callback (wandb.keras.WandbCallback).
TensorFlow Records
An efficient binary format for storing serialized data. Preprocessing (resizing, augmentation) can be done before saving, speeding up training pipelines.
Custom Losses and Metrics
Custom loss functions can be defined as functions or by subclassing tf.keras.losses.Loss. Custom metrics subclass tf.keras.metrics.Metric.
The Functional API and Model Subclassing allow building non‑linear models with skip connections, multi‑inputs, and multi‑outputs.
Combating Overfitting and Underfitting
Overfitting: Model performs well on training data but poorly on unseen data. Causes: small dataset, overly complex model.
Underfitting: Model is too simple to capture the underlying pattern.
Mitigation Strategies for Overfitting
Data Augmentation: Artificially increase dataset size with random transformations (rotation, flipping, brightness adjustment). Use
tf.image, Keras layers, or the Albumentations library.Dropout: Randomly drop a fraction of neurons during training (forces learning of robust features).
Regularization (Weight Decay): Add a penalty to the loss for large weights – L1 (Ltotal=L+λ∑∣w∣) or L2 (Ltotal=L+λ∑w2).
Early Stopping: Stop training when validation performance degrades.
Reduce Model Complexity: Use a smaller architecture.
Hyperparameter Tuning: Search for optimal values (learning rate, dropout rate, etc.).
Batch Normalization: Has a slight regularization effect.
Data augmentation is a highly effective technique to combat overfitting when the dataset is small.
Human Emotion Detection (Multi-Class Classification)
This project classifies facial images into three emotions: angry, happy, sad.
Data Setup
Images from Kaggle are organized into subdirectories (one per class). tf.keras.utils.image_dataset_from_directory automatically infers labels from the folder structure.
Output Layer
For multi-class classification, the final layer uses softmax activation, producing a probability distribution summing to 1:
Loss Function
Categorical Crossentropy (for one-hot labels) or Sparse Categorical Crossentropy (for integer labels).
Metrics
CategoricalAccuracy (or SparseCategoricalAccuracy).
TopKCategoricalAccuracy (e.g., Top‑2 accuracy considers the prediction correct if the true class is among the top two probabilities).
Saving & Loading with HDF5
Models can be saved in HDF5 format using model.save('model.h5') and loaded with tf.keras.models.load_model.
TensorFlow Records for Efficiency
Images are converted into TFRecord format for efficient storage and loading.
Modern Convolutional Neural Network Architectures
AlexNet (2012): Breakthrough model using ReLU activations and multiple GPUs.
VGGNet: Demonstrated that stacking layers with small 3×3 filters is more effective than large filters. Variants: VGG‑16 (16 weight layers), VGG‑19.
ResNet: Introduced residual blocks with skip connections to allow very deep networks (e.g., ResNet‑50, ResNet‑152). Skip connections mitigate the vanishing gradient problem. Batch normalization is a key component.
MobileNet: Uses depthwise separable convolutions to reduce computational cost, ideal for mobile/edge devices.
EfficientNet: Employs compound scaling – uniformly scales depth, width, and resolution – for optimal performance.
The implementation of a ResNet‑34 using model subclassing is a common exercise.
Residual connections in ResNet allow gradients to flow directly through the network, enabling training of very deep models.
Transfer Learning and Fine-Tuning
Transfer learning reuses a pre‑trained model (e.g., EfficientNet) as a feature extractor. The final classification layers are replaced with new ones for the target task. Fine‑tuning unfreezes some or all layers of the pre‑trained model and trains them with a very low learning rate to adapt to the new data.
This technique is especially powerful when the target dataset is small.
Visualizing CNNs (Feature Maps and Grad-CAM)
Feature Map Visualization
By creating a model that outputs intermediate layer activations, one can see what the network “looks at.” Early layers detect low‑level features (edges, colors), while deeper layers detect high‑level concepts (objects, parts).
Grad‑CAM (Gradient‑weighted Class Activation Mapping)
Generates a heatmap highlighting influential regions for a prediction. It computes the gradient of the target class score with respect to the final convolutional feature maps and weights them to produce a coarse localization map.
Vision Transformers (ViTs)
Transformers, originally from NLP, are adapted to images. An image is split into fixed‑size patches (e.g., 16×16). Each patch is flattened and linearly projected to obtain patch embeddings. A learnable class token and positional embeddings are added. The sequence is passed through a standard Transformer encoder (self‑attention and MLP layers). ViTs achieve state‑of‑the‑art results when pre‑trained on very large datasets, often outperforming CNNs.
Deployment
ONNX Format
Open Neural Network Exchange (ONNX) converts models between frameworks (e.g., TensorFlow → PyTorch) and runs using ONNX Runtime on various hardware (CPU, GPU).
Quantization
Reduces model size and speeds inference by converting weights and activations from 32‑bit floats to lower bitwidths (e.g., 8‑bit integers). Types:
Post‑training dynamic quantization: Quantizes weights, activations quantized dynamically.
Post‑training static quantization: Uses a calibration dataset to quantize activations.
Quantization‑Aware Training (QAT): Simulates quantization during training for better accuracy.
TensorFlow Lite
A library for deploying models on mobile and edge devices. The TFLite converter can apply quantization to produce smaller models.
Building an API with FastAPI
A REST API serves the model. FastAPI provides automatic OpenAPI and Swagger UI documentation.
Deployment to Cloud (Heroku)
The API is containerized and deployed to a cloud platform like Heroku.
Load Testing with Locust
Simulates multiple users interacting with the API to measure performance and stability under load.
Quantization can dramatically reduce model size and improve inference speed on resource‑constrained devices.
Object Detection (YOLO)
YOLO (You Only Look Once) frames object detection as a regression problem. It divides the input image into an S×S grid. Each grid cell predicts:
B bounding boxes (each with 4 coordinates + confidence score).
Class probabilities C for the object.
The output tensor shape is S×S×(B×5+C).
Encoding
The center of a bounding box must fall into a grid cell. Coordinates (x,y) are predicted relative to that cell, and width/height are predicted relative to the whole image.
Loss Function
The YOLO loss is a sum of:
Coordinate loss (MSE for box center and size, with a higher weight for larger boxes).
Objectness loss (for cells containing an object).
No‑objectness loss (for cells without an object, with a lower weight).
Classification loss (cross‑entropy for class probabilities).
Intersection over Union (IoU)
IoU measures overlap between predicted and ground‑truth boxes:
Used to assign which predicted box is responsible for an object.
Non‑Max Suppression (NMS)
Eliminates duplicate detections: discards boxes with high IoU overlap with a higher‑confidence box.
Implementation
A YOLO‑like model can be built using a pre‑trained backbone (e.g., ResNet50) followed by convolutional layers and a final prediction layer.
Image Generation (VAE and GAN)
Variational Autoencoders (VAEs)
A generative model with an encoder‑decoder structure. The encoder outputs parameters of a probability distribution (mean μ and variance σ2) instead of a discrete latent vector. The reparameterization trick samples z=μ+σ⋅ϵ (where ϵ∼N(0,1)) to enable backpropagation.
The VAE loss has two parts:
Reconstruction loss (e.g., cross‑entropy or MSE) – encourages output to resemble input.
KL divergence loss – regularizes the latent distribution to be close to a standard normal N(0,1).
Generative Adversarial Networks (GANs)
Two competing networks:
Generator (G): Creates fake data.
Discriminator (D): Distinguishes real from fake.
Training is a min‑max game:
DCGAN (Deep Convolutional GAN) uses convolutional layers in both networks. Tips for stable training:
Label smoothing (use 0.9 instead of 1 for real labels).
Flip generator labels from 0 to 1 (train generator to make discriminator believe fakes are real).
Use Adam optimizer.
Use leaky ReLU activations.
VAEs produce a smooth latent space useful for interpolation; GANs often produce sharper images but are harder to train.
Conclusion
The course equips learners with practical skills in deep learning for computer vision. Key projects include regression (car price prediction), binary classification (malaria diagnosis), multi‑class classification (emotion detection), object detection (YOLO), and image generation (VAE/GAN). Mastery of these techniques enables tackling new challenges such as object tracking, depth estimation, or text detection.

Ask anything
We've read this whole study set, so questions about it get the best answers.