0%

neural networks from first principles, part 1

my first notes from exploring ai: neurons, loss, backprop and a tiny network that learns xor

i started with backend, then web3, and now i am exploring ai too. neural networks are usually taught as piles of formulas, code recipes or history. i wanted one place where the math, the reason and the code sit together, so these notes follow that. they are adapted from the paper "neural networks from first principles" and cover its first half. part 2 comes later.

everything below uses plain text math, and every number comes from code you can run yourself with python and numpy.

the problem: learning a rule from examples

some problems are easy to state and hard to solve with hand written rules. which digit is in this picture? is this medical signal normal? what value comes next? we can collect examples, but we cannot write rules for every variation.

a neural network is a function with adjustable numbers, called parameters, that we fit to examples. we want it to work well on examples it has never seen. the word "neural" is historical: early models were loosely inspired by brain cells, but today a network is best seen as many simple math operations stacked together.

a little math you need

you only need five ideas:

  • derivative: how much the output changes when the input changes a tiny bit. for f(x) = x^2 the slope is 2x.
  • dot product: multiply matching entries and add them up. [1, 2] . [3, 4] = 1*3 + 2*4 = 11.
  • matrix times vector: many dot products at once, one per row.
  • gradient: the list of slopes, one for each input direction.
  • chain rule: if y depends on x and L depends on y, then dL/dx = dL/dy * dy/dx. slopes multiply as you go through a chain. this one idea is the whole engine of backpropagation.

one more: the logarithm turns probabilities into penalties. the loss -log(p) is small when p is near 1 and huge when p is near 0:

probability given to the right answer penalty -log(p)
0.9 0.105
0.01 4.605

so the model is lightly punished for being confidently right, and heavily punished for being confidently wrong.

the neuron

an artificial neuron takes some inputs, makes a weighted sum, adds a bias, and passes the result through an activation function:

z = w . x + b
a = g(z)

what one artificial neuron does in four steps

for example, with x = [1, 0], w = [0.2, -0.3] and b = 0.1, we get z = 0.3. using the sigmoid g(z) = 1 / (1 + e^-z), the output is a = 0.5744. the sigmoid squashes any number into a smooth s shape between 0 and 1.

for several classes, softmax does a similar job. it makes every score positive with e^z, then divides by the total so the outputs add up to 1. for the scores [2, 1, 0] it gives about [0.665, 0.245, 0.090].

why we need a nonlinearity

here is a fun fact. if you stack linear layers with nothing in between, they collapse into one linear layer:

y = W2 (W1 x + b1) + b2 = (W2 W1) x + (W2 b1 + b2)

so depth buys you nothing without an activation. this script proves it, and then shows a relu breaking the collapse:

import numpy as np
 
rng = np.random.default_rng(0)
W1, b1 = rng.normal(size=(4, 3)), rng.normal(size=4)
W2, b2 = rng.normal(size=(2, 4)), rng.normal(size=2)
x = rng.normal(size=3)
 
# two linear layers with nothing in between
two_layers = W2 @ (W1 @ x + b1) + b2
 
# one linear layer with merged weights
W_eq = W2 @ W1
b_eq = W2 @ b1 + b2
one_layer = W_eq @ x + b_eq
print("two layers vs one layer :", np.max(np.abs(two_layers - one_layer)))  # about 1e-16
 
# now put a relu in the middle and the collapse breaks
relu = lambda z: np.maximum(0, z)
with_relu = W2 @ relu(W1 @ x + b1) + b2
print("with a ReLU in between  :", np.max(np.abs(with_relu - one_layer)))  # clearly not zero

you should see a difference near 4e-16 (just rounding noise) for the two linear layers, and a clearly non zero number once a relu sits in the middle.

this is also the story of the perceptron, the early model that outputs 1 when w . x + b > 0. it cannot solve xor (output 1 only when the two inputs differ), because no single straight line separates those four points. we will fix that in a moment with a hidden layer.

activation functions

name formula range note
sigmoid 1 / (1 + e^-z) 0 to 1 good for binary outputs, can saturate
tanh tanh(z) -1 to 1 centered on zero, can saturate
relu max(0, z) 0 to infinity the usual hidden layer default, dead units possible
leaky relu max(0.01 z, z) any reduces dead units

the slope of the activation matters, because backpropagation multiplies by it: the sigmoid's slope is a (1 - a), tanh's is 1 - a^2, and relu's is 0 or 1.

layers are matrix multiplication

a dense layer computes all its neurons at once:

z = W a_prev + b
a = g(z)

