我希望能够将数组子类保存到npy文件中,并在以后恢复结果。在
比如:
>>> class MyArray(np.ndarray): pass
>>> data = MyArray(np.arange(10))
>>> np.save('fname', data)
>>> data2 = np.load('fname')
>>> assert isinstance(data2, MyArray) # raises AssertionError
the docs说(强调我的):
The format explicitly does not need to:
- [...]
- Fully handle arbitrary subclasses of numpy.ndarray. Subclasses will be accepted for writing, but only the array data will be written out. A regular numpy.ndarray object will be created upon reading the file. The API can be used to build a format for a particular subclass, but that is out of scope for the general NPY format.
那么,是否可以使上述代码不引发断言错误?在
我看不到
np.save
处理数组子类的证据。在我试图用它保存一个
np.matrix
,但得到了一个ndarray
。在我试图保存一个
np.ma
数组,但得到了一个错误保存是由
^{pr2}$np.lib.npyio.format.write_array
完成的如果
dtype
是对象,则使用pickle.dump(array, fp ...)
否则它会
array.tofile(fp)
。^{cd9>处理缓冲区。在我认为一个数组的
pickle.dump
最终使用了np.save
,但我不记得是如何触发的。在例如,
pickle
一个数组,并加载它:这个}的情况。所以这可能是你自己的子类需要探索的方向。在
pickle
转储/加载序列适用于测试np.ma
、np.matrix
和{在}上搜索时,我找到了{a1}。答案包括一个自定义的
numpy
和{.__reduce__
和.__setstate__
。在相关问题 更多 >
编程相关推荐