Skip to main content
LearnMLAcademy
Advanced10 min read

How Neural Networks Learn

Follow how artificial neurons compute activations and update synaptic weights, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Beginner Lesson

Neural Networks Explained

Learn what a neural network is using one simple student-result example—before we introduce formulas or code.

You do not need calculus for this lesson.

If you understand “important clues,” “a guess,” and “learning from a mistake,” you already have the ideas needed to begin.

What Is a Neural Network?

A neural network is a computer model that learns a relationship between inputs and an output. It contains small calculation units called neurons, arranged in layers and joined by numbered connections called weights.

During training, the network sees examples with known answers. It makes guesses, checks its mistakes, and slowly changes its weights. After enough useful examples, it can make a prediction for an example it has not seen before.

Important: an artificial neuron is not a real brain cell. It is only a few mathematical operations. The word “neural” comes from historical inspiration, not because the model thinks like a person.

Biological neuron vs artificial neuron

The biological comparison is useful as a memory aid: dendrites receive signals, synapses affect their strength, the cell body combines them, and the axon carries a response. An artificial neuron borrows that rough story using inputs, weights, a calculation, an activation function, and an output.

A biological neuron compared with an artificial neuronDendrites, synapses, cell body, firing response, and axon are compared with inputs, weights, weighted sum and bias, activation, and output.BIOLOGICAL NEURONARTIFICIAL NEURONDendritesreceive signalsCell bodycombines signalsAxoncarries outputSynapses change how strongly signals influence the cell.x₁w1x₂w2x₃w3Σ+bgcombineactivateoutput ŷInputsWeightsNeuronPredictionThis is a memory aid—not a claim that an artificial network thinks like a brain.
Figure 2: The biological analogy helps name the parts, but the artificial neuron is only a mathematical calculation.

From one neuron to a complete network

A network connects many artificial neurons in layers. The following diagram shows those parts in our student-result problem.

A labelled neural network that predicts whether a student will passThree input values connect to four hidden neurons, which connect to one output showing a 67 percent chance of passing.INPUT LAYERFacts we give the networkHIDDEN LAYERCombines the factsOUTPUT LAYERGives the answer0.8Study hours0.9Attendance0.7SleepH1H2H3H467%chance to passLINES AREweightsEach circle is one artificial neuron
Figure 3: Information moves from left to right. The numbers are illustrative, not a real student assessment.

The Five Key Components of a Neural Network

Before solving an example, first see what a neural network is made of. These five ideas appear in every later section.

1

Neurons (or nodes)

Small calculation units. A neuron receives numbers, combines them, and sends a new number forward.

2

Connections

Lines that carry a number from one neuron to another. Each connection has a weight.

3

Weights and biases

Numbers the network learns. Weights control the strength of connections; a bias gives a neuron an adjustable starting push.

4

Propagation

The movement of calculations through the network. A forward pass produces an answer; a backward pass carries information about the error.

5

Learning rule

The method for improving the parameters. Backpropagation finds how each parameter affected the error, and an optimizer changes it a little.

The five parts of an artificial neuronInput values travel along weighted connections, are added with a bias, pass through an activation function, and produce an output.1 · INPUTS2 · WEIGHTED CONNECTIONS3 · ADD + BIAS4 · ACTIVATION5 · OUTPUTx₁w1x₂w2x₃w3Σweighted sumbias bg(z)activation ruleŷoutput = activation(weighted inputs + bias)
Figure 1: The complete journey through one artificial neuron. Every label is explained below before it is used later.

Learning happens in three repeating stages

Stage 1

Input computation

Data enters as numbers. Each neuron multiplies its inputs by weights, adds them, and adds its bias.

Stage 2

Output generation

The values move forward through the layers until the network produces a prediction.

Stage 3

Iterative refinement

The prediction is compared with the known answer. The network adjusts weights and biases, then tries again.

Beginner Word Bank: Know These Terms Before We Use Them

You do not have to memorize this list now. Use it as a map: when a word appears later, you will already know its plain meaning.

