【发布时间】:2021-08-04 22:59:19
【问题描述】:
假设我有一个像 [A,A,A,A...,A] 这样的张量。
如何在torch中快速获取[[A],[A],[A],...,[A]]作为张量?
【问题讨论】:
假设我有一个像 [A,A,A,A...,A] 这样的张量。
如何在torch中快速获取[[A],[A],[A],...,[A]]作为张量?
【问题讨论】:
您可以使用torch.chunk 作为cat 的倒数,但看起来您想要unsqueeze(1):
A = torch.randn(2, 3)
A_rep = (A, A, A, A, A, A, A, A)
catted = torch.cat(A_rep)
#uncatted = torch.chunk(catted, len(A_rep))
catted.unsqueeze(1)
【讨论】:
来自the doc,使用split 或reshape。
>>> a = torch.arange(10).reshape(5,2)
>>> a
tensor([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
>>> torch.split(a, 2)
(tensor([[0, 1],
[2, 3]]),
tensor([[4, 5],
[6, 7]]),
tensor([[8, 9]]))
>>> torch.split(a, [1,4])
(tensor([[0, 1]]),
tensor([[2, 3],
[4, 5],
[6, 7],
[8, 9]]))
【讨论】:
您正在寻找的 torch.unbind 正是您想要的。
import torch
tensor = torch.rand(3, 4, 5) # tensor of shape (3, 4, 5)
l = tensor.unbind(dim=0) # list of 3 tensors of shape (4, 5)
你可以解绑任何你想要的维度,默认是dim 0。你可以使用python解构来快速获取变量中的张量:
a, b, c = tensor.unbind(dim=0) # 3 tensors of shape (4, 5)
【讨论】: