Short on time? Neural networks explained simply: a network is layers of small units called nodes. Each node multiplies its inputs by weights, adds a bias and passes the result through an activation function. Training adjusts the weights by backpropagation until predictions match the data. Stack many layers and you get deep learning, and add attention and you get the Transformer. This full guide covers every step with maths and code.
Neural networks power image recognition, speech tools, recommendation systems and the language models behind modern assistants. The idea is simpler than the name suggests. A neural network is a function with many adjustable numbers, and training is a way of tuning those numbers.
This guide to neural networks explained goes from a single neuron to the Transformer. It includes small programs you can run, a worked example and a study plan. It suits beginners, developers moving into AI and managers who want to talk sensibly with their data teams. Pair it with Machine Learning for Beginners and Deep Learning for Beginners.
Key takeaways
- Google’s machine learning course describes a neural network as nodes arranged in layers, with hidden layers and activation functions that let the model learn non-linear patterns.
- Training uses backpropagation, which Google calls the most common training algorithm for neural networks.
- The PyTorch quickstart builds a small network from a flatten step, linear layers and ReLU activations, trains it with a loss function and an optimiser and evaluates it on test data.
- The Transformer, introduced in 2017, is based solely on attention and underlies modern language models.
- Good results need good data, a held-out test set and careful monitoring.
Contents
- The single neuron
- Activation functions
- Layers and networks
- Loss: measuring how wrong
- Training: gradient descent and backpropagation
- Code: a network from scratch
- Code: the same idea in PyTorch
- Overfitting and how to fight it
- Network types: feed-forward, convolutional, recurrent, Transformer
- Data, features and evaluation
- Running neural networks in practice
- A worked example
- Small business and enterprise views
- Common mistakes
- Study plan
1. Neural networks explained from the single neuron
A neuron takes numbers in and gives one number out. For inputs x1, x2 and x3, it uses weights w1, w2 and w3 and a bias b:
output = activation(w1*x1 + w2*x2 + w3*x3 + b) Weights say how much each input matters. The bias shifts the result. The activation function shapes it. A neuron on its own can learn only simple patterns. Many neurons together can learn very complex ones.
def neuron(inputs, weights, bias):
total = sum(w * x for w, x in zip(weights, inputs)) + bias
return max(0.0, total) # ReLU activation
print(neuron([2.0, 1.0, 0.5], [0.4, -0.2, 0.9], bias=0.1)) 2. Activation functions
Without activation functions, a stack of layers collapses into one linear formula. Activations add the bends that let a network model curved relationships. Google’s neural networks module explains that activation functions let networks learn non-linear relationships.
Common choices:
- ReLU: returns zero for negative values and the value itself for positive ones. Simple, fast and widely used in hidden layers.
- Sigmoid: squashes values between 0 and 1. Used for yes-or-no outputs.
- Softmax: turns a set of scores into probabilities that add up to 1. Used for multi-class outputs.
- Tanh: squashes values between -1 and 1.
import math
def relu(x): return max(0.0, x)
def sigmoid(x): return 1 / (1 + math.exp(-x))
for v in (-2, 0, 2):
print(v, relu(v), round(sigmoid(v), 3)) 3. Layers and networks
A layer is a group of neurons that process the same inputs. A network has:
- An input layer, which holds the data, such as pixel values or numbers from a table.
- Hidden layers, which learn intermediate features.
- An output layer, which gives the answer: a number, a yes or no or a probability for each class.
More layers and more nodes give a model more capacity. They also need more data and care. Google’s module describes this structure and how multi-class problems use one output for each class.
The maths in matrix form
A layer with many neurons is one matrix multiplication plus a bias, then an activation:
h = activation(W x + b) W is a matrix of weights, x is the input vector and b is the bias vector. Hardware such as GPUs is fast at exactly this operation, which is why neural networks became practical at large scale.
4. Loss: measuring how wrong
To train, you need a number that says how wrong the network is. That number is the loss.
- Mean squared error for predicting numbers: the average of squared differences between prediction and truth.
- Cross-entropy for classes: it is low when the model gives high probability to the correct class and high when it does not.
def mse(preds, truths):
return sum((p - t) ** 2 for p, t in zip(preds, truths)) / len(preds)
print(mse([2.5, 0.0, 2.1], [3.0, -0.5, 2.0])) Training aims to make the loss small on data the model has not seen.
5. Training: gradient descent and backpropagation
Gradient descent
Imagine standing on a hilly landscape in fog, trying to reach the lowest point. You feel the slope under your feet and step downhill. Gradient descent does this with the loss. The gradient tells you which way each weight should move to reduce the loss, and the learning rate sets the step size.
- A learning rate too high makes training jump around or diverge.
- A learning rate too low makes training very slow.
Backpropagation
A network has many layers, so the loss depends on weights in all of them. Backpropagation uses the chain rule from calculus to work out the gradient for every weight, starting from the output and moving backwards through the layers. Google describes it as the most common training algorithm for neural networks.
One training step
- Take a batch of examples.
- Run them forward to get predictions.
- Compute the loss.
- Run backward to get gradients.
- Update the weights a small step.
- Repeat for many batches and many passes (epochs).
6. Code: a network from scratch
This small program trains a single neuron to learn the rule “output is 1 when the sum of two inputs is above 1”. It uses plain Python so every step is visible:
import math, random
random.seed(1)
data = [((0.1, 0.2), 0), ((0.9, 0.8), 1), ((0.4, 0.3), 0),
((0.7, 0.9), 1), ((0.2, 0.1), 0), ((0.8, 0.6), 1)]
w1, w2, b = random.random(), random.random(), 0.0
lr = 0.5
def sigmoid(x): return 1 / (1 + math.exp(-x))
for epoch in range(2000):
for (x1, x2), y in data:
p = sigmoid(w1 * x1 + w2 * x2 + b) # forward pass
grad = p - y # gradient of cross-entropy loss
w1 -= lr * grad * x1 # backward update
w2 -= lr * grad * x2
b -= lr * grad
for (x1, x2), y in data:
print((x1, x2), y, round(sigmoid(w1 * x1 + w2 * x2 + b), 2)) After training, predictions move close to the labels. This is training in miniature: forward pass, error, gradient, update.
7. Code: the same idea in PyTorch
Libraries do the gradient work for you. The official PyTorch quickstart tutorial trains an image classifier on a standard dataset. Its model is a class that inherits from nn.Module. It flattens a 28 by 28 image, then applies linear layers of 512 units with ReLU activations, and ends with 10 outputs. It uses cross-entropy loss and stochastic gradient descent with a learning rate of 0.001. The core training loop is:
for X, y in dataloader:
pred = model(X)
loss = loss_fn(pred, y)
loss.backward()
optimizer.step()
optimizer.zero_grad() Read it line by line:
pred = model(X)is the forward pass.loss = loss_fn(pred, y)measures the error.loss.backward()runs backpropagation.optimizer.step()updates the weights.optimizer.zero_grad()clears gradients for the next batch.
Here is a compact model in the same style, written for a small table of numbers:
import torch
from torch import nn
class SmallNet(nn.Module):
def __init__(self, n_inputs, n_classes):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(n_inputs, 64),
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
nn.Linear(64, n_classes),
)
def forward(self, x):
return self.layers(x)
model = SmallNet(n_inputs=10, n_classes=3)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) For the full beginner path, follow the PyTorch tutorials step by step. See also Python for AI.
8. Overfitting and how to fight it
A network can memorise its training data and fail on new data. That is overfitting. Signs: training loss keeps falling while validation loss rises.
Remedies:
- More data, or more varied data.
- A simpler model, with fewer layers or nodes.
- Regularisation, such as weight decay.
- Dropout, which randomly switches off nodes during training.
- Early stopping, which halts training when validation loss stops improving.
- Data augmentation, such as flipping or cropping images.
Always keep three sets: training data to learn, validation data to tune and test data to judge at the end. Do not touch the test set while you are tuning.
9. Network types
Feed-forward networks
Data flows one way from input to output. Good for tables of numbers.
Convolutional networks
These scan small filters across images to detect edges, shapes and objects. They work well for vision tasks.
Recurrent networks
These process sequences step by step and carry a memory forward. They were common for text and speech before Transformers.
Transformers
The paper Attention Is All You Need proposed a network based solely on attention mechanisms, which allowed more parallel training. Transformers now underpin most large language models. See Large Language Models Explained.
A tiny sketch of attention, with made-up numbers, shows the idea of weighting:
import math
def softmax(xs):
m = max(xs); e = [math.exp(x - m) for x in xs]; s = sum(e)
return [v / s for v in e]
query = [1.0, 0.0]
keys = [[1.0, 0.1], [0.0, 1.0], [0.9, 0.0]]
values = [10.0, 20.0, 30.0]
scores = [sum(q * k for q, k in zip(query, key)) for key in keys]
weights = softmax(scores)
output = sum(w * v for w, v in zip(weights, values))
print([round(w, 2) for w in weights], round(output, 2)) The query asks a question, the keys say what each item holds and the weights decide how much of each value to mix into the result.
10. Data, features and evaluation
Most project effort goes into data.
- Quality: wrong labels and missing values hurt more than model choice.
- Balance: if 95 percent of examples are one class, a model that always predicts it looks accurate and is useless.
- Scaling: scale numeric inputs so no feature dominates.
- Leakage: make sure nothing in the inputs gives away the answer in a way that will not exist later.
Pick metrics that match the goal. Accuracy suits balanced classes. Precision and recall matter when mistakes have different costs. For numbers, use mean error measures. Always compare with a simple baseline, such as predicting the average.
11. Running neural networks in practice
- Hardware: GPUs speed up training. Small models run on a laptop.
- Reproducibility: fix random seeds, record versions and keep data snapshots.
- Monitoring: watch input drift, accuracy and cost after launch. See AI Model Monitoring.
- Explainability: some uses need reasons for decisions. Plan for it early.
- Governance: follow your risk process. The NIST AI Risk Management Framework offers a structure.
12. A worked example: predicting late deliveries
This example is illustrative.
A logistics firm wants to flag shipments likely to arrive late.
This example puts neural networks explained so far into one project.
- Data: two years of shipments with route, weight, carrier, day of week, weather summary and outcome (on time or late).
- Baseline: predict “on time” for everything, which is right 88 percent of the time but finds no late shipments.
- Model: a small feed-forward network with two hidden layers, trained on the first 18 months and validated on the next 3 months.
- Test: the final 3 months, untouched until the end.
- Metrics: recall for late shipments, and precision so that the team is not flooded with false alarms.
- Result to look for: better recall than a simple model at an acceptable false alarm rate. Also compare with a gradient-boosted tree model, which often does well on tables.
- Deployment: daily scoring, alerts for the top 5 percent of risks, a feedback button and monthly retraining checks.
The honest finding may be that a simpler model is enough. Choose the simplest model that meets the goal.
13. Small business and enterprise views
- Sole trader or small business: you rarely need to train your own network. Use ready-made services, or small models with a few hundred examples.
- Mid-size company: train or fine-tune for narrow tasks where you have good labelled data, and build monitoring from day one.
- Enterprise: run a platform with feature stores, experiment tracking, model registry, review boards and cost controls. See AI Orchestration.
Regional and regulatory notes
Rules on automated decisions, personal data and high-risk AI systems vary by country and by sector. Check data protection duties before using personal data for training. See EU AI Act After the Digital Omnibus.
14. Common mistakes
- Judging a model on training data.
- Skipping a baseline.
- Tuning on the test set.
- Ignoring class imbalance.
- Training a large network when a simple model works.
- Leaving out monitoring after launch.
- Treating the model as a black box with no owner.
15. Study plan
Use this plan to move from neural networks explained in theory to working projects.
Weeks 1 and 2: revise vectors, matrices and derivatives at an intuitive level. Run the code in this guide.
Weeks 3 and 4: complete the Google neural networks module and the PyTorch quickstart.
Weeks 5 and 6: build a classifier for a dataset you care about, with a baseline, a validation set and a test set.
Weeks 7 and 8: read the attention paper’s introduction and the Hugging Face course chapters on Transformers.
After that: pick a project, such as a small image or text classifier, and write up your results honestly.
How SoftSapien supports neural network projects
SoftSapien’s data scientists and AI engineers help teams frame problems, prepare data, build and test models, deploy them and monitor results, and train staff in the basics. See our AI development and data science services.
To discuss a model project, use the contact page to chat with our team, send a message or schedule a free consultation call.
Frequently asked questions
What is a neural network?
A function made of layers of nodes. Each node multiplies inputs by weights, adds a bias and applies an activation function.
What is backpropagation?
The algorithm that works out how each weight should change to reduce the loss. Google calls it the most common training algorithm for neural networks.
What is overfitting?
When a model memorises its training data and fails on new data. Use validation data, regularisation, dropout and early stopping.
Do I need a GPU?
Not to learn. Small models run on a laptop, and GPUs help once models and data grow.
Can SoftSapien help with a model project?
Yes, from data to deployment. Contact SoftSapien through the contact page to chat with our team, send a message or schedule a free consultation call.