72 min total

Computer Vision & OpenCV

Neural networks

Neural networks

Error function: computes the difference between and

Loss function: Defines how error value is computed. We use different loss function depending upon the task

Cost function: average of loss values over the entire dataset

Sigmoid neuron and binary-label probabilities

Training minimizes a task-appropriate objective while evaluation checks generalization.

To find W and b values that minimize this loss we use optimizer algorithm. Optimizer algorithm requires knowing the partial derivative of loss function with respect to each parameter.

Weights decide how much influence each input feature has on the output.

Bias parameters shift a neuron’s pre-activation independently of its inputs.

If the predicted probability of class 1 is 0.9, the probability assigned to a true label y = 1 is 0.9, while that assigned to y = 0 is 0.1.

The model assigns 90% probability to class 1 and 10% to class 0. The probability assigned to the observed label changes with the label.

Since each data point ( ,​) is considered independent of each other. If we want the total probability (likelihood) of observing all labels , we multiply the probabilities due to rule:

The resulting likelihood is:

But since the OG likelihood equation is hard to optimize due to product of many small probabilities, underflows etc, we convert it into log to make it easier to compute. So now: minimizing negative log likelihood = maximizing log likelihood

Cross-entropy is an information-theoretic objective that compares target labels with predicted probabilities. Minimizing it rewards the model for assigning higher probability to the correct labels.

For multiclass classification

N is the number of training examples, C the number of classes, y the one-hot target, and z the raw logit.

Classification types

  • Binary classification: only 2 classes
  • Multiclass/multinomial classification: more than 2 classes
  • Multilabel classification: each input can belong to multiple classes at the same time
Common activation functions

Full-batch gradient descent uses the entire training set for each update; stochastic gradient descent uses one example, and mini-batch gradient descent uses a subset.

For the output of a sigmoid neuron, the chain rule includes the factor σ(u)(1−σ(u)); gradients for preceding weights also include the derivative of each intervening layer.

Batch and individual-weight updates

For a half-squared-error sum, the chain rule produces the following batch update. An averaged MSE adds the appropriate factor 1/N or 2/N.

For the notebook’s hidden sigmoid activation o₁₂ and output weight θ₇, an individual θ₃ update with a linear output expands as:

If the output neuron is also sigmoid, its derivative ŷᵢ(1−ŷᵢ) must be included for squared-error loss. The original abbreviated update omitted that distinction; the full chain rule depends on the output activation and loss.

At x = 0, ReLU is not differentiable; implementations choose a subgradient. The MSE expression is a loss, not its derivative.

Correction: the original MSE expression is the loss, not its derivative. The derivative and its averaging factor are written separately here. ReLU has no unique derivative at zero; implementations select a convention for that point.

Neural network and backpropagation paths

Gradient-descent update schemes

  • Online/stochastic Gradient descent: updates weight after every training sample, good for streaming data, noisy updates
  • Mini-batch Gradient descent: updates weight after every small batch, allows for training large data on small GPUs
  • Batch Gradient descent: computes gradients over entire before updating, most stable but slow and memory intensive

Gradient descent: is an optimizer, minimizes the cost function

Gradient descent along a loss curve

Loss functions examples

Stochastic Gradient Descent: When the dataset is too large, performing gradient descent with respect to all data points can be computationally expensive and slow. SGD samples a single data point to compute the gradient to update the model.

Process:

  • Shuffle the dataset to avoid bias in training.
  • pick data point i (or mini batch)
  • Calculate error and update weights of whole network based on point i (or mini batch)

Epoch: one complete pass through entire training dataset

Iteration: number of iterations per epoch is determined by the batch size and total number of training samples

Momentum accumulates gradients across updates, reducing oscillation and accelerating movement along directions with consistent gradients.

Gradient-update path on a contour plot, clean schematic redraw

Without momentum, an update uses only the current gradient. The notebook contrasts this with a two-gradient expression containing α times the previous gradient. Full momentum accumulates the entire exponentially weighted gradient history:

The two-gradient form is a truncated illustration; the velocity recurrence above is the full update. The clean contour drawing restores the omitted visual without the highlighted formula backgrounds.

Learning-rate effects on training loss

Regularization penalizes overly complex solutions to reduce overfitting.

Ensemble training: train multiple networks with different random initializations, each network independently makes a prediction. While inference, all network predictions are considered (voting, averaging) while making final decision. Reduces overfitting

Dropout randomly sets selected activations to zero during training, with a chosen dropout probability.

NN Training Steps

  • Define Network
  • Define Loss function
  • Random parameter initialization
  • Load training data
  • Prepare Batches
  • Feedforward
  • Compute loss
  • Backprop gradients
  • Update weights
  • Repeat

Alexnet

Training settings in the AlexNet notes

SettingValue
ActivationReLU
Dropout0.5
Batch size128
OptimizerSGD
Momentum0.9
Initial learning rate0.01
L2 weight decay0.0005

Historical wording: the notebook calls AlexNet the “first use of ReLU.” That broad claim is not retained as a historical fact. ReLU is the activation used in the architecture described here.

AlexNet layer arrangement
Convolution, subsampling, and classification

Residual networks: Deep networks tend to perform worse as the number of layers increases. As layers are added, gradients become very small. A resnet also learns the difference between output and input (residual)

A residual block with an identity shortcut

GoogLeNet uses Inception modules that apply 1×1, 3×3, and 5×5 convolutions and max pooling in parallel, then combine their outputs.

Inception makes the network wider by using parallel branches that capture local patterns at different spatial scales. The 1×1 convolutions can reduce channel dimensions before the more expensive 3×3 and 5×5 operations, controlling computational cost while preserving a multi-scale representation. The outputs are concatenated along the channel dimension.

An Inception module with parallel filter sizes

DenseNet concatenates features from preceding layers within a dense block, encouraging feature reuse and supporting gradient flow.

Dense connections across convolutional layers