torch.stack() & torch.repeat() & torch.repeat_interleave() & torch转置 详解

torch.stack((a,b),dim=n)

把tensor按垂直方向堆起来

h1=torch.tensor([1, 1, 1, 1])
h2=torch.tensor([2, 2, 2, 2])
result = torch.stack((h1,h2),dim=0)
result,result.shape
(tensor([[1, 1, 1, 1],
         [2, 2, 2, 2]]),
 torch.Size([2, 4]))

把tesnsor按水平方向堆起来

h1=torch.tensor([1, 1, 1, 1])
h2=torch.tensor([2, 2, 2, 2])
result = torch.stack((h1,h2),dim=1)
result,result.shape
(tensor([[1, 2],
         [1, 2],
         [1, 2],
         [1, 2]]),
 torch.Size([4, 2]))

转置

(tensor([[1, 2],
         [1, 2],
         [1, 2],
         [1, 2]]),
 torch.Size([4, 2]))
result_t = result.T
result_t
tensor([[1, 1, 1, 1],
        [2, 2, 2, 2]])

torch.repeat()

result = result_t.repeat(1,1)
result

tensor([[1, 1, 1, 1],
        [2, 2, 2, 2]])



result = result_t.repeat(1,2)
result

tensor([[1, 1, 1, 1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2, 2, 2, 2]])

#%%
result = result_t.repeat(2,1)
result

tensor([[1, 1, 1, 1],
        [2, 2, 2, 2],
        [1, 1, 1, 1],
        [2, 2, 2, 2]])

#%%
result = result_t.repeat(2,2)
result

tensor([[1, 1, 1, 1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2, 2, 2, 2],
        [1, 1, 1, 1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2, 2, 2, 2]])

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)
tensor([1, 1, 2, 2, 3, 3, 4, 4])

你可能感兴趣的:(机器学习&深度学习笔记,pytorch,深度学习,python)