如何将 1D Torch 张量插入到特定行的现有 2D Torch 张量中?

How do I insert a 1D Torch tensor into an existing 2D Torch tensor into a specific row?

我想将一个 1D Torch 张量插入一个特定的行号到一个 2D Torch 张量中(使用 Pytorch)。

一维张量和二维张量将始终具有相同的长度,因此您可以轻松地将其可视化为具有行和列的 table。
二维张量是现有的 table,我希望能够指定将插入一维张量(或行)的行号。
当我说我想使用 Pytorch 时,我不想将任何东西变成非 Pytorch 列表并通过 CPU 和 GPU 来回发送计算。张量都已经在我的 CUDA 设备上了,为了节省时间,我想把它们留在那里。

二维张量three_by_four

tensor([[0.7421, 0.1584, 0.3231, 0.4840],
        [0.4065, 0.7646, 0.9677, 0.4537],
        [0.5226, 0.6216, 0.9420, 0.0605]], device='cuda:1')  

一维张量one_by_three

tensor([[0.3095, 0.8460, 0.2900, 0.9683]], device='cuda:1')

我能做的最好的事情是根据顺序将新行(一维张量)附加到二维张量的底部或顶部,torch.cat
添加到顶部的一维张量。

torch.cat([one_by_three, three_by_four])  

tensor([[0.3095, 0.8460, 0.2900, 0.9683],
        [0.7421, 0.1584, 0.3231, 0.4840],
        [0.4065, 0.7646, 0.9677, 0.4537],
        [0.5226, 0.6216, 0.9420, 0.0605]], device='cuda:1')  

添加到底部的一维张量

torch.cat([three_by_four, one_by_three])  
tensor([[0.7421, 0.1584, 0.3231, 0.4840],
        [0.4065, 0.7646, 0.9677, 0.4537],
        [0.5226, 0.6216, 0.9420, 0.0605],
        [0.3095, 0.8460, 0.2900, 0.9683]], device='cuda:1')  

我想要什么,例如,如果我可以把它放在这个例子中的位置 1 或 2。

tensor([[0.7421, 0.1584, 0.3231, 0.4840],
        [0.4065, 0.7646, 0.9677, 0.4537],
        [0.3095, 0.8460, 0.2900, 0.9683]
        [0.5226, 0.6216, 0.9420, 0.0605]], device='cuda:1')  

到目前为止我能找到的最好的

from torch import tensor, cat
x = tensor([[0.7421, 0.1584, 0.3231, 0.4840],
        [0.4065, 0.7646, 0.9677, 0.4537],
        [0.5226, 0.6216, 0.9420, 0.0605]])
y = tensor([[0.3095, 0.8460, 0.2900, 0.9683]])
cat([x[:1], y, x[1:]])
'''
tensor([[0.7421, 0.1584, 0.3231, 0.4840],
        [0.3095, 0.8460, 0.2900, 0.9683],
        [0.4065, 0.7646, 0.9677, 0.4537],
        [0.5226, 0.6216, 0.9420, 0.0605]])
'''

https://discuss.pytorch.org/t/is-there-a-way-to-insert-a-tensor-into-an-existing-tensor/14642