PyTorch Neural Network Basics
A neural network is a computational model that mimics the way the human brain processes information; it consists of many interconnected nodes (neurons) arranged in layers.
The power of neural networks lies in their ability to automatically learn complex patterns and features from large amounts of data, without manually designing feature extractors.
With the development of deep learning, neural networks have become a key technology for solving many complex problems.
Neuron
The neuron is the basic unit of a neural network; it receives input signals, computes a weighted sum, adds a bias, and then processes the result through an activation function to produce an output.
A neuron's weights and bias are the parameters that need to be adjusted during network learning.
Input and Output:
- Input: input is the starting point of the network, which can be feature data such as image pixel values or word vectors of text.
- Output: output is the endpoint of the network, representing the model's prediction result, such as a class label in a classification task.
A neuron receives multiple inputs (e.g., x1, x2, ..., xn); if the weighted sum of inputs exceeds the activation potential, it produces a binary output.

A neuron's output can be seen as the weighted sum of inputs plus a bias; the mathematical representation of a neuron is:

Here, wj is the weight, xj is the input, and Bias is the bias term.
Layer
Layers between the input and output layers are called hidden layers; the density and type of connections between layers constitute the network's configuration.
A neural network consists of multiple layers, including:
- Input Layer: receives the raw input data.
- Hidden Layer: processes the input data; there can be multiple hidden layers.
- Output Layer: produces the final output result.
A typical neural network architecture:

Diagram:
** Input layer
** Hidden layer
** Output layer
** Weighted connections
** Activation signals
Feedforward Neural Network (FNN)
The Feedforward Neural Network (FNN) is a fundamental unit in the neural network family.
Feedforward neural networks are characterized by data flowing from the input layer, through one or more hidden layers, and finally to the output layer, with no loops or feedback throughout.

** Basic structure of a feedforward neural network: **
-
Input layer: The entry point for data into the network. Each node in the input layer represents an input feature.
-
Hidden layer:One or more layers used to capture non-linear features of the data. Each hidden layer consists of multiple neurons, and each neuron adds non-linearity through an activation function.
-
Output layer:Outputs the network's prediction result. The number of nodes depends on the problem type; for example, in a classification problem the number of output nodes equals the number of classes.
-
Connection Weights and Biases:Each neuron's inputs are weighted and summed, a bias value is added, and the result is passed through an activation function.
Recurrent Neural Network (RNN)
A Recurrent Neural Network (RNN) is a class of neural networks specialized for processing sequential data, capable of capturing dependencies in temporal or ordered information within the input data.
What makes RNNs special is their "memory ability", which allows them to store information from previous time steps in the network's hidden state.
Recurrent neural networks are used to handle data patterns that change over time.
In an RNN, the same layer is used to receive input parameters and display output parameters in the specified neural network.

PyTorch provides powerful tools for building and training neural networks.
Neural networks are implemented in PyTorch through the torch.nn module.
The torch.nn module provides various network layers (such as fully connected and convolutional layers), loss functions, and optimizers, making the construction and training of neural networks more convenient.

