Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch Fundamentals

PyTorch Fundamentals

PyTorch is an open-source deep learning framework widely popular for its flexibility and dynamic computational graph.

PyTorch has several core concepts: Tensor, Autograd, neural network modules (nn.Module), optimizers (optim), and more.


PyTorch Architecture Overview

PyTorch uses a modular design, composed of several cooperating core components. Understanding the role of these components and how they relate is key to mastering PyTorch.

PyTorch architecture diagram



┌─────────────────────────────────────────────────────────────┐

│                    PyTorch 生态系统                          │

├─────────────────────────────────────────────────────────────┤

│  torchvision  │  torchtext  │  torchaudio  │  其他专业库     │

├─────────────────────────────────────────────────────────────┤

│                     PyTorch 核心                            │

├───────────────┬─────────────────┬───────────────────────────┤

│   torch.nn    │   torch.optim   │      torch.utils          │

│   (神经网络)   │   (优化器)      │      (工具函数)           │

├───────────────┼─────────────────┼───────────────────────────┤

│               │                 │   torch.utils.data        │

│  torch 核心   │  autograd       │   (数据加载)              │

│  (张量计算)   │  (自动微分)     │                           │

└───────────────┴─────────────────┴───────────────────────────┘

PyTorch adopts aLayered Architecturedesign, arranged from the top layer down as follows:

1. Python API (top layer)

2. C++ Core (middle layer)

3. Foundation libraries (low-level)

Execution flow:
Python code -> C++ core computation -> low-level CUDA/C library acceleration -> return results.
Maintaining ease of use while ensuring high performance.

Tensor

A Tensor is the core data structure in PyTorch, used to store and manipulate multi-dimensional arrays.

A tensor can be viewed as a multi-dimensional array that supports accelerated computation operations.

In PyTorch, the concept of a tensor is similar to an array in NumPy, but PyTorch tensors can run on different devices such as CPU and GPU, which makes them very suitable for large-scale parallel computation, especially in the field of deep learning.

Tensor creation:

Example

import

torch

Create a 2x3 all-zero tensor

a

=

torch.

zeros

(

2

,

3

)

print

(

a

)

Create a 2x3 all-one tensor

b

=

torch.

ones

(

2

,

3

)

print

(

b

)

Create a 2x3 random tensor

c

=

torch.

randn

(

2

,

3

)

print

(

c

)

Create a tensor from a NumPy array

import

numpy

as

np

numpy_array

=

np.

array

(

[

[

1

,

2

]

,

[

3

,

4

]

]

)

tensor_from_numpy

=

torch.

from_numpy

(

numpy_array

)

print

(

tensor_from_numpy

)

Create a tensor on a specified device (CPU/GPU)

device

=

torch.

device

(

"cuda"

if

torch.

cuda

.

is_available

(

)

else

"cpu"

)

d

=

torch.

randn

(

2

,

3

,

device

=

device

)

print

(

d

)

The output is similar to the following:

tensor([[0., 0., 0.],

        [0., 0., 0.]])

tensor([[1., 1., 1.],

        [1., 1., 1.]])

tensor([[ 1.0189, -0.5718, -1.2814],

        [-0.5865,  1.0855,  1.1727]])

tensor([[1, 2],

        [3, 4]])

tensor([[-0.3360,  0.2203,  1.3463],

        [-0.5982, -0.2704,  0.5429]])

Common tensor operations:

Example

Tensor addition

e

=

torch.

randn

(

2

,

3

)

f

=

torch.

randn

(

2

,

3

)

print

(

e + f

)

Element-wise multiplication

print

(

e * f

)

Tensor transpose

g

=

torch.

randn

(

3

,

2

)

print

(

g.

t

(

)

)

 

or g.transpose(0, 1)

Tensor shape

print

(

g.

shape

)

 

Return the shape

Tensors and devices

PyTorch tensors can exist on different devices, including CPU and GPU; you can move a tensor to the GPU to accelerate computation:

if torch.cuda.is_available():

    tensor_gpu = tensor_from_list.to('cuda')  # 将张量移动到GPU

Gradients and automatic differentiation

PyTorch tensors support automatic differentiation, a key feature in deep learning. When you create a tensor that requires gradients, PyTorch can automatically compute its gradients:

Example

Create a tensor that requires gradients

tensor_requires_grad

=

torch.

tensor

(

[

1.0

]

,

requires_grad

=

True

)

Perform some operations

tensor_result

=

