2

There is a list of PyTorch's Tensors and I want to convert it to array but it raised with error:

'list' object has no attribute 'cpu'

How can I convert it to array?

import torch
result = []
for i in range(3):
    x = torch.randn((3, 4, 5))
    result.append(x)
a = result.cpu().detach().numpy()

1 Answer 1

3

You can stack them and convert to NumPy array:

import torch
result = [torch.randn((3, 4, 5)) for i in range(3)]
a = torch.stack(result).cpu().detach().numpy()

In this case, a will have the following shape: [3, 3, 4, 5].

If you want to concatenate them in a [3*3, 4, 5] array, then:

a = torch.cat(result).cpu().detach().numpy()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.