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
< > Code:
You must be a Member to view code
Access all courses and lessons, gain confidence and expertise, and learn how things work and how to use them.
or Log In
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.
Then we check what version of PyTorch we are using.
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:
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.
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.
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:
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.
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.