DEV Community

Super Kai (Kazuya Ito)

Posted on • Updated on

Access a tensor in PyTorch

*Memos:

You can access a 0D or more D tensor with these ways as shown below. *I give much more ways to access a 1D tensor than a 0D, 2D and 3D tensor:

``````import torch

my_tensor = torch.tensor(-3) # 0D tensor

my_tensor
# tensor(-3)

my_tensor = torch.tensor([-3]) # 1D tensor

my_tensor
# tensor([-3])

my_tensor = torch.tensor([-3, 7, -5, 2, 6, 3, 8, 0, -1, 4, 9, -6])
# 1D tensor
my_tensor[4]
my_tensor[4,]
my_tensor[-10]
my_tensor[-10,]
my_tensor[4:5]
my_tensor[4:5,]
my_tensor[-8:5]
my_tensor[-8:5,]
my_tensor[4:-7]
my_tensor[4:-7,]
my_tensor[-8:-7]
my_tensor[-8:-7,]
# tensor(6)

my_tensor[4:8]
my_tensor[4:8,]
my_tensor[-8:8]
my_tensor[-8:8,]
my_tensor[4:-4]
my_tensor[4:-4,]
my_tensor[-8:-4]
my_tensor[-8:-4,]
# tensor([6, 3, 8, 0])

my_tensor[:7]
my_tensor[:7,]
my_tensor[:-5]
my_tensor[:-5,]
my_tensor[0:7]
my_tensor[0:7,]
my_tensor[-12:7]
my_tensor[-12:7,]
my_tensor[0:-5]
my_tensor[0:-5,]
my_tensor[-12:-5]
my_tensor[-12:-5,]
# tensor([-3, 7, -5, 2, 6, 3, 8])

my_tensor[5:]
my_tensor[5:,]
my_tensor[-7:]
my_tensor[-7:,]
my_tensor[5:12]
my_tensor[5:12,]
my_tensor[-7:12]
my_tensor[-7:12,]
# tensor([3, 8, 0, -1, 4, 9, -6])

my_tensor[:]
my_tensor[:,]
my_tensor[0:12]
my_tensor[0:12,]
# tensor([-3, 7, -5, 2, 6, 3, 8, 0, -1, 4, 9, -6])

my_tensor = torch.tensor([[-3, 7, -5, 2, 6, 3],
[8, 0, -1, 4, 9, -6]])
# 2D tensor
my_tensor[1]
my_tensor[:][1]
my_tensor[1, :]
# tensor([8, 0, -1, 4, 9, -6])

my_tensor[1][3]
my_tensor[1, 3]
# tensor(4)

my_tensor[1][:4]
my_tensor[1, :4]
# tensor([8, 0, -1, 4])

my_tensor[1][2:]
my_tensor[1, 2:]
# tensor([-1, 4, 9, -6])

my_tensor[:, 3]
# tensor([2, 4])

my_tensor[:]
# tensor([[-3, 7, -5, 2, 6, 3], [8, 0, -1, 4, 9, -6]])

my_tensor = torch.tensor([[[-3, 7, -5], [2, 6, 3]],
[[8, 0, -1], [4, 9, -6]]])
my_tensor[1]             # 3D tensor
my_tensor[:][1]
my_tensor[1, :]
my_tensor[1][:2]
my_tensor[1, :2]
my_tensor[1][0:]
my_tensor[1, 0:]
# tensor([[8, 0, -1], [4, 9, -6]])

my_tensor[1][0]
# tensor([8, 0, -1])

my_tensor[1][0][2]
my_tensor[1, 0, 2]
# tensor(-1)

my_tensor[1][0][:2]
my_tensor[1, 0, :2]
# tensor([8, 0])

my_tensor[1][0][1:]
my_tensor[1, 0, 1:]
# tensor([0, -1])

my_tensor[:, :, 1]
# tensor([[7, 6], [0, 9]])

my_tensor[:]
# tensor([[[-3, 7, -5], [2, 6, 3]],
#         [[8, 0, -1], [4, 9, -6]]])
``````