PyTorch向量变换基本操作

一、torch.cat()或者时torch.concat()

对张量在指定维度进行拼接

# 例如有一个维度为[2,3]的向量x = torch.tensor([[1, 2, 3], [4, 5, 6]])


>>> torch.cat((x, x), 1)
tensor([[1, 2, 3, 1, 2, 3],
        [4, 5, 6, 4, 5, 6]])
>>> torch.cat((x, x), 0)
tensor([[1, 2, 3],
        [4, 5, 6],
        [1, 2, 3],
        [4, 5, 6]])

二、tesnsor.unzqueeze()

对张量进行维度扩展

>>> x = torch.tensor([1,2,3,4,])
>>> x.shape
torch.Size([4])
>>> x = x.unsqueeze(0)
>>> x.shape
torch.Size([1, 4])
>>> x = x.unsqueeze(1)
>>> x.shape
torch.Size([1, 1, 4])

三、tensor.permute()

对张量进行维度变换

# 借用上面x的值
>>> x.shape
torch.Size([1, 1, 4])
>>> x=x.permute(0,2,1)
>>> x.shape
torch.Size([1, 4, 1])
>>> x=x.permute(1,0,2)
>>> x.shape
torch.Size([4, 1, 1])

四、torch.full()

使用指定数字对指定形状的向量进行填充

>>> bert = [[1,2,3],[2,3,1]]
>>> bert_tensor = torch.tensor(bert,dtype=torch.long)
>>> bert_tensor.shape
torch.Size([2, 3])

>>> pad = torch.full([1,5,bert_tensor.shape[1]],0, dtype = torch.long)
>>> pad
tensor([[[0, 0, 0],
         [0, 0, 0],
         [0, 0, 0],
         [0, 0, 0],
         [0, 0, 0]]])

五、torch.repeat_interleave()

对张量进行重复

x = torch.tensor([1, 2, 3])
x.repeat_interleave(2)
# tensor([1, 1, 2, 2, 3, 3])
y = torch.tensor([[1, 2], [3, 4]])
torch.repeat_interleave(y, 2)  # 全部展平成(x,1)维的张量
# tensor([1, 1, 2, 2, 3, 3, 4, 4])
torch.repeat_interleave(y, 3, dim=1)  # 在指定维度进行重复
# tensor([[1, 1, 1, 2, 2, 2],
#         [3, 3, 3, 4, 4, 4]])
torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0)  # 进行指定形状的重复
#tensor([[1, 2],
#        [3, 4],
#        [3, 4]])
torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3)
# tensor([[1, 2],
#         [3, 4],
#         [3, 4]])

你可能感兴趣的:(#,pytorch编程基础,pytorch,深度学习,机器学习)