tensor_requires_grad *

2

Compute gradients

tensor_result.

backward

(

)

print

(

tensor_requires_grad.

grad

)

 

Print the gradient

Memory and performance

PyTorch tensors also provide some memory management features, such as the .clone(), .detach(), and .to() methods, which can help you optimize memory usage and improve performance.


Autograd

Automatic differentiation (abbreviated as Autograd) is a core feature of deep learning frameworks that allows computers to automatically compute the derivatives of mathematical functions.

In deep learning, automatic differentiation is mainly used in two aspects:First, computing gradients when training neural networks, Second, implementing the backpropagation algorithm.

Automatic differentiation is based on the chain rule, a mathematical rule for computing the derivatives of complex functions. The chain rule states that the derivative of a composite function is the product of the derivatives of its component parts. In deep learning, a model is usually a complex function composed of many layers, and automatic differentiation can efficiently compute the gradients of these layers.

Dynamic graphs and static graphs:

PyTorch provides automatic differentiation through the autograd module to compute gradients automatically.

A torch.Tensor object has a requires_grad attribute that indicates whether the gradient of that tensor needs to be computed.

When you create a tensor with requires_grad=True, PyTorch automatically tracks all operations on it so that gradients can be computed later.

Create a tensor that requires gradients:

Example

Create a tensor that requires gradient computation

x

=

torch.

randn

(

2

,

2

,

requires_grad

=

True

)

print

(

x

)

Perform some operations

y

=

x +

2

z

=

y * y *

3

out

=

z.

mean

(

)

print

(

out

)

The output is similar to the following:

tensor([[0., 0., 0.],

        [0., 0., 0.]])

tensor([[1., 1., 1.],

        [1., 1., 1.]])

tensor([[ 1.0189, -0.5718, -1.2814],

        [-0.5865,  1.0855,  1.1727]])

tensor([[1, 2],

        [3, 4]])

tensor([[-0.3360,  0.2203,  1.3463],

        [-0.5982, -0.2704,  0.5429]])

tianqixin@Mac-mini runoob-test % python3 test.py

tensor([[-0.1908,  0.2811],

        [ 0.8068,  0.8002]], requires_grad=True)

tensor(18.1469, grad_fn=)

Backpropagation

Once the computational graph is defined, gradients can be computed via the .backward() method.

Example

Backpropagate and compute gradients

out.

backward

(

)

View the gradient of x

print

(

x.

grad

)

In neural network training, automatic differentiation is mainly used to implement the backpropagation algorithm.

Backpropagation is a method of training neural networks by computing the gradient of the loss function with respect to the network parameters. In each iteration, the forward pass of the network computes the output and loss, then backpropagation computes the gradient of the loss with respect to each parameter and uses these gradients to update the parameters.

Stop gradient computation

If you do not want gradients to be computed for certain tensors (for example, when you don't need backpropagation), you can use torch.no_grad() or set requires_grad=False.

Example

Disable gradient computation with torch.no_grad()

with

torch.

no_grad

(

)

:

    y

=

x *

2


Neural Networks (nn.Module)

A neural network is a computational model that mimics the connections of neurons in the human brain. It consists of multiple layers of nodes (neurons) and is used to learn complex patterns and relationships in data.

A neural network optimizes prediction results by adjusting the connection weights between neurons; this process involves forward propagation, loss computation, backpropagation, and parameter updates.

Types of neural networks include feedforward neural networks, convolutional neural networks (CNN), recurrent neural networks (RNN), and long short-term memory networks (LSTM), which are widely used in fields such as image recognition, speech processing, and natural language processing.

PyTorch provides a very convenient interface for building neural network models, namely torch.nn.Module.

We can inherit from the nn.Module class and define our own network layers.

Create a simple neural network:

Example

import

torch.

nn

as

nn

import

torch.

optim

as

optim

Define a simple fully connected neural network

class

SimpleNN

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

SimpleNN

,

self

)

.

init

(

)

       

self

.

fc1

=

nn.

Linear

(

2

,

2

)

 

Input layer to hidden layer

       

self

.

fc2

=

nn.

Linear

(

2

,

1

)

 

Hidden layer to output layer

   

   

def

forward

(

self

,

x

)

:

        x

=

torch.

relu

(

self

.

fc1

(

x

)

)

 

ReLU activation function

        x

=

self

.

fc2

(

x

)

       

return

x

Create a network instance

model

=

SimpleNN

(

)

Print the model structure

print

(

model

)

