How to Get the Value of a Tensor in PyTorch

To get the value of a Tensor in PyTorch, you can “use the .item() method.” The .item() method returns the value of a tensor as a Python scalar.

import torch

# Create a tensor
inter = torch.tensor(19)

# Get the value of the tensor
value = inter.item()

print(value)

Output

19

The .item() method only works with a scalar tensor.

You can also get the value of the first element of tensor “using indexing.”

import torch

# Create a tensor
inter = torch.tensor([19, 21])

value = inter[0]

print(value)

Output

tensor(19)

If you have a tensor with more than one element, you can use indexing to get the value of a specific element.

import torch

# Create a tensor
inter = torch.tensor([[19, 21], [46, 18]])

value = inter[0][1]

print(value)

Output

tensor(21)

To convert the tensor into a NumPy array, you can use the “.numpy()” method.

import torch

# Create a tensor
inter = torch.tensor([19, 21])

# Get the value of the tensor
value = inter.numpy()

print(value)

Output

[19 21]

That’s it!

Related posts

PyTorch Tensors Get the Index of a Specific Value

Python List to PyTorch Tensor

PyTorch Tensor to Python List

Convert a 1D IntTensor to int in PyTorch

Leave a Comment