Skip to content
Advertisement

replacing an item (tensor) in a list with another tensor but of different shape, using pytorch

I have a list of tensors

t_list=[tensor([[1],
         [1],
         [1]]),
 tensor([[1],
         [1],
         [1]]),
 tensor([[1],
         [1],
         [1]])]

and want to convert it to

[tensor([[1,0,0],
         [1,0,0],
         [1,0,0]]),
 tensor([[1,0,0],
         [1,0,0],
         [1,0,0]]),
 tensor([[1,0,0],
         [1,0,0],
         [1,0,0]])]

I tried this code

import torch
z= torch.zeros(1,2)
for i, item in enumerate(t_list):
    for ii, item2 in enumerate(item):
        unsqueezed = torch.unsqueeze(item2,0)
        cat1 = torch.cat((unsqueezed,z),-1)
        squeezed = torch.squeeze(cat1,0)
        t[i][ii] = squeezed

But got this error

RuntimeError: expand(torch.FloatTensor{[5]}, size=[]): the number of sizes provided (0) must be greater or equal to the number of dimensions in the tensor (1)

I am not sure how to get around this

Advertisement

Answer

You should use list comprehension, and a little “outer product” trick:

t_list = [x_ * torch.tensor([[1, 0, 0]]) for x_ in t_list]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement