Neural network basics

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 basicsMain purpose
Linear AlgebraRepresent data, weights, and linear transformations
CalculusCompute derivatives, gradients, and backpropagation
Probability & StatisticsDefine 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:

x=3x=3

Vector (vector)

One-dimensional collection of values:

x=[x1x2x3]x=\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix}

Matrix (matrix)

Two-dimensional numerical collection:

X=[x11x12x21x22x31x32]X= \begin{bmatrix} x_{11}&x_{12}\\ x_{21}&x_{22}\\ x_{31}&x_{32} \end{bmatrix}

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:

w=[w1w2],x=[x1x2]w=\begin{bmatrix}w_1\\w_2\end{bmatrix}, \qquad x=\begin{bmatrix}x_1\\x_2\end{bmatrix}

Dot product:

wTx=w1x1+w2x2w^Tx=w_1x_1+w_2x_2

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:

X∈R32×3X\in\mathbb{R}^{32\times3} W∈R3×4W\in\mathbb{R}^{3\times4}

Then:

Z=XW+bZ=XW+b

Among them:

Z∈R32×4Z\in\mathbb{R}^{32\times4}

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:

f(x)=x2f(x)=x^2

Then:

f′(x)=2xf'(x)=2x

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:

f(x,y)=x2+3yf(x,y)=x^2+3y

Then:

∂f∂x=2x\frac{\partial f}{\partial x}=2x ∂f∂y=3\frac{\partial f}{\partial y}=3

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:

∇θL=[∂L∂θ1∂L∂θ2⋮∂L∂θn]\nabla_\theta L= \begin{bmatrix} \frac{\partial L}{\partial\theta_1}\\ \frac{\partial L}{\partial\theta_2}\\ \vdots\\ \frac{\partial L}{\partial\theta_n} \end{bmatrix}

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:

y=f(u),u=g(x)y=f(u),\qquad u=g(x)

Then:

dydx=dydududx\frac{dy}{dx}=\frac{dy}{du}\frac{du}{dx}

For multi-layer neural networks, the output is a composite of multiple functions:

L=f4(f3(f2(f1(X))))L=f_4(f_3(f_2(f_1(X))))

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:

  1. Linear Transformation: Weighted sum.
  2. Activation Function: Nonlinear activation.

Its mathematical form:

z=wTx+bz=w^Tx+b a=ϕ(z)a=\phi(z)

Among them:

  • xx: input vector.
  • ww: Learnable weights.
  • bb: Offset.
  • zz: Linear output before activation (Pre-activation).
  • ϕ\phi: activation function.
  • aa: neuron output.

For example:

x=[2,3],w=[0.5,0.2],b=0.1x=[2,3],\quad w=[0.5,0.2],\quad b=0.1

Get:

z=2(0.5)+3(0.2)+0.1=1.7z=2(0.5)+3(0.2)+0.1=1.7

If using ReLU:

a=max⁡(0,1.7)=1.7a=\max(0,1.7)=1.7

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:

h1=W1x+b1h_1=W_1x+b_1 h2=W2h1+b2h_2=W_2h_1+b_2

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:

ReLU(x)=max⁡(0,x)ReLU(x)=\max(0,x)

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

σ(x)=11+e−x\sigma(x)=\frac{1}{1+e^{-x}}

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

tanh⁡(x)=ex−e−xex+e−x\tanh(x)=\frac{e^x-e^{-x}}{e^x+e^{-x}}

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):

Z=XW+bZ=XW+b A=ϕ(Z)A=\phi(Z)

The Batch convention where the input is a row vector is used here.

For example:

X∈R32×10X\in\mathbb{R}^{32\times10}

means:

  • Batch Size = 32。
  • Input Features = 10。

If the layer has 64 neurons:

W∈R10×64W\in\mathbb{R}^{10\times64}

Then the output is:

A∈R32×64A\in\mathbb{R}^{32\times64}

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 Y=XWT+bY=XW^T+b.

This is different from the XW+bXW+b notation used previously only in the way the weight matrix is defined.

Parameters

For a Linear Layer with 10 inputs and 64 outputs:

Parameters=10×64+64=704Parameters=10\times64+64=704

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:

H1=ReLU(XW1+b1)H_1=ReLU(XW_1+b_1) H2=ReLU(H1W2+b2)H_2=ReLU(H_1W_2+b_2) y^=H2W3+b3\hat y=H_2W_3+b_3

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:

Z1=XW1+b1Z_1=XW_1+b_1 A1=ReLU(Z1)A_1=ReLU(Z_1) Z2=A1W2+b2Z_2=A_1W_2+b_2 Y^=Z2\hat Y=Z_2

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:

L=1n∑i=1n(y^i−yi)2L=\frac{1}{n}\sum_{i=1}^{n}(\hat y_i-y_i)^2
criterion = nn.MSELoss()

Binary Classification:Binary Cross-Entropy

Two classification tasks are commonly used:

L=−1n∑i[yilog⁡pi+(1−yi)log⁡(1−pi)]L=-\frac{1}{n}\sum_i \left[ y_i\log p_i+(1-y_i)\log(1-p_i) \right]

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:

θ=[w1,w2,…,wn]\theta=[w_1,w_2,\ldots,w_n]

In order to train the model, it is necessary to calculate:

∂L∂w1,∂L∂w2,…,∂L∂wn\frac{\partial L}{\partial w_1}, \frac{\partial L}{\partial w_2}, \ldots, \frac{\partial L}{\partial w_n}

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:

z=wx+bz=wx+b y^=z\hat y=z L=12(y^−y)2L=\frac{1}{2}(\hat y-y)^2

