如何以便携格式保存/加载scipy sparse csr_matrix
?scipy稀疏矩阵是在Python 3 (Windows 64位)上创建的,以在Python 2 (Linux 64位)上运行。最初,我使用pickle (与protocol=2和fix_imports=True一起使用),但从Python3.2.2(Windows64位)到Python2.7.2(Windows32位)不起作用,并得到以下错误:
TypeError: ('data type not understood', <built-in function _reconstruct>, (<type 'numpy.ndarray'>, (0,), '[98]')).
接下来,我尝试了numpy.save
和numpy.load
以及scipy.io.mmwrite()
和scipy.io.mmread()
,但这些方法都不起作用。
发布于 2015-03-12 05:55:28
尽管你写了,但scipy.io.mmwrite
和scipy.io.mmread
并不适合你,我只想补充一下它们是如何工作的。这个问题是谷歌的头号热门问题,所以我自己从np.savez
和pickle.dump
开始,然后切换到简单而明显的scipy函数。它们为我工作,不应该由那些还没有尝试过它们的人来监督。
from scipy import sparse, io
m = sparse.csr_matrix([[0,0,0],[1,0,0],[0,1,0]])
m # <3x3 sparse matrix of type '<type 'numpy.int64'>' with 2 stored elements in Compressed Sparse Row format>
io.mmwrite("test.mtx", m)
del m
newm = io.mmread("test.mtx")
newm # <3x3 sparse matrix of type '<type 'numpy.int32'>' with 2 stored elements in COOrdinate format>
newm.tocsr() # <3x3 sparse matrix of type '<type 'numpy.int32'>' with 2 stored elements in Compressed Sparse Row format>
newm.toarray() # array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=int32)
发布于 2017-04-03 18:36:23
现在您可以使用scipy.sparse.save_npz
:https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.save_npz.html
发布于 2012-01-22 05:17:10
假设您在两台机器上都安装了scipy,那么您可以只使用pickle
。
但是,在酸洗numpy数组时,请务必指定二进制协议。否则你会得到一个很大的文件。
无论如何,你应该能够做到这一点:
import cPickle as pickle
import numpy as np
import scipy.sparse
# Just for testing, let's make a dense array and convert it to a csr_matrix
x = np.random.random((10,10))
x = scipy.sparse.csr_matrix(x)
with open('test_sparse_array.dat', 'wb') as outfile:
pickle.dump(x, outfile, pickle.HIGHEST_PROTOCOL)
然后,您可以使用以下命令加载它:
import cPickle as pickle
with open('test_sparse_array.dat', 'rb') as infile:
x = pickle.load(infile)
https://stackoverflow.com/questions/8955448
复制相似问题