Cannot convert list to array: ValueError: only one element tensors can be converted to Python scalars Cannot convert list to array: ValueError: only one element tensors can be converted to Python scalars numpy numpy

Cannot convert list to array: ValueError: only one element tensors can be converted to Python scalars


It seems like you have a list of tensors. For each tensor you can see its size() (no need to convert to list/numpy). If you insist, you can convert a tensor to numpy array using numpy():

Return a list of tensor shapes:

>> [t.size() for t in my_list_of_tensors]

Returns a list of numpy arrays:

>> [t.numpy() for t in my_list_of_tensors]

In terms of performance, it is always best to avoid casting of tensors into numpy arrays, as it may incur sync of device/host memory. If you only need to check the shape of a tensor, use size() function.


The simplest way to convert pytorch tensor to numpy array is:

nparray = tensor.numpy()

Also, for size and shape:

tensor_size = tensor.size()tensor_shape = tensor.shape()tensor_size>>> (1080)tensor_shape>>> (32, 3, 128, 128)


A real-world example, would require to handle torch no grad issue:

with torch.no_grad():    probs = [t.numpy() for t in my_tensors]

or

probs = [t.detach().numpy() for t in my_tensors]