Input / feature

A number given to the network, such as study time.

Neuron / node

A unit that multiplies, adds, and activates numbers.

Connection

A path that carries a value from one neuron to another.

Weight (w)

A learned number showing the strength and direction of a connection.

Bias (b)

A learned starting adjustment added inside a neuron.

Weighted sum (z)

Inputs multiplied by weights, added together, then combined with the bias.

Activation function

A rule that changes the weighted sum into the neuron’s outgoing signal.

ReLU

Rectified Linear Unit: it changes negative values to 0 and keeps positive values.

Sigmoid

An activation that turns a number into a value between 0 and 1, often used for a yes/no probability.

Softmax

An output activation that turns several class scores into probabilities adding to 100%.

Layer

A group of neurons working at the same stage: input, hidden, or output.

Prediction / output (ŷ)

The answer produced by the network. The symbol ŷ means “predicted answer.”

Label / target (y)

The known correct answer used during training or evaluation.

Forward pass

Moving calculations from the inputs to the prediction. Also called forward propagation.

Loss

One number that measures how wrong the prediction is. Lower is usually better.

Backpropagation

Calculating how much each parameter contributed to the loss, moving from output toward input.

Optimizer / learning rule

The rule—such as SGD or Adam—that uses gradients to update parameters.

Parameter

Any number the network learns; weights and biases are parameters.

Batch

A small group of training examples processed together.

Epoch

One complete pass through all training examples.

Learning rate

A setting that controls how large each parameter update is.

Notation tip: y is the correct answer; ŷ (“y-hat”) is the network’s predicted answer.

Start With a Real-Life Problem

Our example throughout this lesson

Which students may need extra help before an exam?

A teacher has records from previous students: their study time, attendance, sleep, and whether they passed. The teacher wants a program that can examine a new student’s information and estimate the chance of passing.

Information in

Study, attendance, sleep

Pattern to learn

Which combinations usually lead to passing?

Answer out

A probability such as 67%

We could write fixed rules such as “if study time is above six hours, predict pass.” But real life is rarely one rule. A student may study less and have excellent attendance, or study more but sleep very little. A neural network can learn how several clues work together from examples.

What Happens Inside One Neuron?

A neuron has three small jobs: multiply each input by its weight, add those results and the bias, then activate the result. The diagram follows one imaginary student. To keep the arithmetic readable, we manually scale each teaching input against a stated reference: 8 study hours out of 10 gives 8÷10=0.8; 90% attendance gives 90÷100=0.9; and 7 sleep hours against a 10-hour reference gives 7÷10=0.7. These are teaching choices, not a recommended school-scoring system.

The calculation inside one artificial neuronStudy, attendance, and sleep inputs are multiplied by weights, added with a bias, and passed through an activation function.0.8Study× 0.70.9Attendance× 0.80.7Sleep× 0.3ADDweighted clues+ bias (−0.8)z = 0.69ACTIVATIONturns the scoreinto a useful output0.67outputMultiply → add → activate. That is the basic job of a neuron.
Figure 4: A neuron is a short mathematical recipe, not a tiny human brain.

The same calculation, one line at a time

1

Multiply every clue by its weight

(0.8 × 0.7) + (0.9 × 0.8) + (0.7 × 0.3)

2

Add the three answers

0.56 + 0.72 + 0.21 = 1.49

3

Add the bias

1.49 + (−0.80) = 0.69

4

Apply sigmoid activation

sigmoid(0.69) ≈ 0.67

5

Read the output

The neuron estimates a 67% chance of passing.

These weights were chosen only to show the arithmetic. In a real network, training discovers useful weight and bias values from data.

Why Do We Need More Than One Neuron?

One neuron can form one simple decision. Many neurons can notice different combinations. One hidden neuron may respond strongly to “high attendance and moderate study,” while another may respond to “long study but little sleep.” The next layer can combine those smaller patterns into a better prediction.

Layer 1

Input layer

Receives values

