如何在 PyTorch 的特定新维度中重复张量

How to repeat tensor in a specific new dimension in PyTorch

如果我有一个形状为 [M, N] 的张量 A, 我想重复张量 K 次,以便结果 B 具有 [M, K, N] 的形状 每个切片 B[:, k, :] 应该具有与 A 相同的数据。 这是没有 for 循环的最佳实践。 K可能在其他维度。

torch.repeat_interleave()tensor.repeat() 似乎不起作用。或者我用错了。

tensor.repeat should suit your needs but you need to insert a unitary dimension first. For this we could use either tensor.unsqueeze or tensor.reshape。由于 unsqueeze 被专门定义为插入单一维度,我们将使用它。

B = A.unsqueeze(1).repeat(1, K, 1)

代码说明 A.unsqueeze(1)A[M, N] 变为 [M, 1, N] 并且 .repeat(1, K, 1) 重复张量K 次沿第二个维度。

Einops提供重复功能

import einops
einops.repeat(x, 'm n -> m k n', k=K)

repeat 可以按任意顺序添加任意数量的轴,同时重新排列现有轴。

添加到@Alleo 提供的答案中。您可以使用以下 Einops 函数。

einops.repeat(example_tensor, 'b h w -> (repeat b) h w', repeat=b)

其中 b 是您希望张量重复的次数,hw 是张量的附加维度。

例子-

example_tensor.shape -> torch.Size([1, 40, 50]) 
repeated_tensor = einops.repeat(example_tensor, 'b h w -> (repeat b) h w', repeat=8)
repeated_tensor.shape -> torch.Size([8, 40, 50]) 

此处有更多示例 - https://einops.rocks/api/repeat/

重复的值会占用大量内存,在大多数情况下,最佳做法是使用广播。所以你会使用 A[:, None, :] 这将使 A.shape==(M, 1, N).

我同意重复这些值的一种情况是以下步骤中的就地操作。 由于 numpy 和 torch 的实现方式不同,我喜欢不可知论者 (A * torch.ones(K, 1, 1))) 然后是转置。