if the layer has n_l neurons and the previous layer has n_(l-1), then W has shape n_l x n_(l-1). to process a whole batch of m examples, put them in as columns, and the same weights apply to every example. that is why networks run so well on gpus: it is all big matrix products.

a network with one hidden layer of enough nonlinear units can approximate any continuous function, which is the universal approximation theorem. it says an answer exists. it does not say how many units you need or how to find the weights, and it does not promise the network will work on new data.

the loss: how wrong am i?

a loss function turns "how wrong" into one number. the training objective is the average loss over the dataset. two losses cover most cases:

squared error:  L = 0.5 (prediction - target)^2        slope = prediction - target
cross entropy:  L = -[y log(p) + (1 - y) log(1 - p)]   for a binary yes or no target

squared error makes big mistakes cost a lot. cross entropy is the -log penalty from earlier, and it has a nice meaning: minimizing it is the same as maximizing the likelihood of the labels under a bernoulli model. with several classes and a one hot target, it keeps only -log of the probability given to the correct class.

gradient descent: walking downhill in fog

if the loss is a hilly landscape, gradient descent feels the slope under its feet and steps downhill:

theta_next = theta - eta * gradient

here eta is the learning rate, the step size. try the loss J(w) = w^2, whose slope is 2w:

# gradient descent on j(w) = w^2, whose slope is 2w
w, lr = 3.0, 0.1
for step in range(5):
    print(step, round(w, 4))
    w = w - lr * 2 * w
0 3.0
1 2.4
2 1.92
3 1.536
4 1.2288

each step shrinks w by a factor of 0.8, so it walks toward the minimum at 0. a bigger eta goes faster but can overshoot and bounce, and a tiny one crawls.

backpropagation

backpropagation is the chain rule applied layer by layer from the output back to the input. define the error signal d for a layer as how sensitive the loss is to that layer's z. then:

output layer:     d_L = (dLoss/da) * g'(z)
weight gradient:  dLoss/dW = d  (outer product)  a_prev
bias gradient:    dLoss/db = d
go back a layer:  d_prev = (W^T d) * g'(z_prev)

in words: at the output, the error signal is the loss slope times the activation slope. the gradient for a weight is the error signal times the input that weight saw. to go back one layer, send the error through the transposed weights, then gate it by that layer's activation slope. a computational graph records all these operations, and reverse mode automatic differentiation (what pytorch does for you) walks it backward. that is efficient because there is one scalar loss but millions of parameters.

all of training is just one loop, repeated:

the training loop: forward pass, loss, backward pass, update

a worked example you can check

a tiny 2 input, 2 hidden, 1 output network with sigmoids and squared error. the input is [1, 0] and the target is 1. this script does the forward pass, the backward pass by hand, and then checks the gradients by nudging every weight a tiny amount up and down:

import numpy as np
 
sigmoid = lambda z: 1 / (1 + np.exp(-z))
 
x = np.array([1.0, 0.0])
y = np.array([1.0])
W1 = np.array([[0.2, -0.3], [0.4, 0.1]])
b1 = np.array([0.0, 0.1])
W2 = np.array([[0.3, -0.2]])
b2 = np.array([0.05])
 
 
def forward(W1, b1, W2, b2):
    z1 = W1 @ x + b1
    a1 = sigmoid(z1)
    z2 = W2 @ a1 + b2
    a2 = sigmoid(z2)
    loss = 0.5 * np.sum((a2 - y) ** 2)
    return z1, a1, z2, a2, loss
 
 
z1, a1, z2, a2, loss = forward(W1, b1, W2, b2)
 
# backward pass: the error signal d, then the gradients
d2 = (a2 - y) * a2 * (1 - a2)  # (a2 - y) from the loss, a2 (1 - a2) is the sigmoid slope
dW2, db2 = np.outer(d2, a1), d2
d1 = (W2.T @ d2) * a1 * (1 - a1)  # push back through the weights, then gate by the slope
dW1, db1 = np.outer(d1, x), d1
 
# gradient check: nudge every weight in w1 a tiny bit up and down
eps = 1e-6
numeric = np.zeros_like(W1)
for i in range(2):
    for j in range(2):
        up, down = W1.copy(), W1.copy()
        up[i, j] += eps
        down[i, j] -= eps
        numeric[i, j] = (forward(up, b1, W2, b2)[-1] - forward(down, b1, W2, b2)[-1]) / (2 * eps)
 
print("z1, a1 :", z1, np.round(a1, 6))
print("z2, a2 :", np.round(z2, 6), np.round(a2, 6))
print("loss   :", round(loss, 6))
print("d2     :", np.round(d2, 6))
print("dW2    :", np.round(dW2, 6))
print("d1     :", np.round(d1, 6))
print("dW1    :", np.round(dW1, 6).tolist())
print("check  :", np.max(np.abs(dW1 - numeric)) / np.max(np.abs(dW1)))  # tiny, so backprop is right