It does not learn a secret meaning; it holds the facts we provide.

Layer 2

Hidden layer(s)

Builds useful patterns

These layers are called hidden because we do not directly provide or read their answers.

Layer 3

Output layer

Answers the task

Its shape depends on whether we want a number, yes/no answer, or one of many classes.

Why is it called “deep” learning?

A deep neural network contains several learned layers between the input and output. “Deep” describes the stack of transformations—not human-like depth of thought.

How the Network Makes One Prediction

Moving information from input to output is called a forward pass (or forward propagation). Follow our student once through the network:

  1. 1

    Prepare the inputs

    Study, attendance, and sleep are converted to numbers on similar scales. Text or images would also need to be converted to numbers.

  2. 2

    Send values into the hidden layer

    Every hidden neuron receives the inputs, applies its own weights and bias, and uses an activation function.

  3. 3

    Pass hidden outputs forward

    Those outputs become the inputs for the next layer. The same simple neuron calculation happens again.

  4. 4

    Produce a final score

    The output neuron returns 0.67. For this teaching task we read that as an estimated 67% chance of passing.

  5. 5

    Apply a decision rule if needed

    If this teaching example uses 0.50 as its manually chosen threshold, 0.67 becomes “likely to pass.” The probability and threshold are different things.

How Does a Neural Network Learn?

At the beginning, weights are usually small, unhelpful numbers, so the guesses are poor. Training improves them using examples whose correct answers are known.

1

Look

Read one training example

→
2

Guess

Make a prediction

→
3

Check

Measure how wrong it was

→
4

Adjust

Change weights a little

↺ repeat
Figure 5: Training repeats this feedback loop with many examples.
Label / target

The correct answer attached to a training example.

In our example: pass = 1 and fail = 0.

Loss

One number that measures how wrong the model is.

In our example: predicting 0.20 when the answer is pass produces more loss than predicting 0.80.

Backpropagation

A method for finding how each weight contributed to the loss.

In our example: it sends responsibility for the error backward through the layers.

Optimizer

The rule that uses that information to update the parameters.

In our example: SGD or Adam moves each weight a small amount intended to reduce future loss.

One tiny learning moment

What happened?ValuePlain meaning
Known label1 (pass)This past student actually passed.
Network prediction0.35The model gave only a 35% pass chance.
LossHighThe guess was far from the known answer.
CorrectionSmall weight changesBackpropagation and the optimizer make the next guess slightly better.

One pass through all training examples is called an epoch. A small group processed together is a batch. The learning rate controls how large each update is. Too large can jump past a good solution; too small can make learning very slow.

Activation Functions, Without the Mystery

An activation function decides what signal a neuron sends onward. Without non-linear activations, many stacked layers would still behave like one simple straight-line rule.

ReLU

Usually used for: Hidden layers

Negative number → 0. Positive number → keep it.

−2 → 0, 3 → 3

Sigmoid

Usually used for: Yes/no output

Squeezes any number into the range 0 to 1.

0.67 can be read as 67%

Softmax

Usually used for: Many-class output

Turns several scores into probabilities that add to 100%.

cat 70%, dog 20%, bird 10%

Different Neural Networks for Different Data

“Neural network” is a family name. The shape of the network changes to suit the kind of information it receives. As a beginner, remember these main choices:

Dense / Feedforward network

Typical input: Rows of numbers

Data moves forward through fully connected layers.

Example: Student records, house prices, simple classification

→ → →

Convolutional neural network (CNN)

Typical input: Images and grids

Small filters look for local patterns such as edges and shapes.

Example: Recognizing a cat, reading an X-ray, detecting a road sign

▦ → ◫

Recurrent network (RNN, LSTM, GRU)

Typical input: Ordered sequences

A state carries information from earlier steps.

Example: Older text systems, speech, and time-series forecasting

○ ↻ ○

Transformer

Typical input: Long sequences and relationships

Attention lets each item consider other relevant items.

Example: Translation, chatbots, summarization, vision models

● ⇄ ●

Autoencoder