In PyTorch, building a neural network usually requires subclassing the nn.Module class.
nn.Module is the base class of all neural network modules; you need to define the following two parts:
__init__(): define the network layers.forward(): define the forward pass of data.
A simple Fully Connected Network:
Example
import
torch
import
torch.
nn
as
nn
Define a Simple Neural Network Model
class
SimpleNN
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
SimpleNN
,
self
)
.
init
(
)
Define a fully connected layer from input to hidden
self
.
fc1
=
nn.
Linear
(
2
,
2
)
2 input features, 2 output features
Define a fully connected layer from hidden to output
self
.
fc2
=
nn.
Linear
(
2
,
1
)
2 input features, 1 output prediction
def
forward
(
self
,
x
)
:
Forward pass
x
=
torch.
relu
(
self
.
fc1
(
x
)
)
Use the ReLU activation function
x
=
self
.
fc2
(
x
)
Output layer
return
x
Create a model instance
model
=
SimpleNN
(
)
Print the model
(
model
)
The output is as follows:
SimpleNN(
(fc1): Linear(in_features=2, out_features=2, bias=True)
(fc2): Linear(in_features=2, out_features=1, bias=True)
)
PyTorch provides many common neural network layers; here are a few:
nn.Linear(in_features, out_features): fully connected layer, takesin_featuresfeatures, outputsout_featuresfeatures.nn.Conv2d(in_channels, out_channels, kernel_size): 2D convolutional layer, used for image processing.nn.MaxPool2d(kernel_size): 2D max pooling layer, used for dimensionality reduction.nn.ReLU(): ReLU activation function, commonly used in hidden layers.nn.Softmax(dim): Softmax activation function, usually used in the output layer, suitable for multi-class classification problems.
Activation Function
Activation functions determine whether a neuron should be activated. They are non-linear functions that enable neural networks to learn and perform more complex tasks. Common activation functions include:
- Sigmoid: used for binary classification problems, outputs values between 0 and 1.
- Tanh: outputs values between -1 and 1, often used before the output layer.
- ReLU (Rectified Linear Unit): currently one of the most popular activation functions, defined as
f(x) = max(0, x), which helps address the vanishing gradient problem. - Softmax: commonly used in the output layer for multi-class problems, converting outputs into a probability distribution.
Example
import
torch.
nn
.
functional
as
F
ReLU activation
output
=
F.
relu
(
input_tensor
)
Sigmoid activation
output
=
torch.
sigmoid
(
input_tensor
)
Tanh activation
output
=
torch.
tanh
(
input_tensor
)
Loss Function
A loss function measures the difference between the model's predicted values and the true values.
Common loss functions include:
- Mean Squared Error (MSELoss): commonly used for regression problems, computes the squared difference between output and target.
- Cross Entropy Loss (CrossEntropyLoss): commonly used for classification problems, computes the cross entropy between output and true labels.
- BCEWithLogitsLoss: for binary classification problems, combines Sigmoid activation and binary cross entropy loss.
Example
Mean squared error loss
criterion
=
nn.
MSELoss
(
)
Cross entropy loss
criterion
=
nn.
CrossEntropyLoss
(
)
Binary cross entropy loss
criterion
=
nn.
BCEWithLogitsLoss
(
)
Optimizer
The optimizer is responsible for updating the network's weights and biases during training.
Common optimizers include:
- SGD (Stochastic Gradient Descent)
- Adam (Adaptive Moment Estimation)
- RMSprop (Root Mean Square Propagation)
Example
import
torch.
optim
as
optim
Using the SGD optimizer
optimizer
=
optim.
SGD
(
model.
parameters
(
)
,
lr
=
0.01
)
Using the Adam optimizer
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
0.001
)
Training Process
Training a neural network involves the following steps:
- Prepare data: Through
DataLoaderLoad the data. - Define the loss function and optimizer.
- Forward propagation: compute the model's output.
- Compute the loss: compare with the target to obtain the loss value.
- Backpropagation: Through
loss.backward()Compute the gradients. - Update parameters: Through
optimizer.step()Update the model's parameters. - Repeat the above stepsuntil the preset number of training epochs is reached.
Example
Assume the model, loss function, and optimizer have already been defined
Training data example
X
=
torch.
randn
(
10
,
2
)
10 samples, each with 2 features
Y
=
torch.
randn
(
10
,
1
)
10 target labels
Training process
for
epoch
in
range
(
100
)
:
Train for 100 epochs
model.
train
(
)
Set the model to training mode
optimizer.
zero_grad
(
)
Clear gradients
output
=
model
(
X
)
Forward propagation
loss
=
criterion
(
output
,
Y
)
Compute the loss
loss.
backward
(
)
Backpropagation
optimizer.
step
(
)
Update the weights
if
(
epoch +
1
)
%
10
==
0
:
Print the loss every 10 epochs
(
f
'Epoch [{epoch + 1}/100], Loss: {loss.item():.4f}'
)
Testing and evaluation
After training is complete, the model needs to be tested and evaluated.
Common steps include:
- Compute the loss on the test set: test the model's performance on unseen data.
- Compute accuracy: for classification problems, compute the proportion of correct predictions.
Example
Suppose you have a test set X_test and Y_test
model.
eval
(
)
Set the model to evaluation mode
with
torch.
no_grad
(
)
:
Disable gradient computation during evaluation
output
=
model
(
X_test
)
loss
=
criterion
(
output
,
Y_test
)
(
f
'Test Loss: {loss.item():.4f}'
)
Types of neural networks
- Feedforward Neural Networks: data flows in one direction, from the input layer to the output layer, with no feedback connections.
- Convolutional Neural Networks (CNNs): suitable for image processing, using convolutional layers to extract spatial features.
- Recurrent Neural Networks (RNNs): suitable for sequential data such as time-series analysis and natural language processing, allowing feedback loops of information.
- Long Short-Term Memory (LSTM): a special kind of RNN that can learn long-term dependencies.
torch.nn reference
The following are the most commonly used in PyTorch torch.nn functions and classes:
Model definition basics
| function | Description | Example |
|---|---|---|
| nn.Module | Base class for all neural network modules | class Net(nn.Module): ... |
| nn.Sequential | Sequential container that executes layers in order | nn.Sequential(conv, relu, pool) |
| nn.ModuleList | Store submodules in a list | self.layers = nn.ModuleList([...]) |
| nn.Parameter | Create learnable parameter tensors | self.w = nn.Parameter(torch.randn(n)) |
Convolutional layers
| function | Description | Example |
|---|---|---|
| nn.Conv1d | 1D convolution (text, audio) | nn.Conv1d(3, 64, 3) |
| nn.Conv2d | 2D convolution (images) | nn.Conv2d(3, 64, 3, padding=1) |
| nn.Conv3d | 3D convolution (video) | nn.Conv3d(3, 64, 3) |
| nn.ConvTranspose2d | Transposed convolution (decoders, upsampling) | nn.ConvTranspose2d(64, 3, 2, stride=2) |
Pooling layers
| function | Description | Example |
|---|---|---|
| nn.MaxPool2d | 2D max pooling | nn.MaxPool2d(2, 2) |
| nn.AvgPool2d | 2D average pooling | nn.AvgPool2d(2, 2) |
| nn.AdaptiveAvgPool2d | Adaptive average pooling (fixed output size) | nn.AdaptiveAvgPool2d((1, 1)) |
| nn.AdaptiveMaxPool2d | Adaptive max pooling (fixed output size) | nn.AdaptiveMaxPool2d((1, 1)) |
Linear layers
| function | Description | Example |
|---|---|---|
| nn.Linear | Fully connected layer (linear transformation) | nn.Linear(128, 64) |
| nn.Bilinear | Bilinear layer | nn.Bilinear(128, 64, 32) |
| function | Description | Example |
| nn.ReLU | ReLU activation function, f(x) = max(0, x) | nn.ReLU() |
| nn.GELU | Gaussian Error Linear Unit (default for Transformer) | nn.GELU() |
| nn.SiLU | Swish activation function | nn.SiLU() |
| nn.Tanh | Hyperbolic tangent | nn.Tanh() |
| nn.Sigmoid | Sigmoid activation function | nn.Sigmoid() |
| nn.Softmax | Softmax activation function | nn.Softmax(dim=1) |
| nn.LogSoftmax | Log Softmax (numerically stable) | nn.LogSoftmax(dim=1) |
| nn.LeakyReLU | LeakyReLU, allows small gradients for negative values | nn.LeakyReLU(0.01) |
| nn.ELU | Exponential Linear Unit | nn.ELU() |
Normalization layers
| function | Description | Example |
|---|---|---|
| nn.BatchNorm2d | 2D batch normalization (commonly used in convolutional networks) | nn.BatchNorm2d(64) |
| nn.LayerNorm | Layer normalization (commonly used in Transformers) | nn.LayerNorm(512) |
| nn.GroupNorm | Group normalization (commonly used in ResNet and others) | nn.GroupNorm(4, 64) |
| nn.InstanceNorm2d | Instance normalization (commonly used in style transfer) | nn.InstanceNorm2d(64) |
Recurrent layers
| function | Description | Example |
|---|---|---|
| nn.LSTM | LSTM (Long Short-Term Memory) layer | nn.LSTM(256, 512, 2) |
| nn.GRU | GRU (Gated Recurrent Unit) layer | nn.GRU(256, 512, 2) |
| nn.RNN | Simple RNN layer | nn.RNN(256, 512, 2) |
Transformer layer
| function | Description | Example |
|---|---|---|
| nn.Transformer | Complete Transformer model | nn.Transformer(d_model=512, nhead=8) |
| nn.TransformerEncoder | Transformer encoder | nn.TransformerEncoder(layer, num_layers=6) |
| nn.TransformerDecoder | Transformer decoder | nn.TransformerDecoder(layer, num_layers=6) |
| nn.TransformerEncoderLayer | Transformer encoder layer | nn.TransformerEncoderLayer(512, 8) |
| nn.MultiheadAttention | Multi-head attention mechanism | nn.MultiheadAttention(512, 8) |
Embedding layer
| function | Description | Example |
|---|---|---|
| nn.Embedding | Embedding layer (maps vocabulary to vectors) | nn.Embedding(10000, 256) |
| nn.EmbeddingBag | Embedding bag (aggregates multiple embeddings) | nn.EmbeddingBag(10000, 256) |
Dropout layer
| function | Description | Example |
|---|---|---|
| nn.Dropout | Random dropping (prevents overfitting) | nn.Dropout(0.5) |
| nn.Dropout2d | 2D Dropout (drop by feature map) | nn.Dropout2d(0.5) |
Loss function
| function | Description | Example |
|---|---|---|
| nn.CrossEntropyLoss | Cross-entropy loss (multi-class classification) | nn.CrossEntropyLoss() |
| nn.MSELoss | Mean squared error loss (regression) | nn.MSELoss() |
| nn.L1Loss | L1 loss (MAE) | nn.L1Loss() |
| nn.BCEWithLogitsLoss | Binary cross-entropy with Sigmoid | nn.BCEWithLogitsLoss() |
| nn.HuberLoss | Huber loss (robust regression) | nn.HuberLoss() |
| nn.NLLLoss | Negative log-likelihood loss | nn.NLLLoss() |
Functional functions (nn.functional)
| function | Description | Example |
|---|---|---|
F.relu |
ReLU activation | F.relu(x) |
F.gelu |
GELU activation | F.gelu(x) |
F.sigmoid |
Sigmoid activation | F.sigmoid(x) |
F.softmax |
Softmax activation | F.softmax(x, dim=1) |
F.dropout |
Dropout operation | F.dropout(x, 0.5, training) |
F.conv2d |
2D convolution | F.conv2d(x, weight, bias) |
F.linear |
Linear transformation | F.linear(x, weight, bias) |
F.cross_entropy |
Cross entropy loss | F.cross_entropy(logits, targets) |
F.mse_loss |
Mean squared error loss | F.mse_loss(pred, target) |
F.interpolate |
Interpolation (upsampling/downsampling) | F.interpolate(x, scale_factor=2) |
F.embedding |
Embedding operation | F.embedding(indices, weight) |
Utility functions (nn.init)
| function | Description | Example |
|---|---|---|
nn.init.xavier_uniform_ |
Xavier uniform initialization | nn.init.xavier_uniform_(module.weight) |
nn.init.xavier_normal_ |
Xavier normal initialization | nn.init.xavier_normal_(module.weight) |
nn.init.kaiming_uniform_ |
Kaiming uniform initialization (suitable for ReLU) | nn.init.kaiming_uniform_(module.weight) |
nn.init.kaiming_normal_ |
Kaiming normal initialization (suitable for ReLU) | nn.init.kaiming_normal_(module.weight) |
nn.init.zeros_ |
Zero initialization | nn.init.zeros_(module.bias) |
nn.init.normal_ |
Normal initialization | nn.init.normal_(module.weight, 0, 0.01) |
Utility functions (nn.utils)
| function | Description | Example |
|---|---|---|
nn.utils.clip_grad_norm_ |
Clip gradient norm (prevents exploding gradients) | nn.utils.clip_grad_norm_(model.parameters(), 1.0) |
nn.utils.weight_norm |
Weight normalization | nn.utils.weight_norm(module, 'weight') |
nn.utils.spectral_norm |
Spectral normalization (commonly used in GANs) | nn.utils.spectral_norm(module, 'weight') |
nn.utils.rnn.pack_padded_sequence |
Pack variable-length sequences | pack_padded_sequence(x, lengths) |
nn.utils.rnn.pad_packed_sequence |
Unpack sequences | pad_packed_sequence(packed) |