the output matches the paper's numbers exactly:

z1, a1 : [0.2 0.5] [0.549834 0.622459]
z2, a2 : [0.090458] [0.522599]
loss   : 0.113956
d2     : [-0.119106]
dW2    : [[-0.065489 -0.074139]]
d1     : [-0.008844  0.005598]
dW1    : [[-0.008844, -0.0], [0.005598, 0.0]]
check  : 1.2e-09

the last line is the gradient check. the relative difference between my hand derived gradients and the numerical ones is about 1e-9, so backprop is correct. notice the second column of dW1 is zero: the second input was 0, so it had no influence on the output. a gradient check like this is a great habit whenever you write backprop yourself.

train a tiny network to solve xor

now the payoff. here is the same loop on the very problem a single perceptron cannot solve. it uses 4 hidden tanh units, a sigmoid output, and cross entropy, which makes the output error signal simply prediction - target:

import numpy as np
 
rng = np.random.default_rng(1)
sigmoid = lambda z: 1 / (1 + np.exp(-z))
 
# four examples, one per column. xor: output 1 only when the inputs differ.
X = np.array([[0, 0, 1, 1], [0, 1, 0, 1]], dtype=float)
Y = np.array([[0, 1, 1, 0]], dtype=float)
 
W1, b1 = rng.normal(size=(4, 2)), np.zeros((4, 1))  # 4 hidden units
W2, b2 = rng.normal(size=(1, 4)), np.zeros((1, 1))
lr, m = 1.0, X.shape[1]
 
for step in range(5001):
    # forward
    A1 = np.tanh(W1 @ X + b1)
    A2 = sigmoid(W2 @ A1 + b2)
    loss = -np.mean(Y * np.log(A2) + (1 - Y) * np.log(1 - A2))
 
    # backward (sigmoid with cross entropy simplifies to a2 - y)
    dZ2 = (A2 - Y) / m
    dW2, db2 = dZ2 @ A1.T, dZ2.sum(axis=1, keepdims=True)
    dZ1 = (W2.T @ dZ2) * (1 - A1**2)  # the slope of tanh
    dW1, db1 = dZ1 @ X.T, dZ1.sum(axis=1, keepdims=True)
 
    # update
    W1 -= lr * dW1
    b1 -= lr * db1
    W2 -= lr * dW2
    b2 -= lr * db2
 
    if step % 1000 == 0:
        print(f"step {step:4d}  loss {loss:.4f}")
 
print("predictions:", np.round(A2, 3))  # should be close to [0, 1, 1, 0]

when i ran it, the loss fell from 0.68 at the start to 0.0005, and the predictions came out as:

predictions: [[0.    0.999 0.999 0.001]]

that is 0, 1, 1, 0, which is exactly xor. one hidden layer with a nonlinearity was all it took.

better optimizers and learning rates

plain gradient descent on the whole dataset is slow, so in practice we use mini batches and smarter updates:

method idea strength watch out for
sgd gradient from a mini batch simple and scalable noisy, sensitive to eta
momentum add a running average of past gradients calms the zigzag one more setting
rmsprop scale each step by recent gradient size adapts per parameter can be aggressive
adam momentum plus rmsprop with bias correction a strong default may generalize differently

a learning rate schedule lowers eta over time. step decay is eta_t = eta_0 * gamma^floor(t / s): start at eta_0 and multiply by gamma every s steps.

cheat sheet

idea one line
neuron a = g(w . x + b)
nonlinearity without it, stacked layers collapse into one
layer z = W a_prev + b, all neurons at once
loss one number for how wrong, averaged over the data
gradient descent theta = theta - eta * gradient
backprop the chain rule, layer by layer, output to input
gradient check nudge a weight up and down and compare slopes
adam momentum plus per parameter scaling

try it yourself

  1. in descent.py, set lr to 1.1 and then 0.01. describe what happens to w each time.
  2. in xor.py, change the hidden size from 4 to 2, then try a few different seeds. does it always converge?
  3. in backprop_by_hand.py, change the target y to 0 and predict the sign of d2 before you run it.

what is next

part 2 covers what makes training go wrong or right: initialization, vanishing and exploding gradients, overfitting and regularization. after that come the main network families and some small experiments. i am learning this in public, so if i got something wrong, i want to know.


Last updated: November 24, 2026

Enjoyed this? Let's talk

I write about backend, engineering and web3 as I learn them. Always happy to compare notes.

Keep reading