PyTorch Max - Use PyTorch's max operation to calculate the max of a PyTorch tensor

PyTorch Max - Use PyTorch's max operation to calculate the max of a PyTorch tensor

This video will show you how to use PyTorch’s max operation to calculate the max of a PyTorch tensor.

First, we import PyTorch.

```
import torch
```

Then we check what version of PyTorch we are using.

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

We are using PyTorch version 0.4.1.

Let’s next create the tensor we’ll use for the PyTorch max operation example.

```
tensor_max_example = torch.tensor(
[
[
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]
],
[
[4, 4, 4],
[5,50, 5],
[6, 6, 6]
]
]
)
```

So here we have torch.tensor which creates a floating tensor.

We have a 2x3x3 tensor that we’re going to assign to the Python variable tensor_max_example.

Visually, we can see that the max is going to be the number 50.

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

```
print(tensor_max_example)
```

We see that it’s a PyTorch tensor, we see that it is 2x3x3, and we still visually see that the max is going to be 50.

Next, let’s calculate the max of a PyTorch tensor using PyTorch tensor’s max operation.

```
tensor_max_value = torch.max(tensor_max_example)
```

So torch.max, we pass in our tensor_max_example, and we assign the value that’s returned to the Python variable tensor_max_value.

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

```
print(tensor_max_value)
```

We see that the max value is 50.

The one thing to note is that PyTorch returns the max value inside of a 0-dimensional tensor with the value of 50 inside of it.

Let’s double check to see what it is by using Python’s type operation.

```
type(tensor_max_value)
```

We can see that it’s the class of torch.Tensor.

So it is a PyTorch tensor that is returned with the max value inside of it.

Let’s use PyTorch’s item operation to get the value out of the 0-dimensional tensor.

```
torch.max(tensor_max_example).item()
```

And now, we get the number 50.

And just to make sure it’s a number, let’s use the Python type operation to check that this is actually a number.

```
type(torch.max(tensor_max_example).item())
```

And we see that it is a Python of class "int" for integer.

Perfect! We were able to use PyTorch’s max operation to calculate the max of a PyTorch tensor.

Receive the Data Science Weekly Newsletter every Thursday

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