Reputation: 5618
Converting a PyTorch tensor to NumPy I get
print(nn_result.shape)
# (2433, 2)
np_result = torch.argmax(nn_result).numpy()
type(np_result)
# <type 'numpy.ndarray'>
print(len(np_result))
TypeError: len() of unsized object
Why? I thought per documentation the numpy()
function would return a proper ndarray
, yet it seems to be incomplete somehow?
Upvotes: 5
Views: 1530
Reputation: 6864
Perhaps you'd want to use torch.argmax(nn_result, dim=1)
? Since dim
defaults to 0, it returns just a single number constructed as a tensor. Let me illustrate with the below example:
>>> x = np.array(1)
>>> x.shape
()
>>> len(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: len() of unsized object
>>> x = np.array([1])
>>> x.shape
(1,)
>>> len(x)
1
Essentially np.array
will take up any object
type that you construct with. In the first case, object is not an array because of which you do not see a valid shape. Since it is not an array calling len
throws an error.
torch.argmax
with dim=0
returns a tensor as seen in the first case of the above example and hence the error.
Upvotes: 2