PyTorch item: Convert A 0-dim PyTorch Tensor To A Python Number

PyTorch item - Use PyTorch's item operation to convert a 0-dim PyTorch Tensor to a Python number

PyTorch item - Use PyTorch's item operation to convert a 0-dim PyTorch Tensor to a Python number

Video Transcript


This video will show you how to use PyTorch’s item operation to convert a zero-dimensional PyTorch tensor to a Python number.


First, we import PyTorch.

import torch


Then we check what version of PyTorch we are using.

print(torch.__version__)

We are using PyTorch 0.4.1.


Let’s create a zero-dimensional PyTorch tensor.

zero_dim_example_tensor = torch.tensor(10)

Notice that we are not putting the 10 inside of brackets.

If we had, we would then be creating a one-dimensional tensor.

However, since we are creating a zero-dimensional example tensor, we did not use any bracket.

So we use the torch.tensor, and we assign it to the Python variable zero_dim_example_tensor.


Let’s print our Python variable:

print(zero_dim_example_tensor)

And we see that it is a PyTorch tensor with the number 10 inside of it.


Just to make sure, let’s use Python’s type operation to check the type.

type(zero_dim_example_tensor)

So we pass in the tensor created by torch.tensor, we use type, and we see that the class is torch.Tensor.


We’re then going to use PyTorch’s shape operation to check that it is in fact a zero-dimensional tensor.

zero_dim_example_tensor.shape

We can see that it is an empty list which signifies that it has zero dimensions.


To convert the zero-dimensional PyTorch tensor to a Python number, let’s use PyTorch’s item operation.

converted_python_number = zero_dim_example_tensor.item()

So we have our tensor, then we’re going to use the item operation, and we’re going to assign the value returned to the Python variable converted_python_number.


Let’s print this value:

print(converted_python_number)

And we see that it is the number 10.


Then we can use Python’s type operation again to make sure that we have a number rather than a PyTorch tensor.

type(converted_python_number)

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

So this 10 is an integer number.


Perfect! We were able to use PyTorch’s item operation to convert a zero-dimensional PyTorch tensor to a Python number.

Receive the Data Science Weekly Newsletter every Thursday

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