TExcelTAD
Home › Generative AI & LLMs › Neural Network Basics

Neural Network Basics

An LLM is a neural network: a large function made of simple pieces, with billions of adjustable numbers called parameters (weights and biases). Training nudges these numbers until the function's outputs match the training data. This lesson builds the pieces by hand.

One neuron

A neuron takes inputs, multiplies each by a weight, adds a bias, and passes the sum through a non-linear activation function:

text
output = activation(w1·x1 + w2·x2 + … + b)
python · try it yourself
import math

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

def neuron(inputs, weights, bias):
    z = sum(x * w for x, w in zip(inputs, weights)) + bias
    return sigmoid(z)

# A neuron that "fires" when it is warm AND sunny
weights, bias = [4.0, 4.0], -6.0
for warm, sunny in [(0, 0), (0, 1), (1, 0), (1, 1)]:
    print(f"warm={warm} sunny={sunny} -> {neuron([warm, sunny], weights, bias):.3f}")
warm=0 sunny=0 -> 0.002
warm=0 sunny=1 -> 0.119
warm=1 sunny=0 -> 0.119
warm=1 sunny=1 -> 0.881

Here we chose the weights by hand. The magic of machine learning is that the weights can be learned.

Learning with gradient descent

Training repeats three steps:

  1. Forward pass — compute predictions with the current weights.
  2. Loss — measure how wrong they are (one number).
  3. Backward pass — compute the gradient: how the loss changes if each weight changes a little. Then move every weight a small step (the learning rate) in the direction that reduces the loss.

The backward pass is computed automatically by backpropagation, which applies the chain rule from calculus through every layer.

python · try it yourself
import numpy as np

# Learn the AND function from examples
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([0, 0, 0, 1], dtype=float)

w = np.zeros(2)
b = 0.0
lr = 1.0
for step in range(1, 1001):
    pred = 1 / (1 + np.exp(-(X @ w + b)))           # forward
    loss = np.mean((pred - y) ** 2)                 # loss
    grad_z = 2 * (pred - y) * pred * (1 - pred) / len(y)
    w -= lr * (X.T @ grad_z)                         # backward + update
    b -= lr * grad_z.sum()
    if step in (1, 10, 100, 1000):
        print(f"step {step:4}: loss={loss:.4f}")

print("weights:", np.round(w, 2), "bias:", round(b, 2))
print("predictions:", np.round(pred, 2))
step    1: loss=0.2500
step   10: loss=0.1817
step  100: loss=0.0596
step 1000: loss=0.0057
weights: [4.64 4.64] bias: -7.06
predictions: [0.   0.08 0.08 0.9 ]

The loss falls and the predictions approach [0, 0, 0, 1]. Nobody typed the weights in: they were discovered.

Layers: why depth matters

A single neuron can only draw a straight line between classes. Some patterns, like XOR ("exactly one input is on"), need more. Stack neurons into layers and the network can learn curved, complex boundaries. The hidden layer learns its own intermediate features.

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(1)   # try 0: training gets stuck!
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)    # XOR

W1 = rng.normal(0, 1, (2, 4)); b1 = np.zeros(4)   # 2 inputs -> 4 hidden neurons
W2 = rng.normal(0, 1, (4, 1)); b2 = np.zeros(1)   # 4 hidden -> 1 output
sig = lambda z: 1 / (1 + np.exp(-z))

losses = []
for step in range(3000):
    h = np.tanh(X @ W1 + b1)                      # hidden layer
    out = sig(h @ W2 + b2)                        # output layer
    losses.append(float(np.mean((out - y) ** 2)))
    d_out = 2 * (out - y) * out * (1 - out) / len(X)
    d_h = (d_out @ W2.T) * (1 - h ** 2)           # backpropagation
    W2 -= 2.0 * h.T @ d_out; b2 -= 2.0 * d_out.sum(0)
    W1 -= 2.0 * X.T @ d_h;   b1 -= 2.0 * d_h.sum(0)

plt.plot(losses, color="#7c3aed")
plt.xlabel("training step"); plt.ylabel("loss"); plt.title("Learning XOR")
plt.show()
print("parameters:", W1.size + b1.size + W2.size + b2.size)
print("XOR predictions:", np.round(out.ravel(), 2))
print(f"final loss: {losses[-1]:.4f}")
parameters: 17
XOR predictions: [0.   0.99 0.99 0.01]
final loss: 0.0001

The predictions approach [0, 1, 1, 0]. Change the seed to 0 and run again: the same network gets stuck with two predictions near 0.5. The starting weights matter, which is why real training uses careful initialisation and optimisers smarter than this plain gradient descent.

This network has 17 parameters. A large language model has the same ingredients — matrix multiplications, biases, non-linear activations, a loss, backpropagation — repeated across many layers and many billions of parameters.

Vocabulary

Term Meaning
Parameter A learned number (weight or bias)
Layer A group of neurons computed together as one matrix multiplication
Activation Non-linear function (sigmoid, tanh, ReLU, GELU…) applied after each layer
Loss A single number measuring how wrong the predictions are
Gradient Direction and size of change in the loss for each parameter
Learning rate How big a step each update takes
Epoch / step One pass over the data / one update

For language models, the loss is cross-entropy: how surprised the model was by the actual next token. Lower surprise on held-out text means a better model.

Note: Without non-linear activations, any stack of layers collapses into a single linear layer. Non-linearity is what lets depth add expressive power.

Go further: Neurons, Layers and the Forward Pass opens the Deep Learning course, which builds networks like these in NumPy and then in PyTorch.

Test yourself

What are the 'parameters' of a neural network?

  1. The prompts it receives
  2. The learned weights and biases
  3. The number of layers only
  4. The training examples

What does backpropagation compute?

  1. The next token
  2. The gradient of the loss with respect to every parameter
  3. The vocabulary
  4. The learning rate

Why couldn't a single neuron learn XOR?

  1. XOR needs a non-linear boundary; one neuron only separates classes with a straight line
  2. XOR has too many inputs
  3. Neurons can't output 0
  4. XOR can't be expressed with numbers