将张量附加到另一个张量的每个元素

时间:2021-03-01 21:28:30

标签: python pytorch

我有一个 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

3 个答案:

答案 0 :(得分:2)

使用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 的形状

答案 1 :(得分:1)

没有看到任何 pytorch 的原生函数,但您可以使用 np.block

import numpy as np
item = np.array(item) # need to convert item from tensor to ndarray
x = np.block([[item, item], [item, item]]
x = torch.from_numpy(x) # if you want to change it back to tensor

如果它真的很大,你在类型之间转换很多,它可能不是最快的。请注意,以这种方式不需要用零初始化 x

答案 2 :(得分:0)

只有变量支持切片赋值。源和目标之间的形状必须相同。

 a=tf.Variable([[1,2],[3,4]])
 a.assign([[5,6], [7,8]])

 print(a.numpy())

输出: [[5,6] [7 8]]

如果数据是非常规分配,请尝试使用不规则张量

ValueError: Can't convert non-rectangular Python sequence to Tensor

data_tensor=tf.ragged.constant([[1, 2], [3, 4,5]])
print(data_tensor)

输出

<tf.RaggedTensor [[1, 2], [3, 4, 5]]>