将 scipy 对象保存到文件

2024-01-10

我想保存对象interpolator产生自scipy.interpolate.InterpolatedUnivariateSpline到一个文件,以便随后加载并使用它。 这是控制台上的结果:

>>> 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具有通用值:

>>>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

我怎样才能正确保存/加载它?


The interpolator对象不是数组,所以np.save把它包裹在一个object大批。它又回到了pickle保存不是数组的元素。所以你会得到一个包含一个对象的 0d 数组。

用一个简单的字典对象来说明:

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 or [()]将从数组中检索该对象。然后您应该能够像之前一样使用它save.

使用你自己的pickle通话没问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 scipy 对象保存到文件 的相关文章

随机推荐