1

I have a pytorch tensor: x = torch.zeros(2, 2), and another tensor of variable values: item = torch.tensor([[1, 2], [3, 4]]), I am just giving this tensor for example.

I would like add the item tensor as each element of the x tensor, such that

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

So x is a tensor with tensors inside it. I have tried assigning item directly to x, but got an error: RuntimeError: The expanded size of the tensor must match the existing size at non-singleton dimension

Chen
  • 860
  • 10
  • 32

3 Answers3

2

use torch.repeat(), your target_tensor shape will be torch.Size([2, 2, 2, 2]).

item tensor shape is already torch.Size([2, 2])

use :

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

the first two parameters of the repeat() function are x's shape

kiranr
  • 2,087
  • 14
  • 32
1

Didn't see any function native to pytorch for this but you can use 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

might not be the fastest if it's really big sinec you're converting between the types a lot. Note in this way there's no need to inialize x with zeros.

user15270287
  • 1,123
  • 4
  • 11
0

Only Variables support sliced assignment. The shape must be the same between the source and target.

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

 print(a.numpy())

output: [[5,6] [7 8]]

if the data is an non-regular assignment try a raggedtensor

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

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

output

<tf.RaggedTensor [[1, 2], [3, 4, 5]]>
Golden Lion
  • 3,840
  • 2
  • 26
  • 35