如何在 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
可能在另一个维度.
If I have a tensor A
which has shape [M, N]
,
I want to repeat the tensor K times so that the result B
has shape [M, K, N]
and each slice B[:, k, :]
should has the same data as A
.
Which is the best practice without a for loop.
K
might be in other dimension.
torch.repeat_interleave()
和 tensor.repeat()
似乎不起作用.或者我用错了方法.
torch.repeat_interleave()
and tensor.repeat()
does not seem to work. Or I am using it in a wrong way.
推荐答案
tensor.repeat 应该适合您的需求,但您需要先插入一个单一维度.为此,我们可以使用 tensor.reshape
或 tensor.unsqueeze
.由于 unsqueeze
专门定义为插入单一维度,我们将使用它.
tensor.repeat should suit your needs but you need to insert a unitary dimension first. For this we could use either tensor.reshape
or tensor.unsqueeze
. Since unsqueeze
is specifically defined to insert a unitary dimension we will use that.
B = A.unsqueeze(1).repeat(1, K, 1)
代码说明 A.unsqueeze(1)
将 A
从 [M, N]
变成 [M, 1, N]
和 .repeat(1, K, 1)
沿第二维重复张量 K
次.
Code Description A.unsqueeze(1)
turns A
from an [M, N]
to [M, 1, N]
and .repeat(1, K, 1)
repeats the tensor K
times along the second dimension.
这篇关于如何在 PyTorch 中的特定新维度中重复张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!