将scipy对象保存到文件 [英] Save scipy object to file
问题描述
我想将从scipy.interpolate.InterpolatedUnivariateSpline
生成的对象interpolator
保存到文件中,以便以后加载并使用它.
这是在控制台上的结果:
I want to save the object interpolator
generated 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)
这些是尝试将加载的插值器f
与通用值一起使用的结果:
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
或:
>>> 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?
推荐答案
interpolator
对象不是数组,因此np.save
将其包装在object
数组中.它依赖于pickle
来保存不是数组的元素.因此,您将获得一个带有一个对象的0d数组.
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
因此item
或[()]
将从数组中检索此对象.然后,您应该可以像save
之前一样使用它.
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
.
使用您自己的pickle
通话就可以了.
Using your own pickle
calls is fine.
这篇关于将scipy对象保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!