Deep Learning · Essential Mathematics
The Math a Neural Network Uses to Learn
You do not need to finish an advanced mathematics textbook before understanding a neural network. This lesson follows one prediction from input numbers to a weight update, introducing vectors, matrices, dot products, functions, derivatives, gradients, probability and logarithms exactly where each idea becomes useful.
Why These Mathematical Tools Appear
A neural network must do three things: store many examples compactly, calculate predictions quickly, and discover how its adjustable weights should change. Linear algebra handles structured numbers and repeated calculations. Calculus describes how a tiny weight change affects error. Probability expresses uncertain choices, while logarithms turn probability products into stable sums and strongly penalize confident mistakes.
The symbols are not the lesson; they are a shorter language for operations the model performs. Whenever you see a formula below, read the words beside it first, then reproduce the small calculation.
The small set of mathematical ideas used during one learning step
numbers
x, w, b
Represent one example and what the model can change
dot product
z = w·x + b
Combine inputs with learned importance
function
ŷ = f(z)
Turn the score into the required output
loss
L(y, ŷ)
Measure how wrong the prediction is
gradient
∇wL
Tell each weight how loss changes
Scalars, Vectors, Matrices and Tensors Describe the Shape of Data
A scalar is one number, such as one loss value. A vector is an ordered list, such as the three features of one house. A matrix has rows and columns, so it can store several houses as rows and their features as columns. Tensor is the general name for an array with any number of axes; scalars, vectors and matrices are lower-rank tensors.
From one number to a batch: each new axis answers another question
Scalar
7
shape [ ]
one value
Vector
[2, 5, 8]
shape [3]
three values on one axis
Matrix
[[1,2,3],[4,5,6]]
shape [2,3]
two rows × three columns
3-D tensor
2 × 3 × 4
shape [2,3,4]
three named axes
Batch tensor
N × C × H × W
shape [8,3,32,32]
eight colour images
| Object | Plain meaning | Neural-network example | Shape |
|---|---|---|---|
| Scalar | one number | temperature 24; loss 0.18 | no axes / shape [] |
| Vector | ordered list | one house: [area, bedrooms, age] | one axis / shape [3] |
| Matrix | rows and columns | four houses × three features | two axes / shape [4,3] |
| Higher-order tensor | more axes | image batch: examples × channels × height × width | four axes / [N,C,H,W] |
Shape records the length of each axis, in order. A 2×3 matrix has 2 rows and 3 columns. If rows are training examples and columns are features, the matrix contains 2 examples with 3 features each. Order matters: [32,3,224,224] commonly means 32 colour images, while [3,32,224,224] assigns entirely different meanings to the first two axes.
A Dot Product Performs One Neuron's Weighted Sum
A neuron pairs each input with one weight. The weight is an adjustable multiplier: a positive value preserves the input's direction, a negative value reverses it, and a larger magnitude creates a stronger contribution. Multiplication forms each contribution; addition combines all contributions into one score.
Manual dot product
Choose input vector x=[2,3] and weight vector w=[0.5,1.0] as teaching values. The first input pairs with the first weight because both occupy position 1; the second pair occupies position 2.
x · w = (2 × 0.5) + (3 × 1.0)
= 1 + 3
= 4
Why add the products? The neuron needs one score representing the combined evidence from both inputs. A bias can then shift that score: with b=−1, z=x·w+b=4−1=3. Here x would come from data; w and b are teaching parameters that training would normally learn.
A layer evaluates several neurons for several examples at once using matrix multiplication. Its compact formula is Z=XW+b: X is the batch, W contains one column of weights for each neuron, b contains one bias per neuron, and Z contains the resulting pre-activation scores.
Why [4,3] multiplied by [3,2] produces [4,2]
X [4,3]
4 examples
3 features per example
×
W [3,2]
3 incoming features
2 neurons
→
Z [4,2]
4 examples
2 neuron scores each
Functions Map Inputs to Outputs
A function is a rule: supply an input and receive an output. A layer is a function of both its data and its parameters. Several layers compose functions, so a small change early in the network can affect every later result.
Linear rule
z=w·x+b
combines information
Activation
a=f(z)
adds a useful nonlinear response
Loss
L(y,ŷ)
compares target y with prediction ŷ
Without nonlinear activations, multiplying several linear layers still collapses to one linear transformation. That is why activation functions are not a decorative extra.
A Derivative Asks: “If This Weight Moves, What Happens to Loss?”
A derivative is a local rate of change. Imagine the simple function L(w)=w². At w=3, L=9. If w increases to 3.01, L becomes 3.01²=9.0601. The loss changed by 0.0601 when the weight changed by 0.01, so the nearby slope is 0.0601÷0.01=6.01—close to the exact derivative 2w=6 at w=3.
For L(w)=w² at w=3, the derivative is positive
Partial derivatives hold the other weights still
Use prediction ŷ=2w₁+3w₂ and loss L=½(ŷ−10)². Choose w₁=1 and w₂=1 for this teaching point. Then ŷ=2(1)+3(1)=5 and ŷ−10=−5.
∂L/∂w₁ = (ŷ−10) × 2
= −5 × 2
= −10
∂L/∂w₂ = (ŷ−10) × 3
= −5 × 3
= −15
The 2 and 3 come from the input coefficients multiplying w₁ and w₂. The gradient collects both answers as ∇L=[−10,−15]. Its negative entries say that a small increase in either weight would locally reduce this loss; the different magnitudes show different sensitivities.
Gradient descent uses wnew=w−η(∂L/∂w), where η is a developer-chosen learning rate. A zero gradient can mean a flat point; a very large gradient can cause an unstable step. Neither automatically proves that the model has found the best possible solution.
The Chain Rule Connects a Weight to the Final Loss
A deep network is a chain of functions. The chain rule multiplies local sensitivities along that chain. For a tiny model ŷ=wx and squared loss L=(ŷ−y)²:
One complete weight update
Use x=2, target y=4, current weight w=1.5 and learning rate η=0.1.
Forward
ŷ=wx=1.5×2=3
L=(3−4)²=1
Backward
∂L/∂ŷ=2(ŷ−y)=−2
∂ŷ/∂w=x=2
∂L/∂w=(−2)(2)=−4
Update
wnew=1.5−0.1(−4)
=1.9
Check
new ŷ=1.9×2=3.8
new L=(3.8−4)²=0.04
Meaning: multiplying the two local derivatives tells the weight how it influenced loss. This step reduced loss from 1 to 0.04; other examples and learning rates can behave differently.
Probability and Logarithms Explain Classification Confidence
For mutually exclusive classes, a model often converts scores into a probability distribution: non-negative values that sum to 1. A probability of 0.8 is a model statement under its assumptions, not a guarantee that eight of every ten individual predictions are correct. Calibration must be measured.
Cross-entropy uses −log(ptrue). If the true-class probability is 0.8, loss is about 0.223; at 0.1 it is about 2.303. The logarithm therefore penalizes a confident wrong prediction much more strongly. Expected value, E[X]=Σxp(x), is a probability-weighted average and appears in risk, loss and sampling objectives.
Norm ‖x‖
vector length
Used in: gradient clipping; distance
Cosine similarity
directional similarity
Used in: embeddings; contrastive learning
Mean and variance
centre and spread
Used in: normalization; initialization
Verify the Hand Calculation with Automatic Differentiation
import torch
x = torch.tensor(2.0)
y = torch.tensor(4.0)
w = torch.tensor(1.5, requires_grad=True)
prediction = w * x
loss = (prediction - y) ** 2
loss.backward()
print(prediction.item()) # 3.0
print(loss.item()) # 1.0
print(w.grad.item()) # -4.0
with torch.no_grad():
w -= 0.1 * w.grad
print(w.item()) # about 1.9Automatic differentiation calculates the same chain rule from recorded operations. It saves bookkeeping; it does not remove the need to check shapes, loss definitions and gradient values.
Common Mathematical Mistakes in Neural-Network Code
| Symptom | Mathematical cause | Check |
|---|---|---|
| Matrix multiplication error | Inner dimensions do not match | Write every intermediate shape before coding |
| Code runs but result has unexpected shape | Broadcasting aligned an unintended axis | Inspect operands and result; add dimensions explicitly |
| Loss becomes NaN/∞ | Overflow, division/log near zero or exploding values | Check min/max/finite values and use stable library losses |
| No learning | Disconnected graph, zero/saturated derivatives or wrong sign | Inspect gradients and test one manual derivative |
| Update makes loss larger | Step too large or batch gradient differs | Reduce learning rate and test a controlled tiny case |
| High confidence is unreliable | Probabilities are not calibrated | Measure calibration on held-out representative data |
What to Carry into the Next Lessons
Read every neural-network formula as a story about quantities and shapes.
- Vectors and matrices organize examples, features and weights.
- A dot product is a weighted sum; layers perform many of them together.
- Functions compose the prediction, and loss turns quality into a number.
- Derivatives describe local sensitivity; the gradient gathers it for all parameters.
- The chain rule carries responsibility backward; the optimizer uses it to update weights.
- Probability describes uncertainty, while logs make probability-based losses practical.