4

I have a list of tensors:

object_ids = [tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.])]

Intuitively, it seems like I should be able to create a new tensor from this:

torch.as_tensor(object_ids, dtype=torch.float32)

But this does NOT work. Apparently, torch.as_tensor and torch.Tensor can only turn lists of scalars into new tensors. it cannot turn a list of d-dim tensors into a d+1 dim tensor.

user3180
  • 1,369
  • 1
  • 21
  • 38
  • Does this answer your question? [Convert a list of tensors to tensors of tensors pytorch](https://stackoverflow.com/questions/61359162/convert-a-list-of-tensors-to-tensors-of-tensors-pytorch) – iacob Apr 30 '21 at 14:04

1 Answers1

3

You can use torch.stack.

In your example:

>>> object_ids = [tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.])]
>>> torch.stack(object_ids)
tensor([[2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.]])
GoodDeeds
  • 7,956
  • 5
  • 34
  • 61