Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: can't convert np.ndarray of type numpy.object_

Tags:

numpy

pytorch

How to convert a numpy array of dtype=object to torch Tensor?

array([
   array([0.5, 1.0, 2.0], dtype=float16),
   array([4.0, 6.0, 8.0], dtype=float16)
], dtype=object)
like image 214
Whisht Avatar asked Apr 17 '19 09:04

Whisht


People also ask

Can't convert NP Ndarray of type Numpy uint16 the only supported types are?

ndarray of type numpy. uint16. The only supported types are: float64, float32, float16, int64, int32, int16, int8, uint8, and bool.

How do I change the Dtype of a Numpy array?

We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array.


2 Answers

It is difficult to answer properly since you do not show us how you try to do it. From your error message I can see that you try to convert a numpy array containing objects to a torch tensor. This does not work, you will need a numeric data type:

import torch
import numpy as np

# Your test array without 'dtype=object'
a = np.array([
    np.array([0.5, 1.0, 2.0], dtype=np.float16),
    np.array([4.0, 6.0, 8.0], dtype=np.float16),
])

b = torch.from_numpy(a)

print(a.dtype) # This should not be 'object'
print(b)

Output

float16
tensor([[0.5000, 1.0000, 2.0000],
        [4.0000, 6.0000, 8.0000]], dtype=torch.float16)
like image 61
mrzo Avatar answered Oct 15 '22 10:10

mrzo


Just adding to what was written above-

First you should make sure your array dtype ins't a 'O' (Object).

You do that by: (credit)

a=np.vstack(a).astype(np.float)

Then you can use:

b = torch.from_numpy(a)
like image 30
Amir Bialer Avatar answered Oct 15 '22 08:10

Amir Bialer