torch.stack 和 torch.cat 错误:argument 'tensors' (position 1) must be tuple of Tensors, not Tensor

本篇博文介绍pytorch中一些函数的输入问题,主要是tensor 和 tensors的区别。
在pytorch中我们也有对一个数据的叠加:
pytorch.stack ,这个函数可以在数据叠加的同时,扩展数据维度。比如说我们把三个数叠加到一起,可以组成一个二维的矩阵,得到的二维矩阵可以是[1, 2],也可以是[2, 1]。
pytorch.cat,这个函数是直接把两个数据连接起来,维度是不变的。还是上面那个例子,把三个数叠加到一起,维度还是1,为[2].

不过,我相信有些小伙伴对于这个两个函数的输入可能有一些不确定的地方。
首先,我们要知道,tensor和tensors是不同的东西。前者这里不解释了,后者是tensors,可以认为是tensor的列表,或者是tensor的元组。也就是说torch.stack 和 torch.cat 的输入是一个列表或者元组, 这个列表和元组的内容是由tensor组成的。

先看官网:torch.stack。
torch.stack 和 torch.cat 错误:argument 'tensors' (position 1) must be tuple of Tensors, not Tensor_第1张图片

然后有三个例子,分别说明:

  1. 输入为列表,正确,狭义上有也分两种形式: 直接输入一个列表,或者将tensor组成列表
  2. 输入为元组,正确,也分两种,直接一个元组,或者有tensor组成一个元组。
  3. 输入为tensor,出错
    注意到元组和列表的区别。前者可以使用()来显性表示,后者使用[]来显性表示。
    torch.stack 和 torch.cat 错误:argument 'tensors' (position 1) must be tuple of Tensors, not Tensor_第2张图片
    torch.stack 和 torch.cat 错误:argument 'tensors' (position 1) must be tuple of Tensors, not Tensor_第3张图片

你可能感兴趣的:(十年磨一剑,pytorch)