Chapter 3: PyTorch Tensors

Useful tensor methods

face Luca Grillotti

Here are some other useful Tensor methods.

item()

When we calculated the mean of a tensor, the result was a tensor with a single element:

import torch
tensor = torch.Tensor([[1, 2],
                       [3, 4]])
print(type(tensor.mean()))
However, sometimes, we want to convert the single value present in that tensor into a Python scalar. The item() method is made for that purpose.

import torch
tensor = torch.Tensor([[1, 2],
                       [3, 4]])
mean_item = tensor.mean().item()
print(mean_item,  type(mean_item))

size()

If you want to know the shape of a tensor, the size() method (or the shape attribute) is made for you:

import torch

tensor_shape_3_2 = torch.Tensor([[1, 2],
                                 [3, 4],
                                 [5, 6]])  # shape = (3, 2)

print(tensor_shape_3_2.size())
print(tensor_shape_3_2.shape)