Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save scipy object to file

I want to save the object interpolatorgenerated from scipy.interpolate.InterpolatedUnivariateSpline to a file, in order to load it afterwards and use it. This is the result on the console:

>>> interpolator
 <scipy.interpolate.fitpack2.InterpolatedUnivariateSpline object at 0x11C27170>
np.save("interpolator",np.array(interpolator))
>>> f = np.load("interpolator.npy")
>>> f
array(<scipy.interpolate.fitpack2.InterpolatedUnivariateSpline object at 0x11C08FB0>, dtype=object)

These are the results trying to use the loaded interpolator f with a generic value:

>>>f(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'numpy.ndarray' object is not callable

or:

>>> f[0](10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array

How can I save/load it properly?

like image 356
charles Avatar asked Jan 15 '16 13:01

charles


1 Answers

The interpolator object is not an array, so np.save has wrapped it in an object array. And it falls back on pickle to save elements that aren't arrays. So you get back a 0d array with one object.

To illustrate with a simple dictionary object:

In [280]: np.save('test.npy',{'one':1})
In [281]: x=np.load('test.npy')
In [282]: x
Out[282]: array({'one': 1}, dtype=object)
In [283]: x[0]
...
IndexError: 0-d arrays can't be indexed
In [284]: x[()]
Out[284]: {'one': 1}
In [285]: x.item()
Out[285]: {'one': 1}
In [288]: x.item()['one']
Out[288]: 1

So either item or [()] will retrieve this object from the array. You should then be able to use it as you would before the save.

Using your own pickle calls is fine.

like image 110
hpaulj Avatar answered Sep 18 '22 12:09

hpaulj