Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy array type and values from Float64 to Float32

I am trying to convert threshold array(pickle file of isolation forest from scikit learn) of type from Float64 to Float32

for i in range(len(tree.tree_.threshold)):     tree.tree_.threshold[i] = tree.tree_.threshold[i].astype(np.float32) 

​ Then Printing it

for value in tree.tree_.threshold[:5]:     print(type(value))     print(value) 

the output i am getting is :

<class 'numpy.float64'> 526226.0 <class 'numpy.float64'> 91.9514312744 <class 'numpy.float64'> 3.60330319405 <class 'numpy.float64'> -2.0 <class 'numpy.float64'> -2.0 

I am not getting a proper conversion to Float32. I want to convert values and their type to Float32, Did anybody have any workaround this ?

like image 336
Akshay Tilekar Avatar asked Aug 30 '17 08:08

Akshay Tilekar


People also ask

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. We can check the type of numpy array using the dtype class.

Is float32 faster than float64?

float64 is much slower than Python's float, and numpy. float32 is even slower (even though I'm on a 32-bit machine).

How do I convert a numpy array to integer?

To convert numpy float to int array in Python, use the np. astype() function. The np. astype() function takes an array of float values and converts it into an integer array.


2 Answers

The problem is that you do not do any type conversion of the numpy array. You calculate a float32 variable and put it as an entry into a float64 numpy array. numpy then converts it properly back to float64

Try someting like this:

a = np.zeros(4,dtype="float64")  print a.dtype print type(a[0]) a = np.float32(a) print a.dtype print type(a[0]) 

The output (tested with python 2.7)

float64 <type 'numpy.float64'> float32 <type 'numpy.float32'> 

a is in your case the array tree.tree_.threshold

like image 60
Glostas Avatar answered Oct 19 '22 12:10

Glostas


You can try this:

tree.tree_.threshold[i]=tree.tree_.threshold[i].astype('float32',casting='same_kind’) 
like image 42
Woody Avatar answered Oct 19 '22 12:10

Woody