Output result:

SimpleNN(

  (fc1): Linear(in_features=2, out_features=2, bias=True)

  (fc2): Linear(in_features=2, out_features=1, bias=True)

)

Training process:

  1. Forward Propagation: During the forward propagation phase, input data passes through the network layers, with each layer applying weights and an activation function until an output is produced.

  2. Calculate Loss: Compute the value of the loss function based on the network's output and the true labels.

  3. Backpropagation: Backpropagation uses automatic differentiation to compute the gradient of the loss function with respect to each parameter.

  4. Parameter Update: Use an optimizer to update the network's weights and biases based on the gradients.

  5. Iteration: Repeat the above process until the model's performance on the training data reaches a satisfactory level.

Forward propagation and loss computation

Example

Random input

x

=

torch.

randn

(

1

,

2

)

Forward propagation

output

=

model

(

x

)

print

(

output

)

Define a loss function (such as mean squared error, MSE)

criterion

=

nn.

MSELoss

(

)

Assume the target value is 1

target

=

torch.

randn

(

1

,

1

)

Compute the loss

loss

=

criterion

(

output

,

target

)

print

(

loss

)

Optimizers

An optimizer updates the neural network's parameters during training to reduce the value of the loss function.

PyTorch provides a variety of optimizers, such as SGD and Adam.

Parameter update using an optimizer:

Example

Define an optimizer (using the Adam optimizer)

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.001

)

Training step

optimizer.

zero_grad

(

)

 

Clear the gradients

loss.

backward

(

)

 

Backpropagation

optimizer.

step

(

)

 

Update parameters


Train the model

Training a model is a core process in machine learning and deep learning, aiming to learn model parameters from large amounts of data so that the model can make accurate predictions on new, unseen data.

