#Creating Tensors in PyTorch
Note: Before executing any code , ensure that you have completed the PyTorch setup.
If you're using Google Colab, there's no need to worry PyTorch and other necessary libraries are pre-installed, so everything should work seamlessly.
Let’s begin by importing PyTorch and verifying the version we’re working with.
You can create tensors using various methods in PyTorch , let’s break down different types of tensors:
#0-D Tensor (Scalar)
A scalar is a single number. It’s the simplest form of a tensor.
Output:
#1-D Tensor (Vector)
A vector is a one-dimensional tensor that can hold multiple numbers in a single line.
Output:
#2-D Tensor (Matrix)
A matrix is a two-dimensional tensor. It has rows and columns, like a table of numbers.
Output:
#3-D Tensor
A 3-D tensor is like a stack of matrices. It has depth, along with rows and columns.
Output:
Let’s review the key points
- 0-D Tensor (Scalar): A single number.
- 1-D Tensor (Vector): A list of numbers.
- 2-D Tensor (Matrix): A grid of numbers with rows and columns.
- 3-D Tensor: A stack of matrices.
#Random Tensors
In machine learning, tensors are often initialized with random values. This randomness is useful for initializing model parameters before training. PyTorch provides a function to generate tensors with random numbers:
Output:
In this example, torch.rand(2, 3) creates a tensor of shape [2, 3] with random values between 0 and 1.
#Zeros and Ones
Sometimes, you need tensors filled with zeros or ones, especially when initializing weights or masks. PyTorch offers functions to create such tensors:
Output:
Here, torch.zeros(2, 3) creates a tensor of shape [2, 3] filled with zeros, while torch.ones(2, 3) creates one filled with ones.
#Creating a Range of Values
Sometimes, you might need to create a tensor with a range of values. This is useful for creating sequences or grids of values:
Output:
The torch.arange(5) function creates a tensor with values [0, 1, 2, 3, 4].
Sure! Here are two exercises focusing on 1-D and 2-D tensors, with their solutions provided:
#Exercise 1: Creating and Inspecting Tensors
Task:
- Create a 2-D tensor with the following values:
- Create a 1-D tensor with values ranging from 0 to 4.
- Print both tensors .
#Exercise 2: Tensor Initialization and Operations
Task:
- Create a 2-D tensor of shape
[3, 2]filled with zeros. - Create a 2-D tensor of shape
[3, 2]filled with ones. - Create a 1-D tensor with 6 random values between 0 and 1.
- Print all three tensors.
