[Pytorch] Tensor access operation

Tensor access operations

The main operations of Tensor are usually divided into four categories:

  1. Reshaping operations
  2. Element-wise operations
  3. Reduction operations
  4. Access operations

access operation

When we want to get a specific scalar value from a tensor, we can perform access operations on tensors.

(1) Access single element tensor (item tensor method)

t = torch.tensor([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
], dtype=torch.float32)
t.mean()

Show results:

tensor(5.)

access scalar value

t.mean().item()

Show results:

5.0

(2) Access multiple values ​​in a tensor

  1. Convert the output tensor to a python list

    t.mean(dim=0).tolist()
    

    Show results:

    [4.0, 5.0, 6.0]
    
  2. into a numpy array to access

    t.mean(dim=0).numpy()
    

    Show results:

    array([4., 5., 6.], dtype=float32)
    

おすすめ

転載: blog.csdn.net/zzy_NIC/article/details/119567856