Training a model usually includes the following steps:

  1. Data preparation:

  2. Collect and process data, including cleaning, standardization, and normalization.
  3. Split the data into training, validation, and test sets.
  4. - Collect and process data, including cleaning, standardization, and normalization. - Split the data into training, validation, and test sets.
    1. Define the model:

    2. Choose a model architecture, such as a decision tree or neural network.
    3. Initialize the model parameters (weights and biases).
    4. - Choose a model architecture, such as a decision tree or neural network. - Initialize the model parameters (weights and biases).
      1. Choose a loss function:

      2. Choose an appropriate loss function based on the task type (such as classification or regression).
      3. - Choose an appropriate loss function based on the task type (such as classification or regression).
        1. Choose an optimizer:

        2. Choose an optimization algorithm, such as SGD or Adam, to update the model parameters.
        3. - Choose an optimization algorithm, such as SGD or Adam, to update the model parameters.
          1. Forward propagation:

          2. In each iteration, pass the input data through the model to compute the predicted output.
          3. - In each iteration, pass the input data through the model to compute the predicted output.
            1. Compute the loss:

            2. Use a loss function to evaluate the difference between the predicted output and the true labels.
            3. - Use a loss function to evaluate the difference between the predicted output and the true labels.
              1. Backpropagation:

              2. Use automatic differentiation to compute the gradient of the loss with respect to the model parameters.
              3. - Use automatic differentiation to compute the gradient of the loss with respect to the model parameters.
                1. Parameter update:

                2. Update the model parameters based on the computed gradients and the optimizer's strategy.
                3. - Update the model parameters based on the computed gradients and the optimizer's strategy.
                  1. Iterative Optimization:

                  2. Repeat steps 5-8 until the model's performance on the validation set no longer improves or a predetermined number of iterations is reached.
                  3. - Repeat steps 5-8 until the model's performance on the validation set no longer improves or a predetermined number of iterations is reached.
                    1. Evaluation and testing:

                    2. Use the test set to evaluate the model's final performance and ensure the model has not overfit.
                    3. - Use the test set to evaluate the model's final performance and ensure the model has not overfit.
                      1. Model tuning:

                      2. Tune parameters based on the model's performance on the test set, such as changing the learning rate or increasing regularization.
                      3. - Tune parameters based on the model's performance on the test set, such as changing the learning rate or increasing regularization.
                        1. Deploy the model:

                        2. Deploy the trained model to a production environment for real prediction tasks.
                        3. - Deploy the trained model to a production environment for real prediction tasks.

                          Example

                          import

                          torch

                          import

                          torch.

                          nn

                          as

                          nn

                          import

                          torch.

                          optim

                          as

                          optim

                          1. Define a simple neural network model

                          class

                          SimpleNN

                          (

                          nn.

                          Module

                          )

                          :

                             

                          def

                          init

                          (

                          self

                          )

                          :

                                 

                          super

                          (

                          SimpleNN

                          ,

                          self

                          )

                          .

                          init

                          (

                          )

                                 

                          self

                          .

                          fc1

                          =

                          nn.

                          Linear

                          (

                          2

                          ,

                          2

                          )

                           

                          Input layer to hidden layer

                                 

                          self

                          .

                          fc2

                          =

                          nn.

                          Linear

                          (

                          2

                          ,

                          1

                          )

                           

                          Hidden layer to output layer

                             

                             

                          def

                          forward

                          (

                          self

                          ,

                          x

                          )

                          :

                                  x

                          =

                          torch.

                          relu

                          (

                          self

                          .

                          fc1

                          (

                          x

                          )

                          )

                           

                          ReLU activation function

                                  x

                          =

                          self

                          .

                          fc2

                          (

                          x

                          )

                                 

                          return

                          x

                          2. Create a model instance

                          model

                          =

                          SimpleNN

                          (

                          )

                          3. Define the loss function and optimizer

                          criterion

                          =

                          nn.

                          MSELoss

                          (

                          )

                           

                          Mean squared error loss function

                          optimizer

                          =

                          optim.

                          Adam

                          (

                          model.

                          parameters

                          (

                          )

                          ,

                          lr

                          =

                          0.001

                          )

                           

                          Adam optimizer

                          4. Assume we have training data X and Y

                          X

                          =

                          torch.

                          randn

                          (

                          10

                          ,

                          2

                          )

                           

                          10 samples, 2 features

                          Y

                          =

                          torch.

                          randn

                          (

                          10

                          ,

                          1

                          )

                           

                          10 target values

                          5. Training loop

                          for

                          epoch

                          in

                          range

                          (

                          100

                          )

                          :  

                          Train for 100 epochs

                              optimizer.

                          zero_grad

                          (

                          )

                           

                          Clear previous gradients

                              output

                          =

                          model

                          (

                          X

                          )

                           

                          Forward propagation

                              loss

                          =

                          criterion

                          (

                          output

                          ,

                          Y

                          )

                           

                          Compute the loss

                              loss.

                          backward

                          (

                          )

                           

                          Backpropagation

                              optimizer.

                          step

                          (

                          )

                           

                          Update parameters

                             

                             

                          Print the loss every 10 epochs

                             

                          if

                          (

                          epoch+

                          1

                          )

                          %

                          10

                          ==

                          0

                          :

                                 

                          print

                          (

                          f

                          'Epoch [{epoch+1}/100], Loss: {loss.item():.4f}'

                          )

                          The output is as follows:

                          Epoch [10/100], Loss: 1.7180
                          
                          Epoch [20/100], Loss: 1.6352
                          
                          Epoch [30/100], Loss: 1.5590
                          
                          Epoch [40/100], Loss: 1.4896
                          
                          Epoch [50/100], Loss: 1.4268
                          
                          Epoch [60/100], Loss: 1.3704
                          
                          Epoch [70/100], Loss: 1.3198
                          
                          Epoch [80/100], Loss: 1.2747
                          
                          Epoch [90/100], Loss: 1.2346
                          
                          Epoch [100/100], Loss: 1.1991
                          
                          

                          Every 10 epochs, the program prints the current loss value to help us track the model's training progress. As training proceeds, the loss should gradually decrease, indicating that the model is continuously learning and optimizing its parameters.

                          Training a model is an iterative process that requires continuous adjustment and optimization until satisfactory performance is achieved. This process involves extensive experimentation and tuning, with the goal of giving the model good generalization ability on new, unseen data.


                          Device

                          PyTorch allows you to move models and data to the GPU for acceleration.

                          Use torch.device to specify the computing device.

                          Move the model and data to the GPU:

                          Example

                          device

                          =

                          torch.

                          device

                          (

                          "cuda"

                          if

                          torch.

                          cuda

                          .

                          is_available

                          (

                          )

                          else

                          "cpu"

                          )

                          Move the model to the device

                          model.

                          to

                          (

                          device

                          )

                          Move the data to the device

                          X

                          =

                          X.

                          to

                          (

                          device

                          )

                          Y

                          =

                          Y.

                          to

                          (

                          device

                          )

                          During training, all tensors and the model should be moved to the same device (either all on CPU or all on GPU).