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
Convert a 1D IntTensor to int in PyTorch

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.