首页 > 解决方案 > 将张量附加到另一个张量的每个元素

问题描述

我有一个 pytorch 张量:x = torch.zeros(2, 2)和另一个变量值张量:item = torch.tensor([[1, 2], [3, 4]]),例如,我只是给出这个张量。

我想将张量添加item为 x 张量的每个元素,这样

x = [[item, item], 
     [item, item]]

所以 x 是一个张量,里面有张量。我曾尝试item直接分配给 x,但出现错误:RuntimeError: The expanded size of the tensor must match the existing size at non-singleton dimension

标签: pythonpytorch

解决方案


使用torch.repeat(),你的target_tensor形状会torch.Size([2, 2, 2, 2])

item张量形状已经torch.Size([2, 2])

利用 :

target_tensor = item.repeat(2, 2, 1, 1)

repeat() 函数的前两个参数是 x 的形状


推荐阅读