The goal is to calculate:

∂L∂w,∂L∂b\frac{\partial L}{\partial w}, \qquad \frac{\partial L}{\partial b}

According to the chain rule:

∂L∂w=∂L∂y^∂y^∂w\frac{\partial L}{\partial w} = \frac{\partial L}{\partial\hat y} \frac{\partial\hat y}{\partial w}

Among them:

∂L∂y^=y^−y\frac{\partial L}{\partial\hat y}=\hat y-y ∂y^∂w=x\frac{\partial\hat y}{\partial w}=x

Therefore:

∂L∂w=(y^−y)x\boxed{\frac{\partial L}{\partial w}=(\hat y-y)x}

Same reason:

∂L∂b=y^−y\boxed{\frac{\partial L}{\partial b}=\hat y-y}

Numerical example

Assumptions:

x=2,w=0.5,b=0,y=3x=2,\quad w=0.5,\quad b=0,\quad y=3

Forward propagation:

y^=0.5×2=1\hat y=0.5\times2=1

Loss:

L=12(1−3)2=2L=\frac12(1-3)^2=2

Backpropagation:

∂L∂w=(1−3)×2=−4\frac{\partial L}{\partial w}=(1-3)\times2=-4 ∂L∂b=1−3=−2\frac{\partial L}{\partial b}=1-3=-2

The gradient is negative, which means that at the current position, appropriately increasing ww or bb is beneficial to reducing Loss.

10. Backpropagation in multi-layer networks

For multi-layer networks:

Z1=XW1+b1Z_1=XW_1+b_1 A1=ϕ(Z1)A_1=\phi(Z_1) Z2=A1W2+b2Z_2=A_1W_2+b_2 L=ℓ(Z2,Y)L=\ell(Z_2,Y)

Backpropagation starts at Loss.

Definition:

δ2=∂L∂Z2\delta_2=\frac{\partial L}{\partial Z_2}

Then the gradient of the output layer is:

∂L∂W2=A1Tδ2\frac{\partial L}{\partial W_2}=A_1^T\delta_2 ∂L∂b2=∑iδ2,i\frac{\partial L}{\partial b_2} = \sum_i\delta_{2,i}

Then pass the gradient back to the previous layer:

δ1=(δ2W2T)⊙ϕ′(Z1)\delta_1=(\delta_2W_2^T)\odot\phi'(Z_1)

where ⊙\odot represents element-wise multiplication.

First layer parameter gradient:

∂L∂W1=XTδ1\frac{\partial L}{\partial W_1}=X^T\delta_1 ∂L∂b1=∑iδ1,i\frac{\partial L}{\partial b_1} = \sum_i\delta_{1,i}

It is assumed here that the Batch reduction of Loss is already contained in δ2\delta_2.

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:

θt+1=θt−η∇θL\theta_{t+1}=\theta_t-\eta\nabla_\theta L

Among them:

  • θt\theta_t: Current parameters.
  • η\eta:Learning Rate。
  • ∇_θL\nabla\_\theta L: Current parameter gradient.

Numerical example

Following the previous example:

w=0.5,b=0w=0.5,\quad b=0 ∂L∂w=−4\frac{\partial L}{\partial w}=-4 ∂L∂b=−2\frac{\partial L}{\partial b}=-2

Assumptions:

η=0.1\eta=0.1

Updated to get:

wnew=0.5−0.1(−4)=0.9w_{\text{new}}=0.5-0.1(-4)=0.9 bnew=0−0.1(−2)=0.2b_{\text{new}}=0-0.1(-2)=0.2

New predictions:

y^=0.9×2+0.2=2\hat y=0.9\times2+0.2=2

New Loss:

L=12(2−3)2=0.5L=\frac12(2-3)^2=0.5

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

methodData used for each update
Batch Gradient Descentthe entire training set
Stochastic Gradient Descentsingle sample
Mini-batch Gradient Descentsmall 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:

x→z=wx+b→L=(z−y)2x\rightarrow z=wx+b\rightarrow L=(z-y)^2

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:

  1. Forward: Compute Logits by multi-layer linear transformation and ReLU.
  2. Loss: Computes Binary Cross-Entropy between the predicted Logits and the true label.
  3. Backward: Calculate the gradient of each layer parameter through Autograd.
  4. 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:

modelRelationship to Neural Networks
Linear RegressionCan be considered as a single affine output layer, using regression loss
Logistic RegressionCan be treated as a single affine output layer, using a classification loss
MLPCombination of multi-layer linear transformation and non-linear activation
CNNNeural network using convolution operations and parameter sharing
TransformerNetwork 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 pointsimportance
Scalar / Vector / Matrix / Tensorcore
Matrix Multiplicationcore
Derivative / Partial Derivativecore
Gradient / Chain Rulecore
Neuron / Weight / Biascore
Activation Functionscore
MLP / Fully Connected Layercore
Forward Propagationcore
Loss Functioncore
Backpropagationcore
Gradient Descent / Learning Ratecore
Batch / Epoch / Iterationcore
Computational Graph / Autogradcore
Vanishing / Exploding Gradientsimportant
Overfitting / Underfittingimportant

The five most important concepts of neural networks:

  1. Linear Algebra: Neural networks use vectors, matrices and tensors to express data, parameters and calculation processes.
  2. Neuron & Activation: Neurons construct learnable complex functions through linear transformation and nonlinear activation.
  3. Forward Propagation: Pass the input through each layer in sequence to generate model predictions.
  4. Backpropagation: Use the chain rule to calculate the gradient of Loss for each parameter.
  5. 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.

Reference documentation

Back to top