Python module PyTorch introduction and basic syntax
1140225 Meeting
Cover image is the official PyTorch logo, captured from Github on February 22, 2025.
Introduction
PyTorch is an open-source machine learning library developed based on the Python language and is one of the most popular deep learning frameworks today. PyTorch’s origins trace back to the technical accumulation of several research institutions and projects, mainly the Torch library based on the Lua language and Facebook’s Artificial Intelligence Research team (Facebook AI Research, FAIR, now Meta AI), which developed the cross-platform high-performance computing Caffe2 deep learning framework. In 2017, companies like Microsoft, Facebook, and IBM collaborated to develop the Open Neural Network Exchange (ONNX) format, which is hosted as open-source on GitHub, enabling PyTorch to be interoperable with other deep learning frameworks.
Features
Compared to other deep learning frameworks, PyTorch offers the following advantages and features:
Integration with Python
PyTorch uses Python as its main API and has excellent support for other Python modules, such as NumPy and SciPy. Additionally, due to PyTorch’s modular design for neural networks, we can easily and quickly build models by creating layers such as linear layers, convolutional neural network layers (CNN), recurrent neural network layers (RNN), and long short-term memory layers (LSTM).
Automatic Differentiation and Gradient Calculation
Differentiating a model or calculating gradients is often a tedious task. However, PyTorch’s submodule torch.autograd can automatically compute gradients. For programmers, this makes solving various deep learning and optimization problems in a simple, intuitive way possible. We only need to write .backward() in Python to automatically compute gradients, achieving efficient and accurate backpropagation.
GPU Acceleration
PyTorch defines a class called Tensor, which is used to store or compute multi-dimensional arrays of numbers. Tensors are similar to NumPy arrays, making it easy to convert between PyTorch tensors and NumPy arrays. Unlike NumPy, PyTorch can run on Nvidia GPUs with CUDA support. By simply writing .to(device), we can move Tensors or models to the GPU for faster computations compared to the CPU.
Compatibility
PyTorch supports ONNX, allowing it to interoperate with other deep learning frameworks and easily transfer and deploy across different environments and machines.
Basic Syntax
Installing PyTorch
We need to install Python in order to use PyTorch. Below is an example of installation using Python and the pip package management system. If you’re using a different Python distribution, such as Anaconda, please refer to the relevant installation methods.
You can install PyTorch by entering the following command in the terminal or refer to the official documentation https://pytorch.org/get-started/locally/ for further instructions.
| |
Once the installation is complete, we can load the PyTorch module in the Python terminal.
| |
And check the PyTorch version to verify if the installation was successful.
| |
| |
If you have an Nvidia GPU and your GPU supports CUDA, please update the GPU drivers to the latest version. After that, obtain the installation instructions from the official documentation https://pytorch.org/get-started/locally/ and run the installation command in the terminal to enable GPU computation.

| |
We can use the following code to check if CUDA is successfully installed and accessible by PyTorch.
| |
If CUDA is available, it will return True.
| |
Creating a Tensor
When using PyTorch, we can create a Tensor and perform operations on it.
| |
| |
We can also convert a NumPy array to a Tensor.
| |
Similarly, we can convert a Tensor back into a NumPy array.
| |
The .cpu() function ensures that during the conversion, the data in the Tensor can be copied from the GPU to the CPU before conversion, preventing any conversion errors.
GPU Acceleration
We can use .to("cuda") to move a variable from the CPU to the GPU.
| |
| |
However, having to modify the code every time it runs in different environments can be a bit troublesome. Therefore, we can rewrite it as follows to automatically determine which processor should be used.
| |
Creating a Simple Neural Network Model
In Python, we can create a neural network model using the class function through PyTorch. Below is an example.
| |
The example above creates a model with 2-dimensional input and 1-dimensional output, suitable for a simple binary classification problem.
After successfully creating the model, if the execution environment supports CPU acceleration, we can move the model to the GPU.
| |
| |
Training the Model
Next, we define the criterion and optimizer, which are the loss function and gradient descent method, respectively. Since the model defined earlier is for binary classification, we use Binary Cross Entropy Loss as the loss function. The learning rate (lr) for gradient descent is set to 0.01.
| |
Prepare the data for training.
| |
Now, let’s train the model with a simple loop.
| |
| |
- Forward Propagation refers to the process where data is passed through the network layers from the input to the output.
- Backpropagation is a key algorithm in training neural networks, aimed at calculating and updating the model’s weights and biases to minimize the loss function.
Testing the Model
Assume we have a set of data for testing, the prediction result would look like this:
| |
| |
Since the training data is a binary classification model with 0 or 1 labels, we can classify the neural network output as label 0 if it’s less than 0.5 and label 1 if it’s greater than 0.5.
This is how we can establish a simple neural network model.
Of course, larger training datasets and more training iterations may improve the model’s prediction accuracy, but it will also increase the training time. The relationship between dataset size, training iterations, and prediction accuracy is not linear. In fact, too much data or too many training iterations can cause the prediction accuracy to decline, so finding a balance is important.
Conclusion
Neural networks are one of the core technologies in modern machine learning and artificial intelligence. With the development of deep learning, neural networks have become the foundation for many advanced technologies, including speech recognition, image recognition, time-series forecasting, and data imputation. With an in-depth understanding of neural networks, we can try to build more complex model structures and apply them in more complex fields, allowing neural networks to solve various complicated problems for us.
References
- Get Started: Select preferences and run the command to install PyTorch locally, or get started quickly with one of the supported cloud platforms.(n.d.) PyTorch. Retrieved on February 24, 2025 from https://pytorch.org/get-started/locally/
- Open Neural Network Exchange. (October 7, 2024). Wikipedia, the free encyclopedia. Retrieved on February 24, 2025 from https://en.wikipedia.org/wiki/Open_Neural_Network_Exchange
- PyTorch. (October 7, 2024). Wikipedia, the free encyclopedia. Retrieved on February 24, 2025 from https://en.wikipedia.org/wiki/PyTorch
- PyTorch. (February 24, 2025). Github. Retrieved on February 24, 2025 from https://github.com/pytorch/pytorch


![[Thought] Historical Earthquake Locations Around Taiwan](https://Josh-test-lab.github.io/posts/Historical%20Earthquake%20Locations%20Around%20Taiwan/cover%20image.webp)




