Neural network (Neural Network) is the basis of deep learning (Deep Learning). Through multi-layer learnable mathematical transformations, the mapping relationship between input and output is established from the data.
Although modern Transformer, CNN, Diffusion Models and other architectures have different structures, they all rely on some common basic mechanisms:
- Tensor / Linear Algebra: Organize data and parameters using vectors, matrices and tensors.
- Neuron/Layer: Computational units are constructed through linear transformations and nonlinear activations.
- Forward Propagation: Computes model predictions from inputs.
- Loss Function: Measures the difference between the predicted results and the target.
- Backpropagation: Calculates parameter gradients via the chain rule.
- Gradient Descent: Use gradients to update parameters to reduce the loss.
This article focuses on these general principles and does not involve specific deep learning frameworks and complex network architectures.
1. Basic structure of neural network
The most basic neural network is Feedforward Neural Network (feedforward neural network), and a common form is Multilayer Perceptron (MLP, multi-layer perceptron).
MLP usually includes:
- Input Layer: Receive input features.
- Hidden Layers: Perform multiple linear and nonlinear transformations on the input.
- Output Layer: Generate predicted values or classification scores.
For example, enter user age, income, number of consumption and other characteristics to predict user churn probability.
Need to pay attention to:
neural networks do not necessarily imply complex deep structures. Mathematically, basic MLP is just a combination of multiple parameterized functions.
2. Basic mathematics: What knowledge is needed for neural networks?
There are three areas of mathematics that are most important to understanding neural networks:
| Math basics | Main purpose |
|---|---|
| Linear Algebra | Represent data, weights, and linear transformations |
| Calculus | Compute derivatives, gradients, and backpropagation |
| Probability & Statistics | Define loss, understand data distribution and model generalization |
Among them, linear algebra and calculus are the keys to understanding forward propagation and back propagation.
2.1 Scalar、Vector、Matrix、Tensor
Scalar (scalar)
Single value:
Vector (vector)
One-dimensional collection of values:
Matrix (matrix)
Two-dimensional numerical collection:
Tensor (Tensor)
More general multidimensional arrays.
In the deep learning framework, Scalar, Vector, Matrix can all be regarded as Tensor in different dimensions.
For example:
import torch
scalar = torch.tensor(3.0) # shape: []
vector = torch.randn(3) # shape: [3]
matrix = torch.randn(10, 5) # shape: [10, 5]
images = torch.randn(32, 3, 224, 224)
The last dimension of Tensor usually means:
[Batch, Channels, Height, Width]
2.2 Dot Product: dot product
For two vectors:
Dot product:
Weighted summation in neurons is a typical application of dot products.
2.3 Matrix Multiplication: Matrix multiplication
Assume that the input has 3 features and the results of 4 neurons need to be output:
Then:
Among them:
Here 32 is Batch Size.
Understanding matrix shapes is important because most of the linear computations of neural networks can be expressed as matrix multiplications.
2.4 Derivative: Derivative
The derivative represents the instantaneous rate of change of the function's output as the input changes.
For example:
Then:
In neural networks, we usually want to know:
When a certain model parameter of changes slightly, how will Loss change?
2.5 Partial Derivative: Partial derivative
When a function has multiple variables, the partial derivative of each variable can be calculated separately.
For example:
Then:
Loss of neural networks usually rely on thousands or even more parameters, so a large number of partial derivatives need to be calculated.
2.6 Gradient: Gradient
The gradient is a vector composed of partial derivatives of each parameter:
The gradient indicates the direction in parameter space where the function grows locally the fastest.
Therefore, updating parameters along the negative gradient direction can usually reduce Loss in sufficiently small step sizes.
2.7 Chain Rule: Chain Rule
The chain rule is the mathematical basis of Backpropagation.
if:
Then:
For multi-layer neural networks, the output is a composite of multiple functions:
Backpropagation uses the chain rule to transfer the final Loss gradient to each parameter layer by layer.
3. Artificial Neuron: Artificial Neuron
The most basic artificial neuron consists of two steps:
- Linear Transformation: Weighted sum.
- Activation Function: Nonlinear activation.
Its mathematical form:
Among them:
- : input vector.
- : Learnable weights.
- : Offset.
- : Linear output before activation (Pre-activation).
- : activation function.
- : neuron output.
For example:
Get:
If using ReLU:
Weight and Bias
Weight
Used to control the impact of different input features on the output.
Bias
Provides additional learnable offsets so that the model does not have to be forced through the origin.
Both are model parameters (Parameters), which are usually updated continuously during the training process.
4. Activation Functions: activation function
If there are only linear transformations in the neural network:
Then multiple linear layers can still be combined into one affine transformation.
Therefore, the nonlinear activation function is the key for neural networks to express complex functions.
ReLU
Rectified Linear Unit:
Features:
- The calculation is simple.
- Positive region gradient is 1.
- Outputting 0 in the negative area may cause some neurons to be inactive for a long time.
import torch.nn as nn
activation = nn.ReLU()
Sigmoid
The output range is 0~1.
It is often used for output transformation in binary classification probability modeling, and is also used in some gating mechanisms.
The disadvantage is that when the absolute value of the input is large, it is easy to enter the saturation region and the gradient becomes smaller.
Tanh
The output range is -1~1.
It is more common in traditional RNN and other architectures, but there is also the problem of smaller gradients in saturated areas.
GELU and SiLU
Other activation functions common in modern neural networks include:
- GELU (Gaussian Error Linear Unit): widely used in architectures such as Transformer.
- SiLU / Swish: Used in many modern networks.
nn.GELU()
nn.SiLU()
For basic learning, focus on mastering the mathematical principles of ReLU, Sigmoid, Tanh, and why nonlinearity is needed.
GELU, SiLU and gated activation functions can be further covered in the specific architecture articles.
5. Layer: Neural network layer
A Layer usually contains multiple neurons that can process input simultaneously.
For a fully connected layer (Fully Connected Layer):
The Batch convention where the input is a row vector is used here.
For example:
means:
- Batch Size = 32。
- Input Features = 10。
If the layer has 64 neurons:
Then the output is:
PyTorch Linear Layer
import torch
import torch.nn as nn
layer = nn.Linear(
in_features=10,
out_features=64,
)
X = torch.randn(32, 10)
Y = layer(X)
print(Y.shape) # torch.Size([32, 64])
Note: The storage shape of nn.Linear.weight inside PyTorch is [out_features, in_features], and its calculation is equivalent to .
This is different from the notation used previously only in the way the weight matrix is defined.
Parameters
For a Linear Layer with 10 inputs and 64 outputs:
Among them:
- Weight: 640 parameters.
- Bias: 64 parameters.
6. Multilayer Perceptron: Multi-layer perceptron
MLP combines multiple fully connected layers and activation functions.
For example:
Input: 10 Features
↓
Linear(10, 64)
↓
ReLU
↓
Linear(64, 32)
↓
ReLU
↓
Linear(32, 1)
↓
Output
Mathematical expression:
There is no activation function added to the last layer here, so the output is a raw numerical score.
Depending on the task, different output formats and Loss Function can be selected.
PyTorch example
import torch.nn as nn
model = nn.Sequential(
nn.Linear(10, 64),
nn.ReLU(),
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, 1),
)
MLP is the basis for understanding more complex architectures.
For example, Feedforward Network (FFN) of Transformer is also built based on linear layers, activation functions and related variants.
7. Forward Propagation: Forward propagation
Forward Propagation is the process of passing the input data to each layer of the through network in sequence, and finally calculating the prediction result.
For a two-layer network:
Forward propagation process:
Input X
↓
Linear Transformation
↓
Activation
↓
Linear Transformation
↓
Prediction
NumPy implementation
import numpy as np
rng = np.random.default_rng(42)
X = rng.normal(size=(32, 3))
W1 = rng.normal(size=(3, 8))
b1 = np.zeros(8)
W2 = rng.normal(size=(8, 1))
b2 = np.zeros(1)
# first floor
Z1 = X @ W1 + b1
A1 = np.maximum(Z1, 0)
# output layer
Z2 = A1 @ W2 + b2
print(Z2.shape) # (32, 1)
Here:
@represents matrix multiplication.np.maximum()implements ReLU.- Bias utilizes NumPy Broadcasting applied to each sample.
Forward propagation itself is just a mathematical calculation and does not include model parameter updates.
8. Loss Function: Loss function
The neural network must use some objective function to determine whether the current prediction result is ideal.
Loss Function measures the difference between the prediction and the true target.
Regression:MSE
Common regression tasks:
criterion = nn.MSELoss()
Binary Classification:Binary Cross-Entropy
Two classification tasks are commonly used:
In PyTorch it is generally recommended to use:
criterion = nn.BCEWithLogitsLoss()
It internally combines Sigmoid and Binary Cross-Entropy, and the numerical stability is usually better than manual calculation separately.
Therefore, the last layer of the model should output Logits instead of executing Sigmoid beforehand.
Multiclass Classification:Cross-Entropy
Multi-classification models typically output Logits for each class:
[2.3, -0.7, 1.2]
Then the class probability can be obtained by Softmax.
PyTorch Commonly used:
criterion = nn.CrossEntropyLoss()
The Loss accepts Logits without Softmax and performs the corresponding numerical stabilization calculations internally.
The difference between Loss and Metric
- Loss: used for training and calculating gradients.
- Metric: used to measure model performance.
For example:
- Classification training Loss: Cross-Entropy.
- Classification evaluation Metric: Accuracy, F1, ROC-AUC.
- Regression training Loss: MSE.
- Regression evaluation Metric: MAE, RMSE, R².
Loss and Metric are not necessarily the same because some evaluation metrics are not suitable for direct optimization via gradient descent.
9. Backpropagation: Backpropagation
Backpropagation (backpropagation) is used to calculate the gradient of Loss for each parameter of the neural network.
Its core is not a specific neural network architecture, but an efficient derivation algorithm based on the chain rule.
Why is backpropagation needed?
Suppose a neural network has a large number of parameters:
In order to train the model, it is necessary to calculate:
The computational cost is often too high if each parameter is numerically perturbed individually to estimate the derivatives.
Backpropagation efficiently calculates gradients from the network output to the input by reusing intermediate calculation results.
Backpropagation of a single neuron
Consider a simple model:
The goal is to calculate:
According to the chain rule:
Among them:
Therefore:
Same reason:
Numerical example
Assumptions:
Forward propagation:
Loss:
Backpropagation:
The gradient is negative, which means that at the current position, appropriately increasing or is beneficial to reducing Loss.
10. Backpropagation in multi-layer networks
For multi-layer networks:
Backpropagation starts at Loss.
Definition:
Then the gradient of the output layer is:
Then pass the gradient back to the previous layer:
where represents element-wise multiplication.
First layer parameter gradient:
It is assumed here that the Batch reduction of Loss is already contained in .
Intuitive process
Forward Propagation
X → Linear 1 → Activation → Linear 2 → Loss
Backward Propagation
∂L/∂W1 ← ∂L/∂A1 ← ∂L/∂W2 ← ∂L/∂Output
Each layer utilizes:
- The input or intermediate results saved by the current layer.
- The gradient returned by the next layer.
- The local derivative of the current layer operation.
Calculate the gradient of its own parameters and continue to propagate to the previous layer.
backpropagation is only responsible for calculating gradients and is not responsible for updating parameters.
Parameter update is completed by Optimizer.
11. Gradient Descent: Gradient Descent
After obtaining the parameter gradient, you can use Gradient Descent to update the parameters:
Among them:
- : Current parameters.
- :Learning Rate。
- : Current parameter gradient.
Numerical example
Following the previous example:
Assumptions:
Updated to get:
New predictions:
New Loss:
Loss dropped from 2 to 0.5.
But gradient descent does not guarantee that Loss will drop at every step, especially when Learning Rate is too large or training uses random Mini-batch.
Learning Rate
Learning Rate determines the step size of each parameter update.
- Too big: may oscillate or diverge.
- Too small: convergence is slow.
- Fit: A balance between training efficiency and stability.
In actual deep learning, SGD with Momentum, Adam, AdamW and other Optimizer are often used. The details are suitable for explanation in the Neural Network Training article.
12. Batch, Epoch and Iteration
Neural networks typically do not need to use the full training set for each update.
Batch
The set of samples processed in one forward pass and back pass.
For example:
Training Samples: 10000
Batch Size: 100
Each Epoch typically requires about 100 parameter updates.
Epoch
The model completely traverses the training data set once.
Iteration / Step
Usually refers to processing a Batch and completing a parameter update.
For example:
Dataset: 10000 Samples
Batch Size: 100
Epochs: 10
There are approximately 100 Steps for each Epoch.
Total about 1000 Optimization Steps.
In the form of Gradient Descent
| method | Data used for each update |
|---|---|
| Batch Gradient Descent | the entire training set |
| Stochastic Gradient Descent | single sample |
| Mini-batch Gradient Descent | small batch sample |
Modern neural networks usually use Mini-batch Training.
13. Automatic Differentiation: automatic differentiation
While it is important to understand the mathematics of Backpropagation, practical development does not require manually deriving the gradients for each layer.
Frameworks such as PyTorch provide the Automatic Differentiation (automatic differentiation) mechanism.
Computational Graph: calculation graph
For example:
Each operation constitutes a node in the computational graph.
During backpropagation, the framework calculates the gradient according to the calculation graph and the derivation rules of each operation.
Autograd of PyTorch mainly uses reverse mode automatic differentiation (Reverse-mode Automatic Differentiation), which is suitable for training scenarios with many parameters and the output is a scalar Loss.
PyTorch example
import torch
x = torch.tensor(2.0)
y = torch.tensor(3.0)
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
# Forward
y_pred = w * x + b
loss = 0.5 * (y_pred - y) ** 2
# Backward
loss.backward()
print(w.grad) # tensor(-4.)
print(b.grad) # tensor(-2.)
Among them:
requires_grad=True: Requires tracking of relevant calculations in order to find gradients.loss.backward(): Start backpropagation..grad: Save the gradient of the corresponding parameter.
Gradient Accumulation
PyTorch will accumulate new gradients into .grad by default instead of automatically overwriting it.
Therefore, before each normal training update, the previous gradients need to be cleaned:
optimizer.zero_grad()
Complete basic training process:
optimizer.zero_grad()
y_pred = model(X)
loss = criterion(y_pred, y)
loss.backward()
optimizer.step()
These four steps are the most important foundation of PyTorch Training Loop.
14. Implement a simple neural network training from scratch
Below we use PyTorch to construct a simple binary classification MLP.
import torch
import torch.nn as nn
torch.manual_seed(42)
# 1. Generate sample data
X = torch.randn(1000, 2)
y = (
(X[:, 0] + X[:, 1]) > 0
).float().unsqueeze(1)
# 2. Define model
model = nn.Sequential(
nn.Linear(2, 16),
nn.ReLU(),
nn.Linear(16, 1),
)
# 3. Loss
criterion = nn.BCEWithLogitsLoss()
# 4. Optimizer
optimizer = torch.optim.Adam(
model.parameters(),
lr=0.01,
)
# 5. Training
for epoch in range(100):
optimizer.zero_grad()
logits = model(X)
loss = criterion(logits, y)
loss.backward()
optimizer.step()
if (epoch + 1) % 20 == 0:
print(
f"Epoch {epoch + 1}: "
f"Loss = {loss.item():.4f}"
)
Prediction:
model.eval()
with torch.no_grad():
logits = model(X)
probabilities = torch.sigmoid(logits)
predictions = (probabilities >= 0.5).int()
In order to focus on demonstrating the principles here, the same batch of simulation data is directly used for training and demonstration prediction. Real projects need to reasonably divide the training set, verification set and test set.
What happened during training?
Each round of training includes:
- Forward: Compute Logits by multi-layer linear transformation and ReLU.
- Loss: Computes Binary Cross-Entropy between the predicted Logits and the true label.
- Backward: Calculate the gradient of each layer parameter through Autograd.
- Update: Use Adam to update model parameters.
The entire training process is to continuously repeat these steps so that the model gradually fits the patterns in the data.
15. Frequently Asked Questions in Training
Vanishing Gradients: Gradient disappears
When backpropagating multi-layer networks, the chain rule needs to be continuously applied.
If the magnitudes of multiple local derivatives are small, the gradient may decay layer by layer.
Result:
- Early layer parameter updates are small.
- Model training is slow.
- Deep networks are difficult to optimize.
Common mitigation methods include:
- suitable activation function.
- Parameter initialization.
- Residual Connections。
- Normalization。
Exploding Gradients: gradient explosion
If some gradients are continuously amplified during backpropagation, it may cause parameter updates to be too large.
Performance may include:
- Loss fluctuates violently.
- NaN / Inf appears.
- Model training is unstable.
Common processing methods:
- Lower Learning Rate.
- Gradient Clipping。
- Proper initialization with Normalization.
Overfitting: Overfitting
The model performs well on the training set but performs poorly on new data.
Common methods:
- Increase effective training data.
- Weight Decay。
- Dropout。
- Early Stopping。
- Data Augmentation。
- Control model complexity.
Underfitting: Underfitting
The model has difficulty learning patterns in the training data.
Possible reasons:
- The model capacity is insufficient.
- Insufficient feature information.
- Inadequate training.
- Regularization is too strong.
These issues are the focus of neural network training and optimization and can be further expanded on in the Neural Network Training article.
16. The relationship between neural networks and traditional machine learning
Neural networks are not a mathematical system completely different from traditional machine learning.
For example:
| model | Relationship to Neural Networks |
|---|---|
| Linear Regression | Can be considered as a single affine output layer, using regression loss |
| Logistic Regression | Can be treated as a single affine output layer, using a classification loss |
| MLP | Combination of multi-layer linear transformation and non-linear activation |
| CNN | Neural network using convolution operations and parameter sharing |
| Transformer | Network based on Attention, FFN, Normalization and other modules |
Modern complex models still follow the same basic training process:
Input
↓
Forward Propagation
↓
Prediction
↓
Loss
↓
Backpropagation
↓
Gradient Computation
↓
Optimizer Update
↓
Repeat
The main differences between different architectures lie in the computational structure, parameter sharing method, inductive bias and training objectives, rather than completely different training mathematics.
Summary
| Knowledge points | importance |
|---|---|
| Scalar / Vector / Matrix / Tensor | core |
| Matrix Multiplication | core |
| Derivative / Partial Derivative | core |
| Gradient / Chain Rule | core |
| Neuron / Weight / Bias | core |
| Activation Functions | core |
| MLP / Fully Connected Layer | core |
| Forward Propagation | core |
| Loss Function | core |
| Backpropagation | core |
| Gradient Descent / Learning Rate | core |
| Batch / Epoch / Iteration | core |
| Computational Graph / Autograd | core |
| Vanishing / Exploding Gradients | important |
| Overfitting / Underfitting | important |
The five most important concepts of neural networks:
- Linear Algebra: Neural networks use vectors, matrices and tensors to express data, parameters and calculation processes.
- Neuron & Activation: Neurons construct learnable complex functions through linear transformation and nonlinear activation.
- Forward Propagation: Pass the input through each layer in sequence to generate model predictions.
- Backpropagation: Use the chain rule to calculate the gradient of Loss for each parameter.
- Optimization: Optimizer uses gradients to update parameters and continuously lower the training target.
After understanding these principles, you can further study Tensor, Autograd, nn.Module, Optimizer, Dataset, DataLoader and the complete training and inference process of PyTorch.