Calculate the Mean value of all elements in a tensor by using the PyTorch mean operation

Calculate the Mean value of all elements in a tensor by using the PyTorch mean operation

This video will show you how to calculate the mean value of all elements in a tensor by using the PyTorch mean operation.

First, we import PyTorch.

```
import torch
```

Then we print the PyTorch version we are using.

```
print(torch.__version__)
```

We are using PyTorch 0.3.1.post2.

For this example, let’s manually create a PyTorch tensor using the PyTorch FloatTensor operation.

```
pt_tensor_ex = torch.FloatTensor(
[
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]
]
,
[
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]
]
])
```

So torch.FloatTensor.

We pass in our tensor.

We assign it to the variable pt_tensor_ex.

We construct the tensor in this way so that it’s easy to do a manual calculation.

Next, let’s print the pt_tensor_ex Python variable to see what we have.

```
print(pt_tensor_ex)
```

We see that it is a 2x3x3 FloatTensor.

Now, let’s calculate the mean value of all elements in a tensor by using the PyTorch mean operation.

```
pt_tensor_mean_ex = torch.mean(pt_tensor_ex)
```

So we see torch.mean.

We pass in the pt_tensor_ex Python variable and we’re going to assign it to the Python variable pt_tensor_mean_ex.

Let’s print the pt_tensor_mean_ex Python variable to see what we have.

```
print(pt_tensor_mean_ex)
```

We see that we have 2.0.

To manually check that this is the right result, let’s calculate the mean of the PyTorch tensor manually.

First, we see that we have one, two, three, four, five, six rows of 1+2+3.

```
(1 + 2 + 3)
```

So we can do 1+2+3, and we get 6.

Because there are six rows times that number, we can multiply 6 * 6 to get 36.

```
6 * 6
```

So that’s going to be the sum of the whole tensor.

Then because we know the mean is the sum of all the elements divided by the number of elements in a tensor, we can check out the shape of the tensor.

```
pt_tensor_ex.shape
```

We see what we saw before, that it’s 2x3x3.

So 2*3 = 6 * 3 = 18.

Which means that to get the mean of the tensor, we have to divide 36 by 18

```
36 / 18
```

And we see that it is 2.0.

Which is what we got when we printed the pt_tensor_mean_ex variable.

Perfect - we were able to calculate the mean value of all elements in a tensor by using the PyTorch mean operation.

Receive the Data Science Weekly Newsletter every Thursday

Easy to unsubscribe at any time. Your e-mail address is safe.