Understanding Tensors
A tensor is a versatile container for data, similar to a list or table, but with enhanced capabilities. It can hold data across several dimensions:- A scalar is the simplest tensor, representing a single number (a zero-dimensional tensor).
- A vector is a one-dimensional tensor, akin to a list of numbers.
- A matrix is a two-dimensional tensor, organized in rows and columns.




Creating Tensors
PyTorch offers several convenient methods to create tensors, depending on your requirements:-
From Lists or Arrays: Convert a list, tuple, or NumPy array to a tensor using the
torch.tensor()function. -
With Specific Values: Create tensors filled with zeros or ones using
torch.zeros()ortorch.ones(). -
Randomly Initialized Tensors: Use
torch.rand()for tensors populated with random numbers between 0 and 1—ideal for initializing model weights. -
Uninitialized Tensors: Use
torch.empty()for creating a tensor with uninitialized values (contents are based on the current memory state).
Key Tensor Attributes
Every PyTorch tensor carries attributes that describe its structure and storage location:- Shape: Indicates the dimensions (e.g., rows and columns).
- dtype: Specifies the data type (e.g.,
float32,int64). - Device: Shows where the tensor is stored, such as the CPU or GPU.
Knowing these attributes helps you manage tensor operations efficiently and debug your deep learning models.
Common Tensor Operations
PyTorch supports over 100 tensor operations. Here are several commonly used ones:- Indexing and Slicing: Extract specific elements or sections of a tensor. For instance, you can select certain rows or columns in a 2D tensor.

- Joining Tensors: Concatenate tensors along a specific dimension (row-wise or column-wise) using functions like
torch.cat().

- Reshaping Tensors: Adjust the dimensions of a tensor (e.g., flatten a 2D matrix into a 1D vector) with the
torch.reshape()function.

Converting Images to Tensors
Converting images into tensors is a frequent task in machine learning. Typically, the Pillow library is used to open images, and TorchVision—via thetransforms.ToTensor() function—converts them into tensors.
Leveraging GPUs with PyTorch
PyTorch’s strong GPU support significantly boosts deep learning performance. GPUs specialize in handling parallel computations, making them ideal for the heavy matrix operations found in deep learning.

Using dynamic device selection ensures that your code runs efficiently on both GPUs and CPUs.