如果我有一个张量A
有形状[M, N]
,
我想重复张量 K 次,以便结果B
有形状[M, K, N]
和每片B[:, k, :]
应该具有相同的数据A
。
这是没有 for 循环的最佳实践。K
可能在其他维度。
torch.repeat_interleave()
and tensor.repeat()
似乎不起作用。或者我以错误的方式使用它。
tensor.repeat https://pytorch.org/docs/stable/generated/torch.Tensor.repeat.html?highlight=tensor%20repeat#torch.Tensor.repeat应该适合您的需求,但您需要首先插入一个统一的维度。为此,我们可以使用tensor.unsqueeze https://pytorch.org/docs/stable/generated/torch.Tensor.unsqueeze.html?highlight=tensor%20unsqueeze#torch.Tensor.unsqueeze or tensor.reshape https://pytorch.org/docs/stable/generated/torch.Tensor.reshape.html?highlight=tensor%20reshape#torch.Tensor.reshape. Since unsqueeze
被专门定义为插入我们将使用的单一维度。
B = A.unsqueeze(1).repeat(1, K, 1)
代码说明 A.unsqueeze(1)
turns A
从一个[M, N]
to [M, 1, N]
and .repeat(1, K, 1)
重复张量K
沿第二维度的时间。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)