One-Dimensional Tensor in Pytorch
In this article, we are going to discuss a one-dimensional tensor in Python. We will look into the following concepts:
- Creation of One-Dimensional Tensors
- Accessing Elements of Tensor
- Size of Tensor
- Data Types of Elements of Tensors
- View of Tensor
- Floating Point Tensor
The Pytorch is used to process the tensors. Tensors are multidimensional arrays. PyTorch accelerates the scientific computation of tensors as it has various inbuilt functions.
A vector is a one-dimensional tensor that holds elements of multiple data types. We can create vectors using PyTorch. Pytorch is available in the Python torch module. So we need to import it.
Creation of One-Dimensional Tensors:
One dimensional vector is created using the torch.tensor() method.
Where elements are input elements to a tensor
Example: Python program to create tensor elements
tensor([10, 20, 30, 40, 50]) tensor([10.1200, 20.5600, 30.0000, 40.3000, 50.4000])
Accessing Elements of Tensor:
We can access the elements in the tensor vector using the index of elements.
Where the index is the position of the element in the tensor:
- Indexing starts from 0 from first
- Indexing starts from -1 from last
Example: Python program to access elements using the index.
tensor(10) tensor(20) tensor(50) tensor(20) tensor(40)
We can access n elements at a time using the”:” operator, This is known as slicing.
Where start_index is the starting index and end_index is the ending index.
Example: Python program to access multiple elements.
tensor([20, 30, 40]) tensor() tensor()
This is used to get the length(number of elements) in a tensor using the size() method.
Example: Python program to get the tensor size.
Data Types of Elements of Tensors:
We can get the data type of the tensor data elements. Then dtype() is used to get the data type of the tensor
Where tensor_vector is the one-dimensional tensor vector.
View of Tensor:
The view() is used to view the tensor in two-dimensional format ie, rows and columns. We have to specify the number of rows and the number of columns to be viewed.
- tensor is an input one-dimensional tensor
- no_of_rows is the total number of the rows that the tensor is viewed
- no_of_columns is the total number of the columns that the tensor is viewed
Example: Python program to create a tensor with 10 elements and view with 5 rows and 2 columns and vice versa.
tensor([[10., 20.], [30., 40.], [50., 1.], [ 2., 3.], [ 4., 5.]]) tensor([[10., 20., 30., 40., 50.], [ 1., 2., 3., 4., 5.]])
This tensor is used to define the elements with float type. We can create a floating-point Tensor using an integer element by using the FloatTensor property.
torch.FloatTensor([element1,element 2,.,element n])
Example: Python program to create float tensor and get elements.
torch.float32 tensor([10., 20., 30.]) tensor([50.])