Skip to main content

πŸ“ Neural Networks

Description​

< What is it? >​

A neural network is a function built by composing many small units β€” neurons β€” arranged in layers. Each neuron does the same two things: combine its inputs linearly, then pass the result through a non-linear activation. Stacking those layers lets the network approximate mappings that no single linear model can express.

w₁
x₁ ────────┐
wβ‚‚ β”‚
xβ‚‚ ────────┼──▢ z = Ξ£ wα΅’xα΅’ + b ──▢ a = f(z) ──▢ to the next layer
w₃ β”‚ (linear) (activation)
x₃ β”€β”€β”€β”€β”€β”€β”€β”€β”˜
b (bias)
react

Training adjusts the weights and biases; the structure and the choice of activation stay fixed.

Key points​

< Input, hidden, and output layers >​

A neural network usually has three roles of layers:

input features or embeddings β†’ hidden layers β†’ task-specific output layer
  • Input layer: receives numeric features, pixels, or embeddings.
  • Hidden layers: repeatedly transform the representation so the model can learn useful intermediate features.
  • Output layer: produces the value needed by the task, such as one real number, one binary logit, or one logit per class.

< Neurons and connections >​

A neuron holds no data of its own β€” it is a rule for turning a vector of inputs into one number. A connection carries the output of one neuron to the input of another, and every connection has a weight attached to it. In a fully connected layer, every neuron in layer lβˆ’1l-1 connects to every neuron in layer ll, so a layer with nn inputs and mm outputs has nΓ—mn \times m connections.

< Weights and biases >​

The weight wiw_i on a connection says how strongly that input pushes the neuron's output up or down; a weight near zero makes the input irrelevant. The bias bb is an input-independent offset that shifts the neuron's threshold, letting it fire even when every input is zero.

Together they are the network's trainable parameters. A layer collects them into a matrix WW and a vector bb:

W∈RmΓ—n,b∈RmW \in \mathbb{R}^{m \times n}, \quad b \in \mathbb{R}^{m}

For a dense layer with nn inputs and mm outputs, this is mn+mmn+m trainable parameters. CNNs and Transformers use more structured connections or weight sharing, but the same ideaβ€”learn parameters that transform representationsβ€”still applies.

Their starting values matter β€” see Weight Initialization.

< Propagation function: the linear part >​

The propagation function is what aggregates a neuron's incoming signals into a single pre-activation value zz. In practice it is the weighted sum plus bias, which for a whole layer is one matrix multiply:

z(l)=W(l)a(lβˆ’1)+b(l)z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)}

where a(lβˆ’1)a^{(l-1)} is the previous layer's output and a(0)=xa^{(0)} = x, the input. This is a linear function of the inputs (affine, once the bias is included): scaling an input scales its contribution proportionally, and contributions add.

< Batches and tensor shapes >​

Models process many examples together as a batch. In PyTorch, nn.Linear(n, m) maps an input of shape (B, n) to an output of shape (B, m), where B is the batch size. More generally, it transforms the final dimension, so (B, T, n) becomes (B, T, m) for a sequence of T token representations.

< Activation function: the non-linear part >​

The activation function ff maps the pre-activation to the neuron's output:

a(l)=f ⁣(z(l))a^{(l)} = f\!\left(z^{(l)}\right)

It is applied element-wise, so it changes each value's shape but not the layer's dimensions.

ActivationFormulaTypically used for
ReLUmax⁑(0,z)\max(0, z)Default for hidden layers β€” cheap, and its gradient does not saturate for z>0z > 0
GELUzβ‹…Ξ¦(z)z \cdot \Phi(z)Hidden layers in transformers
Sigmoid1/(1+eβˆ’z)1 / (1 + e^{-z})A single output squashed to (0,1)(0, 1) for binary classification
Tanh(ezβˆ’eβˆ’z)/(ez+eβˆ’z)(e^{z} - e^{-z}) / (e^{z} + e^{-z})Outputs centred on zero, common in older recurrent networks
Softmaxezi/βˆ‘jezje^{z_i} / \sum_j e^{z_j}An output layer producing a distribution over classes

< Why the non-linearity is required >​

Without ff, depth buys nothing. Two stacked linear layers collapse into one:

W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)W_2(W_1 x + b_1) + b_2 = (W_2 W_1)x + (W_2 b_1 + b_2)

which is just another affine map. The activation is what makes a deep network more expressive than a single layer. Its derivative also decides how well gradients survive the trip back through many layers β€” see Vanishing & Exploding Gradients.

< Output layer and loss >​

The output layer and loss function depend on the task:

TaskNetwork outputCommon training lossInterpretation at inference
RegressionOne or more real valuesMSE or MAEPredicted quantity, such as price
Binary classificationOne logitBinary cross-entropy with logitsApply sigmoid to obtain a positive-class probability
Multiclass classificationOne logit per mutually exclusive classCross-entropyApply softmax to obtain class probabilities

Stable framework losses usually accept logits directly, so do not manually apply sigmoid or softmax before those losses.

< How a network learns >​

Training repeatedly follows this loop:

batch β†’ forward pass β†’ predictions/logits β†’ loss
β†’ backpropagation β†’ gradients β†’ optimizer update

The forward pass produces predictions. The loss measures their error, backpropagation computes how each trainable parameter affected that error, and an optimizer uses gradient descent to update the parameters. At inference time, the learned parameters are fixed and the model performs only the forward pass.

< In PyTorch >​

import torch.nn as nn

model = nn.Sequential(
nn.Linear(784, 128), # W and b: the propagation function
nn.ReLU(), # f: the activation function
nn.Linear(128, 10), # output layer β€” logits, softmax folded into the loss
)

This model maps a batch of 784-dimensional inputs to 10 logits. nn.Linear(n, m) allocates the weight matrix and bias vector; nn.ReLU() has no parameters at all.

Comparison​

< Linear model vs neural network >​

AspectLinear modelNeural network
FunctionOne affine mappingMany affine mappings separated by non-linear activations
Intermediate featuresUsually engineered outside the modelLearned in hidden layers
StrengthsSimple, fast, interpretable, often strong for small or well-structured dataCan model complex patterns in images, audio, text, and other high-dimensional inputs
TradeoffsCannot represent complex non-linear relationships by itselfUsually needs more data, compute, tuning, and regularization

Video Tutorial​

Reference​