PyTorch Min: Get Minimum Value Of A PyTorch Tensor

PyTorch Min - Use PyTorch's min operation to calculate the min of a PyTorch tensor

PyTorch Min - Use PyTorch's min operation to calculate the min of a PyTorch tensor

Video Transcript


This video will show you how to use PyTorch’s min operation to calculate the minimum 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 now create the tensor we’ll use for the PyTorch min operation example.

tensor_min_example = torch.tensor(
[
  [
      [1,-10, 1],
      [2, 2, 2],
      [3, 3, 3]
  ],
  [
      [4, 4, 4],
      [5,50, 5],
      [6, 6, 6]
  ]
]
)

We use torch.tensor to create a floating point tensor.

We pass in our data structure which is going to be 2x3x3, and we assign it to the Python variable tensor_min_example.


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

print(tensor_min_example)

We see that it’s a tensor.


Visually inspecting the PyTorch tensor, we see that the minimum is going to be -10.


Next, let’s programmatically calculate the minimum of the PyTorch tensor using PyTorch’s min operation.

tensor_min_value = torch.min(tensor_min_example)

So torch.min, we pass in the tensor, and we assign it to the Python variable tensor_min_value.


Let’s print the result

print(tensor_min_value)

And we see that the minimum of the tensor is -10.


One thing to note is that PyTorch returns the answer as a 0-dimensional tensor with a value of -10 inside of it.


We can double check that it is actually a PyTorch tensor by using Python’s type operation, and we pass in our tensor that has -10 inside of it.

type(tensor_min_value)

And we see that it is in fact a class of torch.Tensor.


To get the number 10 from the tensor, we’re going to use PyTorch’s item operation.

tensor_min_example.item()

So we pass in our tensor, and then we have the item.

When we do that, we get back the number 10.


Finally, just to double check that it is actually a number, let’s use the Python type operation here as well.

type(tensor_min_example.item())

So type and we’re going to get the item out of the tensor.

So that should be -10.

And we see that it is in fact of class integer.


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

Receive the Data Science Weekly Newsletter every Thursday

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

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