How can I assign a list to a torch.tensor?

Viewed 2843

Assume that I have a list [(0,0),(1,0),(1,1)] and another list [4,5,6] and a matrix X with size is (3,2). I am trying to assign the list to the matrix like X[0,0] = 4, X[1,0] = 5 and X[1,1] = 6. But it seems like I have a problem of assigning a list to tensor

x = torch.zeros(3,2)
indices = [(0,0),(1,0),(1,1)]
value = [4,5,6]
x[indices] = values

Error:

TypeError                                 Traceback (most recent call last)
<ipython-input-7-dec4e6a479a5> in <module>
     
   4 indices = [(0, 0), (1, 0), (1, 1)]
 
   5 values = [4, 5, 6]

----> 6 x[indices] = values

TypeError: can't assign a list to a torch.FloatTensor
2 Answers

In general, the answer to "how do I change a list to a Tensor" is to use torch.Tensor(list). But that will not solve your actual problem here.

One way would be to associate the index and value and then iterate over them:

for (i,v) in zip(indices,values) :
   x[i] = v

If you can make indices tensor than it would make indexing easy

indices = torch.tensor([(0,0),(1,0),(1,1)])

x[indices[:,0], indices[:,1]] = torch.tensor(values).float()
x
tensor([[4., 0.],
        [5., 6.],
        [0., 0.]])

As our x is float type we need to convert values to same.

Related