Typical input: Compressing and rebuilding data

An encoder compresses; a decoder reconstructs.

Example: Noise removal, anomaly detection, representation learning

wide → narrow → wide

Generative adversarial network (GAN)

Typical input: Creating new samples

A generator and a discriminator improve through competition.

Example: Synthetic faces, artwork, data augmentation

creator ⇄ judge

There are more specialized architectures, but these six give a beginner the most useful map. Later lessons on this site explain CNNs, recurrent networks, transformers, autoencoders, and GANs separately.

A Complete Two-Layer Forward Pass in NumPy

The single-neuron calculation above explains the basic operation. A layer performs several such calculations together. This executable example uses one student row, two hidden neurons, and one output neuron. Every array is written explicitly so the printed intermediate values can be checked.

X shape [1,3]

1 example × 3 input features

W1 shape [3,2]

3 incoming features × 2 hidden neurons

A1 shape [1,2]

2 hidden outputs for the one example

W2 shape [2,1]

2 hidden outputs × 1 final neuron

two_layer_forward.py
import numpy as np

X = np.array([[0.8, 0.9, 0.7]])
W1 = np.array([[ 0.5, -0.4],
               [ 0.3,  0.6],
               [-0.2,  0.1]])
b1 = np.array([0.1, -0.2])

Z1 = X @ W1 + b1
A1 = np.maximum(0, Z1)       # ReLU

W2 = np.array([[0.8],
               [0.4]])
b2 = np.array([-0.1])

Z2 = A1 @ W2 + b2
A2 = 1 / (1 + np.exp(-Z2))   # sigmoid

print("Z1:", Z1)  # [[0.63 0.09]]
print("A1:", A1)  # [[0.63 0.09]]
print("Z2:", Z2)  # [[0.44]]
print("A2:", A2)  # [[0.60825903]]
How the values were chosen: X reuses the three teaching inputs. W1, b1, W2 and b2 are manually chosen example parameters; a real network initializes parameters and then learns them. Z means the value before activation, A means the value after activation, and the layer number is written as 1 or 2. The final 0.608 is produced by the model—not supplied as a label—and means an estimated 60.8% pass probability under this toy setup.

Try the Neuron in Python

This short program repeats the hand calculation from Figure 4. It does not train a full network yet; it shows exactly how one neuron creates an output.

one_neuron.py
import math

# One student's input values (scaled between 0 and 1)
study = 0.8
attendance = 0.9
sleep = 0.7

# Example weights and bias
weighted_sum = (
    study * 0.7
    + attendance * 0.8
    + sleep * 0.3
    - 0.8
)

# Sigmoid changes the raw score into a value from 0 to 1
probability = 1 / (1 + math.exp(-weighted_sum))

print(round(weighted_sum, 2))  # 0.69
print(round(probability, 2))   # 0.67
print(f"Estimated pass chance: {probability:.0%}")
# Estimated pass chance: 67%

Now connect neurons with Keras

Libraries create and train all those connected neurons for us. This is the smallest readable model for three student inputs and one yes/no output:

student_network.py
import numpy as np
from tensorflow import keras

keras.utils.set_random_seed(7)

# Eight labelled teaching examples. Each row is
# [study, attendance, sleep]; each target is pass=1 or fail=0.
X_train = np.array([
    [0.9, 0.9, 0.8], [0.8, 0.7, 0.7], [0.7, 0.9, 0.6], [0.6, 0.8, 0.8],
    [0.2, 0.4, 0.5], [0.3, 0.3, 0.6], [0.4, 0.5, 0.4], [0.1, 0.6, 0.5],
], dtype=np.float32)
y_train = np.array([1, 1, 1, 1, 0, 0, 0, 0], dtype=np.float32)

model = keras.Sequential([
    keras.layers.Input(shape=(3,)),       # 3 inputs
    keras.layers.Dense(4, activation="relu"),  # 4 hidden neurons
    keras.layers.Dense(1, activation="sigmoid") # pass chance
])

