OpenAI的REINFORCE和行动者-批评者强化学习的例子有以下代码:
REINFORCE:
policy_loss = torch.cat(policy_loss).sum()
loss = torch.stack(policy_losses).sum() + torch.stack(value_losses).sum()
一个使用torch.cat
,另一个使用torch.stack
,用于类似的使用情形。
据我所知,医生没有给他们任何明确的区别。
我很乐意了解这些函数之间的差异。
OpenAI的REINFORCE和行动者-批评者强化学习的例子有以下代码:
REINFORCE:
policy_loss = torch.cat(policy_loss).sum()
loss = torch.stack(policy_losses).sum() + torch.stack(value_losses).sum()
一个使用torch.cat
,另一个使用torch.stack
,用于类似的使用情形。
据我所知,医生没有给他们任何明确的区别。
我很乐意了解这些函数之间的差异。
4条答案
按热度按时间ghhkc1vu1#
stack
沿新维度连接Tensor序列。
cat
在给定维度中连接给定的seqTensor序列。
因此,如果
A
和B
的形状为(3,4):torch.cat([A, B], dim=0)
的形状为(6,4)torch.stack([A, B], dim=0)
的形状为(2,3,4)a14dhokn2#
|
torch.stack
|torch.cat
|| - -|- -|
| * *'Stacks'沿着新维度的Tensor序列:
|'Concat**enates'沿着现有维度的Tensor序列:
|
这些函数类似于
numpy.stack
和numpy.concatenate
。h6my8fg23#
最初的答案缺少一个自包含的好例子,所以这里是:
输出:
以下定义仅供参考:
cat:连接指定维度中的指定序列Tensor序列。结果是特定维度的大小会变更,例如dim=0,则您会将元素新增至数据列,以增加数据栏空间的维度。
堆栈:沿着一个新的维度连接Tensor序列。我喜欢把它看作 Torch “附加”操作,因为你可以通过从前面“弹出”来索引/得到你的原始Tensor。它没有参数,把Tensor附加到Tensor的前面。
相关:
tensor.torch
能把一个嵌套的Tensor列表转换成一个大的Tensor,这个Tensor有很多维,并且考虑到了嵌套列表的深度。Update:使用相同大小的嵌套列表
这里有一些单元测试(我没有写更多的测试,但它与我的真实代码一起工作,所以我相信它是好的。如果你愿意,请随时帮助我添加更多的测试):
4si2a6ki4#
如果有人在研究它的性能方面,我做了一个小实验,在我的例子中,我需要把一个标量Tensor列表转换成一个Tensor。
我的结论是,即使你想有
torch.stack
的额外维度,使用torch.cat
,然后reshape
是更好的。**注:**此帖子摘自PyTorch论坛(我是original post的作者)