如何以可移植格式保存/加载scipy稀疏csr_matrix
?scipy稀疏矩阵是在Python 3(Windows 64位)上创建的,在Python 2(linux64位)上运行。最初,我使用pickle(protocol=2,fix_imports=True),但从Python 3.2.2(Windows 64位)到Python 2.7.2(Windows 32位)都不起作用,并得到错误:
TypeError: ('data type not understood', <built-in function _reconstruct>, (<type 'numpy.ndarray'>, (0,), '[98]')).
接下来,尝试了numpy.save
和numpy.load
以及scipy.io.mmwrite()
和scipy.io.mmread()
,但这些方法都不起作用。
下面是使用Jupyter笔记本的三个最高票答案的性能比较。输入为1 m x 100 k随机稀疏矩阵,密度为0.001,包含100 m非零值:
io.mmwrite
/io.mmread
(注意,格式已从csr更改为coo)。
np.savez
/np.load
cPickle
注意:cPickle不能处理非常大的对象(请参见this answer)。 以我的经验,它不适用于270M非零值的270万x 50万矩阵。
np.savez
溶液效果良好。结论
(基于这个简单的CSR矩阵测试)
cPickle
是最快的方法,但它不适用于非常大的矩阵,np.savez
只是稍微慢一点,而io.mmwrite
则慢得多,生成更大的文件并还原到错误的格式。所以np.savez
是这里的赢家。尽管你写,
scipy.io.mmwrite
和scipy.io.mmread
对你不起作用,但我只想补充一下它们是如何工作的。这个问题是Google的头号热门话题,所以在切换到简单而明显的scipy函数之前,我自己先从np.savez
和pickle.dump
开始。他们为我工作,不应该被那些还没有尝试过的人监督。编辑:SciPy 1.19现在有^{} 和^{} 。
对于这两个函数,
file
参数也可以是类似文件的对象(即open
的结果),而不是文件名。从Scipy用户组得到答案:
例如:
相关问题 更多 >
编程相关推荐