torch.stack(sequence, dim=0, out=None),做tensor的拼接。sequence表示Tensor列表,dim表示拼接的维度,注意这个函数和concatenate是不同的,torch的concatenate函数是torch.cat,是在已有的维度上拼接,而stack是建立一个新的维度,然后再在该纬度上进行拼接。
torch.stack
a = torch.rand(3, 4)
b = torch.rand(3, 4)
d = torch.stack((a, b), dim=0)
print(a.shape)
print(b.shape)
print(d.shape)
---------------------------------------------
torch.Size([3, 4])
torch.Size([3, 4])
torch.Size([2, 3, 4])
torch.cat
a=torch.Tensor([[1,2,3]])
b=torch.Tensor([[7,8,9]])
d=torch.cat( (a,b) ,dim = 0)
print(a.shape)
print(b.shape)
print(d.shape)
---------------------
torch.Size([1, 3])
torch.Size([1, 3])
torch.Size([2, 3])
原文:https://blog.youkuaiyun.com/th_num/article/details/81979346
本文详细解析了PyTorch中的stack与cat函数的使用方法与区别。stack函数用于创建一个新的维度并在此维度上进行张量的拼接,而cat函数则在现有维度上实现张量的拼接。通过具体的代码示例展示了两种函数的操作过程及其结果。
250

被折叠的 条评论
为什么被折叠?



