DL_pytorch_
DL_pytorch_
Learning
1 Introduction to PyTorch
PyTorch is a popular open-source library for deep learning, developed by
Facebook AI. It is widely used for research and production because of its
flexibility and ease of use.
Why PyTorch?
• They are not the best for deep learning because they process tasks
sequentially.
1
import torch
device = torch . device ( " cpu " ) # Force PyTorch to use CPU
x = torch . rand (3 , 3 , device = device )
print ( x )
• Unlike CPUs, GPUs have thousands of small cores that allow them to
process many tasks at once.
• This makes them much faster for deep learning and AI tasks.
2
import torch
print ( torch . cuda . is_available () ) # Returns True if a
,→ GPU is available
Selecting a Device
device = torch . device ( " cuda " if torch . cuda . is_available
,→ () else " cpu " )
print ( device )
5 What is a Tensor?
A tensor is a multi-dimensional array, similar to a NumPy array, but with
the added capability of being used on GPUs for faster computation.
Why Tensors?
• Tensors store numerical data.
• They work efficiently with GPUs.
• They are the basic building blocks of deep learning models.
6 Installing PyTorch
Before using PyTorch, install it using:
pip install torch torchvision torchaudio
3
x = torch . zeros (3 , 3)
print ( x )
8. Using reshape()
x = torch . rand (3 , 4)
y = x . reshape (2 , 6)
print ( y )
4
7.4 Mathematical Operations on Tensors
9. Adding two tensors
a = torch . tensor ([1 , 2 , 3])
b = torch . tensor ([4 , 5 , 6])
c = a + b
print ( c )
5
z = torch . from_numpy ( y )
print ( z )
6
7.9 Tensor Reduction Operations
Reduction operations summarize information in tensors.
23. Finding the mean of a tensor
x = torch . tensor ([1.0 , 2.0 , 3.0 , 4.0])
print ( torch . mean ( x ) )
7.11 Conclusion
Tensors are the backbone of deep learning in PyTorch. They allow us to
perform numerical operations efficiently on CPUs and GPUs. Mastering
tensor operations is essential for working with neural networks.
7
2. Create a tensor with values from 1 to 10 and print its shape.
3. Create a 2 × 5 tensor filled with ones and convert its data
type to float32.
4. Generate a random tensor of size 4 × 4 and print its values.
5. Create a tensor with values evenly spaced between 0 and 1,
with 5 elements.