How Neural Networks Work

Updated · 8 min read
mediumPython 3.13aideep-learningneural-networksneuronsactivation-functions

A neural network is a model built from many simple units called neurons, arranged in layers. Each neuron multiplies its inputs by weights, adds a bias, and passes the result through an activation function. One neuron can only draw a straight line through data, but layers of them can learn very complicated patterns: recognizing handwriting, understanding speech, or writing text as a large language model does.

Deep learning is machine learning with neural networks that have many layers. This chapter builds up from one neuron to a network trained in PyTorch that reads handwritten digits.

The Parts of a Neural Network

PartDescription
NeuronIt is used to compute a weighted sum of its inputs plus a bias, then apply an activation function
WeightA number that sets how strongly an input affects a neuron; learned in training
BiasA number added to the weighted sum, shifting the neuron's starting point; learned too
Activation functionIt is used to bend the output, so layers can learn more than straight lines
LayerA group of neurons that all receive the same inputs
Input, hidden and output layersThe data comes in, hidden layers transform it, and the output layer gives the answer
ParametersAll the weights and biases together; what training adjusts

Example: One Neuron

A neuron is a weighted sum and an activation; layers of them do more

This neuron decides whether to send a student a study reminder, from two inputs.

Python
import numpy as np
 
def relu(z):
    return np.maximum(0, z)          # negative becomes 0, positive passes through
 
def sigmoid(z):
    return 1 / (1 + np.exp(-z))      # squashes any number into 0 to 1
 
# One neuron: should a student get a study reminder? Inputs: hours studied this week, days since last login
x = np.array([2.0, 6.0])
w = np.array([-0.8, 0.5])            # weights: more hours lowers the need, more days away raises it
b = -0.5                             # bias: shifts the starting point
z = w @ x + b                        # weighted sum: -0.8*2 + 0.5*6 - 0.5
print("Weighted sum z:", round(z, 2))
print("Sigmoid output:", round(sigmoid(z), 3), "-> send a reminder" if sigmoid(z) > 0.5 else "-> no reminder")
print("ReLU of -2, 0, 3:", relu(np.array([-2, 0, 3])))
Output
Weighted sum z: 0.9
Sigmoid output: 0.711 -> send a reminder
ReLU of -2, 0, 3: [0 0 3]

Explanation: The weighted sum is -0.8 × 2 + 0.5 × 6 - 0.5 = 0.9. The negative weight on hours means studying more lowers the need for a reminder; the positive weight on days away raises it. Sigmoid turns 0.9 into 0.711, which reads like a probability, and since it's above 0.5 the neuron says "send a reminder". ReLU is the most common activation inside networks: it keeps positive numbers and turns negatives into 0.

Here the weights were chosen by hand. In a real network, training finds them, which is what the next two lessons explain.

Activation Functions

FunctionOutputUsed for
ReLU0 for negatives, unchanged for positivesHidden layers; the default choice
Sigmoid0 to 1A yes/no probability at the output
Tanh−1 to 1Hidden layers in older and recurrent networks
SoftmaxSeveral outputs that add up to 1Choosing one of several classes, like digits 0 to 9
None (linear)Any numberPredicting a number, like a price

Without activation functions, stacking layers would be pointless: a weighted sum of weighted sums is still one weighted sum, a straight line. The bend is what gives depth its power.

Example: Layers Solve What One Neuron Can't

XOR ("exclusive or") outputs 1 when exactly one of two inputs is 1. Plot the four cases and no single straight line separates the 1s from the 0s, so no single neuron can learn it. Two layers can:

Python
import numpy as np
 
# XOR: the output is 1 when exactly one input is 1. No single neuron can draw this boundary.
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
 
W1 = np.array([[1.0, 1.0],          # hidden layer: 2 inputs -> 2 neurons
               [1.0, 1.0]])
b1 = np.array([0.0, -1.0])
W2 = np.array([1.0, -2.0])          # output layer: 2 hidden neurons -> 1 output
b2 = 0.0
 
hidden = np.maximum(0, X @ W1 + b1)  # ReLU activation
output = hidden @ W2 + b2
for inputs, h, out in zip(X, hidden, output):
    print(f"inputs {inputs}  hidden {h}  output {out:.0f}")
Output
inputs [0 0]  hidden [0. 0.]  output 0
inputs [0 1]  hidden [1. 0.]  output 1
inputs [1 0]  hidden [1. 0.]  output 1
inputs [1 1]  hidden [2. 1.]  output 0

Explanation: Data flows through the network in a forward pass. X @ W1 + b1 computes both hidden neurons for all four inputs at once, and ReLU bends the result. The first hidden neuron counts the 1s; the second fires only when both inputs are 1. The output adds the first and subtracts twice the second, so 1, 1 gives 2 - 2 = 0. The hidden layer has turned a problem one neuron couldn't solve into one the output neuron can. Real networks learn their hidden features in the same way, but with many more neurons, chosen by training instead of by hand.

Kinds of Neural Network

KindBuilt forExample
Feedforward (fully connected)Tables of numbers; small imagesThis chapter's digit reader
Convolutional (CNN)ImagesPhoto tagging, medical scans
Recurrent (RNN)Sequences, one step at a timeOlder speech and text models
TransformerSequences, all positions at once with attentionLarge language models (see "Transformers and Attention, Simply")

Common Mistakes

Thinking neurons work like brain cells. The name is inspired by biology, but an artificial neuron is just arithmetic.

Forgetting the activation function. Without it, many layers collapse into one straight line.

Using sigmoid in every layer. ReLU trains faster in hidden layers; keep sigmoid and softmax for outputs.

Assuming bigger is always better. More layers and neurons need more data and can overfit, just like the deep trees in "Overfitting, Underfitting and Cross-Validation".

Interview Corner

What does an activation function do, and why is it needed?

It applies a non-linear bend to each neuron's weighted sum. Without it, any stack of layers equals a single linear layer, so the network could only learn straight-line patterns.

What are the parameters of a neural network?

Its weights and biases. Training adjusts them to reduce the loss; a network's size is usually given as its number of parameters.

Practice

Exercise: change the neuron. In the first program, try 8 hours studied and 1 day away. Does the neuron still send a reminder? What weighted sum makes sigmoid exactly 0.5?

Check your understanding:

  1. What does a neuron compute?
  2. Why can't one neuron learn XOR?
  3. What does the second hidden neuron in the XOR network detect?

Quick check: neural networks

4 questions
1What does one neuron compute?
2What does ReLU do?
3Why are activation functions needed?
4Which activation fits choosing one of 10 digits?

Key Takeaways

Quick reference

IdeaNumPy
One neuronsigmoid(w @ x + b)
A layer for a batchnp.maximum(0, X @ W + b)
ReLUnp.maximum(0, z)
Sigmoid1 / (1 + np.exp(-z))

Was this tutorial helpful?

Lesson 134 of 186