model.compile(
    optimizer="adam",              # how weights are adjusted
    loss="binary_crossentropy",     # how wrong each guess is
    metrics=["accuracy"]
)

model.fit(X_train, y_train, epochs=50, batch_size=4, verbose=0)

chance = model.predict([[0.8, 0.9, 0.7]])[0][0]
print(f"Estimated pass chance: {chance:.0%}")
# The seed makes this teaching run repeatable on a given setup, but minor
# numerical differences can still occur across TensorFlow versions/hardware.

How the calls match the concept

Dense creates trainable weights and biases. compile selects the error rule and update algorithm. fit repeats prediction, loss, gradients and updates. predict performs only the forward calculation with the learned parameter values.

What this example cannot justify

Eight invented rows cannot support a real student decision. A real system would need representative data, clear definitions, separate validation and test sets, fairness review and human oversight. This code exists only to make the mechanics executable.

What Can Go Wrong?

ProblemIn simple EnglishWhat to check
Poor or biased dataThe examples do not represent the people or situations where the model will be used.Coverage, labels, missing groups, and data collection.
OverfittingThe network memorizes training examples but performs poorly on new ones.Validation results, simpler models, regularization, and more useful data.
UnderfittingThe network has not learned the useful pattern even on training data.Input quality, model capacity, learning rate, and training time.
Wrong metricA high-looking number hides the failures that actually matter.Precision, recall, class balance, and real-world cost of mistakes.
Too much confidenceA probability is treated as certainty.Calibration, uncertainty, human review, and safe thresholds.

Check Your Understanding

1. What does a weight represent?

It represents how strongly one input or neuron influences the next neuron.

2. What are the three basic jobs inside a neuron?

Multiply inputs by weights, add the results and bias, then apply an activation function.

3. What is the difference between a prediction and a label?

A prediction is the network’s guess. A label is the known correct answer supplied in training or evaluation data.

4. Does backpropagation directly choose the final answer?

No. Backpropagation calculates how the parameters contributed to the loss. An optimizer uses that information to adjust them.

5. Which network would you first consider for images?

A convolutional neural network (CNN), because its filters are designed to find local visual patterns.

Summary: The Whole Idea in Seven Lines

  1. Inputs are numbers that describe one example.
  2. Weights describe how strongly information should influence the next neuron.
  3. Each neuron multiplies, adds a bias, and applies an activation function.
  4. Layers pass those results forward until the network makes a prediction.
  5. A loss function measures the prediction’s error against the known answer.
  6. Backpropagation and an optimizer adjust weights and biases.
  7. Repeating this with useful data lets the network improve on its task.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "How Neural Networks Learn"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
A neuron receives x₁=2 and x₂=3 with weights w₁=0.5 and w₂=1, plus bias b=−1. What is its weighted sum z?
Question 2 of 4
What job does a bias perform in a neuron?
Question 3 of 4
After a forward pass produces a prediction, why is a loss function used?
Question 4 of 4
Which statement correctly separates backpropagation from the optimizer?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1A neuron receives x₁=2 and x₂=3 with weights w₁=0.5 and w₂=1, plus bias b=−1. What is its weighted sum z?▼

Correct Answer: 3

z = x₁w₁ + x₂w₂ + b = (2×0.5) + (3×1) − 1 = 3. An activation function may then transform this value.

2What job does a bias perform in a neuron?▼

Correct Answer: It adds an adjustable offset to the weighted sum before activation

A neuron commonly computes z = Σwx + b. The bias b lets the activation shift instead of being forced through the origin.

3After a forward pass produces a prediction, why is a loss function used?▼

Correct Answer: To measure how the prediction differs from the target with one training objective

The loss converts the prediction-versus-target error into a number that training tries to reduce.

4Which statement correctly separates backpropagation from the optimizer?▼

Correct Answer: Backpropagation computes gradients; the optimizer uses them to update weights and biases

Backpropagation tells us how the loss changes with each parameter. The optimizer turns those gradients into parameter updates.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next