HomeMachine LearningMachine Learning DIYTutorial on One-Dimensional Tensors

# Tutorial on One-Dimensional Tensors

PyTorch is an open-source deep learning framework based on Python language. It allows you to build, train, and deploy deep learning models, offering a lot of versatility and efficiency.

PyTorch is primarily focused on tensor operations while a tensor can be a number, matrix, or a multi-dimensional array.

In this tutorial, we will perform some basic operations on one-dimensional tensors as they are complex mathematical objects and an essential part of the PyTorch library. Therefore, before going into the detail and more advanced concepts, one should know the basics.

After going through this tutorial, you will:

• Understand the basics of one-dimensional tensor operations in PyTorch.
• Know about tensor types and shapes and perform tensor slicing and indexing operations.
• Be able to apply some methods on tensor objects, such as mean, standard deviation, addition, multiplication, and more.

Letâ€™s get started.

## Types and Shapes of One-Dimensional Tensors

First off, letâ€™s import a few libraries weâ€™ll use in this tutorial.

```import torch
import numpy as np
import pandas as pd```

If you have experience in other programming languages, the easiest way to understand a tensor is to consider it as a multidimensional array. Therefore, a one-dimensional tensor is simply a one-dimensional array, or a vector. In order to convert a list of integers to tensor, applyÂ `torch.tensor()`Â constructor. For instance, weâ€™ll take a list of integers and convert it to various tensor objects.

Also, you can apply the same method torch.tensor() to convert a float list to a float tensor.

Note that elements of a list that need to be converted into a tensor must have the same type. Moreover, if you want to convert a list to a certain tensor type, torch also allows you to do that. The code lines below, for example, will convert a list of integers to a float tensor.

Similarly,Â `size()`Â andÂ `ndimension()`Â methods allow you to find the size and dimensions of a tensor object.

For reshaping a tensor object,Â `view()`Â method can be applied. It takesÂ `rows`Â andÂ `columns`Â as arguments. As an example, letâ€™s use this method to reshapeÂ `int_list_to_float_tensor`.

As you can see, theÂ `view()`Â method has changed the size of the tensor toÂ `torch.Size([4, 1])`, with 4 rows and 1 column.

While the number of elements in a tensor object should remain constant afterÂ `view()`Â method is applied, you can useÂ `-1`Â (such asÂ `reshaped_tensor.view(-1, 1)`) to reshape a dynamic-sized tensor.

### Converting Numpy Arrays to Tensors

Pytorch also allows you to convert NumPy arrays to tensors. You can useÂ `torch.from_numpy`Â for this operation. Letâ€™s take a NumPy array and apply the operation.

```numpy_arr = np.array([10.0, 11.0, 12.0, 13.0])
from_numpy_to_tensor = torch.from_numpy(numpy_arr)

print("dtype of the tensor: ", from_numpy_to_tensor.dtype)
print("type of the tensor: ", from_numpy_to_tensor.type())```
```dtype of the tensor: torch.float64
type of the tensor: torch.DoubleTensor```

Similarly, you can convert the tensor object back to a NumPy array. Letâ€™s use the previous example to show how itâ€™s done.

### Converting Pandas Series to Tensors

You can also convert a pandas series to a tensor. For this, first youâ€™ll need to store the pandas series withÂ `values()`Â function using a NumPy array.

Furthermore, the Pytorch framework allows us to do a lot with tensors such as itsÂ `item()`Â method returns a python number from a tensor andÂ `tolist()`Â method returns a list.

## Indexing and Slicing in One-Dimensional Tensors

Indexing and slicing operations are almost the same in Pytorch as python. Therefore, the first index always starts at 0 and the last index is less than the total length of the tensor. Use square brackets to access any number in a tensor.

Like a list in python, you can also perform slicing operations on the values in a tensor. Moreover, the Pytorch library allows you to change certain values in a tensor as well.

Letâ€™s take an example to check how these operations can be applied.

```example_tensor = torch.tensor([50, 11, 22, 33, 44])
sclicing_tensor = example_tensor[1:4]
print("example tensor : ", example_tensor)
print("subset of example tensor:", sclicing_tensor)```
```example tensor : tensor([50, 11, 22, 33, 44])
subset of example tensor: tensor([11, 22, 33])```

Now, letâ€™s change the value at index 3 ofÂ `example_tensor`:

## Some Functions to Apply on One-Dimensional Tensors

In this section, weâ€™ll review some statistical methods that can be applied on tensor objects.

### Min and Max Functions

These two useful methods are employed to find the minimum and maximum value in a tensor. Here is how they work.

Weâ€™ll use aÂ `sample_tensor`Â as an example to apply these methods.

```sample_tensor = torch.tensor([5, 4, 3, 2, 1])
min_value = sample_tensor.min()
max_value = sample_tensor.max()
print("check minimum value in the tensor: ", min_value)
print("check maximum value in the tensor: ", max_value)```
```check minimum value in the tensor: tensor(1)
check maximum value in the tensor: tensor(5)```

### Mean and Standard Deviation

Mean and standard deviation are often used while doing statistical operations on tensors. You can apply these two metrics usingÂ `.mean()`Â andÂ `.std()`Â functions in Pytorch.

Letâ€™s use an example to see how these two metrics are calculated.

```mean_std_tensor = torch.tensor([-1.0, 2.0, 1, -2])
Mean = mean_std_tensor.mean()
print("mean of mean_std_tensor: ", Mean)
std_dev = mean_std_tensor.std()
print("standard deviation of mean_std_tensor: ", std_dev)```
```mean of mean_std_tensor: tensor(0.)
standard deviation of mean_std_tensor: tensor(1.8257)```

## Simple Addition and Multiplication Operations on One-Dimensional Tensors

Addition and Multiplication operations can be easily applied on tensors in Pytorch. In this section, weâ€™ll create two one-dimensional tensors to demonstrate how these operations can be used.

```a = torch.tensor([1, 1])
b = torch.tensor([2, 2])

multiply = a * b

print("multiplication of two tensors: ", multiply)```
```addition of two tensors: tensor([3, 3])
multiplication of two tensors: tensor([2, 2])```

For your convenience, below is all the examples above tying together so